3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Core\System;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Group;
37 use Friendica\Model\Item;
38 use Friendica\Model\Mail;
39 use Friendica\Model\Notification;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Profile;
43 use Friendica\Model\User;
44 use Friendica\Model\Verb;
45 use Friendica\Module\BaseApi;
46 use Friendica\Network\HTTPException;
47 use Friendica\Network\HTTPException\BadRequestException;
48 use Friendica\Network\HTTPException\ForbiddenException;
49 use Friendica\Network\HTTPException\InternalServerErrorException;
50 use Friendica\Network\HTTPException\MethodNotAllowedException;
51 use Friendica\Network\HTTPException\NotFoundException;
52 use Friendica\Network\HTTPException\TooManyRequestsException;
53 use Friendica\Network\HTTPException\UnauthorizedException;
54 use Friendica\Object\Image;
55 use Friendica\Protocol\Activity;
56 use Friendica\Security\BasicAuth;
57 use Friendica\Security\OAuth;
58 use Friendica\Util\DateTimeFormat;
59 use Friendica\Util\Images;
60 use Friendica\Util\Network;
61 use Friendica\Util\Proxy;
62 use Friendica\Util\Strings;
64 require_once __DIR__ . '/../mod/item.php';
65 require_once __DIR__ . '/../mod/wall_upload.php';
67 define('API_METHOD_ANY', '*');
68 define('API_METHOD_GET', 'GET');
69 define('API_METHOD_POST', 'POST,PUT');
70 define('API_METHOD_DELETE', 'POST,DELETE');
72 define('API_LOG_PREFIX', 'API {action} - ');
80 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
81 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
82 * into a page, and visitors will post something without noticing it).
86 $user = OAuth::getCurrentUserID();
91 if (!empty($_SESSION['allow_api'])) {
99 * Get source name from API client
101 * Clients can send 'source' parameter to be show in post metadata
102 * as "sent via <source>".
103 * Some clients doesn't send a source param, we support ones we know
104 * (only Twidere, atm)
107 * Client source name, default to "api" if unset/unknown
110 function api_source()
112 if (requestdata('source')) {
113 return requestdata('source');
116 // Support for known clients that doesn't send a source name
117 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
118 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
122 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
124 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
131 * Format date for API
133 * @param string $str Source date, as UTC
134 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
137 function api_date($str)
139 // Wed May 23 06:01:13 +0000 2007
140 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
144 * Register a function to be the endpoint for defined API path.
146 * @param string $path API URL path, relative to DI::baseUrl()
147 * @param string $func Function name to call on path request
148 * @param bool $auth API need logged user
149 * @param string $method HTTP method reqiured to call this endpoint.
150 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
151 * Default to API_METHOD_ANY
153 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
163 // Workaround for hotot
164 $path = str_replace("api/", "api/1.1/", $path);
174 * Check HTTP method of called API
176 * API endpoints can define which HTTP method to accept when called.
177 * This function check the current HTTP method agains endpoint
180 * @param string $method Required methods, uppercase, separated by comma
183 function api_check_method($method)
185 if ($method == "*") {
188 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
192 * Main API entry point
194 * Authenticate user, call registered API function, set HTTP headers
197 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
198 * @return string|array API call result
201 function api_call(App $a, App\Arguments $args = null)
203 global $API, $called_api;
210 if (strpos($args->getCommand(), ".xml") > 0) {
213 if (strpos($args->getCommand(), ".json") > 0) {
216 if (strpos($args->getCommand(), ".rss") > 0) {
219 if (strpos($args->getCommand(), ".atom") > 0) {
224 foreach ($API as $p => $info) {
225 if (strpos($args->getCommand(), $p) === 0) {
226 if (!api_check_method($info['method'])) {
227 throw new MethodNotAllowedException();
230 $called_api = explode("/", $p);
232 if (!empty($info['auth']) && api_user() === false) {
233 BasicAuth::getCurrentUserID(true);
234 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
237 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
239 $stamp = microtime(true);
240 $return = call_user_func($info['func'], $type);
241 $duration = floatval(microtime(true) - $stamp);
243 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
245 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
247 if (false === $return) {
249 * api function returned false withour throw an
250 * exception. This should not happend, throw a 500
252 throw new InternalServerErrorException();
257 header("Content-Type: text/xml");
260 header("Content-Type: application/json");
261 if (!empty($return)) {
262 $json = json_encode(end($return));
263 if (!empty($_GET['callback'])) {
264 $json = $_GET['callback'] . "(" . $json . ")";
270 header("Content-Type: application/rss+xml");
271 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
274 header("Content-Type: application/atom+xml");
275 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
282 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
283 throw new NotFoundException();
284 } catch (HTTPException $e) {
285 BaseApi::error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
290 * Set values for RSS template
293 * @param array $arr Array to be passed to template
294 * @param array $user_info User info
296 * @throws BadRequestException
297 * @throws ImagickException
298 * @throws InternalServerErrorException
299 * @throws UnauthorizedException
300 * @todo find proper type-hints
302 function api_rss_extra(App $a, $arr, $user_info)
304 if (is_null($user_info)) {
305 $user_info = api_get_user();
308 $arr['$user'] = $user_info;
310 'alternate' => $user_info['url'],
311 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
312 'base' => DI::baseUrl(),
313 'updated' => api_date(null),
314 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
315 'language' => $user_info['lang'],
316 'logo' => DI::baseUrl() . "/images/friendica-32.png",
324 * Unique contact to contact url.
326 * @param int $id Contact id
327 * @return bool|string
328 * Contact url or False if contact id is unknown
331 function api_unique_id_to_nurl($id)
333 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
335 if (DBA::isResult($r)) {
343 * Get user info array.
346 * @param int|string $contact_id Contact ID or URL
348 * @throws BadRequestException
349 * @throws ImagickException
350 * @throws InternalServerErrorException
351 * @throws UnauthorizedException
353 function api_get_user($contact_id = null)
361 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
363 // Searching for contact URL
364 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
365 $user = Strings::normaliseLink($contact_id);
367 $extra_query = "AND `contact`.`nurl` = ? ";
368 if (api_user() !== false) {
369 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
373 // Searching for contact id with uid = 0
374 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
375 $user = api_unique_id_to_nurl(intval($contact_id));
378 throw new BadRequestException("User ID ".$contact_id." not found.");
382 $extra_query = "AND `contact`.`nurl` = ? ";
383 if (api_user() !== false) {
384 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
388 if (is_null($user) && !empty($_GET['user_id'])) {
389 $user = api_unique_id_to_nurl($_GET['user_id']);
392 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
396 $extra_query = "AND `contact`.`nurl` = ? ";
397 if (api_user() !== false) {
398 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
401 if (is_null($user) && !empty($_GET['screen_name'])) {
402 $user = $_GET['screen_name'];
403 $extra_query = "AND `contact`.`nick` = ? ";
404 if (api_user() !== false) {
405 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
409 if (is_null($user) && !empty($_GET['profileurl'])) {
410 $user = Strings::normaliseLink($_GET['profileurl']);
411 $extra_query = "AND `contact`.`nurl` = ? ";
412 if (api_user() !== false) {
413 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
417 // $called_api is the API path exploded on / and is expected to have at least 2 elements
418 if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
419 $argid = count($called_api);
420 if (!empty(DI::args()->getArgv()[$argid])) {
421 $data = explode(".", DI::args()->getArgv()[$argid]);
422 if (count($data) > 1) {
423 list($user, $null) = $data;
426 if (is_numeric($user)) {
427 $user = api_unique_id_to_nurl(intval($user));
431 $extra_query = "AND `contact`.`nurl` = ? ";
432 if (api_user() !== false) {
433 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
437 $extra_query = "AND `contact`.`nick` = ? ";
438 if (api_user() !== false) {
439 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
444 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
447 if (api_user() === false) {
448 BasicAuth::getCurrentUserID(true);
452 $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
456 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
459 $uinfo = DBA::toArray(DBA::p(
460 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
466 // Selecting the id by priority, friendica first
467 if (is_array($uinfo)) {
468 api_best_nickname($uinfo);
471 // if the contact wasn't found, fetch it from the contacts with uid = 0
472 if (!DBA::isResult($uinfo)) {
474 throw new BadRequestException("User not found.");
477 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
479 if (DBA::isResult($contact)) {
481 'id' => $contact["id"],
482 'id_str' => (string) $contact["id"],
483 'name' => $contact["name"],
484 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
485 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
486 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
487 'profile_image_url' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_MICRO),
488 'profile_image_url_https' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_MICRO),
489 'profile_image_url_profile_size' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_THUMB),
490 'profile_image_url_large' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_SMALL),
491 'url' => $contact["url"],
492 'protected' => false,
493 'followers_count' => 0,
494 'friends_count' => 0,
496 'created_at' => api_date($contact["created"]),
497 'favourites_count' => 0,
499 'time_zone' => 'UTC',
500 'geo_enabled' => false,
502 'statuses_count' => 0,
504 'contributors_enabled' => false,
505 'is_translator' => false,
506 'is_translation_enabled' => false,
507 'following' => false,
508 'follow_request_sent' => false,
509 'statusnet_blocking' => false,
510 'notifications' => false,
511 'statusnet_profile_url' => $contact["url"],
513 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
514 'pid' => Contact::getIdForURL($contact["url"], 0, false),
516 'network' => $contact["network"],
521 throw new BadRequestException("User ".$url." not found.");
525 if ($uinfo[0]['self']) {
526 if ($uinfo[0]['network'] == "") {
527 $uinfo[0]['network'] = Protocol::DFRN;
530 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
531 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
538 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
540 if (!empty($profile['about'])) {
541 $description = $profile['about'];
543 $description = $uinfo[0]["about"];
546 if (!empty($usr['default-location'])) {
547 $location = $usr['default-location'];
548 } elseif (!empty($uinfo[0]["location"])) {
549 $location = $uinfo[0]["location"];
551 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
555 'id' => intval($pcontact_id),
556 'id_str' => (string) intval($pcontact_id),
557 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
558 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
559 'location' => $location,
560 'description' => BBCode::toPlaintext($description ?? ''),
561 'profile_image_url' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_MICRO),
562 'profile_image_url_https' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_MICRO),
563 'profile_image_url_profile_size' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_THUMB),
564 'profile_image_url_large' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_SMALL),
565 'url' => $uinfo[0]['url'],
566 'protected' => false,
567 'followers_count' => intval($countfollowers),
568 'friends_count' => intval($countfriends),
570 'created_at' => api_date($uinfo[0]['created']),
571 'favourites_count' => intval($starred),
573 'time_zone' => 'UTC',
574 'geo_enabled' => false,
576 'statuses_count' => intval($countitems),
578 'contributors_enabled' => false,
579 'is_translator' => false,
580 'is_translation_enabled' => false,
581 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
582 'follow_request_sent' => false,
583 'statusnet_blocking' => false,
584 'notifications' => false,
586 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
587 'statusnet_profile_url' => $uinfo[0]['url'],
588 'uid' => intval($uinfo[0]['uid']),
589 'cid' => intval($uinfo[0]['cid']),
590 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
591 'self' => $uinfo[0]['self'],
592 'network' => $uinfo[0]['network'],
595 // If this is a local user and it uses Frio, we can get its color preferences.
597 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
598 if ($theme_info['theme'] === 'frio') {
599 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
601 if ($schema && ($schema != '---')) {
602 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
603 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
604 require_once $schemefile;
607 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
608 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
609 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
611 if (empty($nav_bg)) {
614 if (empty($link_color)) {
615 $link_color = "#6fdbe8";
617 if (empty($bgcolor)) {
618 $bgcolor = "#ededed";
621 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
622 $ret['profile_link_color'] = str_replace('#', '', $link_color);
623 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
631 * return api-formatted array for item's author and owner
634 * @param array $item item from db
635 * @return array(array:author, array:owner)
636 * @throws BadRequestException
637 * @throws ImagickException
638 * @throws InternalServerErrorException
639 * @throws UnauthorizedException
641 function api_item_get_user(App $a, $item)
643 $status_user = api_get_user($item['author-id'] ?? null);
645 $author_user = $status_user;
647 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
649 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
650 $owner_user = api_get_user($item['owner-id'] ?? null);
652 $owner_user = $author_user;
655 return ([$status_user, $author_user, $owner_user]);
663 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
664 * returns a 401 status code and an error message if not.
666 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
668 * @param string $type Return type (atom, rss, xml, json)
669 * @return array|string
670 * @throws BadRequestException
671 * @throws ForbiddenException
672 * @throws ImagickException
673 * @throws InternalServerErrorException
674 * @throws UnauthorizedException
676 function api_account_verify_credentials($type)
680 if (api_user() === false) {
681 throw new ForbiddenException();
684 unset($_REQUEST["user_id"]);
685 unset($_GET["user_id"]);
687 unset($_REQUEST["screen_name"]);
688 unset($_GET["screen_name"]);
690 $skip_status = $_REQUEST['skip_status'] ?? false;
692 $user_info = api_get_user();
694 // "verified" isn't used here in the standard
695 unset($user_info["verified"]);
697 // - Adding last status
699 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
701 $user_info['status'] = api_format_item($item, $type);
705 // "uid" and "self" are only needed for some internal stuff, so remove it from here
706 unset($user_info["uid"]);
707 unset($user_info["self"]);
709 return BaseApi::formatData("user", $type, ['user' => $user_info]);
712 /// @TODO move to top of file or somewhere better
713 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
716 * Get data from $_POST or $_GET
721 function requestdata($k)
723 if (!empty($_POST[$k])) {
726 if (!empty($_GET[$k])) {
733 * Deprecated function to upload media.
735 * @param string $type Return type (atom, rss, xml, json)
737 * @return array|string
738 * @throws BadRequestException
739 * @throws ForbiddenException
740 * @throws ImagickException
741 * @throws InternalServerErrorException
742 * @throws UnauthorizedException
744 function api_statuses_mediap($type)
748 if (api_user() === false) {
749 logger::notice('api_statuses_update: no user');
750 throw new ForbiddenException();
752 $user_info = api_get_user();
754 $_REQUEST['profile_uid'] = api_user();
755 $_REQUEST['api_source'] = true;
756 $txt = requestdata('status') ?? '';
757 /// @TODO old-lost code?
758 //$txt = urldecode(requestdata('status'));
760 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
761 $txt = HTML::toBBCodeVideo($txt);
762 $config = HTMLPurifier_Config::createDefault();
763 $config->set('Cache.DefinitionImpl', null);
764 $purifier = new HTMLPurifier($config);
765 $txt = $purifier->purify($txt);
767 $txt = HTML::toBBCode($txt);
769 DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
771 $picture = wall_upload_post($a, false);
773 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
774 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
775 $item_id = item_post($a);
777 // output the post that we just posted.
778 return api_status_show($type, $item_id);
781 /// @TODO move this to top of file or somewhere better!
782 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
785 * Updates the user’s current status.
787 * @param string $type Return type (atom, rss, xml, json)
789 * @return array|string
790 * @throws BadRequestException
791 * @throws ForbiddenException
792 * @throws ImagickException
793 * @throws InternalServerErrorException
794 * @throws TooManyRequestsException
795 * @throws UnauthorizedException
796 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
798 function api_statuses_update($type)
802 if (api_user() === false) {
803 logger::notice('api_statuses_update: no user');
804 throw new ForbiddenException();
809 // convert $_POST array items to the form we use for web posts.
810 if (requestdata('htmlstatus')) {
811 $txt = requestdata('htmlstatus') ?? '';
812 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
813 $txt = HTML::toBBCodeVideo($txt);
815 $config = HTMLPurifier_Config::createDefault();
816 $config->set('Cache.DefinitionImpl', null);
818 $purifier = new HTMLPurifier($config);
819 $txt = $purifier->purify($txt);
821 $_REQUEST['body'] = HTML::toBBCode($txt);
824 $_REQUEST['body'] = requestdata('status');
827 $_REQUEST['title'] = requestdata('title');
829 $parent = requestdata('in_reply_to_status_id');
831 // Twidere sends "-1" if it is no reply ...
836 if (ctype_digit($parent)) {
837 $_REQUEST['parent'] = $parent;
839 $_REQUEST['parent_uri'] = $parent;
842 if (requestdata('lat') && requestdata('long')) {
843 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
845 $_REQUEST['profile_uid'] = api_user();
848 // Check for throttling (maximum posts per day, week and month)
849 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
850 if ($throttle_day > 0) {
851 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
853 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
854 $posts_day = Post::count($condition);
856 if ($posts_day > $throttle_day) {
857 logger::info('Daily posting limit reached for user '.api_user());
858 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
859 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));
863 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
864 if ($throttle_week > 0) {
865 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
867 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
868 $posts_week = Post::count($condition);
870 if ($posts_week > $throttle_week) {
871 logger::info('Weekly posting limit reached for user '.api_user());
872 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
873 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));
877 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
878 if ($throttle_month > 0) {
879 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
881 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
882 $posts_month = Post::count($condition);
884 if ($posts_month > $throttle_month) {
885 logger::info('Monthly posting limit reached for user '.api_user());
886 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
887 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));
892 if (requestdata('media_ids')) {
893 $ids = explode(',', requestdata('media_ids') ?? '');
894 } elseif (!empty($_FILES['media'])) {
895 // upload the image if we have one
896 $picture = wall_upload_post($a, false);
897 if (is_array($picture)) {
898 $ids[] = $picture['id'];
906 foreach ($ids as $id) {
907 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
908 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
909 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
910 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
912 if (!empty($media)) {
913 $ressources[] = $media[0]['resource-id'];
914 $phototypes = Images::supportedTypes();
915 $ext = $phototypes[$media[0]['type']];
917 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
918 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
919 'size' => $media[0]['datasize'],
920 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
921 'description' => $media[0]['desc'] ?? '',
922 'width' => $media[0]['width'],
923 'height' => $media[0]['height']];
925 if (count($media) > 1) {
926 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
927 $attachment['preview-width'] = $media[1]['width'];
928 $attachment['preview-height'] = $media[1]['height'];
930 $attachments[] = $attachment;
934 // We have to avoid that the post is rejected because of an empty body
935 if (empty($_REQUEST['body'])) {
936 $_REQUEST['body'] = '[hr]';
940 if (!empty($attachments)) {
941 $_REQUEST['attachments'] = $attachments;
944 // set this so that the item_post() function is quiet and doesn't redirect or emit json
946 $_REQUEST['api_source'] = true;
948 if (empty($_REQUEST['source'])) {
949 $_REQUEST["source"] = api_source();
952 // call out normal post function
953 $item_id = item_post($a);
955 if (!empty($ressources) && !empty($item_id)) {
956 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
957 foreach ($ressources as $ressource) {
958 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
962 // output the post that we just posted.
963 return api_status_show($type, $item_id);
966 /// @TODO move to top of file or somewhere better
967 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
968 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
971 * Uploads an image to Friendica.
974 * @throws BadRequestException
975 * @throws ForbiddenException
976 * @throws ImagickException
977 * @throws InternalServerErrorException
978 * @throws UnauthorizedException
979 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
981 function api_media_upload()
985 if (api_user() === false) {
986 logger::notice('no user');
987 throw new ForbiddenException();
992 if (empty($_FILES['media'])) {
994 throw new BadRequestException("No media.");
997 $media = wall_upload_post($a, false);
1000 throw new InternalServerErrorException();
1004 $returndata["media_id"] = $media["id"];
1005 $returndata["media_id_string"] = (string)$media["id"];
1006 $returndata["size"] = $media["size"];
1007 $returndata["image"] = ["w" => $media["width"],
1008 "h" => $media["height"],
1009 "image_type" => $media["type"],
1010 "friendica_preview_url" => $media["preview"]];
1012 Logger::info('Media uploaded', ['return' => $returndata]);
1014 return ["media" => $returndata];
1017 /// @TODO move to top of file or somewhere better
1018 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1021 * Updates media meta data (picture descriptions)
1023 * @param string $type Return type (atom, rss, xml, json)
1025 * @return array|string
1026 * @throws BadRequestException
1027 * @throws ForbiddenException
1028 * @throws ImagickException
1029 * @throws InternalServerErrorException
1030 * @throws TooManyRequestsException
1031 * @throws UnauthorizedException
1032 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1034 * @todo Compare the corresponding Twitter function for correct return values
1036 function api_media_metadata_create($type)
1040 if (api_user() === false) {
1041 Logger::info('no user');
1042 throw new ForbiddenException();
1047 $postdata = Network::postdata();
1049 if (empty($postdata)) {
1050 throw new BadRequestException("No post data");
1053 $data = json_decode($postdata, true);
1055 throw new BadRequestException("Invalid post data");
1058 if (empty($data['media_id']) || empty($data['alt_text'])) {
1059 throw new BadRequestException("Missing post data values");
1062 if (empty($data['alt_text']['text'])) {
1063 throw new BadRequestException("No alt text.");
1066 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1068 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1069 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1070 if (!DBA::isResult($photo)) {
1071 throw new BadRequestException("Metadata not found.");
1074 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1077 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1080 * @param string $type Return format (atom, rss, xml, json)
1081 * @param int $item_id
1082 * @return array|string
1085 function api_status_show($type, $item_id)
1087 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1091 $item = api_get_item(['id' => $item_id]);
1092 if (!empty($item)) {
1093 $status_info = api_format_item($item, $type);
1096 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1098 return BaseApi::formatData('statuses', $type, ['status' => $status_info]);
1102 * Retrieves the last public status of the provided user info
1104 * @param int $ownerId Public contact Id
1105 * @param int $uid User Id
1109 function api_get_last_status($ownerId, $uid)
1112 'author-id'=> $ownerId,
1114 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1115 'private' => [Item::PUBLIC, Item::UNLISTED]
1118 $item = api_get_item($condition);
1124 * Retrieves a single item record based on the provided condition and converts it for API use.
1126 * @param array $condition Item table condition array
1130 function api_get_item(array $condition)
1132 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1138 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1139 * The author's most recent status will be returned inline.
1141 * @param string $type Return type (atom, rss, xml, json)
1142 * @return array|string
1143 * @throws BadRequestException
1144 * @throws ImagickException
1145 * @throws InternalServerErrorException
1146 * @throws UnauthorizedException
1147 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1149 function api_users_show($type)
1151 $a = Friendica\DI::app();
1153 $user_info = api_get_user();
1155 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1156 if (!empty($item)) {
1157 $user_info['status'] = api_format_item($item, $type);
1160 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1161 unset($user_info['uid']);
1162 unset($user_info['self']);
1164 return BaseApi::formatData('user', $type, ['user' => $user_info]);
1167 /// @TODO move to top of file or somewhere better
1168 api_register_func('api/users/show', 'api_users_show');
1169 api_register_func('api/externalprofile/show', 'api_users_show');
1172 * Search a public user account.
1174 * @param string $type Return type (atom, rss, xml, json)
1176 * @return array|string
1177 * @throws BadRequestException
1178 * @throws ImagickException
1179 * @throws InternalServerErrorException
1180 * @throws UnauthorizedException
1181 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1183 function api_users_search($type)
1189 if (!empty($_GET['q'])) {
1190 $contacts = Contact::selectToArray(
1193 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1201 if (DBA::isResult($contacts)) {
1203 foreach ($contacts as $contact) {
1204 $user_info = api_get_user($contact['id']);
1206 if ($type == 'xml') {
1207 $userlist[$k++ . ':user'] = $user_info;
1209 $userlist[] = $user_info;
1212 $userlist = ['users' => $userlist];
1214 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1217 throw new BadRequestException('No search term specified.');
1220 return BaseApi::formatData('users', $type, $userlist);
1223 /// @TODO move to top of file or somewhere better
1224 api_register_func('api/users/search', 'api_users_search');
1227 * Return user objects
1229 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1231 * @param string $type Return format: json or xml
1233 * @return array|string
1234 * @throws BadRequestException
1235 * @throws ImagickException
1236 * @throws InternalServerErrorException
1237 * @throws NotFoundException if the results are empty.
1238 * @throws UnauthorizedException
1240 function api_users_lookup($type)
1244 if (!empty($_REQUEST['user_id'])) {
1245 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1247 $users[] = api_get_user($id);
1252 if (empty($users)) {
1253 throw new NotFoundException;
1256 return BaseApi::formatData("users", $type, ['users' => $users]);
1259 /// @TODO move to top of file or somewhere better
1260 api_register_func('api/users/lookup', 'api_users_lookup', true);
1263 * Returns statuses that match a specified query.
1265 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1267 * @param string $type Return format: json, xml, atom, rss
1269 * @return array|string
1270 * @throws BadRequestException if the "q" parameter is missing.
1271 * @throws ForbiddenException
1272 * @throws ImagickException
1273 * @throws InternalServerErrorException
1274 * @throws UnauthorizedException
1276 function api_search($type)
1279 $user_info = api_get_user();
1281 if (api_user() === false || $user_info === false) {
1282 throw new ForbiddenException();
1285 if (empty($_REQUEST['q'])) {
1286 throw new BadRequestException('q parameter is required.');
1289 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1292 $data['status'] = [];
1294 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1295 if (!empty($_REQUEST['rpp'])) {
1296 $count = $_REQUEST['rpp'];
1297 } elseif (!empty($_REQUEST['count'])) {
1298 $count = $_REQUEST['count'];
1301 $since_id = $_REQUEST['since_id'] ?? 0;
1302 $max_id = $_REQUEST['max_id'] ?? 0;
1303 $page = $_REQUEST['page'] ?? 1;
1305 $start = max(0, ($page - 1) * $count);
1307 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1308 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1309 $searchTerm = $matches[1];
1310 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1311 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1313 while ($tag = DBA::fetch($tags)) {
1314 $uriids[] = $tag['uri-id'];
1318 if (empty($uriids)) {
1319 return BaseApi::formatData('statuses', $type, $data);
1322 $condition = ['uri-id' => $uriids];
1323 if ($exclude_replies) {
1324 $condition['gravity'] = GRAVITY_PARENT;
1327 $params['group_by'] = ['uri-id'];
1329 $condition = ["`id` > ?
1330 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1331 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1332 AND `body` LIKE CONCAT('%',?,'%')",
1333 $since_id, api_user(), $_REQUEST['q']];
1335 $condition[0] .= ' AND `id` <= ?';
1336 $condition[] = $max_id;
1342 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1343 $id = Item::fetchByLink($searchTerm, api_user());
1346 $id = Item::fetchByLink($searchTerm);
1350 $statuses = Post::select([], ['id' => $id]);
1354 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1356 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1358 bindComments($data['status']);
1360 return BaseApi::formatData('statuses', $type, $data);
1363 /// @TODO move to top of file or somewhere better
1364 api_register_func('api/search/tweets', 'api_search', true);
1365 api_register_func('api/search', 'api_search', true);
1368 * Returns the most recent statuses posted by the user and the users they follow.
1370 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1372 * @param string $type Return type (atom, rss, xml, json)
1374 * @return array|string
1375 * @throws BadRequestException
1376 * @throws ForbiddenException
1377 * @throws ImagickException
1378 * @throws InternalServerErrorException
1379 * @throws UnauthorizedException
1380 * @todo Optional parameters
1381 * @todo Add reply info
1383 function api_statuses_home_timeline($type)
1386 $user_info = api_get_user();
1388 if (api_user() === false || $user_info === false) {
1389 throw new ForbiddenException();
1392 unset($_REQUEST["user_id"]);
1393 unset($_GET["user_id"]);
1395 unset($_REQUEST["screen_name"]);
1396 unset($_GET["screen_name"]);
1398 // get last network messages
1401 $count = $_REQUEST['count'] ?? 20;
1402 $page = $_REQUEST['page']?? 0;
1403 $since_id = $_REQUEST['since_id'] ?? 0;
1404 $max_id = $_REQUEST['max_id'] ?? 0;
1405 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1406 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1408 $start = max(0, ($page - 1) * $count);
1410 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1411 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1414 $condition[0] .= " AND `id` <= ?";
1415 $condition[] = $max_id;
1417 if ($exclude_replies) {
1418 $condition[0] .= ' AND `gravity` = ?';
1419 $condition[] = GRAVITY_PARENT;
1421 if ($conversation_id > 0) {
1422 $condition[0] .= " AND `parent` = ?";
1423 $condition[] = $conversation_id;
1426 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1427 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1429 $items = Post::toArray($statuses);
1431 $ret = api_format_items($items, $user_info, false, $type);
1433 // Set all posts from the query above to seen
1435 foreach ($items as $item) {
1436 $idarray[] = intval($item["id"]);
1439 if (!empty($idarray)) {
1440 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1442 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1448 $data = ['status' => $ret];
1453 $data = api_rss_extra($a, $data, $user_info);
1457 return BaseApi::formatData("statuses", $type, $data);
1461 /// @TODO move to top of file or somewhere better
1462 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1463 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1466 * Returns the most recent statuses from public users.
1468 * @param string $type Return type (atom, rss, xml, json)
1470 * @return array|string
1471 * @throws BadRequestException
1472 * @throws ForbiddenException
1473 * @throws ImagickException
1474 * @throws InternalServerErrorException
1475 * @throws UnauthorizedException
1477 function api_statuses_public_timeline($type)
1480 $user_info = api_get_user();
1482 if (api_user() === false || $user_info === false) {
1483 throw new ForbiddenException();
1486 // get last network messages
1489 $count = $_REQUEST['count'] ?? 20;
1490 $page = $_REQUEST['page'] ?? 1;
1491 $since_id = $_REQUEST['since_id'] ?? 0;
1492 $max_id = $_REQUEST['max_id'] ?? 0;
1493 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1494 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1496 $start = max(0, ($page - 1) * $count);
1498 if ($exclude_replies && !$conversation_id) {
1499 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1500 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1503 $condition[0] .= " AND `id` <= ?";
1504 $condition[] = $max_id;
1507 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1508 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1510 $r = Post::toArray($statuses);
1512 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1513 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1516 $condition[0] .= " AND `id` <= ?";
1517 $condition[] = $max_id;
1519 if ($conversation_id > 0) {
1520 $condition[0] .= " AND `parent` = ?";
1521 $condition[] = $conversation_id;
1524 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1525 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1527 $r = Post::toArray($statuses);
1530 $ret = api_format_items($r, $user_info, false, $type);
1534 $data = ['status' => $ret];
1539 $data = api_rss_extra($a, $data, $user_info);
1543 return BaseApi::formatData("statuses", $type, $data);
1546 /// @TODO move to top of file or somewhere better
1547 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1550 * Returns the most recent statuses posted by users this node knows about.
1552 * @param string $type Return format: json, xml, atom, rss
1553 * @return array|string
1554 * @throws BadRequestException
1555 * @throws ForbiddenException
1556 * @throws ImagickException
1557 * @throws InternalServerErrorException
1558 * @throws UnauthorizedException
1560 function api_statuses_networkpublic_timeline($type)
1563 $user_info = api_get_user();
1565 if (api_user() === false || $user_info === false) {
1566 throw new ForbiddenException();
1569 $since_id = $_REQUEST['since_id'] ?? 0;
1570 $max_id = $_REQUEST['max_id'] ?? 0;
1573 $count = $_REQUEST['count'] ?? 20;
1574 $page = $_REQUEST['page'] ?? 1;
1576 $start = max(0, ($page - 1) * $count);
1578 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1579 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1582 $condition[0] .= " AND `id` <= ?";
1583 $condition[] = $max_id;
1586 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1587 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1589 $ret = api_format_items($statuses, $user_info, false, $type);
1593 $data = ['status' => $ret];
1598 $data = api_rss_extra($a, $data, $user_info);
1602 return BaseApi::formatData("statuses", $type, $data);
1605 /// @TODO move to top of file or somewhere better
1606 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1609 * Returns a single status.
1611 * @param string $type Return type (atom, rss, xml, json)
1613 * @return array|string
1614 * @throws BadRequestException
1615 * @throws ForbiddenException
1616 * @throws ImagickException
1617 * @throws InternalServerErrorException
1618 * @throws UnauthorizedException
1619 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1621 function api_statuses_show($type)
1624 $user_info = api_get_user();
1626 if (api_user() === false || $user_info === false) {
1627 throw new ForbiddenException();
1631 $id = intval(DI::args()->getArgv()[3] ?? 0);
1634 $id = intval($_REQUEST['id'] ?? 0);
1639 $id = intval(DI::args()->getArgv()[4] ?? 0);
1642 logger::notice('API: api_statuses_show: ' . $id);
1644 $conversation = !empty($_REQUEST['conversation']);
1646 // try to fetch the item for the local user - or the public item, if there is no local one
1647 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1648 if (!DBA::isResult($uri_item)) {
1649 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1652 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1653 if (!DBA::isResult($item)) {
1654 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1659 if ($conversation) {
1660 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1661 $params = ['order' => ['id' => true]];
1663 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1667 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1669 /// @TODO How about copying this to above methods which don't check $r ?
1670 if (!DBA::isResult($statuses)) {
1671 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1674 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1676 if ($conversation) {
1677 $data = ['status' => $ret];
1678 return BaseApi::formatData("statuses", $type, $data);
1680 $data = ['status' => $ret[0]];
1681 return BaseApi::formatData("status", $type, $data);
1685 /// @TODO move to top of file or somewhere better
1686 api_register_func('api/statuses/show', 'api_statuses_show', true);
1690 * @param string $type Return type (atom, rss, xml, json)
1692 * @return array|string
1693 * @throws BadRequestException
1694 * @throws ForbiddenException
1695 * @throws ImagickException
1696 * @throws InternalServerErrorException
1697 * @throws UnauthorizedException
1698 * @todo nothing to say?
1700 function api_conversation_show($type)
1703 $user_info = api_get_user();
1705 if (api_user() === false || $user_info === false) {
1706 throw new ForbiddenException();
1710 $id = intval(DI::args()->getArgv()[3] ?? 0);
1711 $since_id = intval($_REQUEST['since_id'] ?? 0);
1712 $max_id = intval($_REQUEST['max_id'] ?? 0);
1713 $count = intval($_REQUEST['count'] ?? 20);
1714 $page = intval($_REQUEST['page'] ?? 1);
1716 $start = max(0, ($page - 1) * $count);
1719 $id = intval($_REQUEST['id'] ?? 0);
1724 $id = intval(DI::args()->getArgv()[4] ?? 0);
1727 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1729 // try to fetch the item for the local user - or the public item, if there is no local one
1730 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1731 if (!DBA::isResult($item)) {
1732 throw new BadRequestException("There is no status with the id $id.");
1735 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1736 if (!DBA::isResult($parent)) {
1737 throw new BadRequestException("There is no status with this id.");
1740 $id = $parent['id'];
1742 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1743 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1746 $condition[0] .= " AND `id` <= ?";
1747 $condition[] = $max_id;
1750 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1751 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1753 if (!DBA::isResult($statuses)) {
1754 throw new BadRequestException("There is no status with id $id.");
1757 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1759 $data = ['status' => $ret];
1760 return BaseApi::formatData("statuses", $type, $data);
1763 /// @TODO move to top of file or somewhere better
1764 api_register_func('api/conversation/show', 'api_conversation_show', true);
1765 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1770 * @param string $type Return type (atom, rss, xml, json)
1772 * @return array|string
1773 * @throws BadRequestException
1774 * @throws ForbiddenException
1775 * @throws ImagickException
1776 * @throws InternalServerErrorException
1777 * @throws UnauthorizedException
1778 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1780 function api_statuses_repeat($type)
1786 if (api_user() === false) {
1787 throw new ForbiddenException();
1793 $id = intval(DI::args()->getArgv()[3] ?? 0);
1796 $id = intval($_REQUEST['id'] ?? 0);
1801 $id = intval(DI::args()->getArgv()[4] ?? 0);
1804 logger::notice('API: api_statuses_repeat: ' . $id);
1806 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1807 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1809 if (DBA::isResult($item) && !empty($item['body'])) {
1810 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1811 if (!Item::performActivity($id, 'announce', local_user())) {
1812 throw new InternalServerErrorException();
1817 if (strpos($item['body'], "[/share]") !== false) {
1818 $pos = strpos($item['body'], "[share");
1819 $post = substr($item['body'], $pos);
1821 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1823 if (!empty($item['title'])) {
1824 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1827 $post .= $item['body'];
1828 $post .= "[/share]";
1830 $_REQUEST['body'] = $post;
1831 $_REQUEST['profile_uid'] = api_user();
1832 $_REQUEST['api_source'] = true;
1834 if (empty($_REQUEST['source'])) {
1835 $_REQUEST["source"] = api_source();
1838 $item_id = item_post($a);
1841 throw new ForbiddenException();
1844 // output the post that we just posted.
1846 return api_status_show($type, $item_id);
1849 /// @TODO move to top of file or somewhere better
1850 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1853 * Destroys a specific status.
1855 * @param string $type Return type (atom, rss, xml, json)
1857 * @return array|string
1858 * @throws BadRequestException
1859 * @throws ForbiddenException
1860 * @throws ImagickException
1861 * @throws InternalServerErrorException
1862 * @throws UnauthorizedException
1863 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1865 function api_statuses_destroy($type)
1869 if (api_user() === false) {
1870 throw new ForbiddenException();
1876 $id = intval(DI::args()->getArgv()[3] ?? 0);
1879 $id = intval($_REQUEST['id'] ?? 0);
1884 $id = intval(DI::args()->getArgv()[4] ?? 0);
1887 logger::notice('API: api_statuses_destroy: ' . $id);
1889 $ret = api_statuses_show($type);
1891 Item::deleteForUser(['id' => $id], api_user());
1896 /// @TODO move to top of file or somewhere better
1897 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1900 * Returns the most recent mentions.
1902 * @param string $type Return type (atom, rss, xml, json)
1904 * @return array|string
1905 * @throws BadRequestException
1906 * @throws ForbiddenException
1907 * @throws ImagickException
1908 * @throws InternalServerErrorException
1909 * @throws UnauthorizedException
1910 * @see http://developer.twitter.com/doc/get/statuses/mentions
1912 function api_statuses_mentions($type)
1915 $user_info = api_get_user();
1917 if (api_user() === false || $user_info === false) {
1918 throw new ForbiddenException();
1921 unset($_REQUEST["user_id"]);
1922 unset($_GET["user_id"]);
1924 unset($_REQUEST["screen_name"]);
1925 unset($_GET["screen_name"]);
1927 // get last network messages
1930 $since_id = intval($_REQUEST['since_id'] ?? 0);
1931 $max_id = intval($_REQUEST['max_id'] ?? 0);
1932 $count = intval($_REQUEST['count'] ?? 20);
1933 $page = intval($_REQUEST['page'] ?? 1);
1935 $start = max(0, ($page - 1) * $count);
1937 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1938 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1939 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1942 GRAVITY_PARENT, GRAVITY_COMMENT,
1944 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1945 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1946 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1947 api_user(), $since_id,
1951 $query .= " AND `id` <= ?";
1952 $condition[] = $max_id;
1955 array_unshift($condition, $query);
1957 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1958 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1960 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1962 $data = ['status' => $ret];
1967 $data = api_rss_extra($a, $data, $user_info);
1971 return BaseApi::formatData("statuses", $type, $data);
1974 /// @TODO move to top of file or somewhere better
1975 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1976 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1979 * Returns the most recent statuses posted by the user.
1981 * @param string $type Either "json" or "xml"
1982 * @return string|array
1983 * @throws BadRequestException
1984 * @throws ForbiddenException
1985 * @throws ImagickException
1986 * @throws InternalServerErrorException
1987 * @throws UnauthorizedException
1988 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1990 function api_statuses_user_timeline($type)
1993 $user_info = api_get_user();
1995 if (api_user() === false || $user_info === false) {
1996 throw new ForbiddenException();
1999 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2001 $since_id = $_REQUEST['since_id'] ?? 0;
2002 $max_id = $_REQUEST['max_id'] ?? 0;
2003 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2004 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2007 $count = $_REQUEST['count'] ?? 20;
2008 $page = $_REQUEST['page'] ?? 1;
2010 $start = max(0, ($page - 1) * $count);
2012 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2013 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2015 if ($user_info['self'] == 1) {
2016 $condition[0] .= ' AND `wall` ';
2019 if ($exclude_replies) {
2020 $condition[0] .= ' AND `gravity` = ?';
2021 $condition[] = GRAVITY_PARENT;
2024 if ($conversation_id > 0) {
2025 $condition[0] .= " AND `parent` = ?";
2026 $condition[] = $conversation_id;
2030 $condition[0] .= " AND `id` <= ?";
2031 $condition[] = $max_id;
2033 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2034 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2036 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2040 $data = ['status' => $ret];
2045 $data = api_rss_extra($a, $data, $user_info);
2049 return BaseApi::formatData("statuses", $type, $data);
2052 /// @TODO move to top of file or somewhere better
2053 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2056 * Star/unstar an item.
2057 * param: id : id of the item
2059 * @param string $type Return type (atom, rss, xml, json)
2061 * @return array|string
2062 * @throws BadRequestException
2063 * @throws ForbiddenException
2064 * @throws ImagickException
2065 * @throws InternalServerErrorException
2066 * @throws UnauthorizedException
2067 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2069 function api_favorites_create_destroy($type)
2073 if (api_user() === false) {
2074 throw new ForbiddenException();
2077 // for versioned api.
2078 /// @TODO We need a better global soluton
2079 $action_argv_id = 2;
2080 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
2081 $action_argv_id = 3;
2084 if (DI::args()->getArgc() <= $action_argv_id) {
2085 throw new BadRequestException("Invalid request.");
2087 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
2088 if (DI::args()->getArgc() == $action_argv_id + 2) {
2089 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
2091 $itemid = intval($_REQUEST['id'] ?? 0);
2094 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2096 if (!DBA::isResult($item)) {
2097 throw new BadRequestException("Invalid item.");
2102 $item['starred'] = 1;
2105 $item['starred'] = 0;
2108 throw new BadRequestException("Invalid action ".$action);
2111 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2114 throw new InternalServerErrorException("DB error");
2118 $user_info = api_get_user();
2119 $rets = api_format_items([$item], $user_info, false, $type);
2122 $data = ['status' => $ret];
2127 $data = api_rss_extra($a, $data, $user_info);
2131 return BaseApi::formatData("status", $type, $data);
2134 /// @TODO move to top of file or somewhere better
2135 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2136 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2139 * Returns the most recent favorite statuses.
2141 * @param string $type Return type (atom, rss, xml, json)
2143 * @return string|array
2144 * @throws BadRequestException
2145 * @throws ForbiddenException
2146 * @throws ImagickException
2147 * @throws InternalServerErrorException
2148 * @throws UnauthorizedException
2150 function api_favorites($type)
2155 $user_info = api_get_user();
2157 if (api_user() === false || $user_info === false) {
2158 throw new ForbiddenException();
2163 // in friendica starred item are private
2164 // return favorites only for self
2165 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2167 if ($user_info['self'] == 0) {
2171 $since_id = $_REQUEST['since_id'] ?? 0;
2172 $max_id = $_REQUEST['max_id'] ?? 0;
2173 $count = $_GET['count'] ?? 20;
2174 $page = $_REQUEST['page'] ?? 1;
2176 $start = max(0, ($page - 1) * $count);
2178 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2179 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2181 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2184 $condition[0] .= " AND `id` <= ?";
2185 $condition[] = $max_id;
2188 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2190 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2195 $data = ['status' => $ret];
2200 $data = api_rss_extra($a, $data, $user_info);
2204 return BaseApi::formatData("statuses", $type, $data);
2207 /// @TODO move to top of file or somewhere better
2208 api_register_func('api/favorites', 'api_favorites', true);
2212 * @param array $item
2213 * @param array $recipient
2214 * @param array $sender
2217 * @throws InternalServerErrorException
2219 function api_format_messages($item, $recipient, $sender)
2221 // standard meta information
2223 'id' => $item['id'],
2224 'sender_id' => $sender['id'],
2226 'recipient_id' => $recipient['id'],
2227 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2228 'sender_screen_name' => $sender['screen_name'],
2229 'recipient_screen_name' => $recipient['screen_name'],
2230 'sender' => $sender,
2231 'recipient' => $recipient,
2233 'friendica_seen' => $item['seen'] ?? 0,
2234 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2237 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2238 if (isset($ret['sender']['uid'])) {
2239 unset($ret['sender']['uid']);
2241 if (isset($ret['sender']['self'])) {
2242 unset($ret['sender']['self']);
2244 if (isset($ret['recipient']['uid'])) {
2245 unset($ret['recipient']['uid']);
2247 if (isset($ret['recipient']['self'])) {
2248 unset($ret['recipient']['self']);
2251 //don't send title to regular StatusNET requests to avoid confusing these apps
2252 if (!empty($_GET['getText'])) {
2253 $ret['title'] = $item['title'];
2254 if ($_GET['getText'] == 'html') {
2255 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2256 } elseif ($_GET['getText'] == 'plain') {
2257 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2260 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2262 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2263 unset($ret['sender']);
2264 unset($ret['recipient']);
2272 * @param array $item
2275 * @throws InternalServerErrorException
2277 function api_convert_item($item)
2279 $body = api_add_attachments_to_body($item);
2281 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2283 // Add pictures to the attachment array and remove them from the body
2284 $attachments = api_get_attachments($body, $item['uri-id']);
2286 // Workaround for ostatus messages where the title is identically to the body
2287 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2288 $statusbody = trim(HTML::toPlaintext($html, 0));
2290 // handle data: images
2291 $statusbody = api_format_items_embeded_images($item, $statusbody);
2293 $statustitle = trim($item['title']);
2295 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2296 $statustext = trim($statusbody);
2298 $statustext = trim($statustitle."\n\n".$statusbody);
2301 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2302 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2305 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2307 // Workaround for clients with limited HTML parser functionality
2308 $search = ["<br>", "<blockquote>", "</blockquote>",
2309 "<h1>", "</h1>", "<h2>", "</h2>",
2310 "<h3>", "</h3>", "<h4>", "</h4>",
2311 "<h5>", "</h5>", "<h6>", "</h6>"];
2312 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2313 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2314 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2315 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2316 $statushtml = str_replace($search, $replace, $statushtml);
2318 if ($item['title'] != "") {
2319 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2323 $oldtext = $statushtml;
2324 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2325 } while ($oldtext != $statushtml);
2327 if (substr($statushtml, 0, 4) == '<br>') {
2328 $statushtml = substr($statushtml, 4);
2331 if (substr($statushtml, 0, -4) == '<br>') {
2332 $statushtml = substr($statushtml, -4);
2335 // feeds without body should contain the link
2336 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2337 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2341 "text" => $statustext,
2342 "html" => $statushtml,
2343 "attachments" => $attachments,
2344 "entities" => $entities
2349 * Add media attachments to the body
2351 * @param array $item
2352 * @return string body with added media
2354 function api_add_attachments_to_body(array $item)
2356 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2358 if (strpos($body, '[/img]') !== false) {
2362 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2363 if (!empty($media['preview'])) {
2364 $description = $media['description'] ?: $media['name'];
2365 if (!empty($description)) {
2366 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2368 $body .= "\n[img]" . $media['preview'] .'[/img]';
2378 * @param string $body
2382 * @throws InternalServerErrorException
2384 function api_get_attachments(&$body, $uriid)
2386 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2387 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2389 $URLSearchString = "^\[\]";
2390 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2394 // Remove all embedded pictures, since they are added as attachments
2395 foreach ($images[0] as $orig) {
2396 $body = str_replace($orig, '', $body);
2401 foreach ($images[1] as $image) {
2402 $imagedata = Images::getInfoFromURLCached($image);
2405 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2409 return $attachments;
2414 * @param string $text
2415 * @param string $bbcode
2418 * @throws InternalServerErrorException
2419 * @todo Links at the first character of the post
2421 function api_get_entitities(&$text, $bbcode, $uriid)
2423 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2425 if ($include_entities != "true") {
2426 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2428 foreach ($images[1] as $image) {
2429 $replace = Post\Link::getByLink($uriid, $image);
2430 $text = str_replace($image, $replace, $text);
2435 $bbcode = BBCode::cleanPictureLinks($bbcode);
2437 // Change pure links in text to bbcode uris
2438 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2441 $entities["hashtags"] = [];
2442 $entities["symbols"] = [];
2443 $entities["urls"] = [];
2444 $entities["user_mentions"] = [];
2446 $URLSearchString = "^\[\]";
2448 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2450 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2451 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2453 $bbcode = preg_replace(
2454 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2455 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2458 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2460 $bbcode = preg_replace(
2461 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2462 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2465 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2467 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2469 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2472 foreach ($urls[1] as $id => $url) {
2473 $start = iconv_strpos($text, $url, 0, "UTF-8");
2474 if (!($start === false)) {
2475 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2479 ksort($ordered_urls);
2483 foreach ($ordered_urls as $url) {
2484 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2485 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2487 $display_url = $url["title"];
2489 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2490 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2492 if (strlen($display_url) > 26) {
2493 $display_url = substr($display_url, 0, 25)."…";
2497 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2498 if (!($start === false)) {
2499 $entities["urls"][] = ["url" => $url["url"],
2500 "expanded_url" => $url["url"],
2501 "display_url" => $display_url,
2502 "indices" => [$start, $start+strlen($url["url"])]];
2503 $offset = $start + 1;
2507 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2508 $ordered_images = [];
2509 foreach ($images as $image) {
2510 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2511 if (!($start === false)) {
2512 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2516 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2517 foreach ($images[1] as $image) {
2518 $start = iconv_strpos($text, $image, 0, "UTF-8");
2519 if (!($start === false)) {
2520 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2526 foreach ($ordered_images as $image) {
2527 $url = $image['url'];
2528 $ext_alt_text = $image['alt'];
2530 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2531 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2533 if (strlen($display_url) > 26) {
2534 $display_url = substr($display_url, 0, 25)."…";
2537 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2538 if (!($start === false)) {
2539 $image = Images::getInfoFromURLCached($url);
2541 $media_url = Post\Link::getByLink($uriid, $url);
2542 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2544 $entities["media"][] = [
2546 "id_str" => (string) ($start + 1),
2547 "indices" => [$start, $start+strlen($url)],
2548 "media_url" => Strings::normaliseLink($media_url),
2549 "media_url_https" => $media_url,
2551 "display_url" => $display_url,
2552 "expanded_url" => $url,
2553 "ext_alt_text" => $ext_alt_text,
2557 $offset = $start + 1;
2566 * @param array $item
2567 * @param string $text
2571 function api_format_items_embeded_images($item, $text)
2573 $text = preg_replace_callback(
2574 '|data:image/([^;]+)[^=]+=*|m',
2575 function () use ($item) {
2576 return DI::baseUrl() . '/display/' . $item['guid'];
2584 * return <a href='url'>name</a> as array
2586 * @param string $txt text
2591 function api_contactlink_to_array($txt)
2594 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2595 if ($r && count($match)==3) {
2597 'name' => $match[2],
2611 * return likes, dislikes and attend status for item
2613 * @param array $item array
2614 * @param string $type Return type (atom, rss, xml, json)
2617 * likes => int count,
2618 * dislikes => int count
2619 * @throws BadRequestException
2620 * @throws ImagickException
2621 * @throws InternalServerErrorException
2622 * @throws UnauthorizedException
2624 function api_format_items_activities($item, $type = "json")
2633 'attendmaybe' => [],
2637 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2638 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2640 while ($parent_item = Post::fetch($ret)) {
2641 // not used as result should be structured like other user data
2642 //builtin_activity_puller($i, $activities);
2644 // get user data and add it to the array of the activity
2645 $user = api_get_user($parent_item['author-id']);
2646 switch ($parent_item['verb']) {
2647 case Activity::LIKE:
2648 $activities['like'][] = $user;
2650 case Activity::DISLIKE:
2651 $activities['dislike'][] = $user;
2653 case Activity::ATTEND:
2654 $activities['attendyes'][] = $user;
2656 case Activity::ATTENDNO:
2657 $activities['attendno'][] = $user;
2659 case Activity::ATTENDMAYBE:
2660 $activities['attendmaybe'][] = $user;
2662 case Activity::ANNOUNCE:
2663 $activities['announce'][] = $user;
2672 if ($type == "xml") {
2673 $xml_activities = [];
2674 foreach ($activities as $k => $v) {
2675 // change xml element from "like" to "friendica:like"
2676 $xml_activities["friendica:".$k] = $v;
2677 // add user data into xml output
2679 foreach ($v as $user) {
2680 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2683 $activities = $xml_activities;
2690 * format items to be returned by api
2692 * @param array $items array of items
2693 * @param array $user_info
2694 * @param bool $filter_user filter items by $user_info
2695 * @param string $type Return type (atom, rss, xml, json)
2697 * @throws BadRequestException
2698 * @throws ImagickException
2699 * @throws InternalServerErrorException
2700 * @throws UnauthorizedException
2702 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2704 $a = Friendica\DI::app();
2708 if (empty($items)) {
2712 foreach ((array)$items as $item) {
2713 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2715 // Look if the posts are matching if they should be filtered by user id
2716 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2720 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2729 * @param array $item Item record
2730 * @param string $type Return format (atom, rss, xml, json)
2731 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2732 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2733 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2734 * @return array API-formatted status
2735 * @throws BadRequestException
2736 * @throws ImagickException
2737 * @throws InternalServerErrorException
2738 * @throws UnauthorizedException
2740 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2742 $a = Friendica\DI::app();
2744 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2745 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2748 DI::contentItem()->localize($item);
2750 $in_reply_to = api_in_reply_to($item);
2752 $converted = api_convert_item($item);
2754 if ($type == "xml") {
2755 $geo = "georss:point";
2761 'text' => $converted["text"],
2762 'truncated' => false,
2763 'created_at'=> api_date($item['created']),
2764 'in_reply_to_status_id' => $in_reply_to['status_id'],
2765 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2766 'source' => (($item['app']) ? $item['app'] : 'web'),
2767 'id' => intval($item['id']),
2768 'id_str' => (string) intval($item['id']),
2769 'in_reply_to_user_id' => $in_reply_to['user_id'],
2770 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2771 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2773 'favorited' => $item['starred'] ? true : false,
2774 'user' => $status_user,
2775 'friendica_author' => $author_user,
2776 'friendica_owner' => $owner_user,
2777 'friendica_private' => $item['private'] == Item::PRIVATE,
2778 //'entities' => NULL,
2779 'statusnet_html' => $converted["html"],
2780 'statusnet_conversation_id' => $item['parent'],
2781 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2782 'friendica_activities' => api_format_items_activities($item, $type),
2783 'friendica_title' => $item['title'],
2784 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2787 if (count($converted["attachments"]) > 0) {
2788 $status["attachments"] = $converted["attachments"];
2791 if (count($converted["entities"]) > 0) {
2792 $status["entities"] = $converted["entities"];
2795 if ($status["source"] == 'web') {
2796 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2797 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2798 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2801 $retweeted_item = [];
2804 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2805 $announce = api_get_announce($item);
2806 if (!empty($announce)) {
2807 $retweeted_item = $item;
2809 $status['friendica_owner'] = api_get_user($announce['author-id']);
2813 if (!empty($quoted_item)) {
2814 if ($quoted_item['id'] != $item['id']) {
2815 $quoted_status = api_format_item($quoted_item);
2816 /// @todo Only remove the attachments that are also contained in the quotes status
2817 unset($status['attachments']);
2818 unset($status['entities']);
2820 $conv_quoted = api_convert_item($quoted_item);
2821 $quoted_status = $status;
2822 unset($quoted_status['attachments']);
2823 unset($quoted_status['entities']);
2824 unset($quoted_status['statusnet_conversation_id']);
2825 $quoted_status['text'] = $conv_quoted['text'];
2826 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2828 $quoted_status["user"] = api_get_user($quoted_item["author-id"]);
2829 } catch (BadRequestException $e) {
2830 // user not found. should be found?
2831 /// @todo check if the user should be always found
2832 $quoted_status["user"] = [];
2835 unset($quoted_status['friendica_author']);
2836 unset($quoted_status['friendica_owner']);
2837 unset($quoted_status['friendica_activities']);
2838 unset($quoted_status['friendica_private']);
2841 if (!empty($retweeted_item)) {
2842 $retweeted_status = $status;
2843 unset($retweeted_status['friendica_author']);
2844 unset($retweeted_status['friendica_owner']);
2845 unset($retweeted_status['friendica_activities']);
2846 unset($retweeted_status['friendica_private']);
2847 unset($retweeted_status['statusnet_conversation_id']);
2848 $status['user'] = $status['friendica_owner'];
2850 $retweeted_status["user"] = api_get_user($retweeted_item["author-id"]);
2851 } catch (BadRequestException $e) {
2852 // user not found. should be found?
2853 /// @todo check if the user should be always found
2854 $retweeted_status["user"] = [];
2857 $rt_converted = api_convert_item($retweeted_item);
2859 $retweeted_status['text'] = $rt_converted["text"];
2860 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2861 $retweeted_status['friendica_html'] = $rt_converted["html"];
2862 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2864 if (!empty($quoted_status)) {
2865 $retweeted_status['quoted_status'] = $quoted_status;
2868 $status['friendica_author'] = $retweeted_status['user'];
2869 $status['retweeted_status'] = $retweeted_status;
2870 } elseif (!empty($quoted_status)) {
2871 $root_status = api_convert_item($item);
2873 $status['text'] = $root_status["text"];
2874 $status['statusnet_html'] = $root_status["html"];
2875 $status['quoted_status'] = $quoted_status;
2878 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2879 unset($status["user"]["uid"]);
2880 unset($status["user"]["self"]);
2882 if ($item["coord"] != "") {
2883 $coords = explode(' ', $item["coord"]);
2884 if (count($coords) == 2) {
2885 if ($type == "json") {
2886 $status["geo"] = ['type' => 'Point',
2887 'coordinates' => [(float) $coords[0],
2888 (float) $coords[1]]];
2889 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2890 $status["georss:point"] = $item["coord"];
2899 * Returns all lists the user subscribes to.
2901 * @param string $type Return type (atom, rss, xml, json)
2903 * @return array|string
2904 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2906 function api_lists_list($type)
2909 /// @TODO $ret is not filled here?
2910 return BaseApi::formatData('lists', $type, ["lists_list" => $ret]);
2913 /// @TODO move to top of file or somewhere better
2914 api_register_func('api/lists/list', 'api_lists_list', true);
2915 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2918 * Returns all groups the user owns.
2920 * @param string $type Return type (atom, rss, xml, json)
2922 * @return array|string
2923 * @throws BadRequestException
2924 * @throws ForbiddenException
2925 * @throws ImagickException
2926 * @throws InternalServerErrorException
2927 * @throws UnauthorizedException
2928 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2930 function api_lists_ownerships($type)
2934 if (api_user() === false) {
2935 throw new ForbiddenException();
2939 $user_info = api_get_user();
2940 $uid = $user_info['uid'];
2942 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2944 // loop through all groups
2946 foreach ($groups as $group) {
2947 if ($group['visible']) {
2953 'name' => $group['name'],
2954 'id' => intval($group['id']),
2955 'id_str' => (string) $group['id'],
2956 'user' => $user_info,
2960 return BaseApi::formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2963 /// @TODO move to top of file or somewhere better
2964 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2967 * Returns recent statuses from users in the specified group.
2969 * @param string $type Return type (atom, rss, xml, json)
2971 * @return array|string
2972 * @throws BadRequestException
2973 * @throws ForbiddenException
2974 * @throws ImagickException
2975 * @throws InternalServerErrorException
2976 * @throws UnauthorizedException
2977 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2979 function api_lists_statuses($type)
2983 $user_info = api_get_user();
2984 if (api_user() === false || $user_info === false) {
2985 throw new ForbiddenException();
2988 unset($_REQUEST["user_id"]);
2989 unset($_GET["user_id"]);
2991 unset($_REQUEST["screen_name"]);
2992 unset($_GET["screen_name"]);
2994 if (empty($_REQUEST['list_id'])) {
2995 throw new BadRequestException('list_id not specified');
2999 $count = $_REQUEST['count'] ?? 20;
3000 $page = $_REQUEST['page'] ?? 1;
3001 $since_id = $_REQUEST['since_id'] ?? 0;
3002 $max_id = $_REQUEST['max_id'] ?? 0;
3003 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3004 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3006 $start = max(0, ($page - 1) * $count);
3008 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3009 $gids = array_column($groups, 'contact-id');
3010 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3011 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3014 $condition[0] .= " AND `id` <= ?";
3015 $condition[] = $max_id;
3017 if ($exclude_replies > 0) {
3018 $condition[0] .= ' AND `gravity` = ?';
3019 $condition[] = GRAVITY_PARENT;
3021 if ($conversation_id > 0) {
3022 $condition[0] .= " AND `parent` = ?";
3023 $condition[] = $conversation_id;
3026 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3027 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3029 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3031 $data = ['status' => $items];
3036 $data = api_rss_extra($a, $data, $user_info);
3040 return BaseApi::formatData("statuses", $type, $data);
3043 /// @TODO move to top of file or somewhere better
3044 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3047 * Returns either the friends of the follower list
3049 * Considers friends and followers lists to be private and won't return
3050 * anything if any user_id parameter is passed.
3052 * @param string $qtype Either "friends" or "followers"
3053 * @return boolean|array
3054 * @throws BadRequestException
3055 * @throws ForbiddenException
3056 * @throws ImagickException
3057 * @throws InternalServerErrorException
3058 * @throws UnauthorizedException
3060 function api_statuses_f($qtype)
3064 if (api_user() === false) {
3065 throw new ForbiddenException();
3069 $count = $_GET['count'] ?? 20;
3070 $page = $_GET['page'] ?? 1;
3072 $start = max(0, ($page - 1) * $count);
3074 $user_info = api_get_user();
3076 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3077 /* this is to stop Hotot to load friends multiple times
3078 * I'm not sure if I'm missing return something or
3079 * is a bug in hotot. Workaround, meantime
3083 return array('$users' => $ret);*/
3088 if ($qtype == 'friends') {
3089 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3090 } elseif ($qtype == 'followers') {
3091 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3094 // friends and followers only for self
3095 if ($user_info['self'] == 0) {
3096 $sql_extra = " AND false ";
3099 if ($qtype == 'blocks') {
3100 $sql_filter = 'AND `blocked` AND NOT `pending`';
3101 } elseif ($qtype == 'incoming') {
3102 $sql_filter = 'AND `pending`';
3104 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3107 // @todo This query most likely can be replaced with a Contact::select...
3108 $r = DBA::toArray(DBA::p(
3123 foreach ($r as $cid) {
3124 $user = api_get_user($cid['nurl']);
3125 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3126 unset($user["uid"]);
3127 unset($user["self"]);
3134 return ['user' => $ret];
3139 * Returns the list of friends of the provided user
3141 * @deprecated By Twitter API in favor of friends/list
3143 * @param string $type Either "json" or "xml"
3144 * @return boolean|string|array
3145 * @throws BadRequestException
3146 * @throws ForbiddenException
3148 function api_statuses_friends($type)
3150 $data = api_statuses_f("friends");
3151 if ($data === false) {
3154 return BaseApi::formatData("users", $type, $data);
3158 * Returns the list of followers of the provided user
3160 * @deprecated By Twitter API in favor of friends/list
3162 * @param string $type Either "json" or "xml"
3163 * @return boolean|string|array
3164 * @throws BadRequestException
3165 * @throws ForbiddenException
3167 function api_statuses_followers($type)
3169 $data = api_statuses_f("followers");
3170 if ($data === false) {
3173 return BaseApi::formatData("users", $type, $data);
3176 /// @TODO move to top of file or somewhere better
3177 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3178 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3181 * Returns the list of blocked users
3183 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3185 * @param string $type Either "json" or "xml"
3187 * @return boolean|string|array
3188 * @throws BadRequestException
3189 * @throws ForbiddenException
3191 function api_blocks_list($type)
3193 $data = api_statuses_f('blocks');
3194 if ($data === false) {
3197 return BaseApi::formatData("users", $type, $data);
3200 /// @TODO move to top of file or somewhere better
3201 api_register_func('api/blocks/list', 'api_blocks_list', true);
3204 * Returns the list of pending users IDs
3206 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3208 * @param string $type Either "json" or "xml"
3210 * @return boolean|string|array
3211 * @throws BadRequestException
3212 * @throws ForbiddenException
3214 function api_friendships_incoming($type)
3216 $data = api_statuses_f('incoming');
3217 if ($data === false) {
3222 foreach ($data['user'] as $user) {
3223 $ids[] = $user['id'];
3226 return BaseApi::formatData("ids", $type, ['id' => $ids]);
3229 /// @TODO move to top of file or somewhere better
3230 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3233 * Returns the instance's configuration information.
3235 * @param string $type Return type (atom, rss, xml, json)
3237 * @return array|string
3238 * @throws InternalServerErrorException
3240 function api_statusnet_config($type)
3242 $name = DI::config()->get('config', 'sitename');
3243 $server = DI::baseUrl()->getHostname();
3244 $logo = DI::baseUrl() . '/images/friendica-64.png';
3245 $email = DI::config()->get('config', 'admin_email');
3246 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3247 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3248 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3249 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3250 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3253 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3254 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3255 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3256 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3257 'shorturllength' => '30',
3259 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3260 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3261 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3262 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3267 return BaseApi::formatData('config', $type, ['config' => $config]);
3270 /// @TODO move to top of file or somewhere better
3271 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3272 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3275 * Sends a new direct message.
3277 * @param string $type Return type (atom, rss, xml, json)
3279 * @return array|string
3280 * @throws BadRequestException
3281 * @throws ForbiddenException
3282 * @throws ImagickException
3283 * @throws InternalServerErrorException
3284 * @throws NotFoundException
3285 * @throws UnauthorizedException
3286 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3288 function api_direct_messages_new($type)
3292 if (api_user() === false) {
3293 throw new ForbiddenException();
3296 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3300 $sender = api_get_user();
3303 if (!empty($_POST['screen_name'])) {
3304 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => api_user(), 'nick' => $_POST['screen_name']]);
3305 if (DBA::isResult($contacts)) {
3306 // Selecting the id by priority, friendica first
3307 api_best_nickname($contacts);
3309 $recipient = api_get_user($contacts[0]['nurl']);
3312 $recipient = api_get_user($_POST['user_id']);
3315 if (empty($recipient)) {
3316 throw new NotFoundException('Recipient not found');
3320 if (!empty($_REQUEST['replyto'])) {
3321 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => api_user(), 'id' => $_REQUEST['replyto']]);
3322 $replyto = $mail['parent-uri'];
3323 $sub = $mail['title'];
3325 if (!empty($_REQUEST['title'])) {
3326 $sub = $_REQUEST['title'];
3328 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3332 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3335 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3336 $ret = api_format_messages($mail, $recipient, $sender);
3338 $ret = ["error" => $id];
3341 $data = ['direct_message'=>$ret];
3347 $data = api_rss_extra($a, $data, $sender);
3351 return BaseApi::formatData("direct-messages", $type, $data);
3354 /// @TODO move to top of file or somewhere better
3355 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3358 * delete a direct_message from mail table through api
3360 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3361 * @return string|array
3362 * @throws BadRequestException
3363 * @throws ForbiddenException
3364 * @throws ImagickException
3365 * @throws InternalServerErrorException
3366 * @throws UnauthorizedException
3367 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3369 function api_direct_messages_destroy($type)
3373 if (api_user() === false) {
3374 throw new ForbiddenException();
3378 $user_info = api_get_user();
3380 $id = $_REQUEST['id'] ?? 0;
3382 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3383 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3384 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3386 $uid = $user_info['uid'];
3387 // error if no id or parenturi specified (for clients posting parent-uri as well)
3388 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3389 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3390 return BaseApi::formatData("direct_messages_delete", $type, ['$result' => $answer]);
3393 // BadRequestException if no id specified (for clients using Twitter API)
3395 throw new BadRequestException('Message id not specified');
3398 // add parent-uri to sql command if specified by calling app
3399 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3401 // error message if specified id is not in database
3402 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3403 if ($verbose == "true") {
3404 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3405 return BaseApi::formatData("direct_messages_delete", $type, ['$result' => $answer]);
3407 /// @todo BadRequestException ok for Twitter API clients?
3408 throw new BadRequestException('message id not in database');
3412 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3414 if ($verbose == "true") {
3417 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3418 return BaseApi::formatData("direct_message_delete", $type, ['$result' => $answer]);
3420 $answer = ['result' => 'error', 'message' => 'unknown error'];
3421 return BaseApi::formatData("direct_messages_delete", $type, ['$result' => $answer]);
3424 /// @todo return JSON data like Twitter API not yet implemented
3427 /// @TODO move to top of file or somewhere better
3428 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3433 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3434 * @return string|array
3435 * @throws HTTPException\BadRequestException
3436 * @throws HTTPException\ExpectationFailedException
3437 * @throws HTTPException\ForbiddenException
3438 * @throws HTTPException\InternalServerErrorException
3439 * @throws HTTPException\NotFoundException
3440 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3442 function api_friendships_destroy($type)
3446 if ($uid === false) {
3447 throw new HTTPException\ForbiddenException();
3450 $owner = User::getOwnerDataById($uid);
3452 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3453 throw new HTTPException\NotFoundException('Error Processing Request');
3456 $contact_id = $_REQUEST['user_id'] ?? 0;
3458 if (empty($contact_id)) {
3459 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3460 throw new HTTPException\BadRequestException('no user_id specified');
3463 // Get Contact by given id
3464 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3466 if(!DBA::isResult($contact)) {
3467 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3468 throw new HTTPException\NotFoundException('no contact found to given ID');
3471 $url = $contact['url'];
3473 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3474 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3475 Strings::normaliseLink($url), $url];
3476 $contact = DBA::selectFirst('contact', [], $condition);
3478 if (!DBA::isResult($contact)) {
3479 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3480 throw new HTTPException\NotFoundException('Not following Contact');
3484 $result = Contact::terminateFriendship($owner, $contact);
3486 if ($result === null) {
3487 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3488 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3491 if ($result === false) {
3492 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3494 } catch (Exception $e) {
3495 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3496 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3499 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3500 unset($contact['uid']);
3501 unset($contact['self']);
3503 // Set screen_name since Twidere requests it
3504 $contact['screen_name'] = $contact['nick'];
3506 return BaseApi::formatData('friendships-destroy', $type, ['user' => $contact]);
3508 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3512 * @param string $type Return type (atom, rss, xml, json)
3513 * @param string $box
3514 * @param string $verbose
3516 * @return array|string
3517 * @throws BadRequestException
3518 * @throws ForbiddenException
3519 * @throws ImagickException
3520 * @throws InternalServerErrorException
3521 * @throws UnauthorizedException
3523 function api_direct_messages_box($type, $box, $verbose)
3526 if (api_user() === false) {
3527 throw new ForbiddenException();
3530 $count = $_GET['count'] ?? 20;
3531 $page = $_REQUEST['page'] ?? 1;
3533 $since_id = $_REQUEST['since_id'] ?? 0;
3534 $max_id = $_REQUEST['max_id'] ?? 0;
3536 $user_id = $_REQUEST['user_id'] ?? '';
3537 $screen_name = $_REQUEST['screen_name'] ?? '';
3540 unset($_REQUEST["user_id"]);
3541 unset($_GET["user_id"]);
3543 unset($_REQUEST["screen_name"]);
3544 unset($_GET["screen_name"]);
3546 $user_info = api_get_user();
3547 if ($user_info === false) {
3548 throw new ForbiddenException();
3550 $profile_url = $user_info["url"];
3553 $start = max(0, ($page - 1) * $count);
3558 if ($box=="sentbox") {
3559 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3560 } elseif ($box == "conversation") {
3561 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3562 } elseif ($box == "all") {
3563 $sql_extra = "true";
3564 } elseif ($box == "inbox") {
3565 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3569 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3572 if ($user_id != "") {
3573 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3574 } elseif ($screen_name !="") {
3575 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3578 $r = DBA::toArray(DBA::p(
3579 "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 ?,?",
3585 if ($verbose == "true" && !DBA::isResult($r)) {
3586 $answer = ['result' => 'error', 'message' => 'no mails available'];
3587 return BaseApi::formatData("direct_messages_all", $type, ['$result' => $answer]);
3591 foreach ($r as $item) {
3592 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3593 $recipient = $user_info;
3594 $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
3595 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3596 $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
3597 $sender = $user_info;
3600 if (isset($recipient) && isset($sender)) {
3601 $ret[] = api_format_messages($item, $recipient, $sender);
3606 $data = ['direct_message' => $ret];
3611 $data = api_rss_extra($a, $data, $user_info);
3615 return BaseApi::formatData("direct-messages", $type, $data);
3619 * Returns the most recent direct messages sent by the user.
3621 * @param string $type Return type (atom, rss, xml, json)
3623 * @return array|string
3624 * @throws BadRequestException
3625 * @throws ForbiddenException
3626 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3628 function api_direct_messages_sentbox($type)
3630 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3631 return api_direct_messages_box($type, "sentbox", $verbose);
3635 * Returns the most recent direct messages sent to the user.
3637 * @param string $type Return type (atom, rss, xml, json)
3639 * @return array|string
3640 * @throws BadRequestException
3641 * @throws ForbiddenException
3642 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3644 function api_direct_messages_inbox($type)
3646 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3647 return api_direct_messages_box($type, "inbox", $verbose);
3652 * @param string $type Return type (atom, rss, xml, json)
3654 * @return array|string
3655 * @throws BadRequestException
3656 * @throws ForbiddenException
3658 function api_direct_messages_all($type)
3660 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3661 return api_direct_messages_box($type, "all", $verbose);
3666 * @param string $type Return type (atom, rss, xml, json)
3668 * @return array|string
3669 * @throws BadRequestException
3670 * @throws ForbiddenException
3672 function api_direct_messages_conversation($type)
3674 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3675 return api_direct_messages_box($type, "conversation", $verbose);
3678 /// @TODO move to top of file or somewhere better
3679 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3680 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3681 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3682 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3685 * list all photos of the authenticated user
3687 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3688 * @return string|array
3689 * @throws ForbiddenException
3690 * @throws InternalServerErrorException
3692 function api_fr_photos_list($type)
3694 if (api_user() === false) {
3695 throw new ForbiddenException();
3697 $r = DBA::toArray(DBA::p(
3698 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3699 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3700 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3701 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3704 'image/jpeg' => 'jpg',
3705 'image/png' => 'png',
3706 'image/gif' => 'gif'
3708 $data = ['photo'=>[]];
3709 if (DBA::isResult($r)) {
3710 foreach ($r as $rr) {
3712 $photo['id'] = $rr['resource-id'];
3713 $photo['album'] = $rr['album'];
3714 $photo['filename'] = $rr['filename'];
3715 $photo['type'] = $rr['type'];
3716 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3717 $photo['created'] = $rr['created'];
3718 $photo['edited'] = $rr['edited'];
3719 $photo['desc'] = $rr['desc'];
3721 if ($type == "xml") {
3722 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3724 $photo['thumb'] = $thumb;
3725 $data['photo'][] = $photo;
3729 return BaseApi::formatData("photos", $type, $data);
3733 * upload a new photo or change an existing photo
3735 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3736 * @return string|array
3737 * @throws BadRequestException
3738 * @throws ForbiddenException
3739 * @throws ImagickException
3740 * @throws InternalServerErrorException
3741 * @throws NotFoundException
3743 function api_fr_photo_create_update($type)
3745 if (api_user() === false) {
3746 throw new ForbiddenException();
3749 $photo_id = $_REQUEST['photo_id'] ?? null;
3750 $desc = $_REQUEST['desc'] ?? null;
3751 $album = $_REQUEST['album'] ?? null;
3752 $album_new = $_REQUEST['album_new'] ?? null;
3753 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3754 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3755 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3756 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3757 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3759 // do several checks on input parameters
3760 // we do not allow calls without album string
3761 if ($album == null) {
3762 throw new BadRequestException("no albumname specified");
3764 // if photo_id == null --> we are uploading a new photo
3765 if ($photo_id == null) {
3768 // error if no media posted in create-mode
3769 if (empty($_FILES['media'])) {
3771 throw new BadRequestException("no media data submitted");
3774 // album_new will be ignored in create-mode
3779 // check if photo is existing in databasei
3780 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
3781 throw new BadRequestException("photo not available");
3785 // checks on acl strings provided by clients
3786 $acl_input_error = false;
3787 $acl_input_error |= check_acl_input($allow_cid);
3788 $acl_input_error |= check_acl_input($deny_cid);
3789 $acl_input_error |= check_acl_input($allow_gid);
3790 $acl_input_error |= check_acl_input($deny_gid);
3791 if ($acl_input_error) {
3792 throw new BadRequestException("acl data invalid");
3794 // now let's upload the new media in create-mode
3795 if ($mode == "create") {
3796 $media = $_FILES['media'];
3797 $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);
3799 // return success of updating or error message
3800 if (!is_null($data)) {
3801 return BaseApi::formatData("photo_create", $type, $data);
3803 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3807 // now let's do the changes in update-mode
3808 if ($mode == "update") {
3809 $updated_fields = [];
3811 if (!is_null($desc)) {
3812 $updated_fields['desc'] = $desc;
3815 if (!is_null($album_new)) {
3816 $updated_fields['album'] = $album_new;
3819 if (!is_null($allow_cid)) {
3820 $allow_cid = trim($allow_cid);
3821 $updated_fields['allow_cid'] = $allow_cid;
3824 if (!is_null($deny_cid)) {
3825 $deny_cid = trim($deny_cid);
3826 $updated_fields['deny_cid'] = $deny_cid;
3829 if (!is_null($allow_gid)) {
3830 $allow_gid = trim($allow_gid);
3831 $updated_fields['allow_gid'] = $allow_gid;
3834 if (!is_null($deny_gid)) {
3835 $deny_gid = trim($deny_gid);
3836 $updated_fields['deny_gid'] = $deny_gid;
3840 if (count($updated_fields) > 0) {
3841 $nothingtodo = false;
3842 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
3844 $nothingtodo = true;
3847 if (!empty($_FILES['media'])) {
3848 $nothingtodo = false;
3849 $media = $_FILES['media'];
3850 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3851 if (!is_null($data)) {
3852 return BaseApi::formatData("photo_update", $type, $data);
3856 // return success of updating or error message
3858 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3859 return BaseApi::formatData("photo_update", $type, ['$result' => $answer]);
3862 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3863 return BaseApi::formatData("photo_update", $type, ['$result' => $answer]);
3865 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3868 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3872 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3874 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3875 * @return string|array
3876 * @throws BadRequestException
3877 * @throws ForbiddenException
3878 * @throws InternalServerErrorException
3879 * @throws NotFoundException
3881 function api_fr_photo_detail($type)
3883 if (api_user() === false) {
3884 throw new ForbiddenException();
3886 if (empty($_REQUEST['photo_id'])) {
3887 throw new BadRequestException("No photo id.");
3890 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3891 $photo_id = $_REQUEST['photo_id'];
3893 // prepare json/xml output with data from database for the requested photo
3894 $data = prepare_photo_data($type, $scale, $photo_id);
3896 return BaseApi::formatData("photo_detail", $type, $data);
3901 * updates the profile image for the user (either a specified profile or the default profile)
3903 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3905 * @return string|array
3906 * @throws BadRequestException
3907 * @throws ForbiddenException
3908 * @throws ImagickException
3909 * @throws InternalServerErrorException
3910 * @throws NotFoundException
3911 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3913 function api_account_update_profile_image($type)
3915 if (api_user() === false) {
3916 throw new ForbiddenException();
3919 $profile_id = $_REQUEST['profile_id'] ?? 0;
3921 // error if image data is missing
3922 if (empty($_FILES['image'])) {
3923 throw new BadRequestException("no media data submitted");
3926 // check if specified profile id is valid
3927 if ($profile_id != 0) {
3928 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
3929 // error message if specified profile id is not in database
3930 if (!DBA::isResult($profile)) {
3931 throw new BadRequestException("profile_id not available");
3933 $is_default_profile = $profile['is-default'];
3935 $is_default_profile = 1;
3938 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3940 if (!empty($_FILES['image'])) {
3941 $media = $_FILES['image'];
3942 } elseif (!empty($_FILES['media'])) {
3943 $media = $_FILES['media'];
3945 // save new profile image
3946 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3949 if (is_array($media['type'])) {
3950 $filetype = $media['type'][0];
3952 $filetype = $media['type'];
3954 if ($filetype == "image/jpeg") {
3956 } elseif ($filetype == "image/png") {
3959 throw new InternalServerErrorException('Unsupported filetype');
3962 // change specified profile or all profiles to the new resource-id
3963 if ($is_default_profile) {
3964 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
3965 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3967 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3968 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3969 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
3972 Contact::updateSelfFromUserID(api_user(), true);
3974 // Update global directory in background
3975 Profile::publishUpdate(api_user());
3977 // output for client
3979 return api_account_verify_credentials($type);
3981 // SaveMediaToDatabase failed for some reason
3982 throw new InternalServerErrorException("image upload failed");
3986 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3987 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3988 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3989 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3990 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3991 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3994 * Update user profile
3996 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3998 * @return array|string
3999 * @throws BadRequestException
4000 * @throws ForbiddenException
4001 * @throws ImagickException
4002 * @throws InternalServerErrorException
4003 * @throws UnauthorizedException
4005 function api_account_update_profile($type)
4007 $local_user = api_user();
4008 $api_user = api_get_user();
4010 if (!empty($_POST['name'])) {
4011 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4012 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4013 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4014 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
4017 if (isset($_POST['description'])) {
4018 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4019 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4020 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
4023 Profile::publishUpdate($local_user);
4025 return api_account_verify_credentials($type);
4028 /// @TODO move to top of file or somewhere better
4029 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4033 * @param string $acl_string
4037 function check_acl_input($acl_string)
4039 if (empty($acl_string)) {
4043 $contact_not_found = false;
4045 // split <x><y><z> into array of cid's
4046 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4048 // check for each cid if it is available on server
4049 $cid_array = $array[0];
4050 foreach ($cid_array as $cid) {
4051 $cid = str_replace("<", "", $cid);
4052 $cid = str_replace(">", "", $cid);
4053 $condition = ['id' => $cid, 'uid' => api_user()];
4054 $contact_not_found |= !DBA::exists('contact', $condition);
4056 return $contact_not_found;
4060 * @param string $mediatype
4061 * @param array $media
4062 * @param string $type
4063 * @param string $album
4064 * @param string $allow_cid
4065 * @param string $deny_cid
4066 * @param string $allow_gid
4067 * @param string $deny_gid
4068 * @param string $desc
4069 * @param integer $phototype
4070 * @param boolean $visibility
4071 * @param string $photo_id
4073 * @throws BadRequestException
4074 * @throws ForbiddenException
4075 * @throws ImagickException
4076 * @throws InternalServerErrorException
4077 * @throws NotFoundException
4078 * @throws UnauthorizedException
4080 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)
4088 if (is_array($media)) {
4089 if (is_array($media['tmp_name'])) {
4090 $src = $media['tmp_name'][0];
4092 $src = $media['tmp_name'];
4094 if (is_array($media['name'])) {
4095 $filename = basename($media['name'][0]);
4097 $filename = basename($media['name']);
4099 if (is_array($media['size'])) {
4100 $filesize = intval($media['size'][0]);
4102 $filesize = intval($media['size']);
4104 if (is_array($media['type'])) {
4105 $filetype = $media['type'][0];
4107 $filetype = $media['type'];
4111 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4114 "File upload src: " . $src . " - filename: " . $filename .
4115 " - size: " . $filesize . " - type: " . $filetype);
4117 // check if there was a php upload error
4118 if ($filesize == 0 && $media['error'] == 1) {
4119 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4121 // check against max upload size within Friendica instance
4122 $maximagesize = DI::config()->get('system', 'maximagesize');
4123 if ($maximagesize && ($filesize > $maximagesize)) {
4124 $formattedBytes = Strings::formatBytes($maximagesize);
4125 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4128 // create Photo instance with the data of the image
4129 $imagedata = @file_get_contents($src);
4130 $Image = new Image($imagedata, $filetype);
4131 if (!$Image->isValid()) {
4132 throw new InternalServerErrorException("unable to process image data");
4135 // check orientation of image
4136 $Image->orient($src);
4139 // check max length of images on server
4140 $max_length = DI::config()->get('system', 'max_image_length');
4141 if ($max_length > 0) {
4142 $Image->scaleDown($max_length);
4143 logger::info("File upload: Scaling picture to new size " . $max_length);
4145 $width = $Image->getWidth();
4146 $height = $Image->getHeight();
4148 // create a new resource-id if not already provided
4149 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4151 if ($mediatype == "photo") {
4152 // upload normal image (scales 0, 1, 2)
4153 logger::info("photo upload: starting new photo upload");
4155 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4157 logger::notice("photo upload: image upload with scale 0 (original size) failed");
4159 if ($width > 640 || $height > 640) {
4160 $Image->scaleDown(640);
4161 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4163 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
4167 if ($width > 320 || $height > 320) {
4168 $Image->scaleDown(320);
4169 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4171 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
4174 logger::info("photo upload: new photo upload ended");
4175 } elseif ($mediatype == "profileimage") {
4176 // upload profile image (scales 4, 5, 6)
4177 logger::info("photo upload: starting new profile image upload");
4179 if ($width > 300 || $height > 300) {
4180 $Image->scaleDown(300);
4181 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4183 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
4187 if ($width > 80 || $height > 80) {
4188 $Image->scaleDown(80);
4189 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4191 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
4195 if ($width > 48 || $height > 48) {
4196 $Image->scaleDown(48);
4197 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4199 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
4202 $Image->__destruct();
4203 logger::info("photo upload: new profile image upload ended");
4207 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4208 if ($photo_id == null && $mediatype == "photo") {
4209 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4211 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4212 return prepare_photo_data($type, false, $resource_id);
4214 throw new InternalServerErrorException("image upload failed");
4220 * @param string $hash
4221 * @param string $allow_cid
4222 * @param string $deny_cid
4223 * @param string $allow_gid
4224 * @param string $deny_gid
4225 * @param string $filetype
4226 * @param boolean $visibility
4227 * @throws InternalServerErrorException
4229 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4231 // get data about the api authenticated user
4232 $uri = Item::newURI(intval(api_user()));
4233 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4236 $arr['guid'] = System::createUUID();
4237 $arr['uid'] = intval(api_user());
4239 $arr['type'] = 'photo';
4241 $arr['resource-id'] = $hash;
4242 $arr['contact-id'] = $owner_record['id'];
4243 $arr['owner-name'] = $owner_record['name'];
4244 $arr['owner-link'] = $owner_record['url'];
4245 $arr['owner-avatar'] = $owner_record['thumb'];
4246 $arr['author-name'] = $owner_record['name'];
4247 $arr['author-link'] = $owner_record['url'];
4248 $arr['author-avatar'] = $owner_record['thumb'];
4250 $arr['allow_cid'] = $allow_cid;
4251 $arr['allow_gid'] = $allow_gid;
4252 $arr['deny_cid'] = $deny_cid;
4253 $arr['deny_gid'] = $deny_gid;
4254 $arr['visible'] = $visibility;
4258 'image/jpeg' => 'jpg',
4259 'image/png' => 'png',
4260 'image/gif' => 'gif'
4263 // adds link to the thumbnail scale photo
4264 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4265 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4268 // do the magic for storing the item in the database and trigger the federation to other contacts
4274 * @param string $type
4276 * @param string $photo_id
4279 * @throws BadRequestException
4280 * @throws ForbiddenException
4281 * @throws ImagickException
4282 * @throws InternalServerErrorException
4283 * @throws NotFoundException
4284 * @throws UnauthorizedException
4286 function prepare_photo_data($type, $scale, $photo_id)
4289 $user_info = api_get_user();
4291 if ($user_info === false) {
4292 throw new ForbiddenException();
4295 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4296 $data_sql = ($scale === false ? "" : "data, ");
4298 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4299 // clients needs to convert this in their way for further processing
4300 $r = DBA::toArray(DBA::p(
4301 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4302 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4303 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4304 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4305 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4306 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4312 'image/jpeg' => 'jpg',
4313 'image/png' => 'png',
4314 'image/gif' => 'gif'
4317 // prepare output data for photo
4318 if (DBA::isResult($r)) {
4319 $data = ['photo' => $r[0]];
4320 $data['photo']['id'] = $data['photo']['resource-id'];
4321 if ($scale !== false) {
4322 $data['photo']['data'] = base64_encode($data['photo']['data']);
4324 unset($data['photo']['datasize']); //needed only with scale param
4326 if ($type == "xml") {
4327 $data['photo']['links'] = [];
4328 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4329 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4331 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4334 $data['photo']['link'] = [];
4335 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4337 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4338 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4342 unset($data['photo']['resource-id']);
4343 unset($data['photo']['minscale']);
4344 unset($data['photo']['maxscale']);
4346 throw new NotFoundException();
4349 // retrieve item element for getting activities (like, dislike etc.) related to photo
4350 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4351 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4352 if (!DBA::isResult($item)) {
4353 throw new NotFoundException('Photo-related item not found.');
4356 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4358 // retrieve comments on photo
4359 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4360 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4362 $statuses = Post::selectForUser(api_user(), [], $condition);
4364 // prepare output of comments
4365 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4367 if ($type == "xml") {
4369 foreach ($commentData as $comment) {
4370 $comments[$k++ . ":comment"] = $comment;
4373 foreach ($commentData as $comment) {
4374 $comments[] = $comment;
4377 $data['photo']['friendica_comments'] = $comments;
4379 // include info if rights on photo and rights on item are mismatching
4380 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4381 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4382 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4383 $data['photo']['deny_gid'] != $item['deny_gid'];
4384 $data['photo']['rights_mismatch'] = $rights_mismatch;
4390 * Return an item with announcer data if it had been announced
4392 * @param array $item Item array
4393 * @return array Item array with announce data
4395 function api_get_announce($item)
4397 // Quit if the item already has got a different owner and author
4398 if ($item['owner-id'] != $item['author-id']) {
4402 // Don't change original or Diaspora posts
4403 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4407 // Quit if we do now the original author and it had been a post from a native network
4408 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4412 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4413 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4414 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4415 if (!DBA::isResult($announce)) {
4419 return array_merge($item, $announce);
4424 * @param array $item
4429 function api_in_reply_to($item)
4433 $in_reply_to['status_id'] = null;
4434 $in_reply_to['user_id'] = null;
4435 $in_reply_to['status_id_str'] = null;
4436 $in_reply_to['user_id_str'] = null;
4437 $in_reply_to['screen_name'] = null;
4439 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4440 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4441 if (DBA::isResult($parent)) {
4442 $in_reply_to['status_id'] = intval($parent['id']);
4444 $in_reply_to['status_id'] = intval($item['parent']);
4447 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4449 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4450 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4452 if (DBA::isResult($parent)) {
4453 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4454 $in_reply_to['user_id'] = intval($parent['author-id']);
4455 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4458 // There seems to be situation, where both fields are identical:
4459 // https://github.com/friendica/friendica/issues/1010
4460 // This is a bugfix for that.
4461 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4462 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']]);
4463 $in_reply_to['status_id'] = null;
4464 $in_reply_to['user_id'] = null;
4465 $in_reply_to['status_id_str'] = null;
4466 $in_reply_to['user_id_str'] = null;
4467 $in_reply_to['screen_name'] = null;
4471 return $in_reply_to;
4476 * @param string $text
4479 * @throws InternalServerErrorException
4481 function api_clean_plain_items($text)
4483 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4485 $text = BBCode::cleanPictureLinks($text);
4486 $URLSearchString = "^\[\]";
4488 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4490 if ($include_entities == "true") {
4491 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4494 // Simplify "attachment" element
4495 $text = BBCode::removeAttachment($text);
4502 * @param array $contacts
4506 function api_best_nickname(&$contacts)
4510 if (count($contacts) == 0) {
4514 foreach ($contacts as $contact) {
4515 if ($contact["network"] == "") {
4516 $contact["network"] = "dfrn";
4517 $best_contact = [$contact];
4521 if (sizeof($best_contact) == 0) {
4522 foreach ($contacts as $contact) {
4523 if ($contact["network"] == "dfrn") {
4524 $best_contact = [$contact];
4529 if (sizeof($best_contact) == 0) {
4530 foreach ($contacts as $contact) {
4531 if ($contact["network"] == "dspr") {
4532 $best_contact = [$contact];
4537 if (sizeof($best_contact) == 0) {
4538 foreach ($contacts as $contact) {
4539 if ($contact["network"] == "stat") {
4540 $best_contact = [$contact];
4545 if (sizeof($best_contact) == 0) {
4546 foreach ($contacts as $contact) {
4547 if ($contact["network"] == "pump") {
4548 $best_contact = [$contact];
4553 if (sizeof($best_contact) == 0) {
4554 foreach ($contacts as $contact) {
4555 if ($contact["network"] == "twit") {
4556 $best_contact = [$contact];
4561 if (sizeof($best_contact) == 1) {
4562 $contacts = $best_contact;
4564 $contacts = [$contacts[0]];
4569 * Return all or a specified group of the user with the containing contacts.
4571 * @param string $type Return type (atom, rss, xml, json)
4573 * @return array|string
4574 * @throws BadRequestException
4575 * @throws ForbiddenException
4576 * @throws ImagickException
4577 * @throws InternalServerErrorException
4578 * @throws UnauthorizedException
4580 function api_friendica_group_show($type)
4584 if (api_user() === false) {
4585 throw new ForbiddenException();
4589 $user_info = api_get_user();
4590 $gid = $_REQUEST['gid'] ?? 0;
4591 $uid = $user_info['uid'];
4593 // get data of the specified group id or all groups if not specified
4595 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4597 // error message if specified gid is not in database
4598 if (!DBA::isResult($groups)) {
4599 throw new BadRequestException("gid not available");
4602 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4605 // loop through all groups and retrieve all members for adding data in the user array
4607 foreach ($groups as $rr) {
4608 $members = Contact\Group::getById($rr['id']);
4611 if ($type == "xml") {
4612 $user_element = "users";
4614 foreach ($members as $member) {
4615 $user = api_get_user($member['nurl']);
4616 $users[$k++.":user"] = $user;
4619 $user_element = "user";
4620 foreach ($members as $member) {
4621 $user = api_get_user($member['nurl']);
4625 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4627 return BaseApi::formatData("groups", $type, ['group' => $grps]);
4629 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4633 * Delete the specified group of the user.
4635 * @param string $type Return type (atom, rss, xml, json)
4637 * @return array|string
4638 * @throws BadRequestException
4639 * @throws ForbiddenException
4640 * @throws ImagickException
4641 * @throws InternalServerErrorException
4642 * @throws UnauthorizedException
4644 function api_friendica_group_delete($type)
4648 if (api_user() === false) {
4649 throw new ForbiddenException();
4653 $user_info = api_get_user();
4654 $gid = $_REQUEST['gid'] ?? 0;
4655 $name = $_REQUEST['name'] ?? '';
4656 $uid = $user_info['uid'];
4658 // error if no gid specified
4659 if ($gid == 0 || $name == "") {
4660 throw new BadRequestException('gid or name not specified');
4663 // error message if specified gid is not in database
4664 if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid])) {
4665 throw new BadRequestException('gid not available');
4668 // error message if specified gid is not in database
4669 if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid, 'name' => $name])) {
4670 throw new BadRequestException('wrong group name');
4674 $gid = Group::getIdByName($uid, $name);
4676 throw new BadRequestException('other API error');
4679 $ret = Group::remove($gid);
4683 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
4684 return BaseApi::formatData("group_delete", $type, ['result' => $success]);
4686 throw new BadRequestException('other API error');
4689 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4694 * @param string $type Return type (atom, rss, xml, json)
4696 * @return array|string
4697 * @throws BadRequestException
4698 * @throws ForbiddenException
4699 * @throws ImagickException
4700 * @throws InternalServerErrorException
4701 * @throws UnauthorizedException
4702 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4704 function api_lists_destroy($type)
4708 if (api_user() === false) {
4709 throw new ForbiddenException();
4713 $user_info = api_get_user();
4714 $gid = $_REQUEST['list_id'] ?? 0;
4715 $uid = $user_info['uid'];
4717 // error if no gid specified
4719 throw new BadRequestException('gid not specified');
4722 // get data of the specified group id
4723 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4724 // error message if specified gid is not in database
4726 throw new BadRequestException('gid not available');
4729 if (Group::remove($gid)) {
4731 'name' => $group['name'],
4732 'id' => intval($gid),
4733 'id_str' => (string) $gid,
4734 'user' => $user_info
4737 return BaseApi::formatData("lists", $type, ['lists' => $list]);
4740 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4743 * Add a new group to the database.
4745 * @param string $name Group name
4746 * @param int $uid User ID
4747 * @param array $users List of users to add to the group
4750 * @throws BadRequestException
4752 function group_create($name, $uid, $users = [])
4754 // error if no name specified
4756 throw new BadRequestException('group name not specified');
4759 // error message if specified group name already exists
4760 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4761 throw new BadRequestException('group name already exists');
4764 // Check if the group needs to be reactivated
4765 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4766 $reactivate_group = true;
4770 $ret = Group::create($uid, $name);
4772 $gid = Group::getIdByName($uid, $name);
4774 throw new BadRequestException('other API error');
4778 $erroraddinguser = false;
4780 foreach ($users as $user) {
4781 $cid = $user['cid'];
4782 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4783 Group::addMember($gid, $cid);
4785 $erroraddinguser = true;
4786 $errorusers[] = $cid;
4790 // return success message incl. missing users in array
4791 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4793 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4797 * Create the specified group with the posted array of contacts.
4799 * @param string $type Return type (atom, rss, xml, json)
4801 * @return array|string
4802 * @throws BadRequestException
4803 * @throws ForbiddenException
4804 * @throws ImagickException
4805 * @throws InternalServerErrorException
4806 * @throws UnauthorizedException
4808 function api_friendica_group_create($type)
4812 if (api_user() === false) {
4813 throw new ForbiddenException();
4817 $user_info = api_get_user();
4818 $name = $_REQUEST['name'] ?? '';
4819 $uid = $user_info['uid'];
4820 $json = json_decode($_POST['json'], true);
4821 $users = $json['user'];
4823 $success = group_create($name, $uid, $users);
4825 return BaseApi::formatData("group_create", $type, ['result' => $success]);
4827 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4830 * Create a new group.
4832 * @param string $type Return type (atom, rss, xml, json)
4834 * @return array|string
4835 * @throws BadRequestException
4836 * @throws ForbiddenException
4837 * @throws ImagickException
4838 * @throws InternalServerErrorException
4839 * @throws UnauthorizedException
4840 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4842 function api_lists_create($type)
4846 if (api_user() === false) {
4847 throw new ForbiddenException();
4851 $user_info = api_get_user();
4852 $name = $_REQUEST['name'] ?? '';
4853 $uid = $user_info['uid'];
4855 $success = group_create($name, $uid);
4856 if ($success['success']) {
4858 'name' => $success['name'],
4859 'id' => intval($success['gid']),
4860 'id_str' => (string) $success['gid'],
4861 'user' => $user_info
4864 return BaseApi::formatData("lists", $type, ['lists'=>$grp]);
4867 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4870 * Update the specified group with the posted array of contacts.
4872 * @param string $type Return type (atom, rss, xml, json)
4874 * @return array|string
4875 * @throws BadRequestException
4876 * @throws ForbiddenException
4877 * @throws ImagickException
4878 * @throws InternalServerErrorException
4879 * @throws UnauthorizedException
4881 function api_friendica_group_update($type)
4885 if (api_user() === false) {
4886 throw new ForbiddenException();
4890 $user_info = api_get_user();
4891 $uid = $user_info['uid'];
4892 $gid = $_REQUEST['gid'] ?? 0;
4893 $name = $_REQUEST['name'] ?? '';
4894 $json = json_decode($_POST['json'], true);
4895 $users = $json['user'];
4897 // error if no name specified
4899 throw new BadRequestException('group name not specified');
4902 // error if no gid specified
4904 throw new BadRequestException('gid not specified');
4908 $members = Contact\Group::getById($gid);
4909 foreach ($members as $member) {
4910 $cid = $member['id'];
4911 foreach ($users as $user) {
4912 $found = ($user['cid'] == $cid ? true : false);
4914 if (!isset($found) || !$found) {
4915 $gid = Group::getIdByName($uid, $name);
4916 Group::removeMember($gid, $cid);
4921 $erroraddinguser = false;
4923 foreach ($users as $user) {
4924 $cid = $user['cid'];
4926 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4927 Group::addMember($gid, $cid);
4929 $erroraddinguser = true;
4930 $errorusers[] = $cid;
4934 // return success message incl. missing users in array
4935 $status = ($erroraddinguser ? "missing user" : "ok");
4936 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4937 return BaseApi::formatData("group_update", $type, ['result' => $success]);
4940 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4943 * Update information about a group.
4945 * @param string $type Return type (atom, rss, xml, json)
4947 * @return array|string
4948 * @throws BadRequestException
4949 * @throws ForbiddenException
4950 * @throws ImagickException
4951 * @throws InternalServerErrorException
4952 * @throws UnauthorizedException
4953 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4955 function api_lists_update($type)
4959 if (api_user() === false) {
4960 throw new ForbiddenException();
4964 $user_info = api_get_user();
4965 $gid = $_REQUEST['list_id'] ?? 0;
4966 $name = $_REQUEST['name'] ?? '';
4967 $uid = $user_info['uid'];
4969 // error if no gid specified
4971 throw new BadRequestException('gid not specified');
4974 // get data of the specified group id
4975 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4976 // error message if specified gid is not in database
4978 throw new BadRequestException('gid not available');
4981 if (Group::update($gid, $name)) {
4984 'id' => intval($gid),
4985 'id_str' => (string) $gid,
4986 'user' => $user_info
4989 return BaseApi::formatData("lists", $type, ['lists' => $list]);
4993 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4996 * Set notification as seen and returns associated item (if possible)
4998 * POST request with 'id' param as notification id
5000 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5001 * @return string|array
5002 * @throws BadRequestException
5003 * @throws ForbiddenException
5004 * @throws ImagickException
5005 * @throws InternalServerErrorException
5006 * @throws UnauthorizedException
5008 function api_friendica_notification_seen($type)
5011 $user_info = api_get_user();
5013 if (api_user() === false || $user_info === false) {
5014 throw new ForbiddenException();
5016 if (DI::args()->getArgc() !== 4) {
5017 throw new BadRequestException('Invalid argument count');
5020 $id = intval($_REQUEST['id'] ?? 0);
5023 $Notify = DI::notify()->selectOneById($id);
5024 if ($Notify->uid !== api_user()) {
5025 throw new NotFoundException();
5028 if ($Notify->uriId) {
5029 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
5033 DI::notify()->save($Notify);
5035 if ($Notify->otype === Notification\ObjectType::ITEM) {
5036 $item = Post::selectFirstForUser(api_user(), [], ['id' => $Notify->iid, 'uid' => api_user()]);
5037 if (DBA::isResult($item)) {
5038 // we found the item, return it to the user
5039 $ret = api_format_items([$item], $user_info, false, $type);
5040 $data = ['status' => $ret];
5041 return BaseApi::formatData('status', $type, $data);
5043 // the item can't be found, but we set the notification as seen, so we count this as a success
5046 return BaseApi::formatData('result', $type, ['result' => 'success']);
5047 } catch (NotFoundException $e) {
5048 throw new BadRequestException('Invalid argument', $e);
5049 } catch (Exception $e) {
5050 throw new InternalServerErrorException('Internal Server exception', $e);
5054 /// @TODO move to top of file or somewhere better
5055 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5058 * search for direct_messages containing a searchstring through api
5060 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5061 * @param string $box
5062 * @return string|array (success: success=true if found and search_result contains found messages,
5063 * success=false if nothing was found, search_result='nothing found',
5064 * error: result=error with error message)
5065 * @throws BadRequestException
5066 * @throws ForbiddenException
5067 * @throws ImagickException
5068 * @throws InternalServerErrorException
5069 * @throws UnauthorizedException
5071 function api_friendica_direct_messages_search($type, $box = "")
5075 if (api_user() === false) {
5076 throw new ForbiddenException();
5080 $user_info = api_get_user();
5081 $searchstring = $_REQUEST['searchstring'] ?? '';
5082 $uid = $user_info['uid'];
5084 // error if no searchstring specified
5085 if ($searchstring == "") {
5086 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5087 return BaseApi::formatData("direct_messages_search", $type, ['$result' => $answer]);
5090 // get data for the specified searchstring
5091 $r = DBA::toArray(DBA::p(
5092 "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",
5094 '%'.$searchstring.'%'
5097 $profile_url = $user_info["url"];
5099 // message if nothing was found
5100 if (!DBA::isResult($r)) {
5101 $success = ['success' => false, 'search_results' => 'problem with query'];
5102 } elseif (count($r) == 0) {
5103 $success = ['success' => false, 'search_results' => 'nothing found'];
5106 foreach ($r as $item) {
5107 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5108 $recipient = $user_info;
5109 $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
5110 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5111 $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
5112 $sender = $user_info;
5115 if (isset($recipient) && isset($sender)) {
5116 $ret[] = api_format_messages($item, $recipient, $sender);
5119 $success = ['success' => true, 'search_results' => $ret];
5122 return BaseApi::formatData("direct_message_search", $type, ['$result' => $success]);
5125 /// @TODO move to top of file or somewhere better
5126 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5129 * Number of comments
5131 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
5133 * @param object $data [Status, Status]
5137 function bindComments(&$data)
5139 if (count($data) == 0) {
5145 foreach ($data as $item) {
5146 $ids[] = $item['id'];
5149 $idStr = DBA::escape(implode(', ', $ids));
5150 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
5151 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
5152 $itemsData = DBA::toArray($items);
5154 foreach ($itemsData as $item) {
5155 $comments[$item['parent']] = $item['comments'];
5158 foreach ($data as $idx => $item) {
5160 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
5165 @TODO Maybe open to implement?
5167 [pagename] => api/1.1/statuses/lookup.json
5168 [id] => 605138389168451584
5169 [include_cards] => true
5170 [cards_platform] => Android-12
5171 [include_entities] => true
5172 [include_my_retweet] => 1
5174 [include_reply_count] => true
5175 [include_descendent_reply_count] => true
5179 Not implemented by now:
5180 statuses/retweets_of_me
5185 account/update_location
5186 account/update_profile_background_image
5189 friendica/profile/update
5190 friendica/profile/create
5191 friendica/profile/delete
5193 Not implemented in status.net:
5194 statuses/retweeted_to_me
5195 statuses/retweeted_by_me
5196 direct_messages/destroy
5198 account/update_delivery_device
5199 notifications/follow