3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Core\System;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Group;
37 use Friendica\Model\Item;
38 use Friendica\Model\Mail;
39 use Friendica\Model\Notification;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Profile;
43 use Friendica\Model\User;
44 use Friendica\Model\Verb;
45 use Friendica\Module\BaseApi;
46 use Friendica\Network\HTTPException;
47 use Friendica\Network\HTTPException\BadRequestException;
48 use Friendica\Network\HTTPException\ForbiddenException;
49 use Friendica\Network\HTTPException\InternalServerErrorException;
50 use Friendica\Network\HTTPException\MethodNotAllowedException;
51 use Friendica\Network\HTTPException\NotFoundException;
52 use Friendica\Network\HTTPException\TooManyRequestsException;
53 use Friendica\Network\HTTPException\UnauthorizedException;
54 use Friendica\Object\Image;
55 use Friendica\Protocol\Activity;
56 use Friendica\Security\BasicAuth;
57 use Friendica\Util\DateTimeFormat;
58 use Friendica\Util\Images;
59 use Friendica\Util\Network;
60 use Friendica\Util\Strings;
62 require_once __DIR__ . '/../mod/item.php';
63 require_once __DIR__ . '/../mod/wall_upload.php';
65 define('API_METHOD_ANY', '*');
66 define('API_METHOD_GET', 'GET');
67 define('API_METHOD_POST', 'POST,PUT');
68 define('API_METHOD_DELETE', 'POST,DELETE');
70 define('API_LOG_PREFIX', 'API {action} - ');
75 * Get source name from API client
77 * Clients can send 'source' parameter to be show in post metadata
78 * as "sent via <source>".
79 * Some clients doesn't send a source param, we support ones we know
83 * Client source name, default to "api" if unset/unknown
88 if (requestdata('source')) {
89 return requestdata('source');
92 // Support for known clients that doesn't send a source name
93 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
94 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
98 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
100 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
107 * Format date for API
109 * @param string $str Source date, as UTC
110 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
113 function api_date($str)
115 // Wed May 23 06:01:13 +0000 2007
116 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
120 * Register a function to be the endpoint for defined API path.
122 * @param string $path API URL path, relative to DI::baseUrl()
123 * @param string $func Function name to call on path request
124 * @param bool $auth API need logged user
125 * @param string $method HTTP method reqiured to call this endpoint.
126 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
127 * Default to API_METHOD_ANY
129 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
139 // Workaround for hotot
140 $path = str_replace("api/", "api/1.1/", $path);
150 * Check HTTP method of called API
152 * API endpoints can define which HTTP method to accept when called.
153 * This function check the current HTTP method agains endpoint
156 * @param string $method Required methods, uppercase, separated by comma
159 function api_check_method($method)
161 if ($method == "*") {
164 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
168 * Main API entry point
170 * Authenticate user, call registered API function, set HTTP headers
173 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
174 * @return string|array API call result
177 function api_call(App $a, App\Arguments $args = null)
186 if (strpos($args->getCommand(), ".xml") > 0) {
189 if (strpos($args->getCommand(), ".json") > 0) {
192 if (strpos($args->getCommand(), ".rss") > 0) {
195 if (strpos($args->getCommand(), ".atom") > 0) {
200 foreach ($API as $p => $info) {
201 if (strpos($args->getCommand(), $p) === 0) {
202 if (!api_check_method($info['method'])) {
203 throw new MethodNotAllowedException();
206 if (!empty($info['auth']) && BaseApi::getCurrentUserID() === false) {
207 BasicAuth::getCurrentUserID(true);
208 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
211 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
213 $stamp = microtime(true);
214 $return = call_user_func($info['func'], $type);
215 $duration = floatval(microtime(true) - $stamp);
217 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
219 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
221 if (false === $return) {
223 * api function returned false withour throw an
224 * exception. This should not happend, throw a 500
226 throw new InternalServerErrorException();
231 header("Content-Type: text/xml");
234 header("Content-Type: application/json");
235 if (!empty($return)) {
236 $json = json_encode(end($return));
237 if (!empty($_GET['callback'])) {
238 $json = $_GET['callback'] . "(" . $json . ")";
244 header("Content-Type: application/rss+xml");
245 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
248 header("Content-Type: application/atom+xml");
249 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
256 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
257 throw new NotFoundException();
258 } catch (HTTPException $e) {
259 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
264 * Set values for RSS template
266 * @param array $arr Array to be passed to template
267 * @param array $user_info User info
269 * @throws BadRequestException
270 * @throws ImagickException
271 * @throws InternalServerErrorException
272 * @throws UnauthorizedException
273 * @todo find proper type-hints
275 function api_rss_extra($arr, $user_info)
277 if (is_null($user_info)) {
278 $uid = BaseApi::getCurrentUserID();
280 throw new ForbiddenException();
283 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
286 $arr['$user'] = $user_info;
288 'alternate' => $user_info['url'],
289 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
290 'base' => DI::baseUrl(),
291 'updated' => api_date(null),
292 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
293 'language' => $user_info['lang'],
294 'logo' => DI::baseUrl() . "/images/friendica-32.png",
302 * Unique contact to contact url.
304 * @param int $id Contact id
305 * @return bool|string
306 * Contact url or False if contact id is unknown
309 function api_unique_id_to_nurl($id)
311 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
313 if (DBA::isResult($r)) {
321 * Get user info array.
324 * @param int|string $contact_id Contact ID or URL
326 * @throws BadRequestException
327 * @throws ImagickException
328 * @throws InternalServerErrorException
329 * @throws UnauthorizedException
331 function api_get_user($contact_id = null)
337 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
339 // Searching for contact URL
340 if (intval($contact_id) == 0) {
341 $user = Strings::normaliseLink($contact_id);
343 $extra_query = "AND `contact`.`nurl` = ? ";
344 if (BaseApi::getCurrentUserID() !== false) {
345 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
349 // Searching for contact id with uid = 0
350 if (intval($contact_id) != 0) {
351 $user = api_unique_id_to_nurl(intval($contact_id));
354 throw new BadRequestException("User ID ".$contact_id." not found.");
358 $extra_query = "AND `contact`.`nurl` = ? ";
359 if (BaseApi::getCurrentUserID() !== false) {
360 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
364 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
370 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
373 $uinfo = DBA::toArray(DBA::p(
374 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
380 if (DBA::isResult($uinfo)) {
381 // Selecting the id by priority, friendica first
382 api_best_nickname($uinfo);
383 return DI::twitterUser()->createFromContactId($uinfo[0]['cid'], $uinfo[0]['uid'])->toArray();
387 throw new BadRequestException("User not found.");
390 $cid = Contact::getIdForURL($url, 0, false);
393 return DI::twitterUser()->createFromContactId($cid, 0)->toArray();
395 throw new BadRequestException("User ".$url." not found.");
400 * return api-formatted array for item's author and owner
403 * @param array $item item from db
404 * @return array(array:author, array:owner)
405 * @throws BadRequestException
406 * @throws ImagickException
407 * @throws InternalServerErrorException
408 * @throws UnauthorizedException
410 function api_item_get_user(App $a, $item)
412 if (empty($item['author-id'])) {
413 $item['author-id'] = Contact::getPublicIdByUserId(BaseApi::getCurrentUserID());
415 $status_user = DI::twitterUser()->createFromContactId($item['author-id'], BaseApi::getCurrentUserID())->toArray();
417 $author_user = $status_user;
419 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
421 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
422 if (empty($item['owner-id'])) {
423 $item['owner-id'] = Contact::getPublicIdByUserId(BaseApi::getCurrentUserID());
425 $owner_user = DI::twitterUser()->createFromContactId($item['owner-id'], BaseApi::getCurrentUserID())->toArray();
427 $owner_user = $author_user;
430 return ([$status_user, $author_user, $owner_user]);
438 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
439 * returns a 401 status code and an error message if not.
441 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
443 * @param string $type Return type (atom, rss, xml, json)
444 * @return array|string
445 * @throws BadRequestException
446 * @throws ForbiddenException
447 * @throws ImagickException
448 * @throws InternalServerErrorException
449 * @throws UnauthorizedException
451 function api_account_verify_credentials($type)
453 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
455 unset($_REQUEST['user_id']);
456 unset($_GET['user_id']);
458 unset($_REQUEST['screen_name']);
459 unset($_GET['screen_name']);
461 $skip_status = $_REQUEST['skip_status'] ?? false;
463 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
465 // "verified" isn't used here in the standard
466 unset($user_info["verified"]);
468 // - Adding last status
470 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
472 $user_info['status'] = api_format_item($item, $type);
476 // "uid" and "self" are only needed for some internal stuff, so remove it from here
477 unset($user_info["uid"]);
478 unset($user_info["self"]);
480 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
483 /// @TODO move to top of file or somewhere better
484 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
487 * Get data from $_POST or $_GET
492 function requestdata($k)
494 if (!empty($_POST[$k])) {
497 if (!empty($_GET[$k])) {
504 * Deprecated function to upload media.
506 * @param string $type Return type (atom, rss, xml, json)
508 * @return array|string
509 * @throws BadRequestException
510 * @throws ForbiddenException
511 * @throws ImagickException
512 * @throws InternalServerErrorException
513 * @throws UnauthorizedException
515 function api_statuses_mediap($type)
519 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
521 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
523 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
524 $_REQUEST['api_source'] = true;
525 $txt = requestdata('status') ?? '';
526 /// @TODO old-lost code?
527 //$txt = urldecode(requestdata('status'));
529 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
530 $txt = HTML::toBBCodeVideo($txt);
531 $config = HTMLPurifier_Config::createDefault();
532 $config->set('Cache.DefinitionImpl', null);
533 $purifier = new HTMLPurifier($config);
534 $txt = $purifier->purify($txt);
536 $txt = HTML::toBBCode($txt);
538 DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
540 $picture = wall_upload_post($a, false);
542 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
543 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
544 $item_id = item_post($a);
546 // output the post that we just posted.
547 return api_status_show($type, $item_id);
550 /// @TODO move this to top of file or somewhere better!
551 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
554 * Updates the user’s current status.
556 * @param string $type Return type (atom, rss, xml, json)
558 * @return array|string
559 * @throws BadRequestException
560 * @throws ForbiddenException
561 * @throws ImagickException
562 * @throws InternalServerErrorException
563 * @throws TooManyRequestsException
564 * @throws UnauthorizedException
565 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
567 function api_statuses_update($type)
571 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
573 // convert $_POST array items to the form we use for web posts.
574 if (requestdata('htmlstatus')) {
575 $txt = requestdata('htmlstatus') ?? '';
576 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
577 $txt = HTML::toBBCodeVideo($txt);
579 $config = HTMLPurifier_Config::createDefault();
580 $config->set('Cache.DefinitionImpl', null);
582 $purifier = new HTMLPurifier($config);
583 $txt = $purifier->purify($txt);
585 $_REQUEST['body'] = HTML::toBBCode($txt);
588 $_REQUEST['body'] = requestdata('status');
591 $_REQUEST['title'] = requestdata('title');
593 $parent = requestdata('in_reply_to_status_id');
595 // Twidere sends "-1" if it is no reply ...
600 if (ctype_digit($parent)) {
601 $_REQUEST['parent'] = $parent;
603 $_REQUEST['parent_uri'] = $parent;
606 if (requestdata('lat') && requestdata('long')) {
607 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
609 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
612 // Check for throttling (maximum posts per day, week and month)
613 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
614 if ($throttle_day > 0) {
615 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
617 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
618 $posts_day = Post::count($condition);
620 if ($posts_day > $throttle_day) {
621 logger::info('Daily posting limit reached for user '.BaseApi::getCurrentUserID());
622 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
623 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));
627 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
628 if ($throttle_week > 0) {
629 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
631 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
632 $posts_week = Post::count($condition);
634 if ($posts_week > $throttle_week) {
635 logger::info('Weekly posting limit reached for user '.BaseApi::getCurrentUserID());
636 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
637 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));
641 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
642 if ($throttle_month > 0) {
643 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
645 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
646 $posts_month = Post::count($condition);
648 if ($posts_month > $throttle_month) {
649 logger::info('Monthly posting limit reached for user '.BaseApi::getCurrentUserID());
650 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
651 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));
656 if (requestdata('media_ids')) {
657 $ids = explode(',', requestdata('media_ids') ?? '');
658 } elseif (!empty($_FILES['media'])) {
659 // upload the image if we have one
660 $picture = wall_upload_post($a, false);
661 if (is_array($picture)) {
662 $ids[] = $picture['id'];
670 foreach ($ids as $id) {
671 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
672 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
673 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
674 ORDER BY `photo`.`width` DESC LIMIT 2", $id, BaseApi::getCurrentUserID()));
676 if (!empty($media)) {
677 $ressources[] = $media[0]['resource-id'];
678 $phototypes = Images::supportedTypes();
679 $ext = $phototypes[$media[0]['type']];
681 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
682 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
683 'size' => $media[0]['datasize'],
684 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
685 'description' => $media[0]['desc'] ?? '',
686 'width' => $media[0]['width'],
687 'height' => $media[0]['height']];
689 if (count($media) > 1) {
690 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
691 $attachment['preview-width'] = $media[1]['width'];
692 $attachment['preview-height'] = $media[1]['height'];
694 $attachments[] = $attachment;
698 // We have to avoid that the post is rejected because of an empty body
699 if (empty($_REQUEST['body'])) {
700 $_REQUEST['body'] = '[hr]';
704 if (!empty($attachments)) {
705 $_REQUEST['attachments'] = $attachments;
708 // set this so that the item_post() function is quiet and doesn't redirect or emit json
710 $_REQUEST['api_source'] = true;
712 if (empty($_REQUEST['source'])) {
713 $_REQUEST['source'] = api_source();
716 // call out normal post function
717 $item_id = item_post($a);
719 if (!empty($ressources) && !empty($item_id)) {
720 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
721 foreach ($ressources as $ressource) {
722 Photo::setPermissionForRessource($ressource, BaseApi::getCurrentUserID(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
726 // output the post that we just posted.
727 return api_status_show($type, $item_id);
730 /// @TODO move to top of file or somewhere better
731 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
732 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
735 * Uploads an image to Friendica.
738 * @throws BadRequestException
739 * @throws ForbiddenException
740 * @throws ImagickException
741 * @throws InternalServerErrorException
742 * @throws UnauthorizedException
743 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
745 function api_media_upload()
749 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
751 if (empty($_FILES['media'])) {
753 throw new BadRequestException("No media.");
756 $media = wall_upload_post($a, false);
759 throw new InternalServerErrorException();
763 $returndata["media_id"] = $media["id"];
764 $returndata["media_id_string"] = (string)$media["id"];
765 $returndata["size"] = $media["size"];
766 $returndata["image"] = ["w" => $media["width"],
767 "h" => $media["height"],
768 "image_type" => $media["type"],
769 "friendica_preview_url" => $media["preview"]];
771 Logger::info('Media uploaded', ['return' => $returndata]);
773 return ["media" => $returndata];
776 /// @TODO move to top of file or somewhere better
777 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
780 * Updates media meta data (picture descriptions)
782 * @param string $type Return type (atom, rss, xml, json)
784 * @return array|string
785 * @throws BadRequestException
786 * @throws ForbiddenException
787 * @throws ImagickException
788 * @throws InternalServerErrorException
789 * @throws TooManyRequestsException
790 * @throws UnauthorizedException
791 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
793 * @todo Compare the corresponding Twitter function for correct return values
795 function api_media_metadata_create($type)
797 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
799 $postdata = Network::postdata();
801 if (empty($postdata)) {
802 throw new BadRequestException("No post data");
805 $data = json_decode($postdata, true);
807 throw new BadRequestException("Invalid post data");
810 if (empty($data['media_id']) || empty($data['alt_text'])) {
811 throw new BadRequestException("Missing post data values");
814 if (empty($data['alt_text']['text'])) {
815 throw new BadRequestException("No alt text.");
818 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
820 $condition = ['id' => $data['media_id'], 'uid' => BaseApi::getCurrentUserID()];
821 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
822 if (!DBA::isResult($photo)) {
823 throw new BadRequestException("Metadata not found.");
826 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
829 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
832 * @param string $type Return format (atom, rss, xml, json)
833 * @param int $item_id
834 * @return array|string
837 function api_status_show($type, $item_id)
839 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
843 $item = api_get_item(['id' => $item_id]);
845 $status_info = api_format_item($item, $type);
848 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
850 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
854 * Retrieves the last public status of the provided user info
856 * @param int $ownerId Public contact Id
857 * @param int $uid User Id
861 function api_get_last_status($ownerId, $uid)
864 'author-id'=> $ownerId,
866 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
867 'private' => [Item::PUBLIC, Item::UNLISTED]
870 $item = api_get_item($condition);
876 * Retrieves a single item record based on the provided condition and converts it for API use.
878 * @param array $condition Item table condition array
882 function api_get_item(array $condition)
884 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
890 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
891 * The author's most recent status will be returned inline.
893 * @param string $type Return type (atom, rss, xml, json)
894 * @return array|string
895 * @throws BadRequestException
896 * @throws ImagickException
897 * @throws InternalServerErrorException
898 * @throws UnauthorizedException
899 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
901 function api_users_show($type)
903 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
905 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
907 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
909 $user_info['status'] = api_format_item($item, $type);
912 // "uid" and "self" are only needed for some internal stuff, so remove it from here
913 unset($user_info['uid']);
914 unset($user_info['self']);
916 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
919 /// @TODO move to top of file or somewhere better
920 api_register_func('api/users/show', 'api_users_show');
921 api_register_func('api/externalprofile/show', 'api_users_show');
924 * Search a public user account.
926 * @param string $type Return type (atom, rss, xml, json)
928 * @return array|string
929 * @throws BadRequestException
930 * @throws ImagickException
931 * @throws InternalServerErrorException
932 * @throws UnauthorizedException
933 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
935 function api_users_search($type)
939 if (!empty($_GET['q'])) {
940 $contacts = Contact::selectToArray(
943 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
951 if (DBA::isResult($contacts)) {
953 foreach ($contacts as $contact) {
954 $user_info = DI::twitterUser()->createFromContactId($contact['id'], BaseApi::getCurrentUserID())->toArray();
956 if ($type == 'xml') {
957 $userlist[$k++ . ':user'] = $user_info;
959 $userlist[] = $user_info;
962 $userlist = ['users' => $userlist];
964 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
967 throw new BadRequestException('No search term specified.');
970 return DI::apiResponse()->formatData('users', $type, $userlist);
973 /// @TODO move to top of file or somewhere better
974 api_register_func('api/users/search', 'api_users_search');
977 * Return user objects
979 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
981 * @param string $type Return format: json or xml
983 * @return array|string
984 * @throws BadRequestException
985 * @throws ImagickException
986 * @throws InternalServerErrorException
987 * @throws NotFoundException if the results are empty.
988 * @throws UnauthorizedException
990 function api_users_lookup($type)
994 if (!empty($_REQUEST['user_id'])) {
995 foreach (explode(',', $_REQUEST['user_id']) as $id) {
997 $users[] = api_get_user($id);
1002 if (empty($users)) {
1003 throw new NotFoundException;
1006 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1009 /// @TODO move to top of file or somewhere better
1010 api_register_func('api/users/lookup', 'api_users_lookup', true);
1013 * Returns statuses that match a specified query.
1015 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1017 * @param string $type Return format: json, xml, atom, rss
1019 * @return array|string
1020 * @throws BadRequestException if the "q" parameter is missing.
1021 * @throws ForbiddenException
1022 * @throws ImagickException
1023 * @throws InternalServerErrorException
1024 * @throws UnauthorizedException
1026 function api_search($type)
1028 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1030 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1032 if (empty($_REQUEST['q'])) {
1033 throw new BadRequestException('q parameter is required.');
1036 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1039 $data['status'] = [];
1041 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1042 if (!empty($_REQUEST['rpp'])) {
1043 $count = $_REQUEST['rpp'];
1044 } elseif (!empty($_REQUEST['count'])) {
1045 $count = $_REQUEST['count'];
1048 $since_id = $_REQUEST['since_id'] ?? 0;
1049 $max_id = $_REQUEST['max_id'] ?? 0;
1050 $page = $_REQUEST['page'] ?? 1;
1052 $start = max(0, ($page - 1) * $count);
1054 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1055 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1056 $searchTerm = $matches[1];
1057 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, BaseApi::getCurrentUserID()];
1058 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1060 while ($tag = DBA::fetch($tags)) {
1061 $uriids[] = $tag['uri-id'];
1065 if (empty($uriids)) {
1066 return DI::apiResponse()->formatData('statuses', $type, $data);
1069 $condition = ['uri-id' => $uriids];
1070 if ($exclude_replies) {
1071 $condition['gravity'] = GRAVITY_PARENT;
1074 $params['group_by'] = ['uri-id'];
1076 $condition = ["`id` > ?
1077 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1078 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1079 AND `body` LIKE CONCAT('%',?,'%')",
1080 $since_id, BaseApi::getCurrentUserID(), $_REQUEST['q']];
1082 $condition[0] .= ' AND `id` <= ?';
1083 $condition[] = $max_id;
1089 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1090 $id = Item::fetchByLink($searchTerm, BaseApi::getCurrentUserID());
1093 $id = Item::fetchByLink($searchTerm);
1097 $statuses = Post::select([], ['id' => $id]);
1101 $statuses = $statuses ?: Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1103 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1105 bindComments($data['status']);
1107 return DI::apiResponse()->formatData('statuses', $type, $data);
1110 /// @TODO move to top of file or somewhere better
1111 api_register_func('api/search/tweets', 'api_search', true);
1112 api_register_func('api/search', 'api_search', true);
1115 * Returns the most recent statuses posted by the user and the users they follow.
1117 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1119 * @param string $type Return type (atom, rss, xml, json)
1121 * @return array|string
1122 * @throws BadRequestException
1123 * @throws ForbiddenException
1124 * @throws ImagickException
1125 * @throws InternalServerErrorException
1126 * @throws UnauthorizedException
1127 * @todo Optional parameters
1128 * @todo Add reply info
1130 function api_statuses_home_timeline($type)
1132 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1134 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1136 unset($_REQUEST['user_id']);
1137 unset($_GET['user_id']);
1139 unset($_REQUEST['screen_name']);
1140 unset($_GET['screen_name']);
1142 // get last network messages
1145 $count = $_REQUEST['count'] ?? 20;
1146 $page = $_REQUEST['page']?? 0;
1147 $since_id = $_REQUEST['since_id'] ?? 0;
1148 $max_id = $_REQUEST['max_id'] ?? 0;
1149 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1150 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1152 $start = max(0, ($page - 1) * $count);
1154 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1155 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1158 $condition[0] .= " AND `id` <= ?";
1159 $condition[] = $max_id;
1161 if ($exclude_replies) {
1162 $condition[0] .= ' AND `gravity` = ?';
1163 $condition[] = GRAVITY_PARENT;
1165 if ($conversation_id > 0) {
1166 $condition[0] .= " AND `parent` = ?";
1167 $condition[] = $conversation_id;
1170 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1171 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1173 $items = Post::toArray($statuses);
1175 $ret = api_format_items($items, $user_info, false, $type);
1177 // Set all posts from the query above to seen
1179 foreach ($items as $item) {
1180 $idarray[] = intval($item["id"]);
1183 if (!empty($idarray)) {
1184 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1186 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1192 $data = ['status' => $ret];
1197 $data = api_rss_extra($data, $user_info);
1201 return DI::apiResponse()->formatData("statuses", $type, $data);
1205 /// @TODO move to top of file or somewhere better
1206 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1207 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1210 * Returns the most recent statuses from public users.
1212 * @param string $type Return type (atom, rss, xml, json)
1214 * @return array|string
1215 * @throws BadRequestException
1216 * @throws ForbiddenException
1217 * @throws ImagickException
1218 * @throws InternalServerErrorException
1219 * @throws UnauthorizedException
1221 function api_statuses_public_timeline($type)
1223 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1225 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1227 // get last network messages
1230 $count = $_REQUEST['count'] ?? 20;
1231 $page = $_REQUEST['page'] ?? 1;
1232 $since_id = $_REQUEST['since_id'] ?? 0;
1233 $max_id = $_REQUEST['max_id'] ?? 0;
1234 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1235 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1237 $start = max(0, ($page - 1) * $count);
1239 if ($exclude_replies && !$conversation_id) {
1240 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1241 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1244 $condition[0] .= " AND `id` <= ?";
1245 $condition[] = $max_id;
1248 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1249 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1251 $r = Post::toArray($statuses);
1253 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1254 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1257 $condition[0] .= " AND `id` <= ?";
1258 $condition[] = $max_id;
1260 if ($conversation_id > 0) {
1261 $condition[0] .= " AND `parent` = ?";
1262 $condition[] = $conversation_id;
1265 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1266 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1268 $r = Post::toArray($statuses);
1271 $ret = api_format_items($r, $user_info, false, $type);
1275 $data = ['status' => $ret];
1280 $data = api_rss_extra($data, $user_info);
1284 return DI::apiResponse()->formatData("statuses", $type, $data);
1287 /// @TODO move to top of file or somewhere better
1288 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1291 * Returns the most recent statuses posted by users this node knows about.
1293 * @param string $type Return format: json, xml, atom, rss
1294 * @return array|string
1295 * @throws BadRequestException
1296 * @throws ForbiddenException
1297 * @throws ImagickException
1298 * @throws InternalServerErrorException
1299 * @throws UnauthorizedException
1301 function api_statuses_networkpublic_timeline($type)
1303 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1305 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1307 $since_id = $_REQUEST['since_id'] ?? 0;
1308 $max_id = $_REQUEST['max_id'] ?? 0;
1311 $count = $_REQUEST['count'] ?? 20;
1312 $page = $_REQUEST['page'] ?? 1;
1314 $start = max(0, ($page - 1) * $count);
1316 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1317 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1320 $condition[0] .= " AND `id` <= ?";
1321 $condition[] = $max_id;
1324 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1325 $statuses = Post::toArray(Post::selectForUser(BaseApi::getCurrentUserID(), Item::DISPLAY_FIELDLIST, $condition, $params));
1327 $ret = api_format_items($statuses, $user_info, false, $type);
1331 $data = ['status' => $ret];
1336 $data = api_rss_extra($data, $user_info);
1340 return DI::apiResponse()->formatData("statuses", $type, $data);
1343 /// @TODO move to top of file or somewhere better
1344 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1347 * Returns a single status.
1349 * @param string $type Return type (atom, rss, xml, json)
1351 * @return array|string
1352 * @throws BadRequestException
1353 * @throws ForbiddenException
1354 * @throws ImagickException
1355 * @throws InternalServerErrorException
1356 * @throws UnauthorizedException
1357 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1359 function api_statuses_show($type)
1361 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1363 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1366 $id = intval(DI::args()->getArgv()[3] ?? 0);
1369 $id = intval($_REQUEST['id'] ?? 0);
1374 $id = intval(DI::args()->getArgv()[4] ?? 0);
1377 logger::notice('API: api_statuses_show: ' . $id);
1379 $conversation = !empty($_REQUEST['conversation']);
1381 // try to fetch the item for the local user - or the public item, if there is no local one
1382 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1383 if (!DBA::isResult($uri_item)) {
1384 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1387 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1388 if (!DBA::isResult($item)) {
1389 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1394 if ($conversation) {
1395 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1396 $params = ['order' => ['id' => true]];
1398 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1402 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1404 /// @TODO How about copying this to above methods which don't check $r ?
1405 if (!DBA::isResult($statuses)) {
1406 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1409 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1411 if ($conversation) {
1412 $data = ['status' => $ret];
1413 return DI::apiResponse()->formatData("statuses", $type, $data);
1415 $data = ['status' => $ret[0]];
1416 return DI::apiResponse()->formatData("status", $type, $data);
1420 /// @TODO move to top of file or somewhere better
1421 api_register_func('api/statuses/show', 'api_statuses_show', true);
1425 * @param string $type Return type (atom, rss, xml, json)
1427 * @return array|string
1428 * @throws BadRequestException
1429 * @throws ForbiddenException
1430 * @throws ImagickException
1431 * @throws InternalServerErrorException
1432 * @throws UnauthorizedException
1433 * @todo nothing to say?
1435 function api_conversation_show($type)
1437 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1439 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1442 $id = intval(DI::args()->getArgv()[3] ?? 0);
1443 $since_id = intval($_REQUEST['since_id'] ?? 0);
1444 $max_id = intval($_REQUEST['max_id'] ?? 0);
1445 $count = intval($_REQUEST['count'] ?? 20);
1446 $page = intval($_REQUEST['page'] ?? 1);
1448 $start = max(0, ($page - 1) * $count);
1451 $id = intval($_REQUEST['id'] ?? 0);
1456 $id = intval(DI::args()->getArgv()[4] ?? 0);
1459 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1461 // try to fetch the item for the local user - or the public item, if there is no local one
1462 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1463 if (!DBA::isResult($item)) {
1464 throw new BadRequestException("There is no status with the id $id.");
1467 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1468 if (!DBA::isResult($parent)) {
1469 throw new BadRequestException("There is no status with this id.");
1472 $id = $parent['id'];
1474 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1475 $id, BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1478 $condition[0] .= " AND `id` <= ?";
1479 $condition[] = $max_id;
1482 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1483 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1485 if (!DBA::isResult($statuses)) {
1486 throw new BadRequestException("There is no status with id $id.");
1489 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1491 $data = ['status' => $ret];
1492 return DI::apiResponse()->formatData("statuses", $type, $data);
1495 /// @TODO move to top of file or somewhere better
1496 api_register_func('api/conversation/show', 'api_conversation_show', true);
1497 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1502 * @param string $type Return type (atom, rss, xml, json)
1504 * @return array|string
1505 * @throws BadRequestException
1506 * @throws ForbiddenException
1507 * @throws ImagickException
1508 * @throws InternalServerErrorException
1509 * @throws UnauthorizedException
1510 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1512 function api_statuses_repeat($type)
1516 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1519 $id = intval(DI::args()->getArgv()[3] ?? 0);
1522 $id = intval($_REQUEST['id'] ?? 0);
1527 $id = intval(DI::args()->getArgv()[4] ?? 0);
1530 logger::notice('API: api_statuses_repeat: ' . $id);
1532 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1533 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1535 if (DBA::isResult($item) && !empty($item['body'])) {
1536 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1537 if (!Item::performActivity($id, 'announce', BaseApi::getCurrentUserID())) {
1538 throw new InternalServerErrorException();
1543 if (strpos($item['body'], "[/share]") !== false) {
1544 $pos = strpos($item['body'], "[share");
1545 $post = substr($item['body'], $pos);
1547 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1549 if (!empty($item['title'])) {
1550 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1553 $post .= $item['body'];
1554 $post .= "[/share]";
1556 $_REQUEST['body'] = $post;
1557 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
1558 $_REQUEST['api_source'] = true;
1560 if (empty($_REQUEST['source'])) {
1561 $_REQUEST['source'] = api_source();
1564 $item_id = item_post($a);
1567 throw new ForbiddenException();
1570 // output the post that we just posted.
1571 return api_status_show($type, $item_id);
1574 /// @TODO move to top of file or somewhere better
1575 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1578 * Destroys a specific status.
1580 * @param string $type Return type (atom, rss, xml, json)
1582 * @return array|string
1583 * @throws BadRequestException
1584 * @throws ForbiddenException
1585 * @throws ImagickException
1586 * @throws InternalServerErrorException
1587 * @throws UnauthorizedException
1588 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1590 function api_statuses_destroy($type)
1592 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1595 $id = intval(DI::args()->getArgv()[3] ?? 0);
1598 $id = intval($_REQUEST['id'] ?? 0);
1603 $id = intval(DI::args()->getArgv()[4] ?? 0);
1606 logger::notice('API: api_statuses_destroy: ' . $id);
1608 $ret = api_statuses_show($type);
1610 Item::deleteForUser(['id' => $id], BaseApi::getCurrentUserID());
1615 /// @TODO move to top of file or somewhere better
1616 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1619 * Returns the most recent mentions.
1621 * @param string $type Return type (atom, rss, xml, json)
1623 * @return array|string
1624 * @throws BadRequestException
1625 * @throws ForbiddenException
1626 * @throws ImagickException
1627 * @throws InternalServerErrorException
1628 * @throws UnauthorizedException
1629 * @see http://developer.twitter.com/doc/get/statuses/mentions
1631 function api_statuses_mentions($type)
1633 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1635 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1637 unset($_REQUEST['user_id']);
1638 unset($_GET['user_id']);
1640 unset($_REQUEST['screen_name']);
1641 unset($_GET['screen_name']);
1643 // get last network messages
1646 $since_id = intval($_REQUEST['since_id'] ?? 0);
1647 $max_id = intval($_REQUEST['max_id'] ?? 0);
1648 $count = intval($_REQUEST['count'] ?? 20);
1649 $page = intval($_REQUEST['page'] ?? 1);
1651 $start = max(0, ($page - 1) * $count);
1653 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1654 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1655 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1658 GRAVITY_PARENT, GRAVITY_COMMENT,
1659 BaseApi::getCurrentUserID(),
1660 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1661 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1662 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1663 BaseApi::getCurrentUserID(), $since_id,
1667 $query .= " AND `id` <= ?";
1668 $condition[] = $max_id;
1671 array_unshift($condition, $query);
1673 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1674 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1676 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1678 $data = ['status' => $ret];
1683 $data = api_rss_extra($data, $user_info);
1687 return DI::apiResponse()->formatData("statuses", $type, $data);
1690 /// @TODO move to top of file or somewhere better
1691 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1692 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1695 * Returns the most recent statuses posted by the user.
1697 * @param string $type Either "json" or "xml"
1698 * @return string|array
1699 * @throws BadRequestException
1700 * @throws ForbiddenException
1701 * @throws ImagickException
1702 * @throws InternalServerErrorException
1703 * @throws UnauthorizedException
1704 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1706 function api_statuses_user_timeline($type)
1708 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1710 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1712 Logger::info('api_statuses_user_timeline', ['api_user' => BaseApi::getCurrentUserID(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
1714 $since_id = $_REQUEST['since_id'] ?? 0;
1715 $max_id = $_REQUEST['max_id'] ?? 0;
1716 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1717 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1720 $count = $_REQUEST['count'] ?? 20;
1721 $page = $_REQUEST['page'] ?? 1;
1723 $start = max(0, ($page - 1) * $count);
1725 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
1726 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
1728 if ($user_info['self'] == 1) {
1729 $condition[0] .= ' AND `wall` ';
1732 if ($exclude_replies) {
1733 $condition[0] .= ' AND `gravity` = ?';
1734 $condition[] = GRAVITY_PARENT;
1737 if ($conversation_id > 0) {
1738 $condition[0] .= " AND `parent` = ?";
1739 $condition[] = $conversation_id;
1743 $condition[0] .= " AND `id` <= ?";
1744 $condition[] = $max_id;
1746 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1747 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1749 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
1753 $data = ['status' => $ret];
1758 $data = api_rss_extra($data, $user_info);
1762 return DI::apiResponse()->formatData("statuses", $type, $data);
1765 /// @TODO move to top of file or somewhere better
1766 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1769 * Star/unstar an item.
1770 * param: id : id of the item
1772 * @param string $type Return type (atom, rss, xml, json)
1774 * @return array|string
1775 * @throws BadRequestException
1776 * @throws ForbiddenException
1777 * @throws ImagickException
1778 * @throws InternalServerErrorException
1779 * @throws UnauthorizedException
1780 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1782 function api_favorites_create_destroy($type)
1784 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1786 // for versioned api.
1787 /// @TODO We need a better global soluton
1788 $action_argv_id = 2;
1789 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1790 $action_argv_id = 3;
1793 if (DI::args()->getArgc() <= $action_argv_id) {
1794 throw new BadRequestException("Invalid request.");
1796 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1797 if (DI::args()->getArgc() == $action_argv_id + 2) {
1798 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1800 $itemid = intval($_REQUEST['id'] ?? 0);
1803 $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $itemid, 'uid' => BaseApi::getCurrentUserID()]);
1805 if (!DBA::isResult($item)) {
1806 throw new BadRequestException("Invalid item.");
1811 $item['starred'] = 1;
1814 $item['starred'] = 0;
1817 throw new BadRequestException("Invalid action ".$action);
1820 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1823 throw new InternalServerErrorException("DB error");
1826 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1827 $rets = api_format_items([$item], $user_info, false, $type);
1830 $data = ['status' => $ret];
1835 $data = api_rss_extra($data, $user_info);
1839 return DI::apiResponse()->formatData("status", $type, $data);
1842 /// @TODO move to top of file or somewhere better
1843 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1844 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1847 * Returns the most recent favorite statuses.
1849 * @param string $type Return type (atom, rss, xml, json)
1851 * @return string|array
1852 * @throws BadRequestException
1853 * @throws ForbiddenException
1854 * @throws ImagickException
1855 * @throws InternalServerErrorException
1856 * @throws UnauthorizedException
1858 function api_favorites($type)
1860 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1862 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1864 // in friendica starred item are private
1865 // return favorites only for self
1866 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
1868 if ($user_info['self'] == 0) {
1872 $since_id = $_REQUEST['since_id'] ?? 0;
1873 $max_id = $_REQUEST['max_id'] ?? 0;
1874 $count = $_GET['count'] ?? 20;
1875 $page = $_REQUEST['page'] ?? 1;
1877 $start = max(0, ($page - 1) * $count);
1879 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
1880 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1882 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1885 $condition[0] .= " AND `id` <= ?";
1886 $condition[] = $max_id;
1889 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1891 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1896 $data = ['status' => $ret];
1901 $data = api_rss_extra($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/favorites', 'api_favorites', true);
1913 * @param array $item
1914 * @param array $recipient
1915 * @param array $sender
1918 * @throws InternalServerErrorException
1920 function api_format_messages($item, $recipient, $sender)
1922 // standard meta information
1924 'id' => $item['id'],
1925 'sender_id' => $sender['id'],
1927 'recipient_id' => $recipient['id'],
1928 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
1929 'sender_screen_name' => $sender['screen_name'],
1930 'recipient_screen_name' => $recipient['screen_name'],
1931 'sender' => $sender,
1932 'recipient' => $recipient,
1934 'friendica_seen' => $item['seen'] ?? 0,
1935 'friendica_parent_uri' => $item['parent-uri'] ?? '',
1938 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1939 if (isset($ret['sender']['uid'])) {
1940 unset($ret['sender']['uid']);
1942 if (isset($ret['sender']['self'])) {
1943 unset($ret['sender']['self']);
1945 if (isset($ret['recipient']['uid'])) {
1946 unset($ret['recipient']['uid']);
1948 if (isset($ret['recipient']['self'])) {
1949 unset($ret['recipient']['self']);
1952 //don't send title to regular StatusNET requests to avoid confusing these apps
1953 if (!empty($_GET['getText'])) {
1954 $ret['title'] = $item['title'];
1955 if ($_GET['getText'] == 'html') {
1956 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
1957 } elseif ($_GET['getText'] == 'plain') {
1958 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
1961 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
1963 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
1964 unset($ret['sender']);
1965 unset($ret['recipient']);
1973 * @param array $item
1976 * @throws InternalServerErrorException
1978 function api_convert_item($item)
1980 $body = api_add_attachments_to_body($item);
1982 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
1984 // Add pictures to the attachment array and remove them from the body
1985 $attachments = api_get_attachments($body, $item['uri-id']);
1987 // Workaround for ostatus messages where the title is identically to the body
1988 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
1989 $statusbody = trim(HTML::toPlaintext($html, 0));
1991 // handle data: images
1992 $statusbody = api_format_items_embeded_images($item, $statusbody);
1994 $statustitle = trim($item['title']);
1996 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
1997 $statustext = trim($statusbody);
1999 $statustext = trim($statustitle."\n\n".$statusbody);
2002 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2003 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2006 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2008 // Workaround for clients with limited HTML parser functionality
2009 $search = ["<br>", "<blockquote>", "</blockquote>",
2010 "<h1>", "</h1>", "<h2>", "</h2>",
2011 "<h3>", "</h3>", "<h4>", "</h4>",
2012 "<h5>", "</h5>", "<h6>", "</h6>"];
2013 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2014 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2015 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2016 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2017 $statushtml = str_replace($search, $replace, $statushtml);
2019 if ($item['title'] != "") {
2020 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2024 $oldtext = $statushtml;
2025 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2026 } while ($oldtext != $statushtml);
2028 if (substr($statushtml, 0, 4) == '<br>') {
2029 $statushtml = substr($statushtml, 4);
2032 if (substr($statushtml, 0, -4) == '<br>') {
2033 $statushtml = substr($statushtml, -4);
2036 // feeds without body should contain the link
2037 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2038 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2042 "text" => $statustext,
2043 "html" => $statushtml,
2044 "attachments" => $attachments,
2045 "entities" => $entities
2050 * Add media attachments to the body
2052 * @param array $item
2053 * @return string body with added media
2055 function api_add_attachments_to_body(array $item)
2057 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2059 if (strpos($body, '[/img]') !== false) {
2063 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2064 if (!empty($media['preview'])) {
2065 $description = $media['description'] ?: $media['name'];
2066 if (!empty($description)) {
2067 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2069 $body .= "\n[img]" . $media['preview'] .'[/img]';
2079 * @param string $body
2083 * @throws InternalServerErrorException
2085 function api_get_attachments(&$body, $uriid)
2087 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2088 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2090 $URLSearchString = "^\[\]";
2091 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2095 // Remove all embedded pictures, since they are added as attachments
2096 foreach ($images[0] as $orig) {
2097 $body = str_replace($orig, '', $body);
2102 foreach ($images[1] as $image) {
2103 $imagedata = Images::getInfoFromURLCached($image);
2106 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2110 return $attachments;
2115 * @param string $text
2116 * @param string $bbcode
2119 * @throws InternalServerErrorException
2120 * @todo Links at the first character of the post
2122 function api_get_entitities(&$text, $bbcode, $uriid)
2124 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2126 if ($include_entities != "true") {
2127 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2129 foreach ($images[1] as $image) {
2130 $replace = Post\Link::getByLink($uriid, $image);
2131 $text = str_replace($image, $replace, $text);
2136 $bbcode = BBCode::cleanPictureLinks($bbcode);
2138 // Change pure links in text to bbcode uris
2139 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2142 $entities["hashtags"] = [];
2143 $entities["symbols"] = [];
2144 $entities["urls"] = [];
2145 $entities["user_mentions"] = [];
2147 $URLSearchString = "^\[\]";
2149 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2151 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2152 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2154 $bbcode = preg_replace(
2155 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2156 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2159 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2161 $bbcode = preg_replace(
2162 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2163 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2166 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2168 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2170 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2173 foreach ($urls[1] as $id => $url) {
2174 $start = iconv_strpos($text, $url, 0, "UTF-8");
2175 if (!($start === false)) {
2176 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2180 ksort($ordered_urls);
2184 foreach ($ordered_urls as $url) {
2185 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2186 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2188 $display_url = $url["title"];
2190 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2191 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2193 if (strlen($display_url) > 26) {
2194 $display_url = substr($display_url, 0, 25)."…";
2198 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2199 if (!($start === false)) {
2200 $entities["urls"][] = ["url" => $url["url"],
2201 "expanded_url" => $url["url"],
2202 "display_url" => $display_url,
2203 "indices" => [$start, $start+strlen($url["url"])]];
2204 $offset = $start + 1;
2208 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2209 $ordered_images = [];
2210 foreach ($images as $image) {
2211 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2212 if (!($start === false)) {
2213 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2217 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2218 foreach ($images[1] as $image) {
2219 $start = iconv_strpos($text, $image, 0, "UTF-8");
2220 if (!($start === false)) {
2221 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2227 foreach ($ordered_images as $image) {
2228 $url = $image['url'];
2229 $ext_alt_text = $image['alt'];
2231 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2232 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2234 if (strlen($display_url) > 26) {
2235 $display_url = substr($display_url, 0, 25)."…";
2238 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2239 if (!($start === false)) {
2240 $image = Images::getInfoFromURLCached($url);
2242 $media_url = Post\Link::getByLink($uriid, $url);
2243 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2245 $entities["media"][] = [
2247 "id_str" => (string) ($start + 1),
2248 "indices" => [$start, $start+strlen($url)],
2249 "media_url" => Strings::normaliseLink($media_url),
2250 "media_url_https" => $media_url,
2252 "display_url" => $display_url,
2253 "expanded_url" => $url,
2254 "ext_alt_text" => $ext_alt_text,
2258 $offset = $start + 1;
2267 * @param array $item
2268 * @param string $text
2272 function api_format_items_embeded_images($item, $text)
2274 $text = preg_replace_callback(
2275 '|data:image/([^;]+)[^=]+=*|m',
2276 function () use ($item) {
2277 return DI::baseUrl() . '/display/' . $item['guid'];
2285 * return <a href='url'>name</a> as array
2287 * @param string $txt text
2292 function api_contactlink_to_array($txt)
2295 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2296 if ($r && count($match)==3) {
2298 'name' => $match[2],
2312 * return likes, dislikes and attend status for item
2314 * @param array $item array
2315 * @param string $type Return type (atom, rss, xml, json)
2318 * likes => int count,
2319 * dislikes => int count
2320 * @throws BadRequestException
2321 * @throws ImagickException
2322 * @throws InternalServerErrorException
2323 * @throws UnauthorizedException
2325 function api_format_items_activities($item, $type = "json")
2332 'attendmaybe' => [],
2336 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2337 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2339 while ($parent_item = Post::fetch($ret)) {
2340 // not used as result should be structured like other user data
2341 //builtin_activity_puller($i, $activities);
2343 // get user data and add it to the array of the activity
2344 $user = DI::twitterUser()->createFromContactId($parent_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2345 switch ($parent_item['verb']) {
2346 case Activity::LIKE:
2347 $activities['like'][] = $user;
2349 case Activity::DISLIKE:
2350 $activities['dislike'][] = $user;
2352 case Activity::ATTEND:
2353 $activities['attendyes'][] = $user;
2355 case Activity::ATTENDNO:
2356 $activities['attendno'][] = $user;
2358 case Activity::ATTENDMAYBE:
2359 $activities['attendmaybe'][] = $user;
2361 case Activity::ANNOUNCE:
2362 $activities['announce'][] = $user;
2371 if ($type == "xml") {
2372 $xml_activities = [];
2373 foreach ($activities as $k => $v) {
2374 // change xml element from "like" to "friendica:like"
2375 $xml_activities["friendica:".$k] = $v;
2376 // add user data into xml output
2378 foreach ($v as $user) {
2379 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2382 $activities = $xml_activities;
2389 * format items to be returned by api
2391 * @param array $items array of items
2392 * @param array $user_info
2393 * @param bool $filter_user filter items by $user_info
2394 * @param string $type Return type (atom, rss, xml, json)
2396 * @throws BadRequestException
2397 * @throws ImagickException
2398 * @throws InternalServerErrorException
2399 * @throws UnauthorizedException
2401 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2407 if (empty($items)) {
2411 foreach ((array)$items as $item) {
2412 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2414 // Look if the posts are matching if they should be filtered by user id
2415 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2419 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2428 * @param array $item Item record
2429 * @param string $type Return format (atom, rss, xml, json)
2430 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2431 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2432 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2433 * @return array API-formatted status
2434 * @throws BadRequestException
2435 * @throws ImagickException
2436 * @throws InternalServerErrorException
2437 * @throws UnauthorizedException
2439 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2443 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2444 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2447 DI::contentItem()->localize($item);
2449 $in_reply_to = api_in_reply_to($item);
2451 $converted = api_convert_item($item);
2453 if ($type == "xml") {
2454 $geo = "georss:point";
2460 'text' => $converted["text"],
2461 'truncated' => false,
2462 'created_at'=> api_date($item['created']),
2463 'in_reply_to_status_id' => $in_reply_to['status_id'],
2464 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2465 'source' => (($item['app']) ? $item['app'] : 'web'),
2466 'id' => intval($item['id']),
2467 'id_str' => (string) intval($item['id']),
2468 'in_reply_to_user_id' => $in_reply_to['user_id'],
2469 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2470 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2472 'favorited' => $item['starred'] ? true : false,
2473 'user' => $status_user,
2474 'friendica_author' => $author_user,
2475 'friendica_owner' => $owner_user,
2476 'friendica_private' => $item['private'] == Item::PRIVATE,
2477 //'entities' => NULL,
2478 'statusnet_html' => $converted["html"],
2479 'statusnet_conversation_id' => $item['parent'],
2480 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2481 'friendica_activities' => api_format_items_activities($item, $type),
2482 'friendica_title' => $item['title'],
2483 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2486 if (count($converted["attachments"]) > 0) {
2487 $status["attachments"] = $converted["attachments"];
2490 if (count($converted["entities"]) > 0) {
2491 $status["entities"] = $converted["entities"];
2494 if ($status["source"] == 'web') {
2495 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2496 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2497 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2500 $retweeted_item = [];
2503 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2504 $announce = api_get_announce($item);
2505 if (!empty($announce)) {
2506 $retweeted_item = $item;
2508 $status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], BaseApi::getCurrentUserID())->toArray();
2512 if (!empty($quoted_item)) {
2513 if ($quoted_item['id'] != $item['id']) {
2514 $quoted_status = api_format_item($quoted_item);
2515 /// @todo Only remove the attachments that are also contained in the quotes status
2516 unset($status['attachments']);
2517 unset($status['entities']);
2519 $conv_quoted = api_convert_item($quoted_item);
2520 $quoted_status = $status;
2521 unset($quoted_status['attachments']);
2522 unset($quoted_status['entities']);
2523 unset($quoted_status['statusnet_conversation_id']);
2524 $quoted_status['text'] = $conv_quoted['text'];
2525 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2527 $quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2528 } catch (BadRequestException $e) {
2529 // user not found. should be found?
2530 /// @todo check if the user should be always found
2531 $quoted_status["user"] = [];
2534 unset($quoted_status['friendica_author']);
2535 unset($quoted_status['friendica_owner']);
2536 unset($quoted_status['friendica_activities']);
2537 unset($quoted_status['friendica_private']);
2540 if (!empty($retweeted_item)) {
2541 $retweeted_status = $status;
2542 unset($retweeted_status['friendica_author']);
2543 unset($retweeted_status['friendica_owner']);
2544 unset($retweeted_status['friendica_activities']);
2545 unset($retweeted_status['friendica_private']);
2546 unset($retweeted_status['statusnet_conversation_id']);
2547 $status['user'] = $status['friendica_owner'];
2549 $retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2550 } catch (BadRequestException $e) {
2551 // user not found. should be found?
2552 /// @todo check if the user should be always found
2553 $retweeted_status["user"] = [];
2556 $rt_converted = api_convert_item($retweeted_item);
2558 $retweeted_status['text'] = $rt_converted["text"];
2559 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2560 $retweeted_status['friendica_html'] = $rt_converted["html"];
2561 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2563 if (!empty($quoted_status)) {
2564 $retweeted_status['quoted_status'] = $quoted_status;
2567 $status['friendica_author'] = $retweeted_status['user'];
2568 $status['retweeted_status'] = $retweeted_status;
2569 } elseif (!empty($quoted_status)) {
2570 $root_status = api_convert_item($item);
2572 $status['text'] = $root_status["text"];
2573 $status['statusnet_html'] = $root_status["html"];
2574 $status['quoted_status'] = $quoted_status;
2577 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2578 unset($status["user"]["uid"]);
2579 unset($status["user"]["self"]);
2581 if ($item["coord"] != "") {
2582 $coords = explode(' ', $item["coord"]);
2583 if (count($coords) == 2) {
2584 if ($type == "json") {
2585 $status["geo"] = ['type' => 'Point',
2586 'coordinates' => [(float) $coords[0],
2587 (float) $coords[1]]];
2588 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2589 $status["georss:point"] = $item["coord"];
2598 * Returns all lists the user subscribes to.
2600 * @param string $type Return type (atom, rss, xml, json)
2602 * @return array|string
2603 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2605 function api_lists_list($type)
2608 /// @TODO $ret is not filled here?
2609 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2612 /// @TODO move to top of file or somewhere better
2613 api_register_func('api/lists/list', 'api_lists_list', true);
2614 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2617 * Returns all groups the user owns.
2619 * @param string $type Return type (atom, rss, xml, json)
2621 * @return array|string
2622 * @throws BadRequestException
2623 * @throws ForbiddenException
2624 * @throws ImagickException
2625 * @throws InternalServerErrorException
2626 * @throws UnauthorizedException
2627 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2629 function api_lists_ownerships($type)
2631 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2634 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2635 $uid = $user_info['uid'];
2637 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2639 // loop through all groups
2641 foreach ($groups as $group) {
2642 if ($group['visible']) {
2648 'name' => $group['name'],
2649 'id' => intval($group['id']),
2650 'id_str' => (string) $group['id'],
2651 'user' => $user_info,
2655 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2658 /// @TODO move to top of file or somewhere better
2659 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2662 * Returns recent statuses from users in the specified group.
2664 * @param string $type Return type (atom, rss, xml, json)
2666 * @return array|string
2667 * @throws BadRequestException
2668 * @throws ForbiddenException
2669 * @throws ImagickException
2670 * @throws InternalServerErrorException
2671 * @throws UnauthorizedException
2672 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2674 function api_lists_statuses($type)
2676 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2678 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2680 unset($_REQUEST['user_id']);
2681 unset($_GET['user_id']);
2683 unset($_REQUEST['screen_name']);
2684 unset($_GET['screen_name']);
2686 if (empty($_REQUEST['list_id'])) {
2687 throw new BadRequestException('list_id not specified');
2691 $count = $_REQUEST['count'] ?? 20;
2692 $page = $_REQUEST['page'] ?? 1;
2693 $since_id = $_REQUEST['since_id'] ?? 0;
2694 $max_id = $_REQUEST['max_id'] ?? 0;
2695 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2696 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2698 $start = max(0, ($page - 1) * $count);
2700 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2701 $gids = array_column($groups, 'contact-id');
2702 $condition = ['uid' => BaseApi::getCurrentUserID(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2703 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2706 $condition[0] .= " AND `id` <= ?";
2707 $condition[] = $max_id;
2709 if ($exclude_replies > 0) {
2710 $condition[0] .= ' AND `gravity` = ?';
2711 $condition[] = GRAVITY_PARENT;
2713 if ($conversation_id > 0) {
2714 $condition[0] .= " AND `parent` = ?";
2715 $condition[] = $conversation_id;
2718 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2719 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
2721 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2723 $data = ['status' => $items];
2728 $data = api_rss_extra($data, $user_info);
2732 return DI::apiResponse()->formatData("statuses", $type, $data);
2735 /// @TODO move to top of file or somewhere better
2736 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2739 * Returns either the friends of the follower list
2741 * Considers friends and followers lists to be private and won't return
2742 * anything if any user_id parameter is passed.
2744 * @param string $qtype Either "friends" or "followers"
2745 * @return boolean|array
2746 * @throws BadRequestException
2747 * @throws ForbiddenException
2748 * @throws ImagickException
2749 * @throws InternalServerErrorException
2750 * @throws UnauthorizedException
2752 function api_statuses_f($qtype)
2754 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2757 $count = $_GET['count'] ?? 20;
2758 $page = $_GET['page'] ?? 1;
2760 $start = max(0, ($page - 1) * $count);
2762 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2764 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2765 /* this is to stop Hotot to load friends multiple times
2766 * I'm not sure if I'm missing return something or
2767 * is a bug in hotot. Workaround, meantime
2771 return array('$users' => $ret);*/
2776 if ($qtype == 'friends') {
2777 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2778 } elseif ($qtype == 'followers') {
2779 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2782 // friends and followers only for self
2783 if ($user_info['self'] == 0) {
2784 $sql_extra = " AND false ";
2787 if ($qtype == 'blocks') {
2788 $sql_filter = 'AND `blocked` AND NOT `pending`';
2789 } elseif ($qtype == 'incoming') {
2790 $sql_filter = 'AND `pending`';
2792 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2795 // @todo This query most likely can be replaced with a Contact::select...
2796 $r = DBA::toArray(DBA::p(
2805 BaseApi::getCurrentUserID(),
2811 foreach ($r as $cid) {
2812 $user = DI::twitterUser()->createFromContactId($cid['id'], BaseApi::getCurrentUserID())->toArray();
2813 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2814 unset($user["uid"]);
2815 unset($user["self"]);
2822 return ['user' => $ret];
2827 * Returns the list of friends of the provided user
2829 * @deprecated By Twitter API in favor of friends/list
2831 * @param string $type Either "json" or "xml"
2832 * @return boolean|string|array
2833 * @throws BadRequestException
2834 * @throws ForbiddenException
2836 function api_statuses_friends($type)
2838 $data = api_statuses_f("friends");
2839 if ($data === false) {
2842 return DI::apiResponse()->formatData("users", $type, $data);
2846 * Returns the list of followers of the provided user
2848 * @deprecated By Twitter API in favor of friends/list
2850 * @param string $type Either "json" or "xml"
2851 * @return boolean|string|array
2852 * @throws BadRequestException
2853 * @throws ForbiddenException
2855 function api_statuses_followers($type)
2857 $data = api_statuses_f("followers");
2858 if ($data === false) {
2861 return DI::apiResponse()->formatData("users", $type, $data);
2864 /// @TODO move to top of file or somewhere better
2865 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2866 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2869 * Returns the list of blocked users
2871 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2873 * @param string $type Either "json" or "xml"
2875 * @return boolean|string|array
2876 * @throws BadRequestException
2877 * @throws ForbiddenException
2879 function api_blocks_list($type)
2881 $data = api_statuses_f('blocks');
2882 if ($data === false) {
2885 return DI::apiResponse()->formatData("users", $type, $data);
2888 /// @TODO move to top of file or somewhere better
2889 api_register_func('api/blocks/list', 'api_blocks_list', true);
2892 * Returns the list of pending users IDs
2894 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
2896 * @param string $type Either "json" or "xml"
2898 * @return boolean|string|array
2899 * @throws BadRequestException
2900 * @throws ForbiddenException
2902 function api_friendships_incoming($type)
2904 $data = api_statuses_f('incoming');
2905 if ($data === false) {
2910 foreach ($data['user'] as $user) {
2911 $ids[] = $user['id'];
2914 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
2917 /// @TODO move to top of file or somewhere better
2918 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
2921 * Sends a new direct message.
2923 * @param string $type Return type (atom, rss, xml, json)
2925 * @return array|string
2926 * @throws BadRequestException
2927 * @throws ForbiddenException
2928 * @throws ImagickException
2929 * @throws InternalServerErrorException
2930 * @throws NotFoundException
2931 * @throws UnauthorizedException
2932 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
2934 function api_direct_messages_new($type)
2936 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2938 $uid = BaseApi::getCurrentUserID();
2940 if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
2944 $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
2947 if (!empty($_POST['screen_name'])) {
2948 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => BaseApi::getCurrentUserID(), 'nick' => $_POST['screen_name']]);
2949 if (DBA::isResult($contacts)) {
2950 // Selecting the id by priority, friendica first
2951 api_best_nickname($contacts);
2953 $recipient = DI::twitterUser()->createFromContactId($contacts[0]['id'], $uid)->toArray();
2956 $recipient = api_get_user($_POST['user_id']);
2959 if (empty($recipient)) {
2960 throw new NotFoundException('Recipient not found');
2964 if (!empty($_REQUEST['replyto'])) {
2965 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $_REQUEST['replyto']]);
2966 $replyto = $mail['parent-uri'];
2967 $sub = $mail['title'];
2969 if (!empty($_REQUEST['title'])) {
2970 $sub = $_REQUEST['title'];
2972 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
2976 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
2979 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
2980 $ret = api_format_messages($mail, $recipient, $sender);
2982 $ret = ["error" => $id];
2985 $data = ['direct_message'=>$ret];
2991 $data = api_rss_extra($data, $sender);
2995 return DI::apiResponse()->formatData("direct-messages", $type, $data);
2998 /// @TODO move to top of file or somewhere better
2999 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3002 * delete a direct_message from mail table through api
3004 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3005 * @return string|array
3006 * @throws BadRequestException
3007 * @throws ForbiddenException
3008 * @throws ImagickException
3009 * @throws InternalServerErrorException
3010 * @throws UnauthorizedException
3011 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3013 function api_direct_messages_destroy($type)
3015 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3018 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3020 $id = $_REQUEST['id'] ?? 0;
3022 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3023 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3024 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3026 $uid = $user_info['uid'];
3027 // error if no id or parenturi specified (for clients posting parent-uri as well)
3028 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3029 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3030 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3033 // BadRequestException if no id specified (for clients using Twitter API)
3035 throw new BadRequestException('Message id not specified');
3038 // add parent-uri to sql command if specified by calling app
3039 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3041 // error message if specified id is not in database
3042 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3043 if ($verbose == "true") {
3044 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3045 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3047 /// @todo BadRequestException ok for Twitter API clients?
3048 throw new BadRequestException('message id not in database');
3052 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3054 if ($verbose == "true") {
3057 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3058 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
3060 $answer = ['result' => 'error', 'message' => 'unknown error'];
3061 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3064 /// @todo return JSON data like Twitter API not yet implemented
3067 /// @TODO move to top of file or somewhere better
3068 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3073 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3074 * @return string|array
3075 * @throws HTTPException\BadRequestException
3076 * @throws HTTPException\ExpectationFailedException
3077 * @throws HTTPException\ForbiddenException
3078 * @throws HTTPException\InternalServerErrorException
3079 * @throws HTTPException\NotFoundException
3080 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3082 function api_friendships_destroy($type)
3084 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3085 $uid = BaseApi::getCurrentUserID();
3087 $owner = User::getOwnerDataById($uid);
3089 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3090 throw new HTTPException\NotFoundException('Error Processing Request');
3093 $contact_id = $_REQUEST['user_id'] ?? 0;
3095 if (empty($contact_id)) {
3096 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3097 throw new HTTPException\BadRequestException('no user_id specified');
3100 // Get Contact by given id
3101 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3103 if(!DBA::isResult($contact)) {
3104 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3105 throw new HTTPException\NotFoundException('no contact found to given ID');
3108 $url = $contact['url'];
3110 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3111 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3112 Strings::normaliseLink($url), $url];
3113 $contact = DBA::selectFirst('contact', [], $condition);
3115 if (!DBA::isResult($contact)) {
3116 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3117 throw new HTTPException\NotFoundException('Not following Contact');
3121 $result = Contact::terminateFriendship($owner, $contact);
3123 if ($result === null) {
3124 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3125 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3128 if ($result === false) {
3129 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3131 } catch (Exception $e) {
3132 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3133 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3136 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3137 unset($contact['uid']);
3138 unset($contact['self']);
3140 // Set screen_name since Twidere requests it
3141 $contact['screen_name'] = $contact['nick'];
3143 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
3146 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3150 * @param string $type Return type (atom, rss, xml, json)
3151 * @param string $box
3152 * @param string $verbose
3154 * @return array|string
3155 * @throws BadRequestException
3156 * @throws ForbiddenException
3157 * @throws ImagickException
3158 * @throws InternalServerErrorException
3159 * @throws UnauthorizedException
3161 function api_direct_messages_box($type, $box, $verbose)
3163 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3166 $count = $_GET['count'] ?? 20;
3167 $page = $_REQUEST['page'] ?? 1;
3169 $since_id = $_REQUEST['since_id'] ?? 0;
3170 $max_id = $_REQUEST['max_id'] ?? 0;
3172 $user_id = $_REQUEST['user_id'] ?? '';
3173 $screen_name = $_REQUEST['screen_name'] ?? '';
3176 unset($_REQUEST['user_id']);
3177 unset($_GET['user_id']);
3179 unset($_REQUEST['screen_name']);
3180 unset($_GET['screen_name']);
3182 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3184 $profile_url = $user_info["url"];
3187 $start = max(0, ($page - 1) * $count);
3192 if ($box=="sentbox") {
3193 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3194 } elseif ($box == "conversation") {
3195 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3196 } elseif ($box == "all") {
3197 $sql_extra = "true";
3198 } elseif ($box == "inbox") {
3199 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3203 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3206 if ($user_id != "") {
3207 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3208 } elseif ($screen_name !="") {
3209 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3212 $r = DBA::toArray(DBA::p(
3213 "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 ?,?",
3214 BaseApi::getCurrentUserID(),
3219 if ($verbose == "true" && !DBA::isResult($r)) {
3220 $answer = ['result' => 'error', 'message' => 'no mails available'];
3221 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
3225 foreach ($r as $item) {
3226 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3227 $recipient = $user_info;
3228 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3229 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3230 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3231 $sender = $user_info;
3234 if (isset($recipient) && isset($sender)) {
3235 $ret[] = api_format_messages($item, $recipient, $sender);
3240 $data = ['direct_message' => $ret];
3245 $data = api_rss_extra($data, $user_info);
3249 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3253 * Returns the most recent direct messages sent by the user.
3255 * @param string $type Return type (atom, rss, xml, json)
3257 * @return array|string
3258 * @throws BadRequestException
3259 * @throws ForbiddenException
3260 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3262 function api_direct_messages_sentbox($type)
3264 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3265 return api_direct_messages_box($type, "sentbox", $verbose);
3269 * Returns the most recent direct messages sent to the user.
3271 * @param string $type Return type (atom, rss, xml, json)
3273 * @return array|string
3274 * @throws BadRequestException
3275 * @throws ForbiddenException
3276 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3278 function api_direct_messages_inbox($type)
3280 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3281 return api_direct_messages_box($type, "inbox", $verbose);
3286 * @param string $type Return type (atom, rss, xml, json)
3288 * @return array|string
3289 * @throws BadRequestException
3290 * @throws ForbiddenException
3292 function api_direct_messages_all($type)
3294 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3295 return api_direct_messages_box($type, "all", $verbose);
3300 * @param string $type Return type (atom, rss, xml, json)
3302 * @return array|string
3303 * @throws BadRequestException
3304 * @throws ForbiddenException
3306 function api_direct_messages_conversation($type)
3308 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3309 return api_direct_messages_box($type, "conversation", $verbose);
3312 /// @TODO move to top of file or somewhere better
3313 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3314 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3315 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3316 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3319 * list all photos of the authenticated user
3321 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3322 * @return string|array
3323 * @throws ForbiddenException
3324 * @throws InternalServerErrorException
3326 function api_fr_photos_list($type)
3328 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3330 $r = DBA::toArray(DBA::p(
3331 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3332 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3333 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3334 BaseApi::getCurrentUserID(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3337 'image/jpeg' => 'jpg',
3338 'image/png' => 'png',
3339 'image/gif' => 'gif'
3341 $data = ['photo'=>[]];
3342 if (DBA::isResult($r)) {
3343 foreach ($r as $rr) {
3345 $photo['id'] = $rr['resource-id'];
3346 $photo['album'] = $rr['album'];
3347 $photo['filename'] = $rr['filename'];
3348 $photo['type'] = $rr['type'];
3349 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3350 $photo['created'] = $rr['created'];
3351 $photo['edited'] = $rr['edited'];
3352 $photo['desc'] = $rr['desc'];
3354 if ($type == "xml") {
3355 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3357 $photo['thumb'] = $thumb;
3358 $data['photo'][] = $photo;
3362 return DI::apiResponse()->formatData("photos", $type, $data);
3366 * upload a new photo or change an existing photo
3368 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3369 * @return string|array
3370 * @throws BadRequestException
3371 * @throws ForbiddenException
3372 * @throws ImagickException
3373 * @throws InternalServerErrorException
3374 * @throws NotFoundException
3376 function api_fr_photo_create_update($type)
3378 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3381 $photo_id = $_REQUEST['photo_id'] ?? null;
3382 $desc = $_REQUEST['desc'] ?? null;
3383 $album = $_REQUEST['album'] ?? null;
3384 $album_new = $_REQUEST['album_new'] ?? null;
3385 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3386 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3387 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3388 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3389 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3391 // do several checks on input parameters
3392 // we do not allow calls without album string
3393 if ($album == null) {
3394 throw new BadRequestException("no albumname specified");
3396 // if photo_id == null --> we are uploading a new photo
3397 if ($photo_id == null) {
3400 // error if no media posted in create-mode
3401 if (empty($_FILES['media'])) {
3403 throw new BadRequestException("no media data submitted");
3406 // album_new will be ignored in create-mode
3411 // check if photo is existing in databasei
3412 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => BaseApi::getCurrentUserID(), 'album' => $album])) {
3413 throw new BadRequestException("photo not available");
3417 // checks on acl strings provided by clients
3418 $acl_input_error = false;
3419 $acl_input_error |= check_acl_input($allow_cid);
3420 $acl_input_error |= check_acl_input($deny_cid);
3421 $acl_input_error |= check_acl_input($allow_gid);
3422 $acl_input_error |= check_acl_input($deny_gid);
3423 if ($acl_input_error) {
3424 throw new BadRequestException("acl data invalid");
3426 // now let's upload the new media in create-mode
3427 if ($mode == "create") {
3428 $media = $_FILES['media'];
3429 $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);
3431 // return success of updating or error message
3432 if (!is_null($data)) {
3433 return DI::apiResponse()->formatData("photo_create", $type, $data);
3435 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3439 // now let's do the changes in update-mode
3440 if ($mode == "update") {
3441 $updated_fields = [];
3443 if (!is_null($desc)) {
3444 $updated_fields['desc'] = $desc;
3447 if (!is_null($album_new)) {
3448 $updated_fields['album'] = $album_new;
3451 if (!is_null($allow_cid)) {
3452 $allow_cid = trim($allow_cid);
3453 $updated_fields['allow_cid'] = $allow_cid;
3456 if (!is_null($deny_cid)) {
3457 $deny_cid = trim($deny_cid);
3458 $updated_fields['deny_cid'] = $deny_cid;
3461 if (!is_null($allow_gid)) {
3462 $allow_gid = trim($allow_gid);
3463 $updated_fields['allow_gid'] = $allow_gid;
3466 if (!is_null($deny_gid)) {
3467 $deny_gid = trim($deny_gid);
3468 $updated_fields['deny_gid'] = $deny_gid;
3472 if (count($updated_fields) > 0) {
3473 $nothingtodo = false;
3474 $result = Photo::update($updated_fields, ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id, 'album' => $album]);
3476 $nothingtodo = true;
3479 if (!empty($_FILES['media'])) {
3480 $nothingtodo = false;
3481 $media = $_FILES['media'];
3482 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3483 if (!is_null($data)) {
3484 return DI::apiResponse()->formatData("photo_update", $type, $data);
3488 // return success of updating or error message
3490 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3491 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3494 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3495 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3497 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3500 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3504 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3506 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3507 * @return string|array
3508 * @throws BadRequestException
3509 * @throws ForbiddenException
3510 * @throws InternalServerErrorException
3511 * @throws NotFoundException
3513 function api_fr_photo_detail($type)
3515 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3517 if (empty($_REQUEST['photo_id'])) {
3518 throw new BadRequestException("No photo id.");
3521 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3522 $photo_id = $_REQUEST['photo_id'];
3524 // prepare json/xml output with data from database for the requested photo
3525 $data = prepare_photo_data($type, $scale, $photo_id);
3527 return DI::apiResponse()->formatData("photo_detail", $type, $data);
3532 * updates the profile image for the user (either a specified profile or the default profile)
3534 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3536 * @return string|array
3537 * @throws BadRequestException
3538 * @throws ForbiddenException
3539 * @throws ImagickException
3540 * @throws InternalServerErrorException
3541 * @throws NotFoundException
3542 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3544 function api_account_update_profile_image($type)
3546 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3549 $profile_id = $_REQUEST['profile_id'] ?? 0;
3551 // error if image data is missing
3552 if (empty($_FILES['image'])) {
3553 throw new BadRequestException("no media data submitted");
3556 // check if specified profile id is valid
3557 if ($profile_id != 0) {
3558 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $profile_id]);
3559 // error message if specified profile id is not in database
3560 if (!DBA::isResult($profile)) {
3561 throw new BadRequestException("profile_id not available");
3563 $is_default_profile = $profile['is-default'];
3565 $is_default_profile = 1;
3568 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3570 if (!empty($_FILES['image'])) {
3571 $media = $_FILES['image'];
3572 } elseif (!empty($_FILES['media'])) {
3573 $media = $_FILES['media'];
3575 // save new profile image
3576 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3579 if (is_array($media['type'])) {
3580 $filetype = $media['type'][0];
3582 $filetype = $media['type'];
3584 if ($filetype == "image/jpeg") {
3586 } elseif ($filetype == "image/png") {
3589 throw new InternalServerErrorException('Unsupported filetype');
3592 // change specified profile or all profiles to the new resource-id
3593 if ($is_default_profile) {
3594 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], BaseApi::getCurrentUserID()];
3595 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3597 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3598 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3599 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => BaseApi::getCurrentUserID()]);
3602 Contact::updateSelfFromUserID(BaseApi::getCurrentUserID(), true);
3604 // Update global directory in background
3605 Profile::publishUpdate(BaseApi::getCurrentUserID());
3607 // output for client
3609 return api_account_verify_credentials($type);
3611 // SaveMediaToDatabase failed for some reason
3612 throw new InternalServerErrorException("image upload failed");
3616 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3617 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3618 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3619 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3620 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3621 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3624 * Update user profile
3626 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3628 * @return array|string
3629 * @throws BadRequestException
3630 * @throws ForbiddenException
3631 * @throws ImagickException
3632 * @throws InternalServerErrorException
3633 * @throws UnauthorizedException
3635 function api_account_update_profile($type)
3637 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3639 $local_user = BaseApi::getCurrentUserID();
3641 $api_user = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3643 if (!empty($_POST['name'])) {
3644 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
3645 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
3646 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
3647 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3650 if (isset($_POST['description'])) {
3651 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
3652 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
3653 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3656 Profile::publishUpdate($local_user);
3658 return api_account_verify_credentials($type);
3661 /// @TODO move to top of file or somewhere better
3662 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3666 * @param string $acl_string
3670 function check_acl_input($acl_string)
3672 if (empty($acl_string)) {
3676 $contact_not_found = false;
3678 // split <x><y><z> into array of cid's
3679 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3681 // check for each cid if it is available on server
3682 $cid_array = $array[0];
3683 foreach ($cid_array as $cid) {
3684 $cid = str_replace("<", "", $cid);
3685 $cid = str_replace(">", "", $cid);
3686 $condition = ['id' => $cid, 'uid' => BaseApi::getCurrentUserID()];
3687 $contact_not_found |= !DBA::exists('contact', $condition);
3689 return $contact_not_found;
3693 * @param string $mediatype
3694 * @param array $media
3695 * @param string $type
3696 * @param string $album
3697 * @param string $allow_cid
3698 * @param string $deny_cid
3699 * @param string $allow_gid
3700 * @param string $deny_gid
3701 * @param string $desc
3702 * @param integer $phototype
3703 * @param boolean $visibility
3704 * @param string $photo_id
3706 * @throws BadRequestException
3707 * @throws ForbiddenException
3708 * @throws ImagickException
3709 * @throws InternalServerErrorException
3710 * @throws NotFoundException
3711 * @throws UnauthorizedException
3713 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)
3721 if (is_array($media)) {
3722 if (is_array($media['tmp_name'])) {
3723 $src = $media['tmp_name'][0];
3725 $src = $media['tmp_name'];
3727 if (is_array($media['name'])) {
3728 $filename = basename($media['name'][0]);
3730 $filename = basename($media['name']);
3732 if (is_array($media['size'])) {
3733 $filesize = intval($media['size'][0]);
3735 $filesize = intval($media['size']);
3737 if (is_array($media['type'])) {
3738 $filetype = $media['type'][0];
3740 $filetype = $media['type'];
3744 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3747 "File upload src: " . $src . " - filename: " . $filename .
3748 " - size: " . $filesize . " - type: " . $filetype);
3750 // check if there was a php upload error
3751 if ($filesize == 0 && $media['error'] == 1) {
3752 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3754 // check against max upload size within Friendica instance
3755 $maximagesize = DI::config()->get('system', 'maximagesize');
3756 if ($maximagesize && ($filesize > $maximagesize)) {
3757 $formattedBytes = Strings::formatBytes($maximagesize);
3758 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3761 // create Photo instance with the data of the image
3762 $imagedata = @file_get_contents($src);
3763 $Image = new Image($imagedata, $filetype);
3764 if (!$Image->isValid()) {
3765 throw new InternalServerErrorException("unable to process image data");
3768 // check orientation of image
3769 $Image->orient($src);
3772 // check max length of images on server
3773 $max_length = DI::config()->get('system', 'max_image_length');
3774 if ($max_length > 0) {
3775 $Image->scaleDown($max_length);
3776 logger::info("File upload: Scaling picture to new size " . $max_length);
3778 $width = $Image->getWidth();
3779 $height = $Image->getHeight();
3781 // create a new resource-id if not already provided
3782 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3784 if ($mediatype == "photo") {
3785 // upload normal image (scales 0, 1, 2)
3786 logger::info("photo upload: starting new photo upload");
3788 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3790 logger::notice("photo upload: image upload with scale 0 (original size) failed");
3792 if ($width > 640 || $height > 640) {
3793 $Image->scaleDown(640);
3794 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3796 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3800 if ($width > 320 || $height > 320) {
3801 $Image->scaleDown(320);
3802 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3804 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3807 logger::info("photo upload: new photo upload ended");
3808 } elseif ($mediatype == "profileimage") {
3809 // upload profile image (scales 4, 5, 6)
3810 logger::info("photo upload: starting new profile image upload");
3812 if ($width > 300 || $height > 300) {
3813 $Image->scaleDown(300);
3814 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3816 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
3820 if ($width > 80 || $height > 80) {
3821 $Image->scaleDown(80);
3822 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3824 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
3828 if ($width > 48 || $height > 48) {
3829 $Image->scaleDown(48);
3830 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3832 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
3835 $Image->__destruct();
3836 logger::info("photo upload: new profile image upload ended");
3840 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3841 if ($photo_id == null && $mediatype == "photo") {
3842 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3844 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3845 return prepare_photo_data($type, false, $resource_id);
3847 throw new InternalServerErrorException("image upload failed");
3853 * @param string $hash
3854 * @param string $allow_cid
3855 * @param string $deny_cid
3856 * @param string $allow_gid
3857 * @param string $deny_gid
3858 * @param string $filetype
3859 * @param boolean $visibility
3860 * @throws InternalServerErrorException
3862 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
3864 // get data about the api authenticated user
3865 $uri = Item::newURI(intval(BaseApi::getCurrentUserID()));
3866 $owner_record = DBA::selectFirst('contact', [], ['uid' => BaseApi::getCurrentUserID(), 'self' => true]);
3869 $arr['guid'] = System::createUUID();
3870 $arr['uid'] = intval(BaseApi::getCurrentUserID());
3872 $arr['type'] = 'photo';
3874 $arr['resource-id'] = $hash;
3875 $arr['contact-id'] = $owner_record['id'];
3876 $arr['owner-name'] = $owner_record['name'];
3877 $arr['owner-link'] = $owner_record['url'];
3878 $arr['owner-avatar'] = $owner_record['thumb'];
3879 $arr['author-name'] = $owner_record['name'];
3880 $arr['author-link'] = $owner_record['url'];
3881 $arr['author-avatar'] = $owner_record['thumb'];
3883 $arr['allow_cid'] = $allow_cid;
3884 $arr['allow_gid'] = $allow_gid;
3885 $arr['deny_cid'] = $deny_cid;
3886 $arr['deny_gid'] = $deny_gid;
3887 $arr['visible'] = $visibility;
3891 'image/jpeg' => 'jpg',
3892 'image/png' => 'png',
3893 'image/gif' => 'gif'
3896 // adds link to the thumbnail scale photo
3897 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
3898 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3901 // do the magic for storing the item in the database and trigger the federation to other contacts
3907 * @param string $type
3909 * @param string $photo_id
3912 * @throws BadRequestException
3913 * @throws ForbiddenException
3914 * @throws ImagickException
3915 * @throws InternalServerErrorException
3916 * @throws NotFoundException
3917 * @throws UnauthorizedException
3919 function prepare_photo_data($type, $scale, $photo_id)
3921 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3923 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3925 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
3926 $data_sql = ($scale === false ? "" : "data, ");
3928 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
3929 // clients needs to convert this in their way for further processing
3930 $r = DBA::toArray(DBA::p(
3931 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3932 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
3933 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
3934 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
3935 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3936 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
3937 BaseApi::getCurrentUserID(),
3942 'image/jpeg' => 'jpg',
3943 'image/png' => 'png',
3944 'image/gif' => 'gif'
3947 // prepare output data for photo
3948 if (DBA::isResult($r)) {
3949 $data = ['photo' => $r[0]];
3950 $data['photo']['id'] = $data['photo']['resource-id'];
3951 if ($scale !== false) {
3952 $data['photo']['data'] = base64_encode($data['photo']['data']);
3954 unset($data['photo']['datasize']); //needed only with scale param
3956 if ($type == "xml") {
3957 $data['photo']['links'] = [];
3958 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3959 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
3961 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
3964 $data['photo']['link'] = [];
3965 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
3967 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3968 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
3972 unset($data['photo']['resource-id']);
3973 unset($data['photo']['minscale']);
3974 unset($data['photo']['maxscale']);
3976 throw new NotFoundException();
3979 // retrieve item element for getting activities (like, dislike etc.) related to photo
3980 $condition = ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id];
3981 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
3982 if (!DBA::isResult($item)) {
3983 throw new NotFoundException('Photo-related item not found.');
3986 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
3988 // retrieve comments on photo
3989 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
3990 $item['parent'], BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT];
3992 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition);
3994 // prepare output of comments
3995 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3997 if ($type == "xml") {
3999 foreach ($commentData as $comment) {
4000 $comments[$k++ . ":comment"] = $comment;
4003 foreach ($commentData as $comment) {
4004 $comments[] = $comment;
4007 $data['photo']['friendica_comments'] = $comments;
4009 // include info if rights on photo and rights on item are mismatching
4010 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4011 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4012 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4013 $data['photo']['deny_gid'] != $item['deny_gid'];
4014 $data['photo']['rights_mismatch'] = $rights_mismatch;
4020 * Return an item with announcer data if it had been announced
4022 * @param array $item Item array
4023 * @return array Item array with announce data
4025 function api_get_announce($item)
4027 // Quit if the item already has got a different owner and author
4028 if ($item['owner-id'] != $item['author-id']) {
4032 // Don't change original or Diaspora posts
4033 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4037 // Quit if we do now the original author and it had been a post from a native network
4038 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4042 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4043 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4044 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4045 if (!DBA::isResult($announce)) {
4049 return array_merge($item, $announce);
4054 * @param array $item
4059 function api_in_reply_to($item)
4063 $in_reply_to['status_id'] = null;
4064 $in_reply_to['user_id'] = null;
4065 $in_reply_to['status_id_str'] = null;
4066 $in_reply_to['user_id_str'] = null;
4067 $in_reply_to['screen_name'] = null;
4069 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4070 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4071 if (DBA::isResult($parent)) {
4072 $in_reply_to['status_id'] = intval($parent['id']);
4074 $in_reply_to['status_id'] = intval($item['parent']);
4077 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4079 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4080 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4082 if (DBA::isResult($parent)) {
4083 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4084 $in_reply_to['user_id'] = intval($parent['author-id']);
4085 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4088 // There seems to be situation, where both fields are identical:
4089 // https://github.com/friendica/friendica/issues/1010
4090 // This is a bugfix for that.
4091 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4092 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']]);
4093 $in_reply_to['status_id'] = null;
4094 $in_reply_to['user_id'] = null;
4095 $in_reply_to['status_id_str'] = null;
4096 $in_reply_to['user_id_str'] = null;
4097 $in_reply_to['screen_name'] = null;
4101 return $in_reply_to;
4106 * @param string $text
4109 * @throws InternalServerErrorException
4111 function api_clean_plain_items($text)
4113 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4115 $text = BBCode::cleanPictureLinks($text);
4116 $URLSearchString = "^\[\]";
4118 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4120 if ($include_entities == "true") {
4121 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4124 // Simplify "attachment" element
4125 $text = BBCode::removeAttachment($text);
4132 * @param array $contacts
4136 function api_best_nickname(&$contacts)
4140 if (count($contacts) == 0) {
4144 foreach ($contacts as $contact) {
4145 if ($contact["network"] == "") {
4146 $contact["network"] = "dfrn";
4147 $best_contact = [$contact];
4151 if (sizeof($best_contact) == 0) {
4152 foreach ($contacts as $contact) {
4153 if ($contact["network"] == "dfrn") {
4154 $best_contact = [$contact];
4159 if (sizeof($best_contact) == 0) {
4160 foreach ($contacts as $contact) {
4161 if ($contact["network"] == "dspr") {
4162 $best_contact = [$contact];
4167 if (sizeof($best_contact) == 0) {
4168 foreach ($contacts as $contact) {
4169 if ($contact["network"] == "stat") {
4170 $best_contact = [$contact];
4175 if (sizeof($best_contact) == 0) {
4176 foreach ($contacts as $contact) {
4177 if ($contact["network"] == "pump") {
4178 $best_contact = [$contact];
4183 if (sizeof($best_contact) == 0) {
4184 foreach ($contacts as $contact) {
4185 if ($contact["network"] == "twit") {
4186 $best_contact = [$contact];
4191 if (sizeof($best_contact) == 1) {
4192 $contacts = $best_contact;
4194 $contacts = [$contacts[0]];
4199 * Return all or a specified group of the user with the containing contacts.
4201 * @param string $type Return type (atom, rss, xml, json)
4203 * @return array|string
4204 * @throws BadRequestException
4205 * @throws ForbiddenException
4206 * @throws ImagickException
4207 * @throws InternalServerErrorException
4208 * @throws UnauthorizedException
4210 function api_friendica_group_show($type)
4212 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4215 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4216 $gid = $_REQUEST['gid'] ?? 0;
4217 $uid = $user_info['uid'];
4219 // get data of the specified group id or all groups if not specified
4221 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4223 // error message if specified gid is not in database
4224 if (!DBA::isResult($groups)) {
4225 throw new BadRequestException("gid not available");
4228 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4231 // loop through all groups and retrieve all members for adding data in the user array
4233 foreach ($groups as $rr) {
4234 $members = Contact\Group::getById($rr['id']);
4237 if ($type == "xml") {
4238 $user_element = "users";
4240 foreach ($members as $member) {
4241 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4242 $users[$k++.":user"] = $user;
4245 $user_element = "user";
4246 foreach ($members as $member) {
4247 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4251 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4253 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
4256 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4261 * @param string $type Return type (atom, rss, xml, json)
4263 * @return array|string
4264 * @throws BadRequestException
4265 * @throws ForbiddenException
4266 * @throws ImagickException
4267 * @throws InternalServerErrorException
4268 * @throws UnauthorizedException
4269 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4271 function api_lists_destroy($type)
4273 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4276 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4277 $gid = $_REQUEST['list_id'] ?? 0;
4278 $uid = $user_info['uid'];
4280 // error if no gid specified
4282 throw new BadRequestException('gid not specified');
4285 // get data of the specified group id
4286 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4287 // error message if specified gid is not in database
4289 throw new BadRequestException('gid not available');
4292 if (Group::remove($gid)) {
4294 'name' => $group['name'],
4295 'id' => intval($gid),
4296 'id_str' => (string) $gid,
4297 'user' => $user_info
4300 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4304 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4307 * Add a new group to the database.
4309 * @param string $name Group name
4310 * @param int $uid User ID
4311 * @param array $users List of users to add to the group
4314 * @throws BadRequestException
4316 function group_create($name, $uid, $users = [])
4318 // error if no name specified
4320 throw new BadRequestException('group name not specified');
4323 // error message if specified group name already exists
4324 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4325 throw new BadRequestException('group name already exists');
4328 // Check if the group needs to be reactivated
4329 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4330 $reactivate_group = true;
4334 $ret = Group::create($uid, $name);
4336 $gid = Group::getIdByName($uid, $name);
4338 throw new BadRequestException('other API error');
4342 $erroraddinguser = false;
4344 foreach ($users as $user) {
4345 $cid = $user['cid'];
4346 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4347 Group::addMember($gid, $cid);
4349 $erroraddinguser = true;
4350 $errorusers[] = $cid;
4354 // return success message incl. missing users in array
4355 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4357 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4361 * Create the specified group with the posted array of contacts.
4363 * @param string $type Return type (atom, rss, xml, json)
4365 * @return array|string
4366 * @throws BadRequestException
4367 * @throws ForbiddenException
4368 * @throws ImagickException
4369 * @throws InternalServerErrorException
4370 * @throws UnauthorizedException
4372 function api_friendica_group_create($type)
4374 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4377 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4378 $name = $_REQUEST['name'] ?? '';
4379 $uid = $user_info['uid'];
4380 $json = json_decode($_POST['json'], true);
4381 $users = $json['user'];
4383 $success = group_create($name, $uid, $users);
4385 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
4388 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4391 * Create a new group.
4393 * @param string $type Return type (atom, rss, xml, json)
4395 * @return array|string
4396 * @throws BadRequestException
4397 * @throws ForbiddenException
4398 * @throws ImagickException
4399 * @throws InternalServerErrorException
4400 * @throws UnauthorizedException
4401 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4403 function api_lists_create($type)
4405 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4408 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4409 $name = $_REQUEST['name'] ?? '';
4410 $uid = $user_info['uid'];
4412 $success = group_create($name, $uid);
4413 if ($success['success']) {
4415 'name' => $success['name'],
4416 'id' => intval($success['gid']),
4417 'id_str' => (string) $success['gid'],
4418 'user' => $user_info
4421 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4425 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4428 * Update the specified group with the posted array of contacts.
4430 * @param string $type Return type (atom, rss, xml, json)
4432 * @return array|string
4433 * @throws BadRequestException
4434 * @throws ForbiddenException
4435 * @throws ImagickException
4436 * @throws InternalServerErrorException
4437 * @throws UnauthorizedException
4439 function api_friendica_group_update($type)
4441 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4444 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4445 $uid = $user_info['uid'];
4446 $gid = $_REQUEST['gid'] ?? 0;
4447 $name = $_REQUEST['name'] ?? '';
4448 $json = json_decode($_POST['json'], true);
4449 $users = $json['user'];
4451 // error if no name specified
4453 throw new BadRequestException('group name not specified');
4456 // error if no gid specified
4458 throw new BadRequestException('gid not specified');
4462 $members = Contact\Group::getById($gid);
4463 foreach ($members as $member) {
4464 $cid = $member['id'];
4465 foreach ($users as $user) {
4466 $found = ($user['cid'] == $cid ? true : false);
4468 if (!isset($found) || !$found) {
4469 $gid = Group::getIdByName($uid, $name);
4470 Group::removeMember($gid, $cid);
4475 $erroraddinguser = false;
4477 foreach ($users as $user) {
4478 $cid = $user['cid'];
4480 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4481 Group::addMember($gid, $cid);
4483 $erroraddinguser = true;
4484 $errorusers[] = $cid;
4488 // return success message incl. missing users in array
4489 $status = ($erroraddinguser ? "missing user" : "ok");
4490 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4491 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4494 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4497 * Update information about a group.
4499 * @param string $type Return type (atom, rss, xml, json)
4501 * @return array|string
4502 * @throws BadRequestException
4503 * @throws ForbiddenException
4504 * @throws ImagickException
4505 * @throws InternalServerErrorException
4506 * @throws UnauthorizedException
4507 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4509 function api_lists_update($type)
4511 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4514 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4515 $gid = $_REQUEST['list_id'] ?? 0;
4516 $name = $_REQUEST['name'] ?? '';
4517 $uid = $user_info['uid'];
4519 // error if no gid specified
4521 throw new BadRequestException('gid not specified');
4524 // get data of the specified group id
4525 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4526 // error message if specified gid is not in database
4528 throw new BadRequestException('gid not available');
4531 if (Group::update($gid, $name)) {
4534 'id' => intval($gid),
4535 'id_str' => (string) $gid,
4536 'user' => $user_info
4539 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4543 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4546 * Set notification as seen and returns associated item (if possible)
4548 * POST request with 'id' param as notification id
4550 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4551 * @return string|array
4552 * @throws BadRequestException
4553 * @throws ForbiddenException
4554 * @throws ImagickException
4555 * @throws InternalServerErrorException
4556 * @throws UnauthorizedException
4558 function api_friendica_notification_seen($type)
4560 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4562 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4564 if (DI::args()->getArgc() !== 4) {
4565 throw new BadRequestException('Invalid argument count');
4568 $id = intval($_REQUEST['id'] ?? 0);
4571 $Notify = DI::notify()->selectOneById($id);
4572 if ($Notify->uid !== BaseApi::getCurrentUserID()) {
4573 throw new NotFoundException();
4576 if ($Notify->uriId) {
4577 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4581 DI::notify()->save($Notify);
4583 if ($Notify->otype === Notification\ObjectType::ITEM) {
4584 $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $Notify->iid, 'uid' => BaseApi::getCurrentUserID()]);
4585 if (DBA::isResult($item)) {
4586 // we found the item, return it to the user
4587 $ret = api_format_items([$item], $user_info, false, $type);
4588 $data = ['status' => $ret];
4589 return DI::apiResponse()->formatData('status', $type, $data);
4591 // the item can't be found, but we set the notification as seen, so we count this as a success
4594 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4595 } catch (NotFoundException $e) {
4596 throw new BadRequestException('Invalid argument', $e);
4597 } catch (Exception $e) {
4598 throw new InternalServerErrorException('Internal Server exception', $e);
4602 /// @TODO move to top of file or somewhere better
4603 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4606 * search for direct_messages containing a searchstring through api
4608 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4609 * @param string $box
4610 * @return string|array (success: success=true if found and search_result contains found messages,
4611 * success=false if nothing was found, search_result='nothing found',
4612 * error: result=error with error message)
4613 * @throws BadRequestException
4614 * @throws ForbiddenException
4615 * @throws ImagickException
4616 * @throws InternalServerErrorException
4617 * @throws UnauthorizedException
4619 function api_friendica_direct_messages_search($type, $box = "")
4621 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4624 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4625 $searchstring = $_REQUEST['searchstring'] ?? '';
4626 $uid = $user_info['uid'];
4628 // error if no searchstring specified
4629 if ($searchstring == "") {
4630 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4631 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4634 // get data for the specified searchstring
4635 $r = DBA::toArray(DBA::p(
4636 "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",
4638 '%'.$searchstring.'%'
4641 $profile_url = $user_info["url"];
4643 // message if nothing was found
4644 if (!DBA::isResult($r)) {
4645 $success = ['success' => false, 'search_results' => 'problem with query'];
4646 } elseif (count($r) == 0) {
4647 $success = ['success' => false, 'search_results' => 'nothing found'];
4650 foreach ($r as $item) {
4651 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4652 $recipient = $user_info;
4653 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4654 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4655 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4656 $sender = $user_info;
4659 if (isset($recipient) && isset($sender)) {
4660 $ret[] = api_format_messages($item, $recipient, $sender);
4663 $success = ['success' => true, 'search_results' => $ret];
4666 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4669 /// @TODO move to top of file or somewhere better
4670 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4673 * Number of comments
4675 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
4677 * @param object $data [Status, Status]
4681 function bindComments(&$data)
4683 if (count($data) == 0) {
4689 foreach ($data as $item) {
4690 $ids[] = $item['id'];
4693 $idStr = DBA::escape(implode(', ', $ids));
4694 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
4695 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
4696 $itemsData = DBA::toArray($items);
4698 foreach ($itemsData as $item) {
4699 $comments[$item['parent']] = $item['comments'];
4702 foreach ($data as $idx => $item) {
4704 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
4709 @TODO Maybe open to implement?
4711 [pagename] => api/1.1/statuses/lookup.json
4712 [id] => 605138389168451584
4713 [include_cards] => true
4714 [cards_platform] => Android-12
4715 [include_entities] => true
4716 [include_my_retweet] => 1
4718 [include_reply_count] => true
4719 [include_descendent_reply_count] => true
4723 Not implemented by now:
4724 statuses/retweets_of_me
4729 account/update_location
4730 account/update_profile_background_image
4733 friendica/profile/update
4734 friendica/profile/create
4735 friendica/profile/delete
4737 Not implemented in status.net:
4738 statuses/retweeted_to_me
4739 statuses/retweeted_by_me
4740 direct_messages/destroy
4742 account/update_delivery_device
4743 notifications/follow