3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Core\System;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Group;
37 use Friendica\Model\Item;
38 use Friendica\Model\Mail;
39 use Friendica\Model\Notification;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Profile;
43 use Friendica\Model\User;
44 use Friendica\Model\Verb;
45 use Friendica\Module\Api\ApiResponse;
46 use Friendica\Module\BaseApi;
47 use Friendica\Network\HTTPException;
48 use Friendica\Network\HTTPException\BadRequestException;
49 use Friendica\Network\HTTPException\ForbiddenException;
50 use Friendica\Network\HTTPException\InternalServerErrorException;
51 use Friendica\Network\HTTPException\MethodNotAllowedException;
52 use Friendica\Network\HTTPException\NotFoundException;
53 use Friendica\Network\HTTPException\TooManyRequestsException;
54 use Friendica\Network\HTTPException\UnauthorizedException;
55 use Friendica\Object\Image;
56 use Friendica\Protocol\Activity;
57 use Friendica\Security\BasicAuth;
58 use Friendica\Security\OAuth;
59 use Friendica\Util\DateTimeFormat;
60 use Friendica\Util\Images;
61 use Friendica\Util\Network;
62 use Friendica\Util\Proxy;
63 use Friendica\Util\Strings;
65 require_once __DIR__ . '/../mod/item.php';
66 require_once __DIR__ . '/../mod/wall_upload.php';
68 define('API_METHOD_ANY', '*');
69 define('API_METHOD_GET', 'GET');
70 define('API_METHOD_POST', 'POST,PUT');
71 define('API_METHOD_DELETE', 'POST,DELETE');
73 define('API_LOG_PREFIX', 'API {action} - ');
81 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
82 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
83 * into a page, and visitors will post something without noticing it).
87 $user = OAuth::getCurrentUserID();
92 if (!empty($_SESSION['allow_api'])) {
100 * Get source name from API client
102 * Clients can send 'source' parameter to be show in post metadata
103 * as "sent via <source>".
104 * Some clients doesn't send a source param, we support ones we know
105 * (only Twidere, atm)
108 * Client source name, default to "api" if unset/unknown
111 function api_source()
113 if (requestdata('source')) {
114 return requestdata('source');
117 // Support for known clients that doesn't send a source name
118 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
119 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
123 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
125 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
132 * Format date for API
134 * @param string $str Source date, as UTC
135 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
138 function api_date($str)
140 // Wed May 23 06:01:13 +0000 2007
141 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
145 * Register a function to be the endpoint for defined API path.
147 * @param string $path API URL path, relative to DI::baseUrl()
148 * @param string $func Function name to call on path request
149 * @param bool $auth API need logged user
150 * @param string $method HTTP method reqiured to call this endpoint.
151 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
152 * Default to API_METHOD_ANY
154 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
164 // Workaround for hotot
165 $path = str_replace("api/", "api/1.1/", $path);
175 * Check HTTP method of called API
177 * API endpoints can define which HTTP method to accept when called.
178 * This function check the current HTTP method agains endpoint
181 * @param string $method Required methods, uppercase, separated by comma
184 function api_check_method($method)
186 if ($method == "*") {
189 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
193 * Main API entry point
195 * Authenticate user, call registered API function, set HTTP headers
198 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
199 * @return string|array API call result
202 function api_call(App $a, App\Arguments $args = null)
204 global $API, $called_api;
211 if (strpos($args->getCommand(), ".xml") > 0) {
214 if (strpos($args->getCommand(), ".json") > 0) {
217 if (strpos($args->getCommand(), ".rss") > 0) {
220 if (strpos($args->getCommand(), ".atom") > 0) {
225 foreach ($API as $p => $info) {
226 if (strpos($args->getCommand(), $p) === 0) {
227 if (!api_check_method($info['method'])) {
228 throw new MethodNotAllowedException();
231 $called_api = explode("/", $p);
233 if (!empty($info['auth']) && api_user() === false) {
234 BasicAuth::getCurrentUserID(true);
235 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
238 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
240 $stamp = microtime(true);
241 $return = call_user_func($info['func'], $type);
242 $duration = floatval(microtime(true) - $stamp);
244 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
246 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
248 if (false === $return) {
250 * api function returned false withour throw an
251 * exception. This should not happend, throw a 500
253 throw new InternalServerErrorException();
258 header("Content-Type: text/xml");
261 header("Content-Type: application/json");
262 if (!empty($return)) {
263 $json = json_encode(end($return));
264 if (!empty($_GET['callback'])) {
265 $json = $_GET['callback'] . "(" . $json . ")";
271 header("Content-Type: application/rss+xml");
272 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
275 header("Content-Type: application/atom+xml");
276 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
283 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
284 throw new NotFoundException();
285 } catch (HTTPException $e) {
286 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
291 * Set values for RSS template
294 * @param array $arr Array to be passed to template
295 * @param array $user_info User info
297 * @throws BadRequestException
298 * @throws ImagickException
299 * @throws InternalServerErrorException
300 * @throws UnauthorizedException
301 * @todo find proper type-hints
303 function api_rss_extra(App $a, $arr, $user_info)
305 if (is_null($user_info)) {
306 $user_info = api_get_user();
309 $arr['$user'] = $user_info;
311 'alternate' => $user_info['url'],
312 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
313 'base' => DI::baseUrl(),
314 'updated' => api_date(null),
315 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
316 'language' => $user_info['lang'],
317 'logo' => DI::baseUrl() . "/images/friendica-32.png",
325 * Unique contact to contact url.
327 * @param int $id Contact id
328 * @return bool|string
329 * Contact url or False if contact id is unknown
332 function api_unique_id_to_nurl($id)
334 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
336 if (DBA::isResult($r)) {
344 * Get user info array.
347 * @param int|string $contact_id Contact ID or URL
349 * @throws BadRequestException
350 * @throws ImagickException
351 * @throws InternalServerErrorException
352 * @throws UnauthorizedException
354 function api_get_user($contact_id = null)
362 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
364 // Searching for contact URL
365 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
366 $user = Strings::normaliseLink($contact_id);
368 $extra_query = "AND `contact`.`nurl` = ? ";
369 if (api_user() !== false) {
370 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
374 // Searching for contact id with uid = 0
375 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
376 $user = api_unique_id_to_nurl(intval($contact_id));
379 throw new BadRequestException("User ID ".$contact_id." not found.");
383 $extra_query = "AND `contact`.`nurl` = ? ";
384 if (api_user() !== false) {
385 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
389 if (is_null($user) && !empty($_GET['user_id'])) {
390 $user = api_unique_id_to_nurl($_GET['user_id']);
393 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
397 $extra_query = "AND `contact`.`nurl` = ? ";
398 if (api_user() !== false) {
399 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
402 if (is_null($user) && !empty($_GET['screen_name'])) {
403 $user = $_GET['screen_name'];
404 $extra_query = "AND `contact`.`nick` = ? ";
405 if (api_user() !== false) {
406 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
410 if (is_null($user) && !empty($_GET['profileurl'])) {
411 $user = Strings::normaliseLink($_GET['profileurl']);
412 $extra_query = "AND `contact`.`nurl` = ? ";
413 if (api_user() !== false) {
414 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
418 // $called_api is the API path exploded on / and is expected to have at least 2 elements
419 if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
420 $argid = count($called_api);
421 if (!empty(DI::args()->getArgv()[$argid])) {
422 $data = explode(".", DI::args()->getArgv()[$argid]);
423 if (count($data) > 1) {
424 [$user, $null] = $data;
427 if (is_numeric($user)) {
428 $user = api_unique_id_to_nurl(intval($user));
432 $extra_query = "AND `contact`.`nurl` = ? ";
433 if (api_user() !== false) {
434 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
438 $extra_query = "AND `contact`.`nick` = ? ";
439 if (api_user() !== false) {
440 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
445 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
448 if (api_user() === false) {
449 BasicAuth::getCurrentUserID(true);
453 $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
457 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
460 $uinfo = DBA::toArray(DBA::p(
461 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
467 // Selecting the id by priority, friendica first
468 if (is_array($uinfo)) {
469 api_best_nickname($uinfo);
472 // if the contact wasn't found, fetch it from the contacts with uid = 0
473 if (!DBA::isResult($uinfo)) {
475 throw new BadRequestException("User not found.");
478 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
480 if (DBA::isResult($contact)) {
482 'id' => $contact["id"],
483 'id_str' => (string) $contact["id"],
484 'name' => $contact["name"],
485 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
486 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
487 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
488 'profile_image_url' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_MICRO),
489 'profile_image_url_https' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_MICRO),
490 'profile_image_url_profile_size' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_THUMB),
491 'profile_image_url_large' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_SMALL),
492 'url' => $contact["url"],
493 'protected' => false,
494 'followers_count' => 0,
495 'friends_count' => 0,
497 'created_at' => api_date($contact["created"]),
498 'favourites_count' => 0,
500 'time_zone' => 'UTC',
501 'geo_enabled' => false,
503 'statuses_count' => 0,
505 'contributors_enabled' => false,
506 'is_translator' => false,
507 'is_translation_enabled' => false,
508 'following' => false,
509 'follow_request_sent' => false,
510 'statusnet_blocking' => false,
511 'notifications' => false,
512 'statusnet_profile_url' => $contact["url"],
514 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
515 'pid' => Contact::getIdForURL($contact["url"], 0, false),
517 'network' => $contact["network"],
522 throw new BadRequestException("User ".$url." not found.");
526 if ($uinfo[0]['self']) {
527 if ($uinfo[0]['network'] == "") {
528 $uinfo[0]['network'] = Protocol::DFRN;
531 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
532 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
539 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
541 if (!empty($profile['about'])) {
542 $description = $profile['about'];
544 $description = $uinfo[0]["about"];
547 if (!empty($usr['default-location'])) {
548 $location = $usr['default-location'];
549 } elseif (!empty($uinfo[0]["location"])) {
550 $location = $uinfo[0]["location"];
552 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
556 'id' => intval($pcontact_id),
557 'id_str' => (string) intval($pcontact_id),
558 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
559 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
560 'location' => $location,
561 'description' => BBCode::toPlaintext($description ?? ''),
562 'profile_image_url' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_MICRO),
563 'profile_image_url_https' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_MICRO),
564 'profile_image_url_profile_size' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_THUMB),
565 'profile_image_url_large' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_SMALL),
566 'url' => $uinfo[0]['url'],
567 'protected' => false,
568 'followers_count' => intval($countfollowers),
569 'friends_count' => intval($countfriends),
571 'created_at' => api_date($uinfo[0]['created']),
572 'favourites_count' => intval($starred),
574 'time_zone' => 'UTC',
575 'geo_enabled' => false,
577 'statuses_count' => intval($countitems),
579 'contributors_enabled' => false,
580 'is_translator' => false,
581 'is_translation_enabled' => false,
582 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
583 'follow_request_sent' => false,
584 'statusnet_blocking' => false,
585 'notifications' => false,
587 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
588 'statusnet_profile_url' => $uinfo[0]['url'],
589 'uid' => intval($uinfo[0]['uid']),
590 'cid' => intval($uinfo[0]['cid']),
591 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
592 'self' => $uinfo[0]['self'],
593 'network' => $uinfo[0]['network'],
596 // If this is a local user and it uses Frio, we can get its color preferences.
598 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
599 if ($theme_info['theme'] === 'frio') {
600 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
602 if ($schema && ($schema != '---')) {
603 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
604 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
605 require_once $schemefile;
608 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
609 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
610 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
612 if (empty($nav_bg)) {
615 if (empty($link_color)) {
616 $link_color = "#6fdbe8";
618 if (empty($bgcolor)) {
619 $bgcolor = "#ededed";
622 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
623 $ret['profile_link_color'] = str_replace('#', '', $link_color);
624 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
632 * return api-formatted array for item's author and owner
635 * @param array $item item from db
636 * @return array(array:author, array:owner)
637 * @throws BadRequestException
638 * @throws ImagickException
639 * @throws InternalServerErrorException
640 * @throws UnauthorizedException
642 function api_item_get_user(App $a, $item)
644 $status_user = api_get_user($item['author-id'] ?? null);
646 $author_user = $status_user;
648 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
650 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
651 $owner_user = api_get_user($item['owner-id'] ?? null);
653 $owner_user = $author_user;
656 return ([$status_user, $author_user, $owner_user]);
664 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
665 * returns a 401 status code and an error message if not.
667 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
669 * @param string $type Return type (atom, rss, xml, json)
670 * @return array|string
671 * @throws BadRequestException
672 * @throws ForbiddenException
673 * @throws ImagickException
674 * @throws InternalServerErrorException
675 * @throws UnauthorizedException
677 function api_account_verify_credentials($type)
681 if (api_user() === false) {
682 throw new ForbiddenException();
685 unset($_REQUEST["user_id"]);
686 unset($_GET["user_id"]);
688 unset($_REQUEST["screen_name"]);
689 unset($_GET["screen_name"]);
691 $skip_status = $_REQUEST['skip_status'] ?? false;
693 $user_info = api_get_user();
695 // "verified" isn't used here in the standard
696 unset($user_info["verified"]);
698 // - Adding last status
700 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
702 $user_info['status'] = api_format_item($item, $type);
706 // "uid" and "self" are only needed for some internal stuff, so remove it from here
707 unset($user_info["uid"]);
708 unset($user_info["self"]);
710 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
713 /// @TODO move to top of file or somewhere better
714 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
717 * Get data from $_POST or $_GET
722 function requestdata($k)
724 if (!empty($_POST[$k])) {
727 if (!empty($_GET[$k])) {
734 * Deprecated function to upload media.
736 * @param string $type Return type (atom, rss, xml, json)
738 * @return array|string
739 * @throws BadRequestException
740 * @throws ForbiddenException
741 * @throws ImagickException
742 * @throws InternalServerErrorException
743 * @throws UnauthorizedException
745 function api_statuses_mediap($type)
749 if (api_user() === false) {
750 logger::notice('api_statuses_update: no user');
751 throw new ForbiddenException();
753 $user_info = api_get_user();
755 $_REQUEST['profile_uid'] = api_user();
756 $_REQUEST['api_source'] = true;
757 $txt = requestdata('status') ?? '';
758 /// @TODO old-lost code?
759 //$txt = urldecode(requestdata('status'));
761 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
762 $txt = HTML::toBBCodeVideo($txt);
763 $config = HTMLPurifier_Config::createDefault();
764 $config->set('Cache.DefinitionImpl', null);
765 $purifier = new HTMLPurifier($config);
766 $txt = $purifier->purify($txt);
768 $txt = HTML::toBBCode($txt);
770 DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
772 $picture = wall_upload_post($a, false);
774 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
775 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
776 $item_id = item_post($a);
778 // output the post that we just posted.
779 return api_status_show($type, $item_id);
782 /// @TODO move this to top of file or somewhere better!
783 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
786 * Updates the user’s current status.
788 * @param string $type Return type (atom, rss, xml, json)
790 * @return array|string
791 * @throws BadRequestException
792 * @throws ForbiddenException
793 * @throws ImagickException
794 * @throws InternalServerErrorException
795 * @throws TooManyRequestsException
796 * @throws UnauthorizedException
797 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
799 function api_statuses_update($type)
803 if (api_user() === false) {
804 logger::notice('api_statuses_update: no user');
805 throw new ForbiddenException();
810 // convert $_POST array items to the form we use for web posts.
811 if (requestdata('htmlstatus')) {
812 $txt = requestdata('htmlstatus') ?? '';
813 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
814 $txt = HTML::toBBCodeVideo($txt);
816 $config = HTMLPurifier_Config::createDefault();
817 $config->set('Cache.DefinitionImpl', null);
819 $purifier = new HTMLPurifier($config);
820 $txt = $purifier->purify($txt);
822 $_REQUEST['body'] = HTML::toBBCode($txt);
825 $_REQUEST['body'] = requestdata('status');
828 $_REQUEST['title'] = requestdata('title');
830 $parent = requestdata('in_reply_to_status_id');
832 // Twidere sends "-1" if it is no reply ...
837 if (ctype_digit($parent)) {
838 $_REQUEST['parent'] = $parent;
840 $_REQUEST['parent_uri'] = $parent;
843 if (requestdata('lat') && requestdata('long')) {
844 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
846 $_REQUEST['profile_uid'] = api_user();
849 // Check for throttling (maximum posts per day, week and month)
850 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
851 if ($throttle_day > 0) {
852 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
854 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
855 $posts_day = Post::count($condition);
857 if ($posts_day > $throttle_day) {
858 logger::info('Daily posting limit reached for user '.api_user());
859 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
860 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));
864 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
865 if ($throttle_week > 0) {
866 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
868 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
869 $posts_week = Post::count($condition);
871 if ($posts_week > $throttle_week) {
872 logger::info('Weekly posting limit reached for user '.api_user());
873 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
874 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));
878 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
879 if ($throttle_month > 0) {
880 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
882 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
883 $posts_month = Post::count($condition);
885 if ($posts_month > $throttle_month) {
886 logger::info('Monthly posting limit reached for user '.api_user());
887 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
888 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));
893 if (requestdata('media_ids')) {
894 $ids = explode(',', requestdata('media_ids') ?? '');
895 } elseif (!empty($_FILES['media'])) {
896 // upload the image if we have one
897 $picture = wall_upload_post($a, false);
898 if (is_array($picture)) {
899 $ids[] = $picture['id'];
907 foreach ($ids as $id) {
908 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
909 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
910 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
911 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
913 if (!empty($media)) {
914 $ressources[] = $media[0]['resource-id'];
915 $phototypes = Images::supportedTypes();
916 $ext = $phototypes[$media[0]['type']];
918 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
919 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
920 'size' => $media[0]['datasize'],
921 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
922 'description' => $media[0]['desc'] ?? '',
923 'width' => $media[0]['width'],
924 'height' => $media[0]['height']];
926 if (count($media) > 1) {
927 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
928 $attachment['preview-width'] = $media[1]['width'];
929 $attachment['preview-height'] = $media[1]['height'];
931 $attachments[] = $attachment;
935 // We have to avoid that the post is rejected because of an empty body
936 if (empty($_REQUEST['body'])) {
937 $_REQUEST['body'] = '[hr]';
941 if (!empty($attachments)) {
942 $_REQUEST['attachments'] = $attachments;
945 // set this so that the item_post() function is quiet and doesn't redirect or emit json
947 $_REQUEST['api_source'] = true;
949 if (empty($_REQUEST['source'])) {
950 $_REQUEST["source"] = api_source();
953 // call out normal post function
954 $item_id = item_post($a);
956 if (!empty($ressources) && !empty($item_id)) {
957 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
958 foreach ($ressources as $ressource) {
959 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
963 // output the post that we just posted.
964 return api_status_show($type, $item_id);
967 /// @TODO move to top of file or somewhere better
968 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
969 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
972 * Uploads an image to Friendica.
975 * @throws BadRequestException
976 * @throws ForbiddenException
977 * @throws ImagickException
978 * @throws InternalServerErrorException
979 * @throws UnauthorizedException
980 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
982 function api_media_upload()
986 if (api_user() === false) {
987 logger::notice('no user');
988 throw new ForbiddenException();
993 if (empty($_FILES['media'])) {
995 throw new BadRequestException("No media.");
998 $media = wall_upload_post($a, false);
1001 throw new InternalServerErrorException();
1005 $returndata["media_id"] = $media["id"];
1006 $returndata["media_id_string"] = (string)$media["id"];
1007 $returndata["size"] = $media["size"];
1008 $returndata["image"] = ["w" => $media["width"],
1009 "h" => $media["height"],
1010 "image_type" => $media["type"],
1011 "friendica_preview_url" => $media["preview"]];
1013 Logger::info('Media uploaded', ['return' => $returndata]);
1015 return ["media" => $returndata];
1018 /// @TODO move to top of file or somewhere better
1019 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1022 * Updates media meta data (picture descriptions)
1024 * @param string $type Return type (atom, rss, xml, json)
1026 * @return array|string
1027 * @throws BadRequestException
1028 * @throws ForbiddenException
1029 * @throws ImagickException
1030 * @throws InternalServerErrorException
1031 * @throws TooManyRequestsException
1032 * @throws UnauthorizedException
1033 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1035 * @todo Compare the corresponding Twitter function for correct return values
1037 function api_media_metadata_create($type)
1041 if (api_user() === false) {
1042 Logger::info('no user');
1043 throw new ForbiddenException();
1048 $postdata = Network::postdata();
1050 if (empty($postdata)) {
1051 throw new BadRequestException("No post data");
1054 $data = json_decode($postdata, true);
1056 throw new BadRequestException("Invalid post data");
1059 if (empty($data['media_id']) || empty($data['alt_text'])) {
1060 throw new BadRequestException("Missing post data values");
1063 if (empty($data['alt_text']['text'])) {
1064 throw new BadRequestException("No alt text.");
1067 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1069 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1070 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1071 if (!DBA::isResult($photo)) {
1072 throw new BadRequestException("Metadata not found.");
1075 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1078 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1081 * @param string $type Return format (atom, rss, xml, json)
1082 * @param int $item_id
1083 * @return array|string
1086 function api_status_show($type, $item_id)
1088 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1092 $item = api_get_item(['id' => $item_id]);
1093 if (!empty($item)) {
1094 $status_info = api_format_item($item, $type);
1097 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1099 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
1103 * Retrieves the last public status of the provided user info
1105 * @param int $ownerId Public contact Id
1106 * @param int $uid User Id
1110 function api_get_last_status($ownerId, $uid)
1113 'author-id'=> $ownerId,
1115 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1116 'private' => [Item::PUBLIC, Item::UNLISTED]
1119 $item = api_get_item($condition);
1125 * Retrieves a single item record based on the provided condition and converts it for API use.
1127 * @param array $condition Item table condition array
1131 function api_get_item(array $condition)
1133 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1139 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1140 * The author's most recent status will be returned inline.
1142 * @param string $type Return type (atom, rss, xml, json)
1143 * @return array|string
1144 * @throws BadRequestException
1145 * @throws ImagickException
1146 * @throws InternalServerErrorException
1147 * @throws UnauthorizedException
1148 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1150 function api_users_show($type)
1152 $a = Friendica\DI::app();
1154 $user_info = api_get_user();
1156 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1157 if (!empty($item)) {
1158 $user_info['status'] = api_format_item($item, $type);
1161 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1162 unset($user_info['uid']);
1163 unset($user_info['self']);
1165 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1168 /// @TODO move to top of file or somewhere better
1169 api_register_func('api/users/show', 'api_users_show');
1170 api_register_func('api/externalprofile/show', 'api_users_show');
1173 * Search a public user account.
1175 * @param string $type Return type (atom, rss, xml, json)
1177 * @return array|string
1178 * @throws BadRequestException
1179 * @throws ImagickException
1180 * @throws InternalServerErrorException
1181 * @throws UnauthorizedException
1182 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1184 function api_users_search($type)
1190 if (!empty($_GET['q'])) {
1191 $contacts = Contact::selectToArray(
1194 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1202 if (DBA::isResult($contacts)) {
1204 foreach ($contacts as $contact) {
1205 $user_info = api_get_user($contact['id']);
1207 if ($type == 'xml') {
1208 $userlist[$k++ . ':user'] = $user_info;
1210 $userlist[] = $user_info;
1213 $userlist = ['users' => $userlist];
1215 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1218 throw new BadRequestException('No search term specified.');
1221 return DI::apiResponse()->formatData('users', $type, $userlist);
1224 /// @TODO move to top of file or somewhere better
1225 api_register_func('api/users/search', 'api_users_search');
1228 * Return user objects
1230 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1232 * @param string $type Return format: json or xml
1234 * @return array|string
1235 * @throws BadRequestException
1236 * @throws ImagickException
1237 * @throws InternalServerErrorException
1238 * @throws NotFoundException if the results are empty.
1239 * @throws UnauthorizedException
1241 function api_users_lookup($type)
1245 if (!empty($_REQUEST['user_id'])) {
1246 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1248 $users[] = api_get_user($id);
1253 if (empty($users)) {
1254 throw new NotFoundException;
1257 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1260 /// @TODO move to top of file or somewhere better
1261 api_register_func('api/users/lookup', 'api_users_lookup', true);
1264 * Returns statuses that match a specified query.
1266 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1268 * @param string $type Return format: json, xml, atom, rss
1270 * @return array|string
1271 * @throws BadRequestException if the "q" parameter is missing.
1272 * @throws ForbiddenException
1273 * @throws ImagickException
1274 * @throws InternalServerErrorException
1275 * @throws UnauthorizedException
1277 function api_search($type)
1280 $user_info = api_get_user();
1282 if (api_user() === false || $user_info === false) {
1283 throw new ForbiddenException();
1286 if (empty($_REQUEST['q'])) {
1287 throw new BadRequestException('q parameter is required.');
1290 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1293 $data['status'] = [];
1295 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1296 if (!empty($_REQUEST['rpp'])) {
1297 $count = $_REQUEST['rpp'];
1298 } elseif (!empty($_REQUEST['count'])) {
1299 $count = $_REQUEST['count'];
1302 $since_id = $_REQUEST['since_id'] ?? 0;
1303 $max_id = $_REQUEST['max_id'] ?? 0;
1304 $page = $_REQUEST['page'] ?? 1;
1306 $start = max(0, ($page - 1) * $count);
1308 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1309 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1310 $searchTerm = $matches[1];
1311 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1312 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1314 while ($tag = DBA::fetch($tags)) {
1315 $uriids[] = $tag['uri-id'];
1319 if (empty($uriids)) {
1320 return DI::apiResponse()->formatData('statuses', $type, $data);
1323 $condition = ['uri-id' => $uriids];
1324 if ($exclude_replies) {
1325 $condition['gravity'] = GRAVITY_PARENT;
1328 $params['group_by'] = ['uri-id'];
1330 $condition = ["`id` > ?
1331 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1332 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1333 AND `body` LIKE CONCAT('%',?,'%')",
1334 $since_id, api_user(), $_REQUEST['q']];
1336 $condition[0] .= ' AND `id` <= ?';
1337 $condition[] = $max_id;
1343 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1344 $id = Item::fetchByLink($searchTerm, api_user());
1347 $id = Item::fetchByLink($searchTerm);
1351 $statuses = Post::select([], ['id' => $id]);
1355 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1357 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1359 bindComments($data['status']);
1361 return DI::apiResponse()->formatData('statuses', $type, $data);
1364 /// @TODO move to top of file or somewhere better
1365 api_register_func('api/search/tweets', 'api_search', true);
1366 api_register_func('api/search', 'api_search', true);
1369 * Returns the most recent statuses posted by the user and the users they follow.
1371 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1373 * @param string $type Return type (atom, rss, xml, json)
1375 * @return array|string
1376 * @throws BadRequestException
1377 * @throws ForbiddenException
1378 * @throws ImagickException
1379 * @throws InternalServerErrorException
1380 * @throws UnauthorizedException
1381 * @todo Optional parameters
1382 * @todo Add reply info
1384 function api_statuses_home_timeline($type)
1387 $user_info = api_get_user();
1389 if (api_user() === false || $user_info === false) {
1390 throw new ForbiddenException();
1393 unset($_REQUEST["user_id"]);
1394 unset($_GET["user_id"]);
1396 unset($_REQUEST["screen_name"]);
1397 unset($_GET["screen_name"]);
1399 // get last network messages
1402 $count = $_REQUEST['count'] ?? 20;
1403 $page = $_REQUEST['page']?? 0;
1404 $since_id = $_REQUEST['since_id'] ?? 0;
1405 $max_id = $_REQUEST['max_id'] ?? 0;
1406 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1407 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1409 $start = max(0, ($page - 1) * $count);
1411 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1412 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1415 $condition[0] .= " AND `id` <= ?";
1416 $condition[] = $max_id;
1418 if ($exclude_replies) {
1419 $condition[0] .= ' AND `gravity` = ?';
1420 $condition[] = GRAVITY_PARENT;
1422 if ($conversation_id > 0) {
1423 $condition[0] .= " AND `parent` = ?";
1424 $condition[] = $conversation_id;
1427 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1428 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1430 $items = Post::toArray($statuses);
1432 $ret = api_format_items($items, $user_info, false, $type);
1434 // Set all posts from the query above to seen
1436 foreach ($items as $item) {
1437 $idarray[] = intval($item["id"]);
1440 if (!empty($idarray)) {
1441 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1443 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1449 $data = ['status' => $ret];
1454 $data = api_rss_extra($a, $data, $user_info);
1458 return DI::apiResponse()->formatData("statuses", $type, $data);
1462 /// @TODO move to top of file or somewhere better
1463 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1464 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1467 * Returns the most recent statuses from public users.
1469 * @param string $type Return type (atom, rss, xml, json)
1471 * @return array|string
1472 * @throws BadRequestException
1473 * @throws ForbiddenException
1474 * @throws ImagickException
1475 * @throws InternalServerErrorException
1476 * @throws UnauthorizedException
1478 function api_statuses_public_timeline($type)
1481 $user_info = api_get_user();
1483 if (api_user() === false || $user_info === false) {
1484 throw new ForbiddenException();
1487 // get last network messages
1490 $count = $_REQUEST['count'] ?? 20;
1491 $page = $_REQUEST['page'] ?? 1;
1492 $since_id = $_REQUEST['since_id'] ?? 0;
1493 $max_id = $_REQUEST['max_id'] ?? 0;
1494 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1495 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1497 $start = max(0, ($page - 1) * $count);
1499 if ($exclude_replies && !$conversation_id) {
1500 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1501 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1504 $condition[0] .= " AND `id` <= ?";
1505 $condition[] = $max_id;
1508 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1509 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1511 $r = Post::toArray($statuses);
1513 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1514 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1517 $condition[0] .= " AND `id` <= ?";
1518 $condition[] = $max_id;
1520 if ($conversation_id > 0) {
1521 $condition[0] .= " AND `parent` = ?";
1522 $condition[] = $conversation_id;
1525 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1526 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1528 $r = Post::toArray($statuses);
1531 $ret = api_format_items($r, $user_info, false, $type);
1535 $data = ['status' => $ret];
1540 $data = api_rss_extra($a, $data, $user_info);
1544 return DI::apiResponse()->formatData("statuses", $type, $data);
1547 /// @TODO move to top of file or somewhere better
1548 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1551 * Returns the most recent statuses posted by users this node knows about.
1553 * @param string $type Return format: json, xml, atom, rss
1554 * @return array|string
1555 * @throws BadRequestException
1556 * @throws ForbiddenException
1557 * @throws ImagickException
1558 * @throws InternalServerErrorException
1559 * @throws UnauthorizedException
1561 function api_statuses_networkpublic_timeline($type)
1564 $user_info = api_get_user();
1566 if (api_user() === false || $user_info === false) {
1567 throw new ForbiddenException();
1570 $since_id = $_REQUEST['since_id'] ?? 0;
1571 $max_id = $_REQUEST['max_id'] ?? 0;
1574 $count = $_REQUEST['count'] ?? 20;
1575 $page = $_REQUEST['page'] ?? 1;
1577 $start = max(0, ($page - 1) * $count);
1579 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1580 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1583 $condition[0] .= " AND `id` <= ?";
1584 $condition[] = $max_id;
1587 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1588 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1590 $ret = api_format_items($statuses, $user_info, false, $type);
1594 $data = ['status' => $ret];
1599 $data = api_rss_extra($a, $data, $user_info);
1603 return DI::apiResponse()->formatData("statuses", $type, $data);
1606 /// @TODO move to top of file or somewhere better
1607 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1610 * Returns a single status.
1612 * @param string $type Return type (atom, rss, xml, json)
1614 * @return array|string
1615 * @throws BadRequestException
1616 * @throws ForbiddenException
1617 * @throws ImagickException
1618 * @throws InternalServerErrorException
1619 * @throws UnauthorizedException
1620 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1622 function api_statuses_show($type)
1625 $user_info = api_get_user();
1627 if (api_user() === false || $user_info === false) {
1628 throw new ForbiddenException();
1632 $id = intval(DI::args()->getArgv()[3] ?? 0);
1635 $id = intval($_REQUEST['id'] ?? 0);
1640 $id = intval(DI::args()->getArgv()[4] ?? 0);
1643 logger::notice('API: api_statuses_show: ' . $id);
1645 $conversation = !empty($_REQUEST['conversation']);
1647 // try to fetch the item for the local user - or the public item, if there is no local one
1648 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1649 if (!DBA::isResult($uri_item)) {
1650 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1653 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1654 if (!DBA::isResult($item)) {
1655 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1660 if ($conversation) {
1661 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1662 $params = ['order' => ['id' => true]];
1664 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1668 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1670 /// @TODO How about copying this to above methods which don't check $r ?
1671 if (!DBA::isResult($statuses)) {
1672 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1675 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1677 if ($conversation) {
1678 $data = ['status' => $ret];
1679 return DI::apiResponse()->formatData("statuses", $type, $data);
1681 $data = ['status' => $ret[0]];
1682 return DI::apiResponse()->formatData("status", $type, $data);
1686 /// @TODO move to top of file or somewhere better
1687 api_register_func('api/statuses/show', 'api_statuses_show', true);
1691 * @param string $type Return type (atom, rss, xml, json)
1693 * @return array|string
1694 * @throws BadRequestException
1695 * @throws ForbiddenException
1696 * @throws ImagickException
1697 * @throws InternalServerErrorException
1698 * @throws UnauthorizedException
1699 * @todo nothing to say?
1701 function api_conversation_show($type)
1704 $user_info = api_get_user();
1706 if (api_user() === false || $user_info === false) {
1707 throw new ForbiddenException();
1711 $id = intval(DI::args()->getArgv()[3] ?? 0);
1712 $since_id = intval($_REQUEST['since_id'] ?? 0);
1713 $max_id = intval($_REQUEST['max_id'] ?? 0);
1714 $count = intval($_REQUEST['count'] ?? 20);
1715 $page = intval($_REQUEST['page'] ?? 1);
1717 $start = max(0, ($page - 1) * $count);
1720 $id = intval($_REQUEST['id'] ?? 0);
1725 $id = intval(DI::args()->getArgv()[4] ?? 0);
1728 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1730 // try to fetch the item for the local user - or the public item, if there is no local one
1731 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1732 if (!DBA::isResult($item)) {
1733 throw new BadRequestException("There is no status with the id $id.");
1736 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1737 if (!DBA::isResult($parent)) {
1738 throw new BadRequestException("There is no status with this id.");
1741 $id = $parent['id'];
1743 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1744 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1747 $condition[0] .= " AND `id` <= ?";
1748 $condition[] = $max_id;
1751 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1752 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1754 if (!DBA::isResult($statuses)) {
1755 throw new BadRequestException("There is no status with id $id.");
1758 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1760 $data = ['status' => $ret];
1761 return DI::apiResponse()->formatData("statuses", $type, $data);
1764 /// @TODO move to top of file or somewhere better
1765 api_register_func('api/conversation/show', 'api_conversation_show', true);
1766 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1771 * @param string $type Return type (atom, rss, xml, json)
1773 * @return array|string
1774 * @throws BadRequestException
1775 * @throws ForbiddenException
1776 * @throws ImagickException
1777 * @throws InternalServerErrorException
1778 * @throws UnauthorizedException
1779 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1781 function api_statuses_repeat($type)
1787 if (api_user() === false) {
1788 throw new ForbiddenException();
1794 $id = intval(DI::args()->getArgv()[3] ?? 0);
1797 $id = intval($_REQUEST['id'] ?? 0);
1802 $id = intval(DI::args()->getArgv()[4] ?? 0);
1805 logger::notice('API: api_statuses_repeat: ' . $id);
1807 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1808 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1810 if (DBA::isResult($item) && !empty($item['body'])) {
1811 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1812 if (!Item::performActivity($id, 'announce', local_user())) {
1813 throw new InternalServerErrorException();
1818 if (strpos($item['body'], "[/share]") !== false) {
1819 $pos = strpos($item['body'], "[share");
1820 $post = substr($item['body'], $pos);
1822 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1824 if (!empty($item['title'])) {
1825 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1828 $post .= $item['body'];
1829 $post .= "[/share]";
1831 $_REQUEST['body'] = $post;
1832 $_REQUEST['profile_uid'] = api_user();
1833 $_REQUEST['api_source'] = true;
1835 if (empty($_REQUEST['source'])) {
1836 $_REQUEST["source"] = api_source();
1839 $item_id = item_post($a);
1842 throw new ForbiddenException();
1845 // output the post that we just posted.
1847 return api_status_show($type, $item_id);
1850 /// @TODO move to top of file or somewhere better
1851 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1854 * Destroys a specific status.
1856 * @param string $type Return type (atom, rss, xml, json)
1858 * @return array|string
1859 * @throws BadRequestException
1860 * @throws ForbiddenException
1861 * @throws ImagickException
1862 * @throws InternalServerErrorException
1863 * @throws UnauthorizedException
1864 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1866 function api_statuses_destroy($type)
1870 if (api_user() === false) {
1871 throw new ForbiddenException();
1877 $id = intval(DI::args()->getArgv()[3] ?? 0);
1880 $id = intval($_REQUEST['id'] ?? 0);
1885 $id = intval(DI::args()->getArgv()[4] ?? 0);
1888 logger::notice('API: api_statuses_destroy: ' . $id);
1890 $ret = api_statuses_show($type);
1892 Item::deleteForUser(['id' => $id], api_user());
1897 /// @TODO move to top of file or somewhere better
1898 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1901 * Returns the most recent mentions.
1903 * @param string $type Return type (atom, rss, xml, json)
1905 * @return array|string
1906 * @throws BadRequestException
1907 * @throws ForbiddenException
1908 * @throws ImagickException
1909 * @throws InternalServerErrorException
1910 * @throws UnauthorizedException
1911 * @see http://developer.twitter.com/doc/get/statuses/mentions
1913 function api_statuses_mentions($type)
1916 $user_info = api_get_user();
1918 if (api_user() === false || $user_info === false) {
1919 throw new ForbiddenException();
1922 unset($_REQUEST["user_id"]);
1923 unset($_GET["user_id"]);
1925 unset($_REQUEST["screen_name"]);
1926 unset($_GET["screen_name"]);
1928 // get last network messages
1931 $since_id = intval($_REQUEST['since_id'] ?? 0);
1932 $max_id = intval($_REQUEST['max_id'] ?? 0);
1933 $count = intval($_REQUEST['count'] ?? 20);
1934 $page = intval($_REQUEST['page'] ?? 1);
1936 $start = max(0, ($page - 1) * $count);
1938 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1939 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1940 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1943 GRAVITY_PARENT, GRAVITY_COMMENT,
1945 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1946 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1947 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1948 api_user(), $since_id,
1952 $query .= " AND `id` <= ?";
1953 $condition[] = $max_id;
1956 array_unshift($condition, $query);
1958 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1959 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1961 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1963 $data = ['status' => $ret];
1968 $data = api_rss_extra($a, $data, $user_info);
1972 return DI::apiResponse()->formatData("statuses", $type, $data);
1975 /// @TODO move to top of file or somewhere better
1976 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1977 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1980 * Returns the most recent statuses posted by the user.
1982 * @param string $type Either "json" or "xml"
1983 * @return string|array
1984 * @throws BadRequestException
1985 * @throws ForbiddenException
1986 * @throws ImagickException
1987 * @throws InternalServerErrorException
1988 * @throws UnauthorizedException
1989 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1991 function api_statuses_user_timeline($type)
1994 $user_info = api_get_user();
1996 if (api_user() === false || $user_info === false) {
1997 throw new ForbiddenException();
2000 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2002 $since_id = $_REQUEST['since_id'] ?? 0;
2003 $max_id = $_REQUEST['max_id'] ?? 0;
2004 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2005 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2008 $count = $_REQUEST['count'] ?? 20;
2009 $page = $_REQUEST['page'] ?? 1;
2011 $start = max(0, ($page - 1) * $count);
2013 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2014 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2016 if ($user_info['self'] == 1) {
2017 $condition[0] .= ' AND `wall` ';
2020 if ($exclude_replies) {
2021 $condition[0] .= ' AND `gravity` = ?';
2022 $condition[] = GRAVITY_PARENT;
2025 if ($conversation_id > 0) {
2026 $condition[0] .= " AND `parent` = ?";
2027 $condition[] = $conversation_id;
2031 $condition[0] .= " AND `id` <= ?";
2032 $condition[] = $max_id;
2034 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2035 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2037 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2041 $data = ['status' => $ret];
2046 $data = api_rss_extra($a, $data, $user_info);
2050 return DI::apiResponse()->formatData("statuses", $type, $data);
2053 /// @TODO move to top of file or somewhere better
2054 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2057 * Star/unstar an item.
2058 * param: id : id of the item
2060 * @param string $type Return type (atom, rss, xml, json)
2062 * @return array|string
2063 * @throws BadRequestException
2064 * @throws ForbiddenException
2065 * @throws ImagickException
2066 * @throws InternalServerErrorException
2067 * @throws UnauthorizedException
2068 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2070 function api_favorites_create_destroy($type)
2074 if (api_user() === false) {
2075 throw new ForbiddenException();
2078 // for versioned api.
2079 /// @TODO We need a better global soluton
2080 $action_argv_id = 2;
2081 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
2082 $action_argv_id = 3;
2085 if (DI::args()->getArgc() <= $action_argv_id) {
2086 throw new BadRequestException("Invalid request.");
2088 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
2089 if (DI::args()->getArgc() == $action_argv_id + 2) {
2090 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
2092 $itemid = intval($_REQUEST['id'] ?? 0);
2095 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2097 if (!DBA::isResult($item)) {
2098 throw new BadRequestException("Invalid item.");
2103 $item['starred'] = 1;
2106 $item['starred'] = 0;
2109 throw new BadRequestException("Invalid action ".$action);
2112 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2115 throw new InternalServerErrorException("DB error");
2119 $user_info = api_get_user();
2120 $rets = api_format_items([$item], $user_info, false, $type);
2123 $data = ['status' => $ret];
2128 $data = api_rss_extra($a, $data, $user_info);
2132 return DI::apiResponse()->formatData("status", $type, $data);
2135 /// @TODO move to top of file or somewhere better
2136 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2137 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2140 * Returns the most recent favorite statuses.
2142 * @param string $type Return type (atom, rss, xml, json)
2144 * @return string|array
2145 * @throws BadRequestException
2146 * @throws ForbiddenException
2147 * @throws ImagickException
2148 * @throws InternalServerErrorException
2149 * @throws UnauthorizedException
2151 function api_favorites($type)
2156 $user_info = api_get_user();
2158 if (api_user() === false || $user_info === false) {
2159 throw new ForbiddenException();
2164 // in friendica starred item are private
2165 // return favorites only for self
2166 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2168 if ($user_info['self'] == 0) {
2172 $since_id = $_REQUEST['since_id'] ?? 0;
2173 $max_id = $_REQUEST['max_id'] ?? 0;
2174 $count = $_GET['count'] ?? 20;
2175 $page = $_REQUEST['page'] ?? 1;
2177 $start = max(0, ($page - 1) * $count);
2179 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2180 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2182 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2185 $condition[0] .= " AND `id` <= ?";
2186 $condition[] = $max_id;
2189 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2191 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2196 $data = ['status' => $ret];
2201 $data = api_rss_extra($a, $data, $user_info);
2205 return DI::apiResponse()->formatData("statuses", $type, $data);
2208 /// @TODO move to top of file or somewhere better
2209 api_register_func('api/favorites', 'api_favorites', true);
2213 * @param array $item
2214 * @param array $recipient
2215 * @param array $sender
2218 * @throws InternalServerErrorException
2220 function api_format_messages($item, $recipient, $sender)
2222 // standard meta information
2224 'id' => $item['id'],
2225 'sender_id' => $sender['id'],
2227 'recipient_id' => $recipient['id'],
2228 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2229 'sender_screen_name' => $sender['screen_name'],
2230 'recipient_screen_name' => $recipient['screen_name'],
2231 'sender' => $sender,
2232 'recipient' => $recipient,
2234 'friendica_seen' => $item['seen'] ?? 0,
2235 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2238 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2239 if (isset($ret['sender']['uid'])) {
2240 unset($ret['sender']['uid']);
2242 if (isset($ret['sender']['self'])) {
2243 unset($ret['sender']['self']);
2245 if (isset($ret['recipient']['uid'])) {
2246 unset($ret['recipient']['uid']);
2248 if (isset($ret['recipient']['self'])) {
2249 unset($ret['recipient']['self']);
2252 //don't send title to regular StatusNET requests to avoid confusing these apps
2253 if (!empty($_GET['getText'])) {
2254 $ret['title'] = $item['title'];
2255 if ($_GET['getText'] == 'html') {
2256 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2257 } elseif ($_GET['getText'] == 'plain') {
2258 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2261 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2263 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2264 unset($ret['sender']);
2265 unset($ret['recipient']);
2273 * @param array $item
2276 * @throws InternalServerErrorException
2278 function api_convert_item($item)
2280 $body = api_add_attachments_to_body($item);
2282 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2284 // Add pictures to the attachment array and remove them from the body
2285 $attachments = api_get_attachments($body, $item['uri-id']);
2287 // Workaround for ostatus messages where the title is identically to the body
2288 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2289 $statusbody = trim(HTML::toPlaintext($html, 0));
2291 // handle data: images
2292 $statusbody = api_format_items_embeded_images($item, $statusbody);
2294 $statustitle = trim($item['title']);
2296 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2297 $statustext = trim($statusbody);
2299 $statustext = trim($statustitle."\n\n".$statusbody);
2302 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2303 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2306 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2308 // Workaround for clients with limited HTML parser functionality
2309 $search = ["<br>", "<blockquote>", "</blockquote>",
2310 "<h1>", "</h1>", "<h2>", "</h2>",
2311 "<h3>", "</h3>", "<h4>", "</h4>",
2312 "<h5>", "</h5>", "<h6>", "</h6>"];
2313 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2314 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2315 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2316 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2317 $statushtml = str_replace($search, $replace, $statushtml);
2319 if ($item['title'] != "") {
2320 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2324 $oldtext = $statushtml;
2325 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2326 } while ($oldtext != $statushtml);
2328 if (substr($statushtml, 0, 4) == '<br>') {
2329 $statushtml = substr($statushtml, 4);
2332 if (substr($statushtml, 0, -4) == '<br>') {
2333 $statushtml = substr($statushtml, -4);
2336 // feeds without body should contain the link
2337 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2338 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2342 "text" => $statustext,
2343 "html" => $statushtml,
2344 "attachments" => $attachments,
2345 "entities" => $entities
2350 * Add media attachments to the body
2352 * @param array $item
2353 * @return string body with added media
2355 function api_add_attachments_to_body(array $item)
2357 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2359 if (strpos($body, '[/img]') !== false) {
2363 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2364 if (!empty($media['preview'])) {
2365 $description = $media['description'] ?: $media['name'];
2366 if (!empty($description)) {
2367 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2369 $body .= "\n[img]" . $media['preview'] .'[/img]';
2379 * @param string $body
2383 * @throws InternalServerErrorException
2385 function api_get_attachments(&$body, $uriid)
2387 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2388 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2390 $URLSearchString = "^\[\]";
2391 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2395 // Remove all embedded pictures, since they are added as attachments
2396 foreach ($images[0] as $orig) {
2397 $body = str_replace($orig, '', $body);
2402 foreach ($images[1] as $image) {
2403 $imagedata = Images::getInfoFromURLCached($image);
2406 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2410 return $attachments;
2415 * @param string $text
2416 * @param string $bbcode
2419 * @throws InternalServerErrorException
2420 * @todo Links at the first character of the post
2422 function api_get_entitities(&$text, $bbcode, $uriid)
2424 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2426 if ($include_entities != "true") {
2427 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2429 foreach ($images[1] as $image) {
2430 $replace = Post\Link::getByLink($uriid, $image);
2431 $text = str_replace($image, $replace, $text);
2436 $bbcode = BBCode::cleanPictureLinks($bbcode);
2438 // Change pure links in text to bbcode uris
2439 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2442 $entities["hashtags"] = [];
2443 $entities["symbols"] = [];
2444 $entities["urls"] = [];
2445 $entities["user_mentions"] = [];
2447 $URLSearchString = "^\[\]";
2449 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2451 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2452 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2454 $bbcode = preg_replace(
2455 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2456 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2459 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2461 $bbcode = preg_replace(
2462 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2463 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2466 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2468 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2470 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2473 foreach ($urls[1] as $id => $url) {
2474 $start = iconv_strpos($text, $url, 0, "UTF-8");
2475 if (!($start === false)) {
2476 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2480 ksort($ordered_urls);
2484 foreach ($ordered_urls as $url) {
2485 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2486 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2488 $display_url = $url["title"];
2490 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2491 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2493 if (strlen($display_url) > 26) {
2494 $display_url = substr($display_url, 0, 25)."…";
2498 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2499 if (!($start === false)) {
2500 $entities["urls"][] = ["url" => $url["url"],
2501 "expanded_url" => $url["url"],
2502 "display_url" => $display_url,
2503 "indices" => [$start, $start+strlen($url["url"])]];
2504 $offset = $start + 1;
2508 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2509 $ordered_images = [];
2510 foreach ($images as $image) {
2511 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2512 if (!($start === false)) {
2513 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2517 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2518 foreach ($images[1] as $image) {
2519 $start = iconv_strpos($text, $image, 0, "UTF-8");
2520 if (!($start === false)) {
2521 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2527 foreach ($ordered_images as $image) {
2528 $url = $image['url'];
2529 $ext_alt_text = $image['alt'];
2531 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2532 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2534 if (strlen($display_url) > 26) {
2535 $display_url = substr($display_url, 0, 25)."…";
2538 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2539 if (!($start === false)) {
2540 $image = Images::getInfoFromURLCached($url);
2542 $media_url = Post\Link::getByLink($uriid, $url);
2543 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2545 $entities["media"][] = [
2547 "id_str" => (string) ($start + 1),
2548 "indices" => [$start, $start+strlen($url)],
2549 "media_url" => Strings::normaliseLink($media_url),
2550 "media_url_https" => $media_url,
2552 "display_url" => $display_url,
2553 "expanded_url" => $url,
2554 "ext_alt_text" => $ext_alt_text,
2558 $offset = $start + 1;
2567 * @param array $item
2568 * @param string $text
2572 function api_format_items_embeded_images($item, $text)
2574 $text = preg_replace_callback(
2575 '|data:image/([^;]+)[^=]+=*|m',
2576 function () use ($item) {
2577 return DI::baseUrl() . '/display/' . $item['guid'];
2585 * return <a href='url'>name</a> as array
2587 * @param string $txt text
2592 function api_contactlink_to_array($txt)
2595 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2596 if ($r && count($match)==3) {
2598 'name' => $match[2],
2612 * return likes, dislikes and attend status for item
2614 * @param array $item array
2615 * @param string $type Return type (atom, rss, xml, json)
2618 * likes => int count,
2619 * dislikes => int count
2620 * @throws BadRequestException
2621 * @throws ImagickException
2622 * @throws InternalServerErrorException
2623 * @throws UnauthorizedException
2625 function api_format_items_activities($item, $type = "json")
2634 'attendmaybe' => [],
2638 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2639 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2641 while ($parent_item = Post::fetch($ret)) {
2642 // not used as result should be structured like other user data
2643 //builtin_activity_puller($i, $activities);
2645 // get user data and add it to the array of the activity
2646 $user = api_get_user($parent_item['author-id']);
2647 switch ($parent_item['verb']) {
2648 case Activity::LIKE:
2649 $activities['like'][] = $user;
2651 case Activity::DISLIKE:
2652 $activities['dislike'][] = $user;
2654 case Activity::ATTEND:
2655 $activities['attendyes'][] = $user;
2657 case Activity::ATTENDNO:
2658 $activities['attendno'][] = $user;
2660 case Activity::ATTENDMAYBE:
2661 $activities['attendmaybe'][] = $user;
2663 case Activity::ANNOUNCE:
2664 $activities['announce'][] = $user;
2673 if ($type == "xml") {
2674 $xml_activities = [];
2675 foreach ($activities as $k => $v) {
2676 // change xml element from "like" to "friendica:like"
2677 $xml_activities["friendica:".$k] = $v;
2678 // add user data into xml output
2680 foreach ($v as $user) {
2681 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2684 $activities = $xml_activities;
2691 * format items to be returned by api
2693 * @param array $items array of items
2694 * @param array $user_info
2695 * @param bool $filter_user filter items by $user_info
2696 * @param string $type Return type (atom, rss, xml, json)
2698 * @throws BadRequestException
2699 * @throws ImagickException
2700 * @throws InternalServerErrorException
2701 * @throws UnauthorizedException
2703 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2705 $a = Friendica\DI::app();
2709 if (empty($items)) {
2713 foreach ((array)$items as $item) {
2714 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2716 // Look if the posts are matching if they should be filtered by user id
2717 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2721 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2730 * @param array $item Item record
2731 * @param string $type Return format (atom, rss, xml, json)
2732 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2733 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2734 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2735 * @return array API-formatted status
2736 * @throws BadRequestException
2737 * @throws ImagickException
2738 * @throws InternalServerErrorException
2739 * @throws UnauthorizedException
2741 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2743 $a = Friendica\DI::app();
2745 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2746 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2749 DI::contentItem()->localize($item);
2751 $in_reply_to = api_in_reply_to($item);
2753 $converted = api_convert_item($item);
2755 if ($type == "xml") {
2756 $geo = "georss:point";
2762 'text' => $converted["text"],
2763 'truncated' => false,
2764 'created_at'=> api_date($item['created']),
2765 'in_reply_to_status_id' => $in_reply_to['status_id'],
2766 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2767 'source' => (($item['app']) ? $item['app'] : 'web'),
2768 'id' => intval($item['id']),
2769 'id_str' => (string) intval($item['id']),
2770 'in_reply_to_user_id' => $in_reply_to['user_id'],
2771 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2772 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2774 'favorited' => $item['starred'] ? true : false,
2775 'user' => $status_user,
2776 'friendica_author' => $author_user,
2777 'friendica_owner' => $owner_user,
2778 'friendica_private' => $item['private'] == Item::PRIVATE,
2779 //'entities' => NULL,
2780 'statusnet_html' => $converted["html"],
2781 'statusnet_conversation_id' => $item['parent'],
2782 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2783 'friendica_activities' => api_format_items_activities($item, $type),
2784 'friendica_title' => $item['title'],
2785 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2788 if (count($converted["attachments"]) > 0) {
2789 $status["attachments"] = $converted["attachments"];
2792 if (count($converted["entities"]) > 0) {
2793 $status["entities"] = $converted["entities"];
2796 if ($status["source"] == 'web') {
2797 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2798 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2799 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2802 $retweeted_item = [];
2805 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2806 $announce = api_get_announce($item);
2807 if (!empty($announce)) {
2808 $retweeted_item = $item;
2810 $status['friendica_owner'] = api_get_user($announce['author-id']);
2814 if (!empty($quoted_item)) {
2815 if ($quoted_item['id'] != $item['id']) {
2816 $quoted_status = api_format_item($quoted_item);
2817 /// @todo Only remove the attachments that are also contained in the quotes status
2818 unset($status['attachments']);
2819 unset($status['entities']);
2821 $conv_quoted = api_convert_item($quoted_item);
2822 $quoted_status = $status;
2823 unset($quoted_status['attachments']);
2824 unset($quoted_status['entities']);
2825 unset($quoted_status['statusnet_conversation_id']);
2826 $quoted_status['text'] = $conv_quoted['text'];
2827 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2829 $quoted_status["user"] = api_get_user($quoted_item["author-id"]);
2830 } catch (BadRequestException $e) {
2831 // user not found. should be found?
2832 /// @todo check if the user should be always found
2833 $quoted_status["user"] = [];
2836 unset($quoted_status['friendica_author']);
2837 unset($quoted_status['friendica_owner']);
2838 unset($quoted_status['friendica_activities']);
2839 unset($quoted_status['friendica_private']);
2842 if (!empty($retweeted_item)) {
2843 $retweeted_status = $status;
2844 unset($retweeted_status['friendica_author']);
2845 unset($retweeted_status['friendica_owner']);
2846 unset($retweeted_status['friendica_activities']);
2847 unset($retweeted_status['friendica_private']);
2848 unset($retweeted_status['statusnet_conversation_id']);
2849 $status['user'] = $status['friendica_owner'];
2851 $retweeted_status["user"] = api_get_user($retweeted_item["author-id"]);
2852 } catch (BadRequestException $e) {
2853 // user not found. should be found?
2854 /// @todo check if the user should be always found
2855 $retweeted_status["user"] = [];
2858 $rt_converted = api_convert_item($retweeted_item);
2860 $retweeted_status['text'] = $rt_converted["text"];
2861 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2862 $retweeted_status['friendica_html'] = $rt_converted["html"];
2863 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2865 if (!empty($quoted_status)) {
2866 $retweeted_status['quoted_status'] = $quoted_status;
2869 $status['friendica_author'] = $retweeted_status['user'];
2870 $status['retweeted_status'] = $retweeted_status;
2871 } elseif (!empty($quoted_status)) {
2872 $root_status = api_convert_item($item);
2874 $status['text'] = $root_status["text"];
2875 $status['statusnet_html'] = $root_status["html"];
2876 $status['quoted_status'] = $quoted_status;
2879 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2880 unset($status["user"]["uid"]);
2881 unset($status["user"]["self"]);
2883 if ($item["coord"] != "") {
2884 $coords = explode(' ', $item["coord"]);
2885 if (count($coords) == 2) {
2886 if ($type == "json") {
2887 $status["geo"] = ['type' => 'Point',
2888 'coordinates' => [(float) $coords[0],
2889 (float) $coords[1]]];
2890 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2891 $status["georss:point"] = $item["coord"];
2900 * Returns all lists the user subscribes to.
2902 * @param string $type Return type (atom, rss, xml, json)
2904 * @return array|string
2905 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2907 function api_lists_list($type)
2910 /// @TODO $ret is not filled here?
2911 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2914 /// @TODO move to top of file or somewhere better
2915 api_register_func('api/lists/list', 'api_lists_list', true);
2916 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2919 * Returns all groups the user owns.
2921 * @param string $type Return type (atom, rss, xml, json)
2923 * @return array|string
2924 * @throws BadRequestException
2925 * @throws ForbiddenException
2926 * @throws ImagickException
2927 * @throws InternalServerErrorException
2928 * @throws UnauthorizedException
2929 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2931 function api_lists_ownerships($type)
2935 if (api_user() === false) {
2936 throw new ForbiddenException();
2940 $user_info = api_get_user();
2941 $uid = $user_info['uid'];
2943 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2945 // loop through all groups
2947 foreach ($groups as $group) {
2948 if ($group['visible']) {
2954 'name' => $group['name'],
2955 'id' => intval($group['id']),
2956 'id_str' => (string) $group['id'],
2957 'user' => $user_info,
2961 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2964 /// @TODO move to top of file or somewhere better
2965 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2968 * Returns recent statuses from users in the specified group.
2970 * @param string $type Return type (atom, rss, xml, json)
2972 * @return array|string
2973 * @throws BadRequestException
2974 * @throws ForbiddenException
2975 * @throws ImagickException
2976 * @throws InternalServerErrorException
2977 * @throws UnauthorizedException
2978 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2980 function api_lists_statuses($type)
2984 $user_info = api_get_user();
2985 if (api_user() === false || $user_info === false) {
2986 throw new ForbiddenException();
2989 unset($_REQUEST["user_id"]);
2990 unset($_GET["user_id"]);
2992 unset($_REQUEST["screen_name"]);
2993 unset($_GET["screen_name"]);
2995 if (empty($_REQUEST['list_id'])) {
2996 throw new BadRequestException('list_id not specified');
3000 $count = $_REQUEST['count'] ?? 20;
3001 $page = $_REQUEST['page'] ?? 1;
3002 $since_id = $_REQUEST['since_id'] ?? 0;
3003 $max_id = $_REQUEST['max_id'] ?? 0;
3004 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3005 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3007 $start = max(0, ($page - 1) * $count);
3009 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3010 $gids = array_column($groups, 'contact-id');
3011 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3012 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3015 $condition[0] .= " AND `id` <= ?";
3016 $condition[] = $max_id;
3018 if ($exclude_replies > 0) {
3019 $condition[0] .= ' AND `gravity` = ?';
3020 $condition[] = GRAVITY_PARENT;
3022 if ($conversation_id > 0) {
3023 $condition[0] .= " AND `parent` = ?";
3024 $condition[] = $conversation_id;
3027 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3028 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3030 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3032 $data = ['status' => $items];
3037 $data = api_rss_extra($a, $data, $user_info);
3041 return DI::apiResponse()->formatData("statuses", $type, $data);
3044 /// @TODO move to top of file or somewhere better
3045 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3048 * Returns either the friends of the follower list
3050 * Considers friends and followers lists to be private and won't return
3051 * anything if any user_id parameter is passed.
3053 * @param string $qtype Either "friends" or "followers"
3054 * @return boolean|array
3055 * @throws BadRequestException
3056 * @throws ForbiddenException
3057 * @throws ImagickException
3058 * @throws InternalServerErrorException
3059 * @throws UnauthorizedException
3061 function api_statuses_f($qtype)
3065 if (api_user() === false) {
3066 throw new ForbiddenException();
3070 $count = $_GET['count'] ?? 20;
3071 $page = $_GET['page'] ?? 1;
3073 $start = max(0, ($page - 1) * $count);
3075 $user_info = api_get_user();
3077 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3078 /* this is to stop Hotot to load friends multiple times
3079 * I'm not sure if I'm missing return something or
3080 * is a bug in hotot. Workaround, meantime
3084 return array('$users' => $ret);*/
3089 if ($qtype == 'friends') {
3090 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3091 } elseif ($qtype == 'followers') {
3092 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3095 // friends and followers only for self
3096 if ($user_info['self'] == 0) {
3097 $sql_extra = " AND false ";
3100 if ($qtype == 'blocks') {
3101 $sql_filter = 'AND `blocked` AND NOT `pending`';
3102 } elseif ($qtype == 'incoming') {
3103 $sql_filter = 'AND `pending`';
3105 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3108 // @todo This query most likely can be replaced with a Contact::select...
3109 $r = DBA::toArray(DBA::p(
3124 foreach ($r as $cid) {
3125 $user = api_get_user($cid['nurl']);
3126 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3127 unset($user["uid"]);
3128 unset($user["self"]);
3135 return ['user' => $ret];
3140 * Returns the list of friends of the provided user
3142 * @deprecated By Twitter API in favor of friends/list
3144 * @param string $type Either "json" or "xml"
3145 * @return boolean|string|array
3146 * @throws BadRequestException
3147 * @throws ForbiddenException
3149 function api_statuses_friends($type)
3151 $data = api_statuses_f("friends");
3152 if ($data === false) {
3155 return DI::apiResponse()->formatData("users", $type, $data);
3159 * Returns the list of followers of the provided user
3161 * @deprecated By Twitter API in favor of friends/list
3163 * @param string $type Either "json" or "xml"
3164 * @return boolean|string|array
3165 * @throws BadRequestException
3166 * @throws ForbiddenException
3168 function api_statuses_followers($type)
3170 $data = api_statuses_f("followers");
3171 if ($data === false) {
3174 return DI::apiResponse()->formatData("users", $type, $data);
3177 /// @TODO move to top of file or somewhere better
3178 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3179 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3182 * Returns the list of blocked users
3184 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3186 * @param string $type Either "json" or "xml"
3188 * @return boolean|string|array
3189 * @throws BadRequestException
3190 * @throws ForbiddenException
3192 function api_blocks_list($type)
3194 $data = api_statuses_f('blocks');
3195 if ($data === false) {
3198 return DI::apiResponse()->formatData("users", $type, $data);
3201 /// @TODO move to top of file or somewhere better
3202 api_register_func('api/blocks/list', 'api_blocks_list', true);
3205 * Returns the list of pending users IDs
3207 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3209 * @param string $type Either "json" or "xml"
3211 * @return boolean|string|array
3212 * @throws BadRequestException
3213 * @throws ForbiddenException
3215 function api_friendships_incoming($type)
3217 $data = api_statuses_f('incoming');
3218 if ($data === false) {
3223 foreach ($data['user'] as $user) {
3224 $ids[] = $user['id'];
3227 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
3230 /// @TODO move to top of file or somewhere better
3231 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3234 * Sends a new direct message.
3236 * @param string $type Return type (atom, rss, xml, json)
3238 * @return array|string
3239 * @throws BadRequestException
3240 * @throws ForbiddenException
3241 * @throws ImagickException
3242 * @throws InternalServerErrorException
3243 * @throws NotFoundException
3244 * @throws UnauthorizedException
3245 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3247 function api_direct_messages_new($type)
3251 if (api_user() === false) {
3252 throw new ForbiddenException();
3255 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3259 $sender = api_get_user();
3262 if (!empty($_POST['screen_name'])) {
3263 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => api_user(), 'nick' => $_POST['screen_name']]);
3264 if (DBA::isResult($contacts)) {
3265 // Selecting the id by priority, friendica first
3266 api_best_nickname($contacts);
3268 $recipient = api_get_user($contacts[0]['nurl']);
3271 $recipient = api_get_user($_POST['user_id']);
3274 if (empty($recipient)) {
3275 throw new NotFoundException('Recipient not found');
3279 if (!empty($_REQUEST['replyto'])) {
3280 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => api_user(), 'id' => $_REQUEST['replyto']]);
3281 $replyto = $mail['parent-uri'];
3282 $sub = $mail['title'];
3284 if (!empty($_REQUEST['title'])) {
3285 $sub = $_REQUEST['title'];
3287 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3291 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3294 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3295 $ret = api_format_messages($mail, $recipient, $sender);
3297 $ret = ["error" => $id];
3300 $data = ['direct_message'=>$ret];
3306 $data = api_rss_extra($a, $data, $sender);
3310 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3313 /// @TODO move to top of file or somewhere better
3314 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3317 * delete a direct_message from mail table through api
3319 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3320 * @return string|array
3321 * @throws BadRequestException
3322 * @throws ForbiddenException
3323 * @throws ImagickException
3324 * @throws InternalServerErrorException
3325 * @throws UnauthorizedException
3326 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3328 function api_direct_messages_destroy($type)
3332 if (api_user() === false) {
3333 throw new ForbiddenException();
3337 $user_info = api_get_user();
3339 $id = $_REQUEST['id'] ?? 0;
3341 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3342 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3343 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3345 $uid = $user_info['uid'];
3346 // error if no id or parenturi specified (for clients posting parent-uri as well)
3347 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3348 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3349 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3352 // BadRequestException if no id specified (for clients using Twitter API)
3354 throw new BadRequestException('Message id not specified');
3357 // add parent-uri to sql command if specified by calling app
3358 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3360 // error message if specified id is not in database
3361 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3362 if ($verbose == "true") {
3363 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3364 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3366 /// @todo BadRequestException ok for Twitter API clients?
3367 throw new BadRequestException('message id not in database');
3371 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3373 if ($verbose == "true") {
3376 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3377 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
3379 $answer = ['result' => 'error', 'message' => 'unknown error'];
3380 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3383 /// @todo return JSON data like Twitter API not yet implemented
3386 /// @TODO move to top of file or somewhere better
3387 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3392 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3393 * @return string|array
3394 * @throws HTTPException\BadRequestException
3395 * @throws HTTPException\ExpectationFailedException
3396 * @throws HTTPException\ForbiddenException
3397 * @throws HTTPException\InternalServerErrorException
3398 * @throws HTTPException\NotFoundException
3399 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3401 function api_friendships_destroy($type)
3405 if ($uid === false) {
3406 throw new HTTPException\ForbiddenException();
3409 $owner = User::getOwnerDataById($uid);
3411 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3412 throw new HTTPException\NotFoundException('Error Processing Request');
3415 $contact_id = $_REQUEST['user_id'] ?? 0;
3417 if (empty($contact_id)) {
3418 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3419 throw new HTTPException\BadRequestException('no user_id specified');
3422 // Get Contact by given id
3423 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3425 if(!DBA::isResult($contact)) {
3426 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3427 throw new HTTPException\NotFoundException('no contact found to given ID');
3430 $url = $contact['url'];
3432 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3433 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3434 Strings::normaliseLink($url), $url];
3435 $contact = DBA::selectFirst('contact', [], $condition);
3437 if (!DBA::isResult($contact)) {
3438 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3439 throw new HTTPException\NotFoundException('Not following Contact');
3443 $result = Contact::terminateFriendship($owner, $contact);
3445 if ($result === null) {
3446 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3447 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3450 if ($result === false) {
3451 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3453 } catch (Exception $e) {
3454 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3455 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3458 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3459 unset($contact['uid']);
3460 unset($contact['self']);
3462 // Set screen_name since Twidere requests it
3463 $contact['screen_name'] = $contact['nick'];
3465 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
3468 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3472 * @param string $type Return type (atom, rss, xml, json)
3473 * @param string $box
3474 * @param string $verbose
3476 * @return array|string
3477 * @throws BadRequestException
3478 * @throws ForbiddenException
3479 * @throws ImagickException
3480 * @throws InternalServerErrorException
3481 * @throws UnauthorizedException
3483 function api_direct_messages_box($type, $box, $verbose)
3486 if (api_user() === false) {
3487 throw new ForbiddenException();
3490 $count = $_GET['count'] ?? 20;
3491 $page = $_REQUEST['page'] ?? 1;
3493 $since_id = $_REQUEST['since_id'] ?? 0;
3494 $max_id = $_REQUEST['max_id'] ?? 0;
3496 $user_id = $_REQUEST['user_id'] ?? '';
3497 $screen_name = $_REQUEST['screen_name'] ?? '';
3500 unset($_REQUEST["user_id"]);
3501 unset($_GET["user_id"]);
3503 unset($_REQUEST["screen_name"]);
3504 unset($_GET["screen_name"]);
3506 $user_info = api_get_user();
3507 if ($user_info === false) {
3508 throw new ForbiddenException();
3510 $profile_url = $user_info["url"];
3513 $start = max(0, ($page - 1) * $count);
3518 if ($box=="sentbox") {
3519 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3520 } elseif ($box == "conversation") {
3521 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3522 } elseif ($box == "all") {
3523 $sql_extra = "true";
3524 } elseif ($box == "inbox") {
3525 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3529 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3532 if ($user_id != "") {
3533 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3534 } elseif ($screen_name !="") {
3535 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3538 $r = DBA::toArray(DBA::p(
3539 "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 ?,?",
3545 if ($verbose == "true" && !DBA::isResult($r)) {
3546 $answer = ['result' => 'error', 'message' => 'no mails available'];
3547 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
3551 foreach ($r as $item) {
3552 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3553 $recipient = $user_info;
3554 $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
3555 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3556 $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
3557 $sender = $user_info;
3560 if (isset($recipient) && isset($sender)) {
3561 $ret[] = api_format_messages($item, $recipient, $sender);
3566 $data = ['direct_message' => $ret];
3571 $data = api_rss_extra($a, $data, $user_info);
3575 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3579 * Returns the most recent direct messages sent by the user.
3581 * @param string $type Return type (atom, rss, xml, json)
3583 * @return array|string
3584 * @throws BadRequestException
3585 * @throws ForbiddenException
3586 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3588 function api_direct_messages_sentbox($type)
3590 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3591 return api_direct_messages_box($type, "sentbox", $verbose);
3595 * Returns the most recent direct messages sent to the user.
3597 * @param string $type Return type (atom, rss, xml, json)
3599 * @return array|string
3600 * @throws BadRequestException
3601 * @throws ForbiddenException
3602 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3604 function api_direct_messages_inbox($type)
3606 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3607 return api_direct_messages_box($type, "inbox", $verbose);
3612 * @param string $type Return type (atom, rss, xml, json)
3614 * @return array|string
3615 * @throws BadRequestException
3616 * @throws ForbiddenException
3618 function api_direct_messages_all($type)
3620 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3621 return api_direct_messages_box($type, "all", $verbose);
3626 * @param string $type Return type (atom, rss, xml, json)
3628 * @return array|string
3629 * @throws BadRequestException
3630 * @throws ForbiddenException
3632 function api_direct_messages_conversation($type)
3634 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3635 return api_direct_messages_box($type, "conversation", $verbose);
3638 /// @TODO move to top of file or somewhere better
3639 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3640 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3641 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3642 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3645 * list all photos of the authenticated user
3647 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3648 * @return string|array
3649 * @throws ForbiddenException
3650 * @throws InternalServerErrorException
3652 function api_fr_photos_list($type)
3654 if (api_user() === false) {
3655 throw new ForbiddenException();
3657 $r = DBA::toArray(DBA::p(
3658 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3659 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3660 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3661 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3664 'image/jpeg' => 'jpg',
3665 'image/png' => 'png',
3666 'image/gif' => 'gif'
3668 $data = ['photo'=>[]];
3669 if (DBA::isResult($r)) {
3670 foreach ($r as $rr) {
3672 $photo['id'] = $rr['resource-id'];
3673 $photo['album'] = $rr['album'];
3674 $photo['filename'] = $rr['filename'];
3675 $photo['type'] = $rr['type'];
3676 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3677 $photo['created'] = $rr['created'];
3678 $photo['edited'] = $rr['edited'];
3679 $photo['desc'] = $rr['desc'];
3681 if ($type == "xml") {
3682 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3684 $photo['thumb'] = $thumb;
3685 $data['photo'][] = $photo;
3689 return DI::apiResponse()->formatData("photos", $type, $data);
3693 * upload a new photo or change an existing photo
3695 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3696 * @return string|array
3697 * @throws BadRequestException
3698 * @throws ForbiddenException
3699 * @throws ImagickException
3700 * @throws InternalServerErrorException
3701 * @throws NotFoundException
3703 function api_fr_photo_create_update($type)
3705 if (api_user() === false) {
3706 throw new ForbiddenException();
3709 $photo_id = $_REQUEST['photo_id'] ?? null;
3710 $desc = $_REQUEST['desc'] ?? null;
3711 $album = $_REQUEST['album'] ?? null;
3712 $album_new = $_REQUEST['album_new'] ?? null;
3713 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3714 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3715 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3716 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3717 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3719 // do several checks on input parameters
3720 // we do not allow calls without album string
3721 if ($album == null) {
3722 throw new BadRequestException("no albumname specified");
3724 // if photo_id == null --> we are uploading a new photo
3725 if ($photo_id == null) {
3728 // error if no media posted in create-mode
3729 if (empty($_FILES['media'])) {
3731 throw new BadRequestException("no media data submitted");
3734 // album_new will be ignored in create-mode
3739 // check if photo is existing in databasei
3740 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
3741 throw new BadRequestException("photo not available");
3745 // checks on acl strings provided by clients
3746 $acl_input_error = false;
3747 $acl_input_error |= check_acl_input($allow_cid);
3748 $acl_input_error |= check_acl_input($deny_cid);
3749 $acl_input_error |= check_acl_input($allow_gid);
3750 $acl_input_error |= check_acl_input($deny_gid);
3751 if ($acl_input_error) {
3752 throw new BadRequestException("acl data invalid");
3754 // now let's upload the new media in create-mode
3755 if ($mode == "create") {
3756 $media = $_FILES['media'];
3757 $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);
3759 // return success of updating or error message
3760 if (!is_null($data)) {
3761 return DI::apiResponse()->formatData("photo_create", $type, $data);
3763 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3767 // now let's do the changes in update-mode
3768 if ($mode == "update") {
3769 $updated_fields = [];
3771 if (!is_null($desc)) {
3772 $updated_fields['desc'] = $desc;
3775 if (!is_null($album_new)) {
3776 $updated_fields['album'] = $album_new;
3779 if (!is_null($allow_cid)) {
3780 $allow_cid = trim($allow_cid);
3781 $updated_fields['allow_cid'] = $allow_cid;
3784 if (!is_null($deny_cid)) {
3785 $deny_cid = trim($deny_cid);
3786 $updated_fields['deny_cid'] = $deny_cid;
3789 if (!is_null($allow_gid)) {
3790 $allow_gid = trim($allow_gid);
3791 $updated_fields['allow_gid'] = $allow_gid;
3794 if (!is_null($deny_gid)) {
3795 $deny_gid = trim($deny_gid);
3796 $updated_fields['deny_gid'] = $deny_gid;
3800 if (count($updated_fields) > 0) {
3801 $nothingtodo = false;
3802 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
3804 $nothingtodo = true;
3807 if (!empty($_FILES['media'])) {
3808 $nothingtodo = false;
3809 $media = $_FILES['media'];
3810 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3811 if (!is_null($data)) {
3812 return DI::apiResponse()->formatData("photo_update", $type, $data);
3816 // return success of updating or error message
3818 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3819 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3822 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3823 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3825 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3828 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3832 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3834 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3835 * @return string|array
3836 * @throws BadRequestException
3837 * @throws ForbiddenException
3838 * @throws InternalServerErrorException
3839 * @throws NotFoundException
3841 function api_fr_photo_detail($type)
3843 if (api_user() === false) {
3844 throw new ForbiddenException();
3846 if (empty($_REQUEST['photo_id'])) {
3847 throw new BadRequestException("No photo id.");
3850 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3851 $photo_id = $_REQUEST['photo_id'];
3853 // prepare json/xml output with data from database for the requested photo
3854 $data = prepare_photo_data($type, $scale, $photo_id);
3856 return DI::apiResponse()->formatData("photo_detail", $type, $data);
3861 * updates the profile image for the user (either a specified profile or the default profile)
3863 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3865 * @return string|array
3866 * @throws BadRequestException
3867 * @throws ForbiddenException
3868 * @throws ImagickException
3869 * @throws InternalServerErrorException
3870 * @throws NotFoundException
3871 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3873 function api_account_update_profile_image($type)
3875 if (api_user() === false) {
3876 throw new ForbiddenException();
3879 $profile_id = $_REQUEST['profile_id'] ?? 0;
3881 // error if image data is missing
3882 if (empty($_FILES['image'])) {
3883 throw new BadRequestException("no media data submitted");
3886 // check if specified profile id is valid
3887 if ($profile_id != 0) {
3888 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
3889 // error message if specified profile id is not in database
3890 if (!DBA::isResult($profile)) {
3891 throw new BadRequestException("profile_id not available");
3893 $is_default_profile = $profile['is-default'];
3895 $is_default_profile = 1;
3898 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3900 if (!empty($_FILES['image'])) {
3901 $media = $_FILES['image'];
3902 } elseif (!empty($_FILES['media'])) {
3903 $media = $_FILES['media'];
3905 // save new profile image
3906 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3909 if (is_array($media['type'])) {
3910 $filetype = $media['type'][0];
3912 $filetype = $media['type'];
3914 if ($filetype == "image/jpeg") {
3916 } elseif ($filetype == "image/png") {
3919 throw new InternalServerErrorException('Unsupported filetype');
3922 // change specified profile or all profiles to the new resource-id
3923 if ($is_default_profile) {
3924 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
3925 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3927 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3928 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3929 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
3932 Contact::updateSelfFromUserID(api_user(), true);
3934 // Update global directory in background
3935 Profile::publishUpdate(api_user());
3937 // output for client
3939 return api_account_verify_credentials($type);
3941 // SaveMediaToDatabase failed for some reason
3942 throw new InternalServerErrorException("image upload failed");
3946 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3947 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3948 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3949 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3950 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3951 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3954 * Update user profile
3956 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3958 * @return array|string
3959 * @throws BadRequestException
3960 * @throws ForbiddenException
3961 * @throws ImagickException
3962 * @throws InternalServerErrorException
3963 * @throws UnauthorizedException
3965 function api_account_update_profile($type)
3967 $local_user = api_user();
3968 $api_user = api_get_user();
3970 if (!empty($_POST['name'])) {
3971 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
3972 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
3973 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
3974 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3977 if (isset($_POST['description'])) {
3978 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
3979 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
3980 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3983 Profile::publishUpdate($local_user);
3985 return api_account_verify_credentials($type);
3988 /// @TODO move to top of file or somewhere better
3989 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3993 * @param string $acl_string
3997 function check_acl_input($acl_string)
3999 if (empty($acl_string)) {
4003 $contact_not_found = false;
4005 // split <x><y><z> into array of cid's
4006 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4008 // check for each cid if it is available on server
4009 $cid_array = $array[0];
4010 foreach ($cid_array as $cid) {
4011 $cid = str_replace("<", "", $cid);
4012 $cid = str_replace(">", "", $cid);
4013 $condition = ['id' => $cid, 'uid' => api_user()];
4014 $contact_not_found |= !DBA::exists('contact', $condition);
4016 return $contact_not_found;
4020 * @param string $mediatype
4021 * @param array $media
4022 * @param string $type
4023 * @param string $album
4024 * @param string $allow_cid
4025 * @param string $deny_cid
4026 * @param string $allow_gid
4027 * @param string $deny_gid
4028 * @param string $desc
4029 * @param integer $phototype
4030 * @param boolean $visibility
4031 * @param string $photo_id
4033 * @throws BadRequestException
4034 * @throws ForbiddenException
4035 * @throws ImagickException
4036 * @throws InternalServerErrorException
4037 * @throws NotFoundException
4038 * @throws UnauthorizedException
4040 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)
4048 if (is_array($media)) {
4049 if (is_array($media['tmp_name'])) {
4050 $src = $media['tmp_name'][0];
4052 $src = $media['tmp_name'];
4054 if (is_array($media['name'])) {
4055 $filename = basename($media['name'][0]);
4057 $filename = basename($media['name']);
4059 if (is_array($media['size'])) {
4060 $filesize = intval($media['size'][0]);
4062 $filesize = intval($media['size']);
4064 if (is_array($media['type'])) {
4065 $filetype = $media['type'][0];
4067 $filetype = $media['type'];
4071 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4074 "File upload src: " . $src . " - filename: " . $filename .
4075 " - size: " . $filesize . " - type: " . $filetype);
4077 // check if there was a php upload error
4078 if ($filesize == 0 && $media['error'] == 1) {
4079 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4081 // check against max upload size within Friendica instance
4082 $maximagesize = DI::config()->get('system', 'maximagesize');
4083 if ($maximagesize && ($filesize > $maximagesize)) {
4084 $formattedBytes = Strings::formatBytes($maximagesize);
4085 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4088 // create Photo instance with the data of the image
4089 $imagedata = @file_get_contents($src);
4090 $Image = new Image($imagedata, $filetype);
4091 if (!$Image->isValid()) {
4092 throw new InternalServerErrorException("unable to process image data");
4095 // check orientation of image
4096 $Image->orient($src);
4099 // check max length of images on server
4100 $max_length = DI::config()->get('system', 'max_image_length');
4101 if ($max_length > 0) {
4102 $Image->scaleDown($max_length);
4103 logger::info("File upload: Scaling picture to new size " . $max_length);
4105 $width = $Image->getWidth();
4106 $height = $Image->getHeight();
4108 // create a new resource-id if not already provided
4109 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4111 if ($mediatype == "photo") {
4112 // upload normal image (scales 0, 1, 2)
4113 logger::info("photo upload: starting new photo upload");
4115 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4117 logger::notice("photo upload: image upload with scale 0 (original size) failed");
4119 if ($width > 640 || $height > 640) {
4120 $Image->scaleDown(640);
4121 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4123 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
4127 if ($width > 320 || $height > 320) {
4128 $Image->scaleDown(320);
4129 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4131 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
4134 logger::info("photo upload: new photo upload ended");
4135 } elseif ($mediatype == "profileimage") {
4136 // upload profile image (scales 4, 5, 6)
4137 logger::info("photo upload: starting new profile image upload");
4139 if ($width > 300 || $height > 300) {
4140 $Image->scaleDown(300);
4141 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4143 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
4147 if ($width > 80 || $height > 80) {
4148 $Image->scaleDown(80);
4149 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4151 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
4155 if ($width > 48 || $height > 48) {
4156 $Image->scaleDown(48);
4157 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4159 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
4162 $Image->__destruct();
4163 logger::info("photo upload: new profile image upload ended");
4167 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4168 if ($photo_id == null && $mediatype == "photo") {
4169 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4171 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4172 return prepare_photo_data($type, false, $resource_id);
4174 throw new InternalServerErrorException("image upload failed");
4180 * @param string $hash
4181 * @param string $allow_cid
4182 * @param string $deny_cid
4183 * @param string $allow_gid
4184 * @param string $deny_gid
4185 * @param string $filetype
4186 * @param boolean $visibility
4187 * @throws InternalServerErrorException
4189 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4191 // get data about the api authenticated user
4192 $uri = Item::newURI(intval(api_user()));
4193 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4196 $arr['guid'] = System::createUUID();
4197 $arr['uid'] = intval(api_user());
4199 $arr['type'] = 'photo';
4201 $arr['resource-id'] = $hash;
4202 $arr['contact-id'] = $owner_record['id'];
4203 $arr['owner-name'] = $owner_record['name'];
4204 $arr['owner-link'] = $owner_record['url'];
4205 $arr['owner-avatar'] = $owner_record['thumb'];
4206 $arr['author-name'] = $owner_record['name'];
4207 $arr['author-link'] = $owner_record['url'];
4208 $arr['author-avatar'] = $owner_record['thumb'];
4210 $arr['allow_cid'] = $allow_cid;
4211 $arr['allow_gid'] = $allow_gid;
4212 $arr['deny_cid'] = $deny_cid;
4213 $arr['deny_gid'] = $deny_gid;
4214 $arr['visible'] = $visibility;
4218 'image/jpeg' => 'jpg',
4219 'image/png' => 'png',
4220 'image/gif' => 'gif'
4223 // adds link to the thumbnail scale photo
4224 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4225 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4228 // do the magic for storing the item in the database and trigger the federation to other contacts
4234 * @param string $type
4236 * @param string $photo_id
4239 * @throws BadRequestException
4240 * @throws ForbiddenException
4241 * @throws ImagickException
4242 * @throws InternalServerErrorException
4243 * @throws NotFoundException
4244 * @throws UnauthorizedException
4246 function prepare_photo_data($type, $scale, $photo_id)
4249 $user_info = api_get_user();
4251 if ($user_info === false) {
4252 throw new ForbiddenException();
4255 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4256 $data_sql = ($scale === false ? "" : "data, ");
4258 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4259 // clients needs to convert this in their way for further processing
4260 $r = DBA::toArray(DBA::p(
4261 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4262 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4263 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4264 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4265 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4266 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4272 'image/jpeg' => 'jpg',
4273 'image/png' => 'png',
4274 'image/gif' => 'gif'
4277 // prepare output data for photo
4278 if (DBA::isResult($r)) {
4279 $data = ['photo' => $r[0]];
4280 $data['photo']['id'] = $data['photo']['resource-id'];
4281 if ($scale !== false) {
4282 $data['photo']['data'] = base64_encode($data['photo']['data']);
4284 unset($data['photo']['datasize']); //needed only with scale param
4286 if ($type == "xml") {
4287 $data['photo']['links'] = [];
4288 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4289 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4291 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4294 $data['photo']['link'] = [];
4295 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4297 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4298 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4302 unset($data['photo']['resource-id']);
4303 unset($data['photo']['minscale']);
4304 unset($data['photo']['maxscale']);
4306 throw new NotFoundException();
4309 // retrieve item element for getting activities (like, dislike etc.) related to photo
4310 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4311 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4312 if (!DBA::isResult($item)) {
4313 throw new NotFoundException('Photo-related item not found.');
4316 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4318 // retrieve comments on photo
4319 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4320 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4322 $statuses = Post::selectForUser(api_user(), [], $condition);
4324 // prepare output of comments
4325 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4327 if ($type == "xml") {
4329 foreach ($commentData as $comment) {
4330 $comments[$k++ . ":comment"] = $comment;
4333 foreach ($commentData as $comment) {
4334 $comments[] = $comment;
4337 $data['photo']['friendica_comments'] = $comments;
4339 // include info if rights on photo and rights on item are mismatching
4340 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4341 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4342 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4343 $data['photo']['deny_gid'] != $item['deny_gid'];
4344 $data['photo']['rights_mismatch'] = $rights_mismatch;
4350 * Return an item with announcer data if it had been announced
4352 * @param array $item Item array
4353 * @return array Item array with announce data
4355 function api_get_announce($item)
4357 // Quit if the item already has got a different owner and author
4358 if ($item['owner-id'] != $item['author-id']) {
4362 // Don't change original or Diaspora posts
4363 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4367 // Quit if we do now the original author and it had been a post from a native network
4368 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4372 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4373 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4374 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4375 if (!DBA::isResult($announce)) {
4379 return array_merge($item, $announce);
4384 * @param array $item
4389 function api_in_reply_to($item)
4393 $in_reply_to['status_id'] = null;
4394 $in_reply_to['user_id'] = null;
4395 $in_reply_to['status_id_str'] = null;
4396 $in_reply_to['user_id_str'] = null;
4397 $in_reply_to['screen_name'] = null;
4399 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4400 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4401 if (DBA::isResult($parent)) {
4402 $in_reply_to['status_id'] = intval($parent['id']);
4404 $in_reply_to['status_id'] = intval($item['parent']);
4407 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4409 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4410 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4412 if (DBA::isResult($parent)) {
4413 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4414 $in_reply_to['user_id'] = intval($parent['author-id']);
4415 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4418 // There seems to be situation, where both fields are identical:
4419 // https://github.com/friendica/friendica/issues/1010
4420 // This is a bugfix for that.
4421 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4422 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']]);
4423 $in_reply_to['status_id'] = null;
4424 $in_reply_to['user_id'] = null;
4425 $in_reply_to['status_id_str'] = null;
4426 $in_reply_to['user_id_str'] = null;
4427 $in_reply_to['screen_name'] = null;
4431 return $in_reply_to;
4436 * @param string $text
4439 * @throws InternalServerErrorException
4441 function api_clean_plain_items($text)
4443 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4445 $text = BBCode::cleanPictureLinks($text);
4446 $URLSearchString = "^\[\]";
4448 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4450 if ($include_entities == "true") {
4451 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4454 // Simplify "attachment" element
4455 $text = BBCode::removeAttachment($text);
4462 * @param array $contacts
4466 function api_best_nickname(&$contacts)
4470 if (count($contacts) == 0) {
4474 foreach ($contacts as $contact) {
4475 if ($contact["network"] == "") {
4476 $contact["network"] = "dfrn";
4477 $best_contact = [$contact];
4481 if (sizeof($best_contact) == 0) {
4482 foreach ($contacts as $contact) {
4483 if ($contact["network"] == "dfrn") {
4484 $best_contact = [$contact];
4489 if (sizeof($best_contact) == 0) {
4490 foreach ($contacts as $contact) {
4491 if ($contact["network"] == "dspr") {
4492 $best_contact = [$contact];
4497 if (sizeof($best_contact) == 0) {
4498 foreach ($contacts as $contact) {
4499 if ($contact["network"] == "stat") {
4500 $best_contact = [$contact];
4505 if (sizeof($best_contact) == 0) {
4506 foreach ($contacts as $contact) {
4507 if ($contact["network"] == "pump") {
4508 $best_contact = [$contact];
4513 if (sizeof($best_contact) == 0) {
4514 foreach ($contacts as $contact) {
4515 if ($contact["network"] == "twit") {
4516 $best_contact = [$contact];
4521 if (sizeof($best_contact) == 1) {
4522 $contacts = $best_contact;
4524 $contacts = [$contacts[0]];
4529 * Return all or a specified group of the user with the containing contacts.
4531 * @param string $type Return type (atom, rss, xml, json)
4533 * @return array|string
4534 * @throws BadRequestException
4535 * @throws ForbiddenException
4536 * @throws ImagickException
4537 * @throws InternalServerErrorException
4538 * @throws UnauthorizedException
4540 function api_friendica_group_show($type)
4544 if (api_user() === false) {
4545 throw new ForbiddenException();
4549 $user_info = api_get_user();
4550 $gid = $_REQUEST['gid'] ?? 0;
4551 $uid = $user_info['uid'];
4553 // get data of the specified group id or all groups if not specified
4555 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4557 // error message if specified gid is not in database
4558 if (!DBA::isResult($groups)) {
4559 throw new BadRequestException("gid not available");
4562 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4565 // loop through all groups and retrieve all members for adding data in the user array
4567 foreach ($groups as $rr) {
4568 $members = Contact\Group::getById($rr['id']);
4571 if ($type == "xml") {
4572 $user_element = "users";
4574 foreach ($members as $member) {
4575 $user = api_get_user($member['nurl']);
4576 $users[$k++.":user"] = $user;
4579 $user_element = "user";
4580 foreach ($members as $member) {
4581 $user = api_get_user($member['nurl']);
4585 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4587 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
4590 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4595 * @param string $type Return type (atom, rss, xml, json)
4597 * @return array|string
4598 * @throws BadRequestException
4599 * @throws ForbiddenException
4600 * @throws ImagickException
4601 * @throws InternalServerErrorException
4602 * @throws UnauthorizedException
4603 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4605 function api_lists_destroy($type)
4609 if (api_user() === false) {
4610 throw new ForbiddenException();
4614 $user_info = api_get_user();
4615 $gid = $_REQUEST['list_id'] ?? 0;
4616 $uid = $user_info['uid'];
4618 // error if no gid specified
4620 throw new BadRequestException('gid not specified');
4623 // get data of the specified group id
4624 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4625 // error message if specified gid is not in database
4627 throw new BadRequestException('gid not available');
4630 if (Group::remove($gid)) {
4632 'name' => $group['name'],
4633 'id' => intval($gid),
4634 'id_str' => (string) $gid,
4635 'user' => $user_info
4638 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4642 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4645 * Add a new group to the database.
4647 * @param string $name Group name
4648 * @param int $uid User ID
4649 * @param array $users List of users to add to the group
4652 * @throws BadRequestException
4654 function group_create($name, $uid, $users = [])
4656 // error if no name specified
4658 throw new BadRequestException('group name not specified');
4661 // error message if specified group name already exists
4662 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4663 throw new BadRequestException('group name already exists');
4666 // Check if the group needs to be reactivated
4667 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4668 $reactivate_group = true;
4672 $ret = Group::create($uid, $name);
4674 $gid = Group::getIdByName($uid, $name);
4676 throw new BadRequestException('other API error');
4680 $erroraddinguser = false;
4682 foreach ($users as $user) {
4683 $cid = $user['cid'];
4684 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4685 Group::addMember($gid, $cid);
4687 $erroraddinguser = true;
4688 $errorusers[] = $cid;
4692 // return success message incl. missing users in array
4693 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4695 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4699 * Create the specified group with the posted array of contacts.
4701 * @param string $type Return type (atom, rss, xml, json)
4703 * @return array|string
4704 * @throws BadRequestException
4705 * @throws ForbiddenException
4706 * @throws ImagickException
4707 * @throws InternalServerErrorException
4708 * @throws UnauthorizedException
4710 function api_friendica_group_create($type)
4714 if (api_user() === false) {
4715 throw new ForbiddenException();
4719 $user_info = api_get_user();
4720 $name = $_REQUEST['name'] ?? '';
4721 $uid = $user_info['uid'];
4722 $json = json_decode($_POST['json'], true);
4723 $users = $json['user'];
4725 $success = group_create($name, $uid, $users);
4727 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
4730 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4733 * Create a new group.
4735 * @param string $type Return type (atom, rss, xml, json)
4737 * @return array|string
4738 * @throws BadRequestException
4739 * @throws ForbiddenException
4740 * @throws ImagickException
4741 * @throws InternalServerErrorException
4742 * @throws UnauthorizedException
4743 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4745 function api_lists_create($type)
4749 if (api_user() === false) {
4750 throw new ForbiddenException();
4754 $user_info = api_get_user();
4755 $name = $_REQUEST['name'] ?? '';
4756 $uid = $user_info['uid'];
4758 $success = group_create($name, $uid);
4759 if ($success['success']) {
4761 'name' => $success['name'],
4762 'id' => intval($success['gid']),
4763 'id_str' => (string) $success['gid'],
4764 'user' => $user_info
4767 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4771 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4774 * Update the specified group with the posted array of contacts.
4776 * @param string $type Return type (atom, rss, xml, json)
4778 * @return array|string
4779 * @throws BadRequestException
4780 * @throws ForbiddenException
4781 * @throws ImagickException
4782 * @throws InternalServerErrorException
4783 * @throws UnauthorizedException
4785 function api_friendica_group_update($type)
4789 if (api_user() === false) {
4790 throw new ForbiddenException();
4794 $user_info = api_get_user();
4795 $uid = $user_info['uid'];
4796 $gid = $_REQUEST['gid'] ?? 0;
4797 $name = $_REQUEST['name'] ?? '';
4798 $json = json_decode($_POST['json'], true);
4799 $users = $json['user'];
4801 // error if no name specified
4803 throw new BadRequestException('group name not specified');
4806 // error if no gid specified
4808 throw new BadRequestException('gid not specified');
4812 $members = Contact\Group::getById($gid);
4813 foreach ($members as $member) {
4814 $cid = $member['id'];
4815 foreach ($users as $user) {
4816 $found = ($user['cid'] == $cid ? true : false);
4818 if (!isset($found) || !$found) {
4819 $gid = Group::getIdByName($uid, $name);
4820 Group::removeMember($gid, $cid);
4825 $erroraddinguser = false;
4827 foreach ($users as $user) {
4828 $cid = $user['cid'];
4830 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4831 Group::addMember($gid, $cid);
4833 $erroraddinguser = true;
4834 $errorusers[] = $cid;
4838 // return success message incl. missing users in array
4839 $status = ($erroraddinguser ? "missing user" : "ok");
4840 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4841 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4844 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4847 * Update information about a group.
4849 * @param string $type Return type (atom, rss, xml, json)
4851 * @return array|string
4852 * @throws BadRequestException
4853 * @throws ForbiddenException
4854 * @throws ImagickException
4855 * @throws InternalServerErrorException
4856 * @throws UnauthorizedException
4857 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4859 function api_lists_update($type)
4863 if (api_user() === false) {
4864 throw new ForbiddenException();
4868 $user_info = api_get_user();
4869 $gid = $_REQUEST['list_id'] ?? 0;
4870 $name = $_REQUEST['name'] ?? '';
4871 $uid = $user_info['uid'];
4873 // error if no gid specified
4875 throw new BadRequestException('gid not specified');
4878 // get data of the specified group id
4879 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4880 // error message if specified gid is not in database
4882 throw new BadRequestException('gid not available');
4885 if (Group::update($gid, $name)) {
4888 'id' => intval($gid),
4889 'id_str' => (string) $gid,
4890 'user' => $user_info
4893 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4897 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4900 * Set notification as seen and returns associated item (if possible)
4902 * POST request with 'id' param as notification id
4904 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4905 * @return string|array
4906 * @throws BadRequestException
4907 * @throws ForbiddenException
4908 * @throws ImagickException
4909 * @throws InternalServerErrorException
4910 * @throws UnauthorizedException
4912 function api_friendica_notification_seen($type)
4915 $user_info = api_get_user();
4917 if (api_user() === false || $user_info === false) {
4918 throw new ForbiddenException();
4920 if (DI::args()->getArgc() !== 4) {
4921 throw new BadRequestException('Invalid argument count');
4924 $id = intval($_REQUEST['id'] ?? 0);
4927 $Notify = DI::notify()->selectOneById($id);
4928 if ($Notify->uid !== api_user()) {
4929 throw new NotFoundException();
4932 if ($Notify->uriId) {
4933 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4937 DI::notify()->save($Notify);
4939 if ($Notify->otype === Notification\ObjectType::ITEM) {
4940 $item = Post::selectFirstForUser(api_user(), [], ['id' => $Notify->iid, 'uid' => api_user()]);
4941 if (DBA::isResult($item)) {
4942 // we found the item, return it to the user
4943 $ret = api_format_items([$item], $user_info, false, $type);
4944 $data = ['status' => $ret];
4945 return DI::apiResponse()->formatData('status', $type, $data);
4947 // the item can't be found, but we set the notification as seen, so we count this as a success
4950 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4951 } catch (NotFoundException $e) {
4952 throw new BadRequestException('Invalid argument', $e);
4953 } catch (Exception $e) {
4954 throw new InternalServerErrorException('Internal Server exception', $e);
4958 /// @TODO move to top of file or somewhere better
4959 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4962 * search for direct_messages containing a searchstring through api
4964 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4965 * @param string $box
4966 * @return string|array (success: success=true if found and search_result contains found messages,
4967 * success=false if nothing was found, search_result='nothing found',
4968 * error: result=error with error message)
4969 * @throws BadRequestException
4970 * @throws ForbiddenException
4971 * @throws ImagickException
4972 * @throws InternalServerErrorException
4973 * @throws UnauthorizedException
4975 function api_friendica_direct_messages_search($type, $box = "")
4979 if (api_user() === false) {
4980 throw new ForbiddenException();
4984 $user_info = api_get_user();
4985 $searchstring = $_REQUEST['searchstring'] ?? '';
4986 $uid = $user_info['uid'];
4988 // error if no searchstring specified
4989 if ($searchstring == "") {
4990 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4991 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4994 // get data for the specified searchstring
4995 $r = DBA::toArray(DBA::p(
4996 "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",
4998 '%'.$searchstring.'%'
5001 $profile_url = $user_info["url"];
5003 // message if nothing was found
5004 if (!DBA::isResult($r)) {
5005 $success = ['success' => false, 'search_results' => 'problem with query'];
5006 } elseif (count($r) == 0) {
5007 $success = ['success' => false, 'search_results' => 'nothing found'];
5010 foreach ($r as $item) {
5011 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5012 $recipient = $user_info;
5013 $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
5014 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5015 $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
5016 $sender = $user_info;
5019 if (isset($recipient) && isset($sender)) {
5020 $ret[] = api_format_messages($item, $recipient, $sender);
5023 $success = ['success' => true, 'search_results' => $ret];
5026 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
5029 /// @TODO move to top of file or somewhere better
5030 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5033 * Number of comments
5035 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
5037 * @param object $data [Status, Status]
5041 function bindComments(&$data)
5043 if (count($data) == 0) {
5049 foreach ($data as $item) {
5050 $ids[] = $item['id'];
5053 $idStr = DBA::escape(implode(', ', $ids));
5054 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
5055 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
5056 $itemsData = DBA::toArray($items);
5058 foreach ($itemsData as $item) {
5059 $comments[$item['parent']] = $item['comments'];
5062 foreach ($data as $idx => $item) {
5064 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
5069 @TODO Maybe open to implement?
5071 [pagename] => api/1.1/statuses/lookup.json
5072 [id] => 605138389168451584
5073 [include_cards] => true
5074 [cards_platform] => Android-12
5075 [include_entities] => true
5076 [include_my_retweet] => 1
5078 [include_reply_count] => true
5079 [include_descendent_reply_count] => true
5083 Not implemented by now:
5084 statuses/retweets_of_me
5089 account/update_location
5090 account/update_profile_background_image
5093 friendica/profile/update
5094 friendica/profile/create
5095 friendica/profile/delete
5097 Not implemented in status.net:
5098 statuses/retweeted_to_me
5099 statuses/retweeted_by_me
5100 direct_messages/destroy
5102 account/update_delivery_device
5103 notifications/follow