3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\BaseObject;
11 use Friendica\Content\ContactSelector;
12 use Friendica\Content\Feature;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\HTML;
15 use Friendica\App\Authentication;
16 use Friendica\Core\Config;
17 use Friendica\Core\Hook;
18 use Friendica\Core\L10n;
19 use Friendica\Core\Logger;
20 use Friendica\Core\PConfig;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\Session;
23 use Friendica\Core\System;
24 use Friendica\Core\Worker;
25 use Friendica\Database\DBA;
26 use Friendica\Model\Contact;
27 use Friendica\Model\Group;
28 use Friendica\Model\Item;
29 use Friendica\Model\Mail;
30 use Friendica\Model\Notify;
31 use Friendica\Model\Photo;
32 use Friendica\Model\Profile;
33 use Friendica\Model\User;
34 use Friendica\Network\FKOAuth1;
35 use Friendica\Network\HTTPException;
36 use Friendica\Network\HTTPException\BadRequestException;
37 use Friendica\Network\HTTPException\ExpectationFailedException;
38 use Friendica\Network\HTTPException\ForbiddenException;
39 use Friendica\Network\HTTPException\InternalServerErrorException;
40 use Friendica\Network\HTTPException\MethodNotAllowedException;
41 use Friendica\Network\HTTPException\NotFoundException;
42 use Friendica\Network\HTTPException\NotImplementedException;
43 use Friendica\Network\HTTPException\TooManyRequestsException;
44 use Friendica\Network\HTTPException\UnauthorizedException;
45 use Friendica\Object\Image;
46 use Friendica\Protocol\Activity;
47 use Friendica\Protocol\Diaspora;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Images;
50 use Friendica\Util\Network;
51 use Friendica\Util\Proxy as ProxyUtils;
52 use Friendica\Util\Strings;
53 use Friendica\Util\XML;
55 require_once __DIR__ . '/../mod/share.php';
56 require_once __DIR__ . '/../mod/item.php';
57 require_once __DIR__ . '/../mod/wall_upload.php';
59 define('API_METHOD_ANY', '*');
60 define('API_METHOD_GET', 'GET');
61 define('API_METHOD_POST', 'POST,PUT');
62 define('API_METHOD_DELETE', 'POST,DELETE');
64 define('API_LOG_PREFIX', 'API {action} - ');
70 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
71 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
72 * into a page, and visitors will post something without noticing it).
74 * @brief Auth API user
78 if (!empty($_SESSION['allow_api'])) {
86 * Clients can send 'source' parameter to be show in post metadata
87 * as "sent via <source>".
88 * Some clients doesn't send a source param, we support ones we know
91 * @brief Get source name from API client
94 * Client source name, default to "api" if unset/unknown
99 if (requestdata('source')) {
100 return requestdata('source');
103 // Support for known clients that doesn't send a source name
104 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
105 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
109 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
111 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
118 * @brief Format date for API
120 * @param string $str Source date, as UTC
121 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
124 function api_date($str)
126 // Wed May 23 06:01:13 +0000 2007
127 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
131 * Register a function to be the endpoint for defined API path.
133 * @brief Register API endpoint
135 * @param string $path API URL path, relative to System::baseUrl()
136 * @param string $func Function name to call on path request
137 * @param bool $auth API need logged user
138 * @param string $method HTTP method reqiured to call this endpoint.
139 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
140 * Default to API_METHOD_ANY
142 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
152 // Workaround for hotot
153 $path = str_replace("api/", "api/1.1/", $path);
163 * Log in user via OAuth1 or Simple HTTP Auth.
164 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
166 * @brief Login API user
169 * @throws ForbiddenException
170 * @throws InternalServerErrorException
171 * @throws UnauthorizedException
172 * @hook 'authenticate'
174 * 'username' => username from login form
175 * 'password' => password from login form
176 * 'authenticated' => return status,
177 * 'user_record' => return authenticated user record
179 function api_login(App $a)
181 $oauth1 = new FKOAuth1();
184 $request = OAuthRequest::from_request();
185 list($consumer, $token) = $oauth1->verify_request($request);
186 if (!is_null($token)) {
187 $oauth1->loginUser($token->uid);
188 Session::set('allow_api', true);
191 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
192 var_dump($consumer, $token);
194 } catch (Exception $e) {
195 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
198 // workaround for HTTP-auth in CGI mode
199 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
200 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
201 if (strlen($userpass)) {
202 list($name, $password) = explode(':', $userpass);
203 $_SERVER['PHP_AUTH_USER'] = $name;
204 $_SERVER['PHP_AUTH_PW'] = $password;
208 if (empty($_SERVER['PHP_AUTH_USER'])) {
209 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
210 header('WWW-Authenticate: Basic realm="Friendica"');
211 throw new UnauthorizedException("This API requires login");
214 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
215 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
217 // allow "user@server" login (but ignore 'server' part)
218 $at = strstr($user, "@", true);
223 // next code from mod/auth.php. needs better solution
227 'username' => trim($user),
228 'password' => trim($password),
229 'authenticated' => 0,
230 'user_record' => null,
234 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
235 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
236 * and later addons should not interfere with an earlier one that succeeded.
238 Hook::callAll('authenticate', $addon_auth);
240 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
241 $record = $addon_auth['user_record'];
243 $user_id = User::authenticate(trim($user), trim($password), true);
244 if ($user_id !== false) {
245 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
249 if (!DBA::isResult($record)) {
250 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
251 header('WWW-Authenticate: Basic realm="Friendica"');
252 //header('HTTP/1.0 401 Unauthorized');
253 //die('This api requires login');
254 throw new UnauthorizedException("This API requires login");
257 /** @var Authentication $authentication */
258 $authentication = BaseObject::getClass(Authentication::class);
259 $authentication->setForUser($a, $record);
261 $_SESSION["allow_api"] = true;
263 Hook::callAll('logged_in', $a->user);
267 * API endpoints can define which HTTP method to accept when called.
268 * This function check the current HTTP method agains endpoint
271 * @brief Check HTTP method of called API
273 * @param string $method Required methods, uppercase, separated by comma
276 function api_check_method($method)
278 if ($method == "*") {
281 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
285 * Authenticate user, call registered API function, set HTTP headers
287 * @brief Main API entry point
290 * @return string|array API call result
293 function api_call(App $a)
295 global $API, $called_api;
298 if (strpos($a->query_string, ".xml") > 0) {
301 if (strpos($a->query_string, ".json") > 0) {
304 if (strpos($a->query_string, ".rss") > 0) {
307 if (strpos($a->query_string, ".atom") > 0) {
312 foreach ($API as $p => $info) {
313 if (strpos($a->query_string, $p) === 0) {
314 if (!api_check_method($info['method'])) {
315 throw new MethodNotAllowedException();
318 $called_api = explode("/", $p);
319 //unset($_SERVER['PHP_AUTH_USER']);
321 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
322 if (!empty($info['auth']) && api_user() === false) {
326 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
327 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
329 $stamp = microtime(true);
330 $return = call_user_func($info['func'], $type);
331 $duration = floatval(microtime(true) - $stamp);
333 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
335 $a->getProfiler()->saveLog($a->getLogger(), API_LOG_PREFIX . 'performance');
337 if (false === $return) {
339 * api function returned false withour throw an
340 * exception. This should not happend, throw a 500
342 throw new InternalServerErrorException();
347 header("Content-Type: text/xml");
350 header("Content-Type: application/json");
351 if (!empty($return)) {
352 $json = json_encode(end($return));
353 if (!empty($_GET['callback'])) {
354 $json = $_GET['callback'] . "(" . $json . ")";
360 header("Content-Type: application/rss+xml");
361 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
364 header("Content-Type: application/atom+xml");
365 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
372 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => $a->query_string]);
373 throw new NotImplementedException();
374 } catch (HTTPException $e) {
375 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
376 return api_error($type, $e);
381 * @brief Format API error string
383 * @param string $type Return type (xml, json, rss, as)
384 * @param object $e HTTPException Error object
385 * @return string|array error message formatted as $type
387 function api_error($type, $e)
391 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
392 /// @TODO: https://dev.twitter.com/overview/api/response-codes
394 $error = ["error" => $error,
395 "code" => $e->getCode() . " " . $e->httpdesc,
396 "request" => $a->query_string];
398 $return = api_format_data('status', $type, ['status' => $error]);
402 header("Content-Type: text/xml");
405 header("Content-Type: application/json");
406 $return = json_encode($return);
409 header("Content-Type: application/rss+xml");
412 header("Content-Type: application/atom+xml");
420 * @brief Set values for RSS template
423 * @param array $arr Array to be passed to template
424 * @param array $user_info User info
426 * @throws BadRequestException
427 * @throws ImagickException
428 * @throws InternalServerErrorException
429 * @throws UnauthorizedException
430 * @todo find proper type-hints
432 function api_rss_extra(App $a, $arr, $user_info)
434 if (is_null($user_info)) {
435 $user_info = api_get_user($a);
438 $arr['$user'] = $user_info;
440 'alternate' => $user_info['url'],
441 'self' => System::baseUrl() . "/" . $a->query_string,
442 'base' => System::baseUrl(),
443 'updated' => api_date(null),
444 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
445 'language' => $user_info['lang'],
446 'logo' => System::baseUrl() . "/images/friendica-32.png",
454 * @brief Unique contact to contact url.
456 * @param int $id Contact id
457 * @return bool|string
458 * Contact url or False if contact id is unknown
461 function api_unique_id_to_nurl($id)
463 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
465 if (DBA::isResult($r)) {
473 * @brief Get user info array.
476 * @param int|string $contact_id Contact ID or URL
478 * @throws BadRequestException
479 * @throws ImagickException
480 * @throws InternalServerErrorException
481 * @throws UnauthorizedException
483 function api_get_user(App $a, $contact_id = null)
491 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
493 // Searching for contact URL
494 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
495 $user = DBA::escape(Strings::normaliseLink($contact_id));
497 $extra_query = "AND `contact`.`nurl` = '%s' ";
498 if (api_user() !== false) {
499 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
503 // Searching for contact id with uid = 0
504 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
505 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
508 throw new BadRequestException("User ID ".$contact_id." not found.");
512 $extra_query = "AND `contact`.`nurl` = '%s' ";
513 if (api_user() !== false) {
514 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
518 if (is_null($user) && !empty($_GET['user_id'])) {
519 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
522 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
526 $extra_query = "AND `contact`.`nurl` = '%s' ";
527 if (api_user() !== false) {
528 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
531 if (is_null($user) && !empty($_GET['screen_name'])) {
532 $user = DBA::escape($_GET['screen_name']);
533 $extra_query = "AND `contact`.`nick` = '%s' ";
534 if (api_user() !== false) {
535 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
539 if (is_null($user) && !empty($_GET['profileurl'])) {
540 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
541 $extra_query = "AND `contact`.`nurl` = '%s' ";
542 if (api_user() !== false) {
543 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
547 // $called_api is the API path exploded on / and is expected to have at least 2 elements
548 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
549 $argid = count($called_api);
550 if (!empty($a->argv[$argid])) {
551 $data = explode(".", $a->argv[$argid]);
552 if (count($data) > 1) {
553 list($user, $null) = $data;
556 if (is_numeric($user)) {
557 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
561 $extra_query = "AND `contact`.`nurl` = '%s' ";
562 if (api_user() !== false) {
563 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
567 $user = DBA::escape($user);
568 $extra_query = "AND `contact`.`nick` = '%s' ";
569 if (api_user() !== false) {
570 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
575 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
578 if (api_user() === false) {
582 $user = $_SESSION['uid'];
583 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
587 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
591 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
597 // Selecting the id by priority, friendica first
598 if (is_array($uinfo)) {
599 api_best_nickname($uinfo);
602 // if the contact wasn't found, fetch it from the contacts with uid = 0
603 if (!DBA::isResult($uinfo)) {
605 throw new BadRequestException("User not found.");
608 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
610 if (DBA::isResult($contact)) {
611 // If no nick where given, extract it from the address
612 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
613 $contact['nick'] = api_get_nick($contact["url"]);
617 'id' => $contact["id"],
618 'id_str' => (string) $contact["id"],
619 'name' => $contact["name"],
620 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
621 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
622 'description' => BBCode::toPlaintext($contact["about"]),
623 'profile_image_url' => $contact["micro"],
624 'profile_image_url_https' => $contact["micro"],
625 'profile_image_url_profile_size' => $contact["thumb"],
626 'profile_image_url_large' => $contact["photo"],
627 'url' => $contact["url"],
628 'protected' => false,
629 'followers_count' => 0,
630 'friends_count' => 0,
632 'created_at' => api_date($contact["created"]),
633 'favourites_count' => 0,
635 'time_zone' => 'UTC',
636 'geo_enabled' => false,
638 'statuses_count' => 0,
640 'contributors_enabled' => false,
641 'is_translator' => false,
642 'is_translation_enabled' => false,
643 'following' => false,
644 'follow_request_sent' => false,
645 'statusnet_blocking' => false,
646 'notifications' => false,
647 'statusnet_profile_url' => $contact["url"],
649 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
650 'pid' => Contact::getIdForURL($contact["url"], 0, true),
652 'network' => $contact["network"],
657 throw new BadRequestException("User ".$url." not found.");
661 if ($uinfo[0]['self']) {
662 if ($uinfo[0]['network'] == "") {
663 $uinfo[0]['network'] = Protocol::DFRN;
666 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
667 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
674 // Add a nick if it isn't present there
675 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
676 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
679 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
681 if (!empty($profile['about'])) {
682 $description = $profile['about'];
684 $description = $uinfo[0]["about"];
687 if (!empty($usr['default-location'])) {
688 $location = $usr['default-location'];
689 } elseif (!empty($uinfo[0]["location"])) {
690 $location = $uinfo[0]["location"];
692 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
696 'id' => intval($pcontact_id),
697 'id_str' => (string) intval($pcontact_id),
698 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
699 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
700 'location' => $location,
701 'description' => BBCode::toPlaintext($description),
702 'profile_image_url' => $uinfo[0]['micro'],
703 'profile_image_url_https' => $uinfo[0]['micro'],
704 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
705 'profile_image_url_large' => $uinfo[0]["photo"],
706 'url' => $uinfo[0]['url'],
707 'protected' => false,
708 'followers_count' => intval($countfollowers),
709 'friends_count' => intval($countfriends),
711 'created_at' => api_date($uinfo[0]['created']),
712 'favourites_count' => intval($starred),
714 'time_zone' => 'UTC',
715 'geo_enabled' => false,
717 'statuses_count' => intval($countitems),
719 'contributors_enabled' => false,
720 'is_translator' => false,
721 'is_translation_enabled' => false,
722 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
723 'follow_request_sent' => false,
724 'statusnet_blocking' => false,
725 'notifications' => false,
727 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
728 'statusnet_profile_url' => $uinfo[0]['url'],
729 'uid' => intval($uinfo[0]['uid']),
730 'cid' => intval($uinfo[0]['cid']),
731 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
732 'self' => $uinfo[0]['self'],
733 'network' => $uinfo[0]['network'],
736 // If this is a local user and it uses Frio, we can get its color preferences.
738 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
739 if ($theme_info['theme'] === 'frio') {
740 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
742 if ($schema && ($schema != '---')) {
743 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
744 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
745 require_once $schemefile;
748 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
749 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
750 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
752 if (empty($nav_bg)) {
755 if (empty($link_color)) {
756 $link_color = "#6fdbe8";
758 if (empty($bgcolor)) {
759 $bgcolor = "#ededed";
762 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
763 $ret['profile_link_color'] = str_replace('#', '', $link_color);
764 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
772 * @brief return api-formatted array for item's author and owner
775 * @param array $item item from db
776 * @return array(array:author, array:owner)
777 * @throws BadRequestException
778 * @throws ImagickException
779 * @throws InternalServerErrorException
780 * @throws UnauthorizedException
782 function api_item_get_user(App $a, $item)
784 $status_user = api_get_user($a, $item['author-id'] ?? null);
786 $author_user = $status_user;
788 $status_user["protected"] = $item['private'] ?? 0;
790 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
791 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
793 $owner_user = $author_user;
796 return ([$status_user, $author_user, $owner_user]);
800 * @brief walks recursively through an array with the possibility to change value and key
802 * @param array $array The array to walk through
803 * @param callable $callback The callback function
805 * @return array the transformed array
807 function api_walk_recursive(array &$array, callable $callback)
811 foreach ($array as $k => $v) {
813 if ($callback($v, $k)) {
814 $new_array[$k] = api_walk_recursive($v, $callback);
817 if ($callback($v, $k)) {
828 * @brief Callback function to transform the array in an array that can be transformed in a XML file
830 * @param mixed $item Array item value
831 * @param string $key Array key
833 * @return boolean Should the array item be deleted?
835 function api_reformat_xml(&$item, &$key)
837 if (is_bool($item)) {
838 $item = ($item ? "true" : "false");
841 if (substr($key, 0, 10) == "statusnet_") {
842 $key = "statusnet:".substr($key, 10);
843 } elseif (substr($key, 0, 10) == "friendica_") {
844 $key = "friendica:".substr($key, 10);
846 /// @TODO old-lost code?
848 // $key = "default:".$key;
854 * @brief Creates the XML from a JSON style array
856 * @param array $data JSON style array
857 * @param string $root_element Name of the root element
859 * @return string The XML data
861 function api_create_xml(array $data, $root_element)
863 $childname = key($data);
864 $data2 = array_pop($data);
866 $namespaces = ["" => "http://api.twitter.com",
867 "statusnet" => "http://status.net/schema/api/1/",
868 "friendica" => "http://friendi.ca/schema/api/1/",
869 "georss" => "http://www.georss.org/georss"];
871 /// @todo Auto detection of needed namespaces
872 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
876 if (is_array($data2)) {
878 api_walk_recursive($data2, "api_reformat_xml");
884 foreach ($data2 as $item) {
885 $data4[$i++ . ":" . $childname] = $item;
892 $data3 = [$root_element => $data2];
894 $ret = XML::fromArray($data3, $xml, false, $namespaces);
899 * @brief Formats the data according to the data type
901 * @param string $root_element Name of the root element
902 * @param string $type Return type (atom, rss, xml, json)
903 * @param array $data JSON style array
905 * @return array|string (string|array) XML data or JSON data
907 function api_format_data($root_element, $type, $data)
913 $ret = api_create_xml($data, $root_element);
928 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
929 * returns a 401 status code and an error message if not.
931 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
933 * @param string $type Return type (atom, rss, xml, json)
934 * @return array|string
935 * @throws BadRequestException
936 * @throws ForbiddenException
937 * @throws ImagickException
938 * @throws InternalServerErrorException
939 * @throws UnauthorizedException
941 function api_account_verify_credentials($type)
945 if (api_user() === false) {
946 throw new ForbiddenException();
949 unset($_REQUEST["user_id"]);
950 unset($_GET["user_id"]);
952 unset($_REQUEST["screen_name"]);
953 unset($_GET["screen_name"]);
955 $skip_status = $_REQUEST['skip_status'] ?? false;
957 $user_info = api_get_user($a);
959 // "verified" isn't used here in the standard
960 unset($user_info["verified"]);
962 // - Adding last status
964 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
966 $user_info['status'] = api_format_item($item, $type);
970 // "uid" and "self" are only needed for some internal stuff, so remove it from here
971 unset($user_info["uid"]);
972 unset($user_info["self"]);
974 return api_format_data("user", $type, ['user' => $user_info]);
977 /// @TODO move to top of file or somewhere better
978 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
981 * Get data from $_POST or $_GET
986 function requestdata($k)
988 if (!empty($_POST[$k])) {
991 if (!empty($_GET[$k])) {
998 * Deprecated function to upload media.
1000 * @param string $type Return type (atom, rss, xml, json)
1002 * @return array|string
1003 * @throws BadRequestException
1004 * @throws ForbiddenException
1005 * @throws ImagickException
1006 * @throws InternalServerErrorException
1007 * @throws UnauthorizedException
1009 function api_statuses_mediap($type)
1013 if (api_user() === false) {
1014 Logger::log('api_statuses_update: no user');
1015 throw new ForbiddenException();
1017 $user_info = api_get_user($a);
1019 $_REQUEST['profile_uid'] = api_user();
1020 $_REQUEST['api_source'] = true;
1021 $txt = requestdata('status');
1022 /// @TODO old-lost code?
1023 //$txt = urldecode(requestdata('status'));
1025 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1026 $txt = HTML::toBBCodeVideo($txt);
1027 $config = HTMLPurifier_Config::createDefault();
1028 $config->set('Cache.DefinitionImpl', null);
1029 $purifier = new HTMLPurifier($config);
1030 $txt = $purifier->purify($txt);
1032 $txt = HTML::toBBCode($txt);
1034 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1036 $picture = wall_upload_post($a, false);
1038 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1039 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1040 $item_id = item_post($a);
1042 // output the post that we just posted.
1043 return api_status_show($type, $item_id);
1046 /// @TODO move this to top of file or somewhere better!
1047 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1050 * Updates the user’s current status.
1052 * @param string $type Return type (atom, rss, xml, json)
1054 * @return array|string
1055 * @throws BadRequestException
1056 * @throws ForbiddenException
1057 * @throws ImagickException
1058 * @throws InternalServerErrorException
1059 * @throws TooManyRequestsException
1060 * @throws UnauthorizedException
1061 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1063 function api_statuses_update($type)
1067 if (api_user() === false) {
1068 Logger::log('api_statuses_update: no user');
1069 throw new ForbiddenException();
1074 // convert $_POST array items to the form we use for web posts.
1075 if (requestdata('htmlstatus')) {
1076 $txt = requestdata('htmlstatus');
1077 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1078 $txt = HTML::toBBCodeVideo($txt);
1080 $config = HTMLPurifier_Config::createDefault();
1081 $config->set('Cache.DefinitionImpl', null);
1083 $purifier = new HTMLPurifier($config);
1084 $txt = $purifier->purify($txt);
1086 $_REQUEST['body'] = HTML::toBBCode($txt);
1089 $_REQUEST['body'] = requestdata('status');
1092 $_REQUEST['title'] = requestdata('title');
1094 $parent = requestdata('in_reply_to_status_id');
1096 // Twidere sends "-1" if it is no reply ...
1097 if ($parent == -1) {
1101 if (ctype_digit($parent)) {
1102 $_REQUEST['parent'] = $parent;
1104 $_REQUEST['parent_uri'] = $parent;
1107 if (requestdata('lat') && requestdata('long')) {
1108 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1110 $_REQUEST['profile_uid'] = api_user();
1113 // Check for throttling (maximum posts per day, week and month)
1114 $throttle_day = Config::get('system', 'throttle_limit_day');
1115 if ($throttle_day > 0) {
1116 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1118 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1119 $posts_day = DBA::count('thread', $condition);
1121 if ($posts_day > $throttle_day) {
1122 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1123 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1124 throw new TooManyRequestsException(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));
1128 $throttle_week = Config::get('system', 'throttle_limit_week');
1129 if ($throttle_week > 0) {
1130 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1132 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1133 $posts_week = DBA::count('thread', $condition);
1135 if ($posts_week > $throttle_week) {
1136 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1137 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1138 throw new TooManyRequestsException(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));
1142 $throttle_month = Config::get('system', 'throttle_limit_month');
1143 if ($throttle_month > 0) {
1144 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1146 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1147 $posts_month = DBA::count('thread', $condition);
1149 if ($posts_month > $throttle_month) {
1150 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1151 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1152 throw new TooManyRequestsException(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));
1157 if (!empty($_FILES['media'])) {
1158 // upload the image if we have one
1159 $picture = wall_upload_post($a, false);
1160 if (is_array($picture)) {
1161 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1165 if (requestdata('media_ids')) {
1166 $ids = explode(',', requestdata('media_ids'));
1167 foreach ($ids as $id) {
1169 "SELECT `resource-id`, `scale`, `nickname`, `type`, `desc` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1173 if (DBA::isResult($r)) {
1174 $phototypes = Images::supportedTypes();
1175 $ext = $phototypes[$r[0]['type']];
1176 $description = $r[0]['desc'] ?? '';
1177 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1178 $_REQUEST['body'] .= '[img=' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1183 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1185 $_REQUEST['api_source'] = true;
1187 if (empty($_REQUEST['source'])) {
1188 $_REQUEST["source"] = api_source();
1191 // call out normal post function
1192 $item_id = item_post($a);
1194 // output the post that we just posted.
1195 return api_status_show($type, $item_id);
1198 /// @TODO move to top of file or somewhere better
1199 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1200 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1203 * Uploads an image to Friendica.
1206 * @throws BadRequestException
1207 * @throws ForbiddenException
1208 * @throws ImagickException
1209 * @throws InternalServerErrorException
1210 * @throws UnauthorizedException
1211 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1213 function api_media_upload()
1217 if (api_user() === false) {
1218 Logger::log('no user');
1219 throw new ForbiddenException();
1224 if (empty($_FILES['media'])) {
1226 throw new BadRequestException("No media.");
1229 $media = wall_upload_post($a, false);
1232 throw new InternalServerErrorException();
1236 $returndata["media_id"] = $media["id"];
1237 $returndata["media_id_string"] = (string)$media["id"];
1238 $returndata["size"] = $media["size"];
1239 $returndata["image"] = ["w" => $media["width"],
1240 "h" => $media["height"],
1241 "image_type" => $media["type"],
1242 "friendica_preview_url" => $media["preview"]];
1244 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1246 return ["media" => $returndata];
1249 /// @TODO move to top of file or somewhere better
1250 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1253 * Updates media meta data (picture descriptions)
1255 * @param string $type Return type (atom, rss, xml, json)
1257 * @return array|string
1258 * @throws BadRequestException
1259 * @throws ForbiddenException
1260 * @throws ImagickException
1261 * @throws InternalServerErrorException
1262 * @throws TooManyRequestsException
1263 * @throws UnauthorizedException
1264 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1266 * @todo Compare the corresponding Twitter function for correct return values
1268 function api_media_metadata_create($type)
1272 if (api_user() === false) {
1273 Logger::info('no user');
1274 throw new ForbiddenException();
1279 $postdata = Network::postdata();
1281 if (empty($postdata)) {
1282 throw new BadRequestException("No post data");
1285 $data = json_decode($postdata, true);
1287 throw new BadRequestException("Invalid post data");
1290 if (empty($data['media_id']) || empty($data['alt_text'])) {
1291 throw new BadRequestException("Missing post data values");
1294 if (empty($data['alt_text']['text'])) {
1295 throw new BadRequestException("No alt text.");
1298 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1300 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1301 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1302 if (!DBA::isResult($photo)) {
1303 throw new BadRequestException("Metadata not found.");
1306 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1309 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1312 * @param string $type Return format (atom, rss, xml, json)
1313 * @param int $item_id
1317 function api_status_show($type, $item_id)
1319 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1323 $item = api_get_item(['id' => $item_id]);
1324 if (!empty($item)) {
1325 $status_info = api_format_item($item, $type);
1328 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1330 return api_format_data('statuses', $type, ['status' => $status_info]);
1334 * Retrieves the last public status of the provided user info
1336 * @param int $ownerId Public contact Id
1337 * @param int $uid User Id
1341 function api_get_last_status($ownerId, $uid)
1344 'author-id'=> $ownerId,
1346 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1350 $item = api_get_item($condition);
1356 * Retrieves a single item record based on the provided condition and converts it for API use.
1358 * @param array $condition Item table condition array
1362 function api_get_item(array $condition)
1364 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1370 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1371 * The author's most recent status will be returned inline.
1373 * @param string $type Return type (atom, rss, xml, json)
1374 * @return array|string
1375 * @throws BadRequestException
1376 * @throws ImagickException
1377 * @throws InternalServerErrorException
1378 * @throws UnauthorizedException
1379 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1381 function api_users_show($type)
1383 $a = BaseObject::getApp();
1385 $user_info = api_get_user($a);
1387 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1388 if (!empty($item)) {
1389 $user_info['status'] = api_format_item($item, $type);
1392 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1393 unset($user_info['uid']);
1394 unset($user_info['self']);
1396 return api_format_data('user', $type, ['user' => $user_info]);
1399 /// @TODO move to top of file or somewhere better
1400 api_register_func('api/users/show', 'api_users_show');
1401 api_register_func('api/externalprofile/show', 'api_users_show');
1404 * Search a public user account.
1406 * @param string $type Return type (atom, rss, xml, json)
1408 * @return array|string
1409 * @throws BadRequestException
1410 * @throws ImagickException
1411 * @throws InternalServerErrorException
1412 * @throws UnauthorizedException
1413 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1415 function api_users_search($type)
1421 if (!empty($_GET['q'])) {
1422 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1424 if (!DBA::isResult($r)) {
1425 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1428 if (DBA::isResult($r)) {
1430 foreach ($r as $user) {
1431 $user_info = api_get_user($a, $user["id"]);
1433 if ($type == "xml") {
1434 $userlist[$k++.":user"] = $user_info;
1436 $userlist[] = $user_info;
1439 $userlist = ["users" => $userlist];
1441 throw new BadRequestException("User ".$_GET["q"]." not found.");
1444 throw new BadRequestException("No user specified.");
1447 return api_format_data("users", $type, $userlist);
1450 /// @TODO move to top of file or somewhere better
1451 api_register_func('api/users/search', 'api_users_search');
1454 * Return user objects
1456 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1458 * @param string $type Return format: json or xml
1460 * @return array|string
1461 * @throws BadRequestException
1462 * @throws ImagickException
1463 * @throws InternalServerErrorException
1464 * @throws NotFoundException if the results are empty.
1465 * @throws UnauthorizedException
1467 function api_users_lookup($type)
1471 if (!empty($_REQUEST['user_id'])) {
1472 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1474 $users[] = api_get_user(get_app(), $id);
1479 if (empty($users)) {
1480 throw new NotFoundException;
1483 return api_format_data("users", $type, ['users' => $users]);
1486 /// @TODO move to top of file or somewhere better
1487 api_register_func('api/users/lookup', 'api_users_lookup', true);
1490 * Returns statuses that match a specified query.
1492 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1494 * @param string $type Return format: json, xml, atom, rss
1496 * @return array|string
1497 * @throws BadRequestException if the "q" parameter is missing.
1498 * @throws ForbiddenException
1499 * @throws ImagickException
1500 * @throws InternalServerErrorException
1501 * @throws UnauthorizedException
1503 function api_search($type)
1506 $user_info = api_get_user($a);
1508 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1510 if (empty($_REQUEST['q'])) {
1511 throw new BadRequestException('q parameter is required.');
1514 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1517 $data['status'] = [];
1519 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1520 if (!empty($_REQUEST['rpp'])) {
1521 $count = $_REQUEST['rpp'];
1522 } elseif (!empty($_REQUEST['count'])) {
1523 $count = $_REQUEST['count'];
1526 $since_id = $_REQUEST['since_id'] ?? 0;
1527 $max_id = $_REQUEST['max_id'] ?? 0;
1528 $page = $_REQUEST['page'] ?? 1;
1530 $start = max(0, ($page - 1) * $count);
1532 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1533 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1534 $searchTerm = $matches[1];
1535 $condition = ["`oid` > ?
1536 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1537 AND `otype` = ? AND `type` = ? AND `term` = ?",
1538 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1540 $condition[0] .= ' AND `oid` <= ?';
1541 $condition[] = $max_id;
1543 $terms = DBA::select('term', ['oid'], $condition, []);
1545 while ($term = DBA::fetch($terms)) {
1546 $itemIds[] = $term['oid'];
1550 if (empty($itemIds)) {
1551 return api_format_data('statuses', $type, $data);
1554 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1555 if ($exclude_replies) {
1556 $preCondition[] = '`id` = `parent`';
1559 $condition = [implode(' AND ', $preCondition)];
1561 $condition = ["`id` > ?
1562 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1563 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1564 AND `body` LIKE CONCAT('%',?,'%')",
1565 $since_id, api_user(), $_REQUEST['q']];
1567 $condition[0] .= ' AND `id` <= ?';
1568 $condition[] = $max_id;
1572 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1574 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1576 bindComments($data['status']);
1578 return api_format_data('statuses', $type, $data);
1581 /// @TODO move to top of file or somewhere better
1582 api_register_func('api/search/tweets', 'api_search', true);
1583 api_register_func('api/search', 'api_search', true);
1586 * Returns the most recent statuses posted by the user and the users they follow.
1588 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1590 * @param string $type Return type (atom, rss, xml, json)
1592 * @return array|string
1593 * @throws BadRequestException
1594 * @throws ForbiddenException
1595 * @throws ImagickException
1596 * @throws InternalServerErrorException
1597 * @throws UnauthorizedException
1598 * @todo Optional parameters
1599 * @todo Add reply info
1601 function api_statuses_home_timeline($type)
1604 $user_info = api_get_user($a);
1606 if (api_user() === false || $user_info === false) {
1607 throw new ForbiddenException();
1610 unset($_REQUEST["user_id"]);
1611 unset($_GET["user_id"]);
1613 unset($_REQUEST["screen_name"]);
1614 unset($_GET["screen_name"]);
1616 // get last network messages
1619 $count = $_REQUEST['count'] ?? 20;
1620 $page = $_REQUEST['page']?? 0;
1621 $since_id = $_REQUEST['since_id'] ?? 0;
1622 $max_id = $_REQUEST['max_id'] ?? 0;
1623 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1624 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1626 $start = max(0, ($page - 1) * $count);
1628 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1629 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1632 $condition[0] .= " AND `item`.`id` <= ?";
1633 $condition[] = $max_id;
1635 if ($exclude_replies) {
1636 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1638 if ($conversation_id > 0) {
1639 $condition[0] .= " AND `item`.`parent` = ?";
1640 $condition[] = $conversation_id;
1643 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1644 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1646 $items = Item::inArray($statuses);
1648 $ret = api_format_items($items, $user_info, false, $type);
1650 // Set all posts from the query above to seen
1652 foreach ($items as $item) {
1653 $idarray[] = intval($item["id"]);
1656 if (!empty($idarray)) {
1657 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1659 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1665 $data = ['status' => $ret];
1670 $data = api_rss_extra($a, $data, $user_info);
1674 return api_format_data("statuses", $type, $data);
1678 /// @TODO move to top of file or somewhere better
1679 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1680 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1683 * Returns the most recent statuses from public users.
1685 * @param string $type Return type (atom, rss, xml, json)
1687 * @return array|string
1688 * @throws BadRequestException
1689 * @throws ForbiddenException
1690 * @throws ImagickException
1691 * @throws InternalServerErrorException
1692 * @throws UnauthorizedException
1694 function api_statuses_public_timeline($type)
1697 $user_info = api_get_user($a);
1699 if (api_user() === false || $user_info === false) {
1700 throw new ForbiddenException();
1703 // get last network messages
1706 $count = $_REQUEST['count'] ?? 20;
1707 $page = $_REQUEST['page'] ?? 1;
1708 $since_id = $_REQUEST['since_id'] ?? 0;
1709 $max_id = $_REQUEST['max_id'] ?? 0;
1710 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1711 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1713 $start = max(0, ($page - 1) * $count);
1715 if ($exclude_replies && !$conversation_id) {
1716 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1717 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1720 $condition[0] .= " AND `thread`.`iid` <= ?";
1721 $condition[] = $max_id;
1724 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1725 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1727 $r = Item::inArray($statuses);
1729 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1730 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1733 $condition[0] .= " AND `item`.`id` <= ?";
1734 $condition[] = $max_id;
1736 if ($conversation_id > 0) {
1737 $condition[0] .= " AND `item`.`parent` = ?";
1738 $condition[] = $conversation_id;
1741 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1742 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1744 $r = Item::inArray($statuses);
1747 $ret = api_format_items($r, $user_info, false, $type);
1751 $data = ['status' => $ret];
1756 $data = api_rss_extra($a, $data, $user_info);
1760 return api_format_data("statuses", $type, $data);
1763 /// @TODO move to top of file or somewhere better
1764 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1767 * Returns the most recent statuses posted by users this node knows about.
1769 * @brief Returns the list of public federated posts this node knows about
1771 * @param string $type Return format: json, xml, atom, rss
1772 * @return array|string
1773 * @throws BadRequestException
1774 * @throws ForbiddenException
1775 * @throws ImagickException
1776 * @throws InternalServerErrorException
1777 * @throws UnauthorizedException
1779 function api_statuses_networkpublic_timeline($type)
1782 $user_info = api_get_user($a);
1784 if (api_user() === false || $user_info === false) {
1785 throw new ForbiddenException();
1788 $since_id = $_REQUEST['since_id'] ?? 0;
1789 $max_id = $_REQUEST['max_id'] ?? 0;
1792 $count = $_REQUEST['count'] ?? 20;
1793 $page = $_REQUEST['page'] ?? 1;
1795 $start = max(0, ($page - 1) * $count);
1797 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1798 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1801 $condition[0] .= " AND `thread`.`iid` <= ?";
1802 $condition[] = $max_id;
1805 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1806 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1808 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1812 $data = ['status' => $ret];
1817 $data = api_rss_extra($a, $data, $user_info);
1821 return api_format_data("statuses", $type, $data);
1824 /// @TODO move to top of file or somewhere better
1825 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1828 * Returns a single status.
1830 * @param string $type Return type (atom, rss, xml, json)
1832 * @return array|string
1833 * @throws BadRequestException
1834 * @throws ForbiddenException
1835 * @throws ImagickException
1836 * @throws InternalServerErrorException
1837 * @throws UnauthorizedException
1838 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1840 function api_statuses_show($type)
1843 $user_info = api_get_user($a);
1845 if (api_user() === false || $user_info === false) {
1846 throw new ForbiddenException();
1850 $id = intval($a->argv[3] ?? 0);
1853 $id = intval($_REQUEST['id'] ?? 0);
1858 $id = intval($a->argv[4] ?? 0);
1861 Logger::log('API: api_statuses_show: ' . $id);
1863 $conversation = !empty($_REQUEST['conversation']);
1865 // try to fetch the item for the local user - or the public item, if there is no local one
1866 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1867 if (!DBA::isResult($uri_item)) {
1868 throw new BadRequestException("There is no status with this id.");
1871 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1872 if (!DBA::isResult($item)) {
1873 throw new BadRequestException("There is no status with this id.");
1878 if ($conversation) {
1879 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1880 $params = ['order' => ['id' => true]];
1882 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1886 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1888 /// @TODO How about copying this to above methods which don't check $r ?
1889 if (!DBA::isResult($statuses)) {
1890 throw new BadRequestException("There is no status with this id.");
1893 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1895 if ($conversation) {
1896 $data = ['status' => $ret];
1897 return api_format_data("statuses", $type, $data);
1899 $data = ['status' => $ret[0]];
1900 return api_format_data("status", $type, $data);
1904 /// @TODO move to top of file or somewhere better
1905 api_register_func('api/statuses/show', 'api_statuses_show', true);
1909 * @param string $type Return type (atom, rss, xml, json)
1911 * @return array|string
1912 * @throws BadRequestException
1913 * @throws ForbiddenException
1914 * @throws ImagickException
1915 * @throws InternalServerErrorException
1916 * @throws UnauthorizedException
1917 * @todo nothing to say?
1919 function api_conversation_show($type)
1922 $user_info = api_get_user($a);
1924 if (api_user() === false || $user_info === false) {
1925 throw new ForbiddenException();
1929 $id = intval($a->argv[3] ?? 0);
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);
1938 $id = intval($_REQUEST['id'] ?? 0);
1943 $id = intval($a->argv[4] ?? 0);
1946 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1948 // try to fetch the item for the local user - or the public item, if there is no local one
1949 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1950 if (!DBA::isResult($item)) {
1951 throw new BadRequestException("There is no status with this id.");
1954 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1955 if (!DBA::isResult($parent)) {
1956 throw new BadRequestException("There is no status with this id.");
1959 $id = $parent['id'];
1961 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1962 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1965 $condition[0] .= " AND `item`.`id` <= ?";
1966 $condition[] = $max_id;
1969 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1970 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1972 if (!DBA::isResult($statuses)) {
1973 throw new BadRequestException("There is no status with id $id.");
1976 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1978 $data = ['status' => $ret];
1979 return api_format_data("statuses", $type, $data);
1982 /// @TODO move to top of file or somewhere better
1983 api_register_func('api/conversation/show', 'api_conversation_show', true);
1984 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1989 * @param string $type Return type (atom, rss, xml, json)
1991 * @return array|string
1992 * @throws BadRequestException
1993 * @throws ForbiddenException
1994 * @throws ImagickException
1995 * @throws InternalServerErrorException
1996 * @throws UnauthorizedException
1997 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1999 function api_statuses_repeat($type)
2005 if (api_user() === false) {
2006 throw new ForbiddenException();
2012 $id = intval($a->argv[3] ?? 0);
2015 $id = intval($_REQUEST['id'] ?? 0);
2020 $id = intval($a->argv[4] ?? 0);
2023 Logger::log('API: api_statuses_repeat: '.$id);
2025 $fields = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2026 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2028 if (DBA::isResult($item) && $item['body'] != "") {
2029 if (strpos($item['body'], "[/share]") !== false) {
2030 $pos = strpos($item['body'], "[share");
2031 $post = substr($item['body'], $pos);
2033 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2035 if (!empty($item['title'])) {
2036 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2039 $post .= $item['body'];
2040 $post .= "[/share]";
2042 $_REQUEST['body'] = $post;
2043 $_REQUEST['tag'] = $item['tag'];
2044 $_REQUEST['attach'] = $item['attach'];
2045 $_REQUEST['profile_uid'] = api_user();
2046 $_REQUEST['api_source'] = true;
2048 if (empty($_REQUEST['source'])) {
2049 $_REQUEST["source"] = api_source();
2052 $item_id = item_post($a);
2054 throw new ForbiddenException();
2057 // output the post that we just posted.
2059 return api_status_show($type, $item_id);
2062 /// @TODO move to top of file or somewhere better
2063 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2066 * Destroys a specific status.
2068 * @param string $type Return type (atom, rss, xml, json)
2070 * @return array|string
2071 * @throws BadRequestException
2072 * @throws ForbiddenException
2073 * @throws ImagickException
2074 * @throws InternalServerErrorException
2075 * @throws UnauthorizedException
2076 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2078 function api_statuses_destroy($type)
2082 if (api_user() === false) {
2083 throw new ForbiddenException();
2089 $id = intval($a->argv[3] ?? 0);
2092 $id = intval($_REQUEST['id'] ?? 0);
2097 $id = intval($a->argv[4] ?? 0);
2100 Logger::log('API: api_statuses_destroy: '.$id);
2102 $ret = api_statuses_show($type);
2104 Item::deleteForUser(['id' => $id], api_user());
2109 /// @TODO move to top of file or somewhere better
2110 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2113 * Returns the most recent mentions.
2115 * @param string $type Return type (atom, rss, xml, json)
2117 * @return array|string
2118 * @throws BadRequestException
2119 * @throws ForbiddenException
2120 * @throws ImagickException
2121 * @throws InternalServerErrorException
2122 * @throws UnauthorizedException
2123 * @see http://developer.twitter.com/doc/get/statuses/mentions
2125 function api_statuses_mentions($type)
2128 $user_info = api_get_user($a);
2130 if (api_user() === false || $user_info === false) {
2131 throw new ForbiddenException();
2134 unset($_REQUEST["user_id"]);
2135 unset($_GET["user_id"]);
2137 unset($_REQUEST["screen_name"]);
2138 unset($_GET["screen_name"]);
2140 // get last network messages
2143 $since_id = $_REQUEST['since_id'] ?? 0;
2144 $max_id = $_REQUEST['max_id'] ?? 0;
2145 $count = $_REQUEST['count'] ?? 20;
2146 $page = $_REQUEST['page'] ?? 1;
2148 $start = max(0, ($page - 1) * $count);
2150 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2151 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2152 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2155 $condition[0] .= " AND `item`.`id` <= ?";
2156 $condition[] = $max_id;
2159 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2160 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2162 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2164 $data = ['status' => $ret];
2169 $data = api_rss_extra($a, $data, $user_info);
2173 return api_format_data("statuses", $type, $data);
2176 /// @TODO move to top of file or somewhere better
2177 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2178 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2181 * Returns the most recent statuses posted by the user.
2183 * @brief Returns a user's public timeline
2185 * @param string $type Either "json" or "xml"
2186 * @return string|array
2187 * @throws BadRequestException
2188 * @throws ForbiddenException
2189 * @throws ImagickException
2190 * @throws InternalServerErrorException
2191 * @throws UnauthorizedException
2192 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2194 function api_statuses_user_timeline($type)
2197 $user_info = api_get_user($a);
2199 if (api_user() === false || $user_info === false) {
2200 throw new ForbiddenException();
2204 "api_statuses_user_timeline: api_user: ". api_user() .
2205 "\nuser_info: ".print_r($user_info, true) .
2206 "\n_REQUEST: ".print_r($_REQUEST, true),
2210 $since_id = $_REQUEST['since_id'] ?? 0;
2211 $max_id = $_REQUEST['max_id'] ?? 0;
2212 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2213 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2216 $count = $_REQUEST['count'] ?? 20;
2217 $page = $_REQUEST['page'] ?? 1;
2219 $start = max(0, ($page - 1) * $count);
2221 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2222 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2224 if ($user_info['self'] == 1) {
2225 $condition[0] .= ' AND `item`.`wall` ';
2228 if ($exclude_replies) {
2229 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2232 if ($conversation_id > 0) {
2233 $condition[0] .= " AND `item`.`parent` = ?";
2234 $condition[] = $conversation_id;
2238 $condition[0] .= " AND `item`.`id` <= ?";
2239 $condition[] = $max_id;
2242 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2243 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2245 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2249 $data = ['status' => $ret];
2254 $data = api_rss_extra($a, $data, $user_info);
2258 return api_format_data("statuses", $type, $data);
2261 /// @TODO move to top of file or somewhere better
2262 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2265 * Star/unstar an item.
2266 * param: id : id of the item
2268 * @param string $type Return type (atom, rss, xml, json)
2270 * @return array|string
2271 * @throws BadRequestException
2272 * @throws ForbiddenException
2273 * @throws ImagickException
2274 * @throws InternalServerErrorException
2275 * @throws UnauthorizedException
2276 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2278 function api_favorites_create_destroy($type)
2282 if (api_user() === false) {
2283 throw new ForbiddenException();
2286 // for versioned api.
2287 /// @TODO We need a better global soluton
2288 $action_argv_id = 2;
2289 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2290 $action_argv_id = 3;
2293 if ($a->argc <= $action_argv_id) {
2294 throw new BadRequestException("Invalid request.");
2296 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2297 if ($a->argc == $action_argv_id + 2) {
2298 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2300 $itemid = intval($_REQUEST['id'] ?? 0);
2303 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2305 if (!DBA::isResult($item)) {
2306 throw new BadRequestException("Invalid item.");
2311 $item['starred'] = 1;
2314 $item['starred'] = 0;
2317 throw new BadRequestException("Invalid action ".$action);
2320 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2323 throw new InternalServerErrorException("DB error");
2327 $user_info = api_get_user($a);
2328 $rets = api_format_items([$item], $user_info, false, $type);
2331 $data = ['status' => $ret];
2336 $data = api_rss_extra($a, $data, $user_info);
2340 return api_format_data("status", $type, $data);
2343 /// @TODO move to top of file or somewhere better
2344 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2345 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2348 * Returns the most recent favorite statuses.
2350 * @param string $type Return type (atom, rss, xml, json)
2352 * @return string|array
2353 * @throws BadRequestException
2354 * @throws ForbiddenException
2355 * @throws ImagickException
2356 * @throws InternalServerErrorException
2357 * @throws UnauthorizedException
2359 function api_favorites($type)
2364 $user_info = api_get_user($a);
2366 if (api_user() === false || $user_info === false) {
2367 throw new ForbiddenException();
2372 // in friendica starred item are private
2373 // return favorites only for self
2374 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2376 if ($user_info['self'] == 0) {
2380 $since_id = $_REQUEST['since_id'] ?? 0;
2381 $max_id = $_REQUEST['max_id'] ?? 0;
2382 $count = $_GET['count'] ?? 20;
2383 $page = $_REQUEST['page'] ?? 1;
2385 $start = max(0, ($page - 1) * $count);
2387 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2388 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2390 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2393 $condition[0] .= " AND `item`.`id` <= ?";
2394 $condition[] = $max_id;
2397 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2399 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2404 $data = ['status' => $ret];
2409 $data = api_rss_extra($a, $data, $user_info);
2413 return api_format_data("statuses", $type, $data);
2416 /// @TODO move to top of file or somewhere better
2417 api_register_func('api/favorites', 'api_favorites', true);
2421 * @param array $item
2422 * @param array $recipient
2423 * @param array $sender
2426 * @throws InternalServerErrorException
2428 function api_format_messages($item, $recipient, $sender)
2430 // standard meta information
2432 'id' => $item['id'],
2433 'sender_id' => $sender['id'],
2435 'recipient_id' => $recipient['id'],
2436 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2437 'sender_screen_name' => $sender['screen_name'],
2438 'recipient_screen_name' => $recipient['screen_name'],
2439 'sender' => $sender,
2440 'recipient' => $recipient,
2442 'friendica_seen' => $item['seen'] ?? 0,
2443 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2446 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2447 if (isset($ret['sender']['uid'])) {
2448 unset($ret['sender']['uid']);
2450 if (isset($ret['sender']['self'])) {
2451 unset($ret['sender']['self']);
2453 if (isset($ret['recipient']['uid'])) {
2454 unset($ret['recipient']['uid']);
2456 if (isset($ret['recipient']['self'])) {
2457 unset($ret['recipient']['self']);
2460 //don't send title to regular StatusNET requests to avoid confusing these apps
2461 if (!empty($_GET['getText'])) {
2462 $ret['title'] = $item['title'];
2463 if ($_GET['getText'] == 'html') {
2464 $ret['text'] = BBCode::convert($item['body'], false);
2465 } elseif ($_GET['getText'] == 'plain') {
2466 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2469 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2471 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2472 unset($ret['sender']);
2473 unset($ret['recipient']);
2481 * @param array $item
2484 * @throws InternalServerErrorException
2486 function api_convert_item($item)
2488 $body = $item['body'];
2489 $attachments = api_get_attachments($body);
2491 // Workaround for ostatus messages where the title is identically to the body
2492 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2493 $statusbody = trim(HTML::toPlaintext($html, 0));
2495 // handle data: images
2496 $statusbody = api_format_items_embeded_images($item, $statusbody);
2498 $statustitle = trim($item['title']);
2500 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2501 $statustext = trim($statusbody);
2503 $statustext = trim($statustitle."\n\n".$statusbody);
2506 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2507 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2510 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2512 // Workaround for clients with limited HTML parser functionality
2513 $search = ["<br>", "<blockquote>", "</blockquote>",
2514 "<h1>", "</h1>", "<h2>", "</h2>",
2515 "<h3>", "</h3>", "<h4>", "</h4>",
2516 "<h5>", "</h5>", "<h6>", "</h6>"];
2517 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2518 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2519 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2520 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2521 $statushtml = str_replace($search, $replace, $statushtml);
2523 if ($item['title'] != "") {
2524 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2528 $oldtext = $statushtml;
2529 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2530 } while ($oldtext != $statushtml);
2532 if (substr($statushtml, 0, 4) == '<br>') {
2533 $statushtml = substr($statushtml, 4);
2536 if (substr($statushtml, 0, -4) == '<br>') {
2537 $statushtml = substr($statushtml, -4);
2540 // feeds without body should contain the link
2541 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2542 $statushtml .= BBCode::convert($item['plink']);
2545 $entities = api_get_entitities($statustext, $body);
2548 "text" => $statustext,
2549 "html" => $statushtml,
2550 "attachments" => $attachments,
2551 "entities" => $entities
2557 * @param string $body
2560 * @throws InternalServerErrorException
2562 function api_get_attachments(&$body)
2565 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2566 $text = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $text);
2568 $URLSearchString = "^\[\]";
2569 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2577 foreach ($images[1] as $image) {
2578 $imagedata = Images::getInfoFromURLCached($image);
2581 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2585 if (strstr($_SERVER['HTTP_USER_AGENT'] ?? '', 'AndStatus')) {
2586 foreach ($images[0] as $orig) {
2587 $body = str_replace($orig, "", $body);
2591 return $attachments;
2596 * @param string $text
2597 * @param string $bbcode
2600 * @throws InternalServerErrorException
2601 * @todo Links at the first character of the post
2603 function api_get_entitities(&$text, $bbcode)
2605 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2607 if ($include_entities != "true") {
2608 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2610 foreach ($images[1] as $image) {
2611 $replace = ProxyUtils::proxifyUrl($image);
2612 $text = str_replace($image, $replace, $text);
2617 $bbcode = BBCode::cleanPictureLinks($bbcode);
2619 // Change pure links in text to bbcode uris
2620 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2623 $entities["hashtags"] = [];
2624 $entities["symbols"] = [];
2625 $entities["urls"] = [];
2626 $entities["user_mentions"] = [];
2628 $URLSearchString = "^\[\]";
2630 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2632 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2633 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2634 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2636 $bbcode = preg_replace(
2637 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2638 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2641 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2643 $bbcode = preg_replace(
2644 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2645 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2648 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2650 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2652 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2653 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2656 foreach ($urls[1] as $id => $url) {
2657 //$start = strpos($text, $url, $offset);
2658 $start = iconv_strpos($text, $url, 0, "UTF-8");
2659 if (!($start === false)) {
2660 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2664 ksort($ordered_urls);
2667 //foreach ($urls[1] AS $id=>$url) {
2668 foreach ($ordered_urls as $url) {
2669 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2670 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2672 $display_url = $url["title"];
2674 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2675 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2677 if (strlen($display_url) > 26) {
2678 $display_url = substr($display_url, 0, 25)."…";
2682 //$start = strpos($text, $url, $offset);
2683 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2684 if (!($start === false)) {
2685 $entities["urls"][] = ["url" => $url["url"],
2686 "expanded_url" => $url["url"],
2687 "display_url" => $display_url,
2688 "indices" => [$start, $start+strlen($url["url"])]];
2689 $offset = $start + 1;
2693 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2694 $ordered_images = [];
2695 foreach ($images as $image) {
2696 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2697 if (!($start === false)) {
2698 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2702 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2703 foreach ($images[1] as $image) {
2704 $start = iconv_strpos($text, $image, 0, "UTF-8");
2705 if (!($start === false)) {
2706 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2709 //$entities["media"] = array();
2712 foreach ($ordered_images as $image) {
2713 $url = $image['url'];
2714 $ext_alt_text = $image['alt'];
2716 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2717 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2719 if (strlen($display_url) > 26) {
2720 $display_url = substr($display_url, 0, 25)."…";
2723 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2724 if (!($start === false)) {
2725 $image = Images::getInfoFromURLCached($url);
2727 // If image cache is activated, then use the following sizes:
2728 // thumb (150), small (340), medium (600) and large (1024)
2729 if (!Config::get("system", "proxy_disabled")) {
2730 $media_url = ProxyUtils::proxifyUrl($url);
2733 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2734 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2736 if (($image[0] > 150) || ($image[1] > 150)) {
2737 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2738 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2741 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2742 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2744 if (($image[0] > 600) || ($image[1] > 600)) {
2745 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2746 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2750 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2753 $entities["media"][] = [
2755 "id_str" => (string) ($start + 1),
2756 "indices" => [$start, $start+strlen($url)],
2757 "media_url" => Strings::normaliseLink($media_url),
2758 "media_url_https" => $media_url,
2760 "display_url" => $display_url,
2761 "expanded_url" => $url,
2762 "ext_alt_text" => $ext_alt_text,
2766 $offset = $start + 1;
2775 * @param array $item
2776 * @param string $text
2780 function api_format_items_embeded_images($item, $text)
2782 $text = preg_replace_callback(
2783 '|data:image/([^;]+)[^=]+=*|m',
2784 function () use ($item) {
2785 return System::baseUrl() . '/display/' . $item['guid'];
2793 * @brief return <a href='url'>name</a> as array
2795 * @param string $txt text
2800 function api_contactlink_to_array($txt)
2803 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2804 if ($r && count($match)==3) {
2806 'name' => $match[2],
2820 * @brief return likes, dislikes and attend status for item
2822 * @param array $item array
2823 * @param string $type Return type (atom, rss, xml, json)
2826 * likes => int count,
2827 * dislikes => int count
2828 * @throws BadRequestException
2829 * @throws ImagickException
2830 * @throws InternalServerErrorException
2831 * @throws UnauthorizedException
2833 function api_format_items_activities($item, $type = "json")
2842 'attendmaybe' => [],
2845 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2846 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2848 while ($parent_item = Item::fetch($ret)) {
2849 // not used as result should be structured like other user data
2850 //builtin_activity_puller($i, $activities);
2852 // get user data and add it to the array of the activity
2853 $user = api_get_user($a, $parent_item['author-id']);
2854 switch ($parent_item['verb']) {
2855 case Activity::LIKE:
2856 $activities['like'][] = $user;
2858 case Activity::DISLIKE:
2859 $activities['dislike'][] = $user;
2861 case Activity::ATTEND:
2862 $activities['attendyes'][] = $user;
2864 case Activity::ATTENDNO:
2865 $activities['attendno'][] = $user;
2867 case Activity::ATTENDMAYBE:
2868 $activities['attendmaybe'][] = $user;
2877 if ($type == "xml") {
2878 $xml_activities = [];
2879 foreach ($activities as $k => $v) {
2880 // change xml element from "like" to "friendica:like"
2881 $xml_activities["friendica:".$k] = $v;
2882 // add user data into xml output
2884 foreach ($v as $user) {
2885 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2888 $activities = $xml_activities;
2896 * @brief return data from profiles
2898 * @param array $profile_row array containing data from db table 'profile'
2900 * @throws InternalServerErrorException
2902 function api_format_items_profiles($profile_row)
2905 'profile_id' => $profile_row['id'],
2906 'profile_name' => $profile_row['profile-name'],
2907 'is_default' => $profile_row['is-default'] ? true : false,
2908 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2909 'profile_photo' => $profile_row['photo'],
2910 'profile_thumb' => $profile_row['thumb'],
2911 'publish' => $profile_row['publish'] ? true : false,
2912 'net_publish' => $profile_row['net-publish'] ? true : false,
2913 'description' => $profile_row['pdesc'],
2914 'date_of_birth' => $profile_row['dob'],
2915 'address' => $profile_row['address'],
2916 'city' => $profile_row['locality'],
2917 'region' => $profile_row['region'],
2918 'postal_code' => $profile_row['postal-code'],
2919 'country' => $profile_row['country-name'],
2920 'hometown' => $profile_row['hometown'],
2921 'gender' => $profile_row['gender'],
2922 'marital' => $profile_row['marital'],
2923 'marital_with' => $profile_row['with'],
2924 'marital_since' => $profile_row['howlong'],
2925 'sexual' => $profile_row['sexual'],
2926 'politic' => $profile_row['politic'],
2927 'religion' => $profile_row['religion'],
2928 'public_keywords' => $profile_row['pub_keywords'],
2929 'private_keywords' => $profile_row['prv_keywords'],
2930 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2931 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2932 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2933 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2934 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2935 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2936 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2937 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2938 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2939 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2940 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2941 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2942 'homepage' => $profile_row['homepage'],
2949 * @brief format items to be returned by api
2951 * @param array $items array of items
2952 * @param array $user_info
2953 * @param bool $filter_user filter items by $user_info
2954 * @param string $type Return type (atom, rss, xml, json)
2956 * @throws BadRequestException
2957 * @throws ImagickException
2958 * @throws InternalServerErrorException
2959 * @throws UnauthorizedException
2961 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2963 $a = BaseObject::getApp();
2967 foreach ((array)$items as $item) {
2968 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2970 // Look if the posts are matching if they should be filtered by user id
2971 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2975 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2984 * @param array $item Item record
2985 * @param string $type Return format (atom, rss, xml, json)
2986 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2987 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2988 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2989 * @return array API-formatted status
2990 * @throws BadRequestException
2991 * @throws ImagickException
2992 * @throws InternalServerErrorException
2993 * @throws UnauthorizedException
2995 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2997 $a = BaseObject::getApp();
2999 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3000 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3003 localize_item($item);
3005 $in_reply_to = api_in_reply_to($item);
3007 $converted = api_convert_item($item);
3009 if ($type == "xml") {
3010 $geo = "georss:point";
3016 'text' => $converted["text"],
3017 'truncated' => false,
3018 'created_at'=> api_date($item['created']),
3019 'in_reply_to_status_id' => $in_reply_to['status_id'],
3020 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3021 'source' => (($item['app']) ? $item['app'] : 'web'),
3022 'id' => intval($item['id']),
3023 'id_str' => (string) intval($item['id']),
3024 'in_reply_to_user_id' => $in_reply_to['user_id'],
3025 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3026 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3028 'favorited' => $item['starred'] ? true : false,
3029 'user' => $status_user,
3030 'friendica_author' => $author_user,
3031 'friendica_owner' => $owner_user,
3032 'friendica_private' => $item['private'] == 1,
3033 //'entities' => NULL,
3034 'statusnet_html' => $converted["html"],
3035 'statusnet_conversation_id' => $item['parent'],
3036 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3037 'friendica_activities' => api_format_items_activities($item, $type),
3038 'friendica_title' => $item['title'],
3039 'friendica_html' => BBCode::convert($item['body'], false)
3042 if (count($converted["attachments"]) > 0) {
3043 $status["attachments"] = $converted["attachments"];
3046 if (count($converted["entities"]) > 0) {
3047 $status["entities"] = $converted["entities"];
3050 if ($status["source"] == 'web') {
3051 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3052 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3053 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3056 $retweeted_item = [];
3059 if ($item["id"] == $item["parent"]) {
3060 $body = $item['body'];
3061 $retweeted_item = api_share_as_retweet($item);
3062 if ($body != $item['body']) {
3063 $quoted_item = $retweeted_item;
3064 $retweeted_item = [];
3068 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3069 $announce = api_get_announce($item);
3070 if (!empty($announce)) {
3071 $retweeted_item = $item;
3073 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3077 if (!empty($quoted_item)) {
3078 $conv_quoted = api_convert_item($quoted_item);
3079 $quoted_status = $status;
3080 unset($quoted_status['friendica_author']);
3081 unset($quoted_status['friendica_owner']);
3082 unset($quoted_status['friendica_activities']);
3083 unset($quoted_status['friendica_private']);
3084 unset($quoted_status['statusnet_conversation_id']);
3085 $quoted_status['text'] = $conv_quoted['text'];
3086 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3088 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3089 } catch (BadRequestException $e) {
3090 // user not found. should be found?
3091 /// @todo check if the user should be always found
3092 $quoted_status["user"] = [];
3096 if (!empty($retweeted_item)) {
3097 $retweeted_status = $status;
3098 unset($retweeted_status['friendica_author']);
3099 unset($retweeted_status['friendica_owner']);
3100 unset($retweeted_status['friendica_activities']);
3101 unset($retweeted_status['friendica_private']);
3102 unset($retweeted_status['statusnet_conversation_id']);
3103 $status['user'] = $status['friendica_owner'];
3105 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3106 } catch (BadRequestException $e) {
3107 // user not found. should be found?
3108 /// @todo check if the user should be always found
3109 $retweeted_status["user"] = [];
3112 $rt_converted = api_convert_item($retweeted_item);
3114 $retweeted_status['text'] = $rt_converted["text"];
3115 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3116 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3118 if (!empty($quoted_status)) {
3119 $retweeted_status['quoted_status'] = $quoted_status;
3122 $status['friendica_author'] = $retweeted_status['user'];
3123 $status['retweeted_status'] = $retweeted_status;
3124 } elseif (!empty($quoted_status)) {
3125 $root_status = api_convert_item($item);
3127 $status['text'] = $root_status["text"];
3128 $status['statusnet_html'] = $root_status["html"];
3129 $status['quoted_status'] = $quoted_status;
3132 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3133 unset($status["user"]["uid"]);
3134 unset($status["user"]["self"]);
3136 if ($item["coord"] != "") {
3137 $coords = explode(' ', $item["coord"]);
3138 if (count($coords) == 2) {
3139 if ($type == "json") {
3140 $status["geo"] = ['type' => 'Point',
3141 'coordinates' => [(float) $coords[0],
3142 (float) $coords[1]]];
3143 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3144 $status["georss:point"] = $item["coord"];
3153 * Returns the remaining number of API requests available to the user before the API limit is reached.
3155 * @param string $type Return type (atom, rss, xml, json)
3157 * @return array|string
3160 function api_account_rate_limit_status($type)
3162 if ($type == "xml") {
3164 'remaining-hits' => '150',
3165 '@attributes' => ["type" => "integer"],
3166 'hourly-limit' => '150',
3167 '@attributes2' => ["type" => "integer"],
3168 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3169 '@attributes3' => ["type" => "datetime"],
3170 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3171 '@attributes4' => ["type" => "integer"],
3175 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3176 'remaining_hits' => '150',
3177 'hourly_limit' => '150',
3178 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3182 return api_format_data('hash', $type, ['hash' => $hash]);
3185 /// @TODO move to top of file or somewhere better
3186 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3189 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3191 * @param string $type Return type (atom, rss, xml, json)
3193 * @return array|string
3195 function api_help_test($type)
3197 if ($type == 'xml') {
3203 return api_format_data('ok', $type, ["ok" => $ok]);
3206 /// @TODO move to top of file or somewhere better
3207 api_register_func('api/help/test', 'api_help_test', false);
3210 * Returns all lists the user subscribes to.
3212 * @param string $type Return type (atom, rss, xml, json)
3214 * @return array|string
3215 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3217 function api_lists_list($type)
3220 /// @TODO $ret is not filled here?
3221 return api_format_data('lists', $type, ["lists_list" => $ret]);
3224 /// @TODO move to top of file or somewhere better
3225 api_register_func('api/lists/list', 'api_lists_list', true);
3226 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3229 * Returns all groups the user owns.
3231 * @param string $type Return type (atom, rss, xml, json)
3233 * @return array|string
3234 * @throws BadRequestException
3235 * @throws ForbiddenException
3236 * @throws ImagickException
3237 * @throws InternalServerErrorException
3238 * @throws UnauthorizedException
3239 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3241 function api_lists_ownerships($type)
3245 if (api_user() === false) {
3246 throw new ForbiddenException();
3250 $user_info = api_get_user($a);
3251 $uid = $user_info['uid'];
3253 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3255 // loop through all groups
3257 foreach ($groups as $group) {
3258 if ($group['visible']) {
3264 'name' => $group['name'],
3265 'id' => intval($group['id']),
3266 'id_str' => (string) $group['id'],
3267 'user' => $user_info,
3271 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3274 /// @TODO move to top of file or somewhere better
3275 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3278 * Returns recent statuses from users in the specified group.
3280 * @param string $type Return type (atom, rss, xml, json)
3282 * @return array|string
3283 * @throws BadRequestException
3284 * @throws ForbiddenException
3285 * @throws ImagickException
3286 * @throws InternalServerErrorException
3287 * @throws UnauthorizedException
3288 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3290 function api_lists_statuses($type)
3294 $user_info = api_get_user($a);
3295 if (api_user() === false || $user_info === false) {
3296 throw new ForbiddenException();
3299 unset($_REQUEST["user_id"]);
3300 unset($_GET["user_id"]);
3302 unset($_REQUEST["screen_name"]);
3303 unset($_GET["screen_name"]);
3305 if (empty($_REQUEST['list_id'])) {
3306 throw new BadRequestException('list_id not specified');
3310 $count = $_REQUEST['count'] ?? 20;
3311 $page = $_REQUEST['page'] ?? 1;
3312 $since_id = $_REQUEST['since_id'] ?? 0;
3313 $max_id = $_REQUEST['max_id'] ?? 0;
3314 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3315 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3317 $start = max(0, ($page - 1) * $count);
3319 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3320 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3323 $condition[0] .= " AND `item`.`id` <= ?";
3324 $condition[] = $max_id;
3326 if ($exclude_replies > 0) {
3327 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3329 if ($conversation_id > 0) {
3330 $condition[0] .= " AND `item`.`parent` = ?";
3331 $condition[] = $conversation_id;
3334 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3335 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3337 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3339 $data = ['status' => $items];
3344 $data = api_rss_extra($a, $data, $user_info);
3348 return api_format_data("statuses", $type, $data);
3351 /// @TODO move to top of file or somewhere better
3352 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3355 * Considers friends and followers lists to be private and won't return
3356 * anything if any user_id parameter is passed.
3358 * @brief Returns either the friends of the follower list
3360 * @param string $qtype Either "friends" or "followers"
3361 * @return boolean|array
3362 * @throws BadRequestException
3363 * @throws ForbiddenException
3364 * @throws ImagickException
3365 * @throws InternalServerErrorException
3366 * @throws UnauthorizedException
3368 function api_statuses_f($qtype)
3372 if (api_user() === false) {
3373 throw new ForbiddenException();
3377 $count = $_GET['count'] ?? 20;
3378 $page = $_GET['page'] ?? 1;
3380 $start = max(0, ($page - 1) * $count);
3382 $user_info = api_get_user($a);
3384 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3385 /* this is to stop Hotot to load friends multiple times
3386 * I'm not sure if I'm missing return something or
3387 * is a bug in hotot. Workaround, meantime
3391 return array('$users' => $ret);*/
3396 if ($qtype == 'friends') {
3397 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3398 } elseif ($qtype == 'followers') {
3399 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3402 // friends and followers only for self
3403 if ($user_info['self'] == 0) {
3404 $sql_extra = " AND false ";
3407 if ($qtype == 'blocks') {
3408 $sql_filter = 'AND `blocked` AND NOT `pending`';
3409 } elseif ($qtype == 'incoming') {
3410 $sql_filter = 'AND `pending`';
3412 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3430 foreach ($r as $cid) {
3431 $user = api_get_user($a, $cid['nurl']);
3432 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3433 unset($user["uid"]);
3434 unset($user["self"]);
3441 return ['user' => $ret];
3446 * Returns the user's friends.
3448 * @brief Returns the list of friends of the provided user
3450 * @deprecated By Twitter API in favor of friends/list
3452 * @param string $type Either "json" or "xml"
3453 * @return boolean|string|array
3454 * @throws BadRequestException
3455 * @throws ForbiddenException
3457 function api_statuses_friends($type)
3459 $data = api_statuses_f("friends");
3460 if ($data === false) {
3463 return api_format_data("users", $type, $data);
3467 * Returns the user's followers.
3469 * @brief Returns the list of followers of the provided user
3471 * @deprecated By Twitter API in favor of friends/list
3473 * @param string $type Either "json" or "xml"
3474 * @return boolean|string|array
3475 * @throws BadRequestException
3476 * @throws ForbiddenException
3478 function api_statuses_followers($type)
3480 $data = api_statuses_f("followers");
3481 if ($data === false) {
3484 return api_format_data("users", $type, $data);
3487 /// @TODO move to top of file or somewhere better
3488 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3489 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3492 * Returns the list of blocked users
3494 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3496 * @param string $type Either "json" or "xml"
3498 * @return boolean|string|array
3499 * @throws BadRequestException
3500 * @throws ForbiddenException
3502 function api_blocks_list($type)
3504 $data = api_statuses_f('blocks');
3505 if ($data === false) {
3508 return api_format_data("users", $type, $data);
3511 /// @TODO move to top of file or somewhere better
3512 api_register_func('api/blocks/list', 'api_blocks_list', true);
3515 * Returns the list of pending users IDs
3517 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3519 * @param string $type Either "json" or "xml"
3521 * @return boolean|string|array
3522 * @throws BadRequestException
3523 * @throws ForbiddenException
3525 function api_friendships_incoming($type)
3527 $data = api_statuses_f('incoming');
3528 if ($data === false) {
3533 foreach ($data['user'] as $user) {
3534 $ids[] = $user['id'];
3537 return api_format_data("ids", $type, ['id' => $ids]);
3540 /// @TODO move to top of file or somewhere better
3541 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3544 * Returns the instance's configuration information.
3546 * @param string $type Return type (atom, rss, xml, json)
3548 * @return array|string
3549 * @throws InternalServerErrorException
3551 function api_statusnet_config($type)
3555 $name = Config::get('config', 'sitename');
3556 $server = $a->getHostName();
3557 $logo = System::baseUrl() . '/images/friendica-64.png';
3558 $email = Config::get('config', 'admin_email');
3559 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3560 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3561 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3562 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3563 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3566 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3567 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3568 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3569 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3570 'shorturllength' => '30',
3572 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3573 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3574 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3575 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3580 return api_format_data('config', $type, ['config' => $config]);
3583 /// @TODO move to top of file or somewhere better
3584 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3585 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3589 * @param string $type Return type (atom, rss, xml, json)
3591 * @return array|string
3593 function api_statusnet_version($type)
3596 $fake_statusnet_version = "0.9.7";
3598 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3601 /// @TODO move to top of file or somewhere better
3602 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3603 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3607 * @param string $type Return type (atom, rss, xml, json)
3609 * @return array|string|void
3610 * @throws BadRequestException
3611 * @throws ForbiddenException
3612 * @throws ImagickException
3613 * @throws InternalServerErrorException
3614 * @throws UnauthorizedException
3615 * @todo use api_format_data() to return data
3617 function api_ff_ids($type)
3620 throw new ForbiddenException();
3627 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3630 "SELECT `pcontact`.`id` FROM `contact`
3631 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3632 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3635 if (!DBA::isResult($r)) {
3640 foreach ($r as $rr) {
3641 if ($stringify_ids) {
3644 $ids[] = intval($rr['id']);
3648 return api_format_data("ids", $type, ['id' => $ids]);
3652 * Returns the ID of every user the user is following.
3654 * @param string $type Return type (atom, rss, xml, json)
3656 * @return array|string
3657 * @throws BadRequestException
3658 * @throws ForbiddenException
3659 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3661 function api_friends_ids($type)
3663 return api_ff_ids($type);
3667 * Returns the ID of every user following the user.
3669 * @param string $type Return type (atom, rss, xml, json)
3671 * @return array|string
3672 * @throws BadRequestException
3673 * @throws ForbiddenException
3674 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3676 function api_followers_ids($type)
3678 return api_ff_ids($type);
3681 /// @TODO move to top of file or somewhere better
3682 api_register_func('api/friends/ids', 'api_friends_ids', true);
3683 api_register_func('api/followers/ids', 'api_followers_ids', true);
3686 * Sends a new direct message.
3688 * @param string $type Return type (atom, rss, xml, json)
3690 * @return array|string
3691 * @throws BadRequestException
3692 * @throws ForbiddenException
3693 * @throws ImagickException
3694 * @throws InternalServerErrorException
3695 * @throws NotFoundException
3696 * @throws UnauthorizedException
3697 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3699 function api_direct_messages_new($type)
3703 if (api_user() === false) {
3704 throw new ForbiddenException();
3707 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3711 $sender = api_get_user($a);
3714 if (!empty($_POST['screen_name'])) {
3716 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3718 DBA::escape($_POST['screen_name'])
3721 if (DBA::isResult($r)) {
3722 // Selecting the id by priority, friendica first
3723 api_best_nickname($r);
3725 $recipient = api_get_user($a, $r[0]['nurl']);
3728 $recipient = api_get_user($a, $_POST['user_id']);
3731 if (empty($recipient)) {
3732 throw new NotFoundException('Recipient not found');
3736 if (!empty($_REQUEST['replyto'])) {
3738 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3740 intval($_REQUEST['replyto'])
3742 $replyto = $r[0]['parent-uri'];
3743 $sub = $r[0]['title'];
3745 if (!empty($_REQUEST['title'])) {
3746 $sub = $_REQUEST['title'];
3748 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3752 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3755 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3756 $ret = api_format_messages($r[0], $recipient, $sender);
3758 $ret = ["error"=>$id];
3761 $data = ['direct_message'=>$ret];
3767 $data = api_rss_extra($a, $data, $sender);
3771 return api_format_data("direct-messages", $type, $data);
3774 /// @TODO move to top of file or somewhere better
3775 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3778 * Destroys a direct message.
3780 * @brief delete a direct_message from mail table through api
3782 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3783 * @return string|array
3784 * @throws BadRequestException
3785 * @throws ForbiddenException
3786 * @throws ImagickException
3787 * @throws InternalServerErrorException
3788 * @throws UnauthorizedException
3789 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3791 function api_direct_messages_destroy($type)
3795 if (api_user() === false) {
3796 throw new ForbiddenException();
3800 $user_info = api_get_user($a);
3802 $id = $_REQUEST['id'] ?? 0;
3804 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3805 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3806 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3808 $uid = $user_info['uid'];
3809 // error if no id or parenturi specified (for clients posting parent-uri as well)
3810 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3811 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3812 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3815 // BadRequestException if no id specified (for clients using Twitter API)
3817 throw new BadRequestException('Message id not specified');
3820 // add parent-uri to sql command if specified by calling app
3821 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3823 // get data of the specified message id
3825 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3830 // error message if specified id is not in database
3831 if (!DBA::isResult($r)) {
3832 if ($verbose == "true") {
3833 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3834 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3836 /// @todo BadRequestException ok for Twitter API clients?
3837 throw new BadRequestException('message id not in database');
3842 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3847 if ($verbose == "true") {
3850 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3851 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3853 $answer = ['result' => 'error', 'message' => 'unknown error'];
3854 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3857 /// @todo return JSON data like Twitter API not yet implemented
3860 /// @TODO move to top of file or somewhere better
3861 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3866 * @brief unfollow contact
3868 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3869 * @return string|array
3870 * @throws BadRequestException
3871 * @throws ForbiddenException
3872 * @throws ImagickException
3873 * @throws InternalServerErrorException
3874 * @throws NotFoundException
3875 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3877 function api_friendships_destroy($type)
3881 if ($uid === false) {
3882 throw new ForbiddenException();
3885 $contact_id = $_REQUEST['user_id'] ?? 0;
3887 if (empty($contact_id)) {
3888 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3889 throw new BadRequestException("no user_id specified");
3892 // Get Contact by given id
3893 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3895 if(!DBA::isResult($contact)) {
3896 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3897 throw new NotFoundException("no contact found to given ID");
3900 $url = $contact["url"];
3902 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3903 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3904 Strings::normaliseLink($url), $url];
3905 $contact = DBA::selectFirst('contact', [], $condition);
3907 if (!DBA::isResult($contact)) {
3908 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3909 throw new NotFoundException("Not following Contact");
3912 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3913 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3914 throw new ExpectationFailedException("Not supported");
3917 $dissolve = ($contact['rel'] == Contact::SHARING);
3919 $owner = User::getOwnerDataById($uid);
3921 Contact::terminateFriendship($owner, $contact, $dissolve);
3924 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3925 throw new NotFoundException("Error Processing Request");
3928 // Sharing-only contacts get deleted as there no relationship any more
3930 Contact::remove($contact['id']);
3932 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3935 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3936 unset($contact["uid"]);
3937 unset($contact["self"]);
3939 // Set screen_name since Twidere requests it
3940 $contact["screen_name"] = $contact["nick"];
3942 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3944 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3948 * @param string $type Return type (atom, rss, xml, json)
3949 * @param string $box
3950 * @param string $verbose
3952 * @return array|string
3953 * @throws BadRequestException
3954 * @throws ForbiddenException
3955 * @throws ImagickException
3956 * @throws InternalServerErrorException
3957 * @throws UnauthorizedException
3959 function api_direct_messages_box($type, $box, $verbose)
3962 if (api_user() === false) {
3963 throw new ForbiddenException();
3966 $count = $_GET['count'] ?? 20;
3967 $page = $_REQUEST['page'] ?? 1;
3969 $since_id = $_REQUEST['since_id'] ?? 0;
3970 $max_id = $_REQUEST['max_id'] ?? 0;
3972 $user_id = $_REQUEST['user_id'] ?? '';
3973 $screen_name = $_REQUEST['screen_name'] ?? '';
3976 unset($_REQUEST["user_id"]);
3977 unset($_GET["user_id"]);
3979 unset($_REQUEST["screen_name"]);
3980 unset($_GET["screen_name"]);
3982 $user_info = api_get_user($a);
3983 if ($user_info === false) {
3984 throw new ForbiddenException();
3986 $profile_url = $user_info["url"];
3989 $start = max(0, ($page - 1) * $count);
3994 if ($box=="sentbox") {
3995 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3996 } elseif ($box == "conversation") {
3997 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3998 } elseif ($box == "all") {
3999 $sql_extra = "true";
4000 } elseif ($box == "inbox") {
4001 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4005 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4008 if ($user_id != "") {
4009 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4010 } elseif ($screen_name !="") {
4011 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4015 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",
4021 if ($verbose == "true" && !DBA::isResult($r)) {
4022 $answer = ['result' => 'error', 'message' => 'no mails available'];
4023 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4027 foreach ($r as $item) {
4028 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4029 $recipient = $user_info;
4030 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4031 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4032 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4033 $sender = $user_info;
4036 if (isset($recipient) && isset($sender)) {
4037 $ret[] = api_format_messages($item, $recipient, $sender);
4042 $data = ['direct_message' => $ret];
4047 $data = api_rss_extra($a, $data, $user_info);
4051 return api_format_data("direct-messages", $type, $data);
4055 * Returns the most recent direct messages sent by the user.
4057 * @param string $type Return type (atom, rss, xml, json)
4059 * @return array|string
4060 * @throws BadRequestException
4061 * @throws ForbiddenException
4062 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4064 function api_direct_messages_sentbox($type)
4066 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4067 return api_direct_messages_box($type, "sentbox", $verbose);
4071 * Returns the most recent direct messages sent to the user.
4073 * @param string $type Return type (atom, rss, xml, json)
4075 * @return array|string
4076 * @throws BadRequestException
4077 * @throws ForbiddenException
4078 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4080 function api_direct_messages_inbox($type)
4082 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4083 return api_direct_messages_box($type, "inbox", $verbose);
4088 * @param string $type Return type (atom, rss, xml, json)
4090 * @return array|string
4091 * @throws BadRequestException
4092 * @throws ForbiddenException
4094 function api_direct_messages_all($type)
4096 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4097 return api_direct_messages_box($type, "all", $verbose);
4102 * @param string $type Return type (atom, rss, xml, json)
4104 * @return array|string
4105 * @throws BadRequestException
4106 * @throws ForbiddenException
4108 function api_direct_messages_conversation($type)
4110 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4111 return api_direct_messages_box($type, "conversation", $verbose);
4114 /// @TODO move to top of file or somewhere better
4115 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4116 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4117 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4118 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4121 * Returns an OAuth Request Token.
4123 * @see https://oauth.net/core/1.0/#auth_step1
4125 function api_oauth_request_token()
4127 $oauth1 = new FKOAuth1();
4129 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4130 } catch (Exception $e) {
4131 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4139 * Returns an OAuth Access Token.
4141 * @return array|string
4142 * @see https://oauth.net/core/1.0/#auth_step3
4144 function api_oauth_access_token()
4146 $oauth1 = new FKOAuth1();
4148 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4149 } catch (Exception $e) {
4150 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4157 /// @TODO move to top of file or somewhere better
4158 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4159 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4163 * @brief delete a complete photoalbum with all containing photos from database through api
4165 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4166 * @return string|array
4167 * @throws BadRequestException
4168 * @throws ForbiddenException
4169 * @throws InternalServerErrorException
4171 function api_fr_photoalbum_delete($type)
4173 if (api_user() === false) {
4174 throw new ForbiddenException();
4177 $album = $_REQUEST['album'] ?? '';
4179 // we do not allow calls without album string
4181 throw new BadRequestException("no albumname specified");
4183 // check if album is existing
4185 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4189 if (!DBA::isResult($r)) {
4190 throw new BadRequestException("album not available");
4193 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4194 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4195 foreach ($r as $rr) {
4196 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4197 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4199 if (!DBA::isResult($photo_item)) {
4200 throw new InternalServerErrorException("problem with deleting items occured");
4202 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4205 // now let's delete all photos from the album
4206 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4208 // return success of deletion or error message
4210 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4211 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4213 throw new InternalServerErrorException("unknown error - deleting from database failed");
4218 * @brief update the name of the album for all photos of an album
4220 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4221 * @return string|array
4222 * @throws BadRequestException
4223 * @throws ForbiddenException
4224 * @throws InternalServerErrorException
4226 function api_fr_photoalbum_update($type)
4228 if (api_user() === false) {
4229 throw new ForbiddenException();
4232 $album = $_REQUEST['album'] ?? '';
4233 $album_new = $_REQUEST['album_new'] ?? '';
4235 // we do not allow calls without album string
4237 throw new BadRequestException("no albumname specified");
4239 if ($album_new == "") {
4240 throw new BadRequestException("no new albumname specified");
4242 // check if album is existing
4243 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4244 throw new BadRequestException("album not available");
4246 // now let's update all photos to the albumname
4247 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4249 // return success of updating or error message
4251 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4252 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4254 throw new InternalServerErrorException("unknown error - updating in database failed");
4260 * @brief list all photos of the authenticated user
4262 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4263 * @return string|array
4264 * @throws ForbiddenException
4265 * @throws InternalServerErrorException
4267 function api_fr_photos_list($type)
4269 if (api_user() === false) {
4270 throw new ForbiddenException();
4273 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4274 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4275 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4276 intval(local_user())
4279 'image/jpeg' => 'jpg',
4280 'image/png' => 'png',
4281 'image/gif' => 'gif'
4283 $data = ['photo'=>[]];
4284 if (DBA::isResult($r)) {
4285 foreach ($r as $rr) {
4287 $photo['id'] = $rr['resource-id'];
4288 $photo['album'] = $rr['album'];
4289 $photo['filename'] = $rr['filename'];
4290 $photo['type'] = $rr['type'];
4291 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4292 $photo['created'] = $rr['created'];
4293 $photo['edited'] = $rr['edited'];
4294 $photo['desc'] = $rr['desc'];
4296 if ($type == "xml") {
4297 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4299 $photo['thumb'] = $thumb;
4300 $data['photo'][] = $photo;
4304 return api_format_data("photos", $type, $data);
4308 * @brief upload a new photo or change an existing photo
4310 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4311 * @return string|array
4312 * @throws BadRequestException
4313 * @throws ForbiddenException
4314 * @throws ImagickException
4315 * @throws InternalServerErrorException
4316 * @throws NotFoundException
4318 function api_fr_photo_create_update($type)
4320 if (api_user() === false) {
4321 throw new ForbiddenException();
4324 $photo_id = $_REQUEST['photo_id'] ?? null;
4325 $desc = $_REQUEST['desc'] ?? null;
4326 $album = $_REQUEST['album'] ?? null;
4327 $album_new = $_REQUEST['album_new'] ?? null;
4328 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4329 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4330 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4331 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4332 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4334 // do several checks on input parameters
4335 // we do not allow calls without album string
4336 if ($album == null) {
4337 throw new BadRequestException("no albumname specified");
4339 // if photo_id == null --> we are uploading a new photo
4340 if ($photo_id == null) {
4343 // error if no media posted in create-mode
4344 if (empty($_FILES['media'])) {
4346 throw new BadRequestException("no media data submitted");
4349 // album_new will be ignored in create-mode
4354 // check if photo is existing in databasei
4355 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4356 throw new BadRequestException("photo not available");
4360 // checks on acl strings provided by clients
4361 $acl_input_error = false;
4362 $acl_input_error |= check_acl_input($allow_cid);
4363 $acl_input_error |= check_acl_input($deny_cid);
4364 $acl_input_error |= check_acl_input($allow_gid);
4365 $acl_input_error |= check_acl_input($deny_gid);
4366 if ($acl_input_error) {
4367 throw new BadRequestException("acl data invalid");
4369 // now let's upload the new media in create-mode
4370 if ($mode == "create") {
4371 $media = $_FILES['media'];
4372 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4374 // return success of updating or error message
4375 if (!is_null($data)) {
4376 return api_format_data("photo_create", $type, $data);
4378 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4382 // now let's do the changes in update-mode
4383 if ($mode == "update") {
4384 $updated_fields = [];
4386 if (!is_null($desc)) {
4387 $updated_fields['desc'] = $desc;
4390 if (!is_null($album_new)) {
4391 $updated_fields['album'] = $album_new;
4394 if (!is_null($allow_cid)) {
4395 $allow_cid = trim($allow_cid);
4396 $updated_fields['allow_cid'] = $allow_cid;
4399 if (!is_null($deny_cid)) {
4400 $deny_cid = trim($deny_cid);
4401 $updated_fields['deny_cid'] = $deny_cid;
4404 if (!is_null($allow_gid)) {
4405 $allow_gid = trim($allow_gid);
4406 $updated_fields['allow_gid'] = $allow_gid;
4409 if (!is_null($deny_gid)) {
4410 $deny_gid = trim($deny_gid);
4411 $updated_fields['deny_gid'] = $deny_gid;
4415 if (count($updated_fields) > 0) {
4416 $nothingtodo = false;
4417 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4419 $nothingtodo = true;
4422 if (!empty($_FILES['media'])) {
4423 $nothingtodo = false;
4424 $media = $_FILES['media'];
4425 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4426 if (!is_null($data)) {
4427 return api_format_data("photo_update", $type, $data);
4431 // return success of updating or error message
4433 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4434 return api_format_data("photo_update", $type, ['$result' => $answer]);
4437 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4438 return api_format_data("photo_update", $type, ['$result' => $answer]);
4440 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4443 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4447 * @brief delete a single photo from the database through api
4449 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4450 * @return string|array
4451 * @throws BadRequestException
4452 * @throws ForbiddenException
4453 * @throws InternalServerErrorException
4455 function api_fr_photo_delete($type)
4457 if (api_user() === false) {
4458 throw new ForbiddenException();
4462 $photo_id = $_REQUEST['photo_id'] ?? null;
4464 // do several checks on input parameters
4465 // we do not allow calls without photo id
4466 if ($photo_id == null) {
4467 throw new BadRequestException("no photo_id specified");
4470 // check if photo is existing in database
4471 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4472 throw new BadRequestException("photo not available");
4475 // now we can perform on the deletion of the photo
4476 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4478 // return success of deletion or error message
4480 // retrieve the id of the parent element (the photo element)
4481 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4482 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4484 if (!DBA::isResult($photo_item)) {
4485 throw new InternalServerErrorException("problem with deleting items occured");
4487 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4488 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4489 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4491 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4492 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4494 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4500 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4502 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4503 * @return string|array
4504 * @throws BadRequestException
4505 * @throws ForbiddenException
4506 * @throws InternalServerErrorException
4507 * @throws NotFoundException
4509 function api_fr_photo_detail($type)
4511 if (api_user() === false) {
4512 throw new ForbiddenException();
4514 if (empty($_REQUEST['photo_id'])) {
4515 throw new BadRequestException("No photo id.");
4518 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4519 $photo_id = $_REQUEST['photo_id'];
4521 // prepare json/xml output with data from database for the requested photo
4522 $data = prepare_photo_data($type, $scale, $photo_id);
4524 return api_format_data("photo_detail", $type, $data);
4529 * Updates the user’s profile image.
4531 * @brief updates the profile image for the user (either a specified profile or the default profile)
4533 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4535 * @return string|array
4536 * @throws BadRequestException
4537 * @throws ForbiddenException
4538 * @throws ImagickException
4539 * @throws InternalServerErrorException
4540 * @throws NotFoundException
4541 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4543 function api_account_update_profile_image($type)
4545 if (api_user() === false) {
4546 throw new ForbiddenException();
4549 $profile_id = $_REQUEST['profile_id'] ?? 0;
4551 // error if image data is missing
4552 if (empty($_FILES['image'])) {
4553 throw new BadRequestException("no media data submitted");
4556 // check if specified profile id is valid
4557 if ($profile_id != 0) {
4558 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4559 // error message if specified profile id is not in database
4560 if (!DBA::isResult($profile)) {
4561 throw new BadRequestException("profile_id not available");
4563 $is_default_profile = $profile['is-default'];
4565 $is_default_profile = 1;
4568 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4570 if (!empty($_FILES['image'])) {
4571 $media = $_FILES['image'];
4572 } elseif (!empty($_FILES['media'])) {
4573 $media = $_FILES['media'];
4575 // save new profile image
4576 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4579 if (is_array($media['type'])) {
4580 $filetype = $media['type'][0];
4582 $filetype = $media['type'];
4584 if ($filetype == "image/jpeg") {
4586 } elseif ($filetype == "image/png") {
4589 throw new InternalServerErrorException('Unsupported filetype');
4592 // change specified profile or all profiles to the new resource-id
4593 if ($is_default_profile) {
4594 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4595 Photo::update(['profile' => false], $condition);
4597 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4598 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4599 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4602 Contact::updateSelfFromUserID(api_user(), true);
4604 // Update global directory in background
4605 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4606 if ($url && strlen(Config::get('system', 'directory'))) {
4607 Worker::add(PRIORITY_LOW, "Directory", $url);
4610 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4612 // output for client
4614 return api_account_verify_credentials($type);
4616 // SaveMediaToDatabase failed for some reason
4617 throw new InternalServerErrorException("image upload failed");
4621 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4622 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4623 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4624 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4625 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4626 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4627 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4628 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4629 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4632 * Update user profile
4634 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4636 * @return array|string
4637 * @throws BadRequestException
4638 * @throws ForbiddenException
4639 * @throws ImagickException
4640 * @throws InternalServerErrorException
4641 * @throws UnauthorizedException
4643 function api_account_update_profile($type)
4645 $local_user = api_user();
4646 $api_user = api_get_user(get_app());
4648 if (!empty($_POST['name'])) {
4649 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4650 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4651 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4652 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4655 if (isset($_POST['description'])) {
4656 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4657 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4658 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4661 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4662 // Update global directory in background
4663 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4664 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4667 return api_account_verify_credentials($type);
4670 /// @TODO move to top of file or somewhere better
4671 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4675 * @param string $acl_string
4679 function check_acl_input($acl_string)
4681 if (empty($acl_string)) {
4685 $contact_not_found = false;
4687 // split <x><y><z> into array of cid's
4688 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4690 // check for each cid if it is available on server
4691 $cid_array = $array[0];
4692 foreach ($cid_array as $cid) {
4693 $cid = str_replace("<", "", $cid);
4694 $cid = str_replace(">", "", $cid);
4695 $condition = ['id' => $cid, 'uid' => api_user()];
4696 $contact_not_found |= !DBA::exists('contact', $condition);
4698 return $contact_not_found;
4702 * @param string $mediatype
4703 * @param array $media
4704 * @param string $type
4705 * @param string $album
4706 * @param string $allow_cid
4707 * @param string $deny_cid
4708 * @param string $allow_gid
4709 * @param string $deny_gid
4710 * @param string $desc
4711 * @param integer $profile
4712 * @param boolean $visibility
4713 * @param string $photo_id
4715 * @throws BadRequestException
4716 * @throws ForbiddenException
4717 * @throws ImagickException
4718 * @throws InternalServerErrorException
4719 * @throws NotFoundException
4720 * @throws UnauthorizedException
4722 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $profile = 0, $visibility = false, $photo_id = null)
4730 if (is_array($media)) {
4731 if (is_array($media['tmp_name'])) {
4732 $src = $media['tmp_name'][0];
4734 $src = $media['tmp_name'];
4736 if (is_array($media['name'])) {
4737 $filename = basename($media['name'][0]);
4739 $filename = basename($media['name']);
4741 if (is_array($media['size'])) {
4742 $filesize = intval($media['size'][0]);
4744 $filesize = intval($media['size']);
4746 if (is_array($media['type'])) {
4747 $filetype = $media['type'][0];
4749 $filetype = $media['type'];
4753 if ($filetype == "") {
4754 $filetype = Images::guessType($filename);
4756 $imagedata = @getimagesize($src);
4758 $filetype = $imagedata['mime'];
4761 "File upload src: " . $src . " - filename: " . $filename .
4762 " - size: " . $filesize . " - type: " . $filetype,
4766 // check if there was a php upload error
4767 if ($filesize == 0 && $media['error'] == 1) {
4768 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4770 // check against max upload size within Friendica instance
4771 $maximagesize = Config::get('system', 'maximagesize');
4772 if ($maximagesize && ($filesize > $maximagesize)) {
4773 $formattedBytes = Strings::formatBytes($maximagesize);
4774 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4777 // create Photo instance with the data of the image
4778 $imagedata = @file_get_contents($src);
4779 $Image = new Image($imagedata, $filetype);
4780 if (!$Image->isValid()) {
4781 throw new InternalServerErrorException("unable to process image data");
4784 // check orientation of image
4785 $Image->orient($src);
4788 // check max length of images on server
4789 $max_length = Config::get('system', 'max_image_length');
4791 $max_length = MAX_IMAGE_LENGTH;
4793 if ($max_length > 0) {
4794 $Image->scaleDown($max_length);
4795 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4797 $width = $Image->getWidth();
4798 $height = $Image->getHeight();
4800 // create a new resource-id if not already provided
4801 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4803 if ($mediatype == "photo") {
4804 // upload normal image (scales 0, 1, 2)
4805 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4807 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4809 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4811 if ($width > 640 || $height > 640) {
4812 $Image->scaleDown(640);
4813 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4815 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4819 if ($width > 320 || $height > 320) {
4820 $Image->scaleDown(320);
4821 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4823 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4826 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4827 } elseif ($mediatype == "profileimage") {
4828 // upload profile image (scales 4, 5, 6)
4829 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4831 if ($width > 300 || $height > 300) {
4832 $Image->scaleDown(300);
4833 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4835 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4839 if ($width > 80 || $height > 80) {
4840 $Image->scaleDown(80);
4841 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4843 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4847 if ($width > 48 || $height > 48) {
4848 $Image->scaleDown(48);
4849 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4851 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4854 $Image->__destruct();
4855 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4858 if (isset($r) && $r) {
4859 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4860 if ($photo_id == null && $mediatype == "photo") {
4861 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4863 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4864 return prepare_photo_data($type, false, $resource_id);
4866 throw new InternalServerErrorException("image upload failed");
4872 * @param string $hash
4873 * @param string $allow_cid
4874 * @param string $deny_cid
4875 * @param string $allow_gid
4876 * @param string $deny_gid
4877 * @param string $filetype
4878 * @param boolean $visibility
4879 * @throws InternalServerErrorException
4881 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4883 // get data about the api authenticated user
4884 $uri = Item::newURI(intval(api_user()));
4885 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4888 $arr['guid'] = System::createUUID();
4889 $arr['uid'] = intval(api_user());
4891 $arr['parent-uri'] = $uri;
4892 $arr['type'] = 'photo';
4894 $arr['resource-id'] = $hash;
4895 $arr['contact-id'] = $owner_record['id'];
4896 $arr['owner-name'] = $owner_record['name'];
4897 $arr['owner-link'] = $owner_record['url'];
4898 $arr['owner-avatar'] = $owner_record['thumb'];
4899 $arr['author-name'] = $owner_record['name'];
4900 $arr['author-link'] = $owner_record['url'];
4901 $arr['author-avatar'] = $owner_record['thumb'];
4903 $arr['allow_cid'] = $allow_cid;
4904 $arr['allow_gid'] = $allow_gid;
4905 $arr['deny_cid'] = $deny_cid;
4906 $arr['deny_gid'] = $deny_gid;
4907 $arr['visible'] = $visibility;
4911 'image/jpeg' => 'jpg',
4912 'image/png' => 'png',
4913 'image/gif' => 'gif'
4916 // adds link to the thumbnail scale photo
4917 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4918 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4921 // do the magic for storing the item in the database and trigger the federation to other contacts
4927 * @param string $type
4929 * @param string $photo_id
4932 * @throws BadRequestException
4933 * @throws ForbiddenException
4934 * @throws ImagickException
4935 * @throws InternalServerErrorException
4936 * @throws NotFoundException
4937 * @throws UnauthorizedException
4939 function prepare_photo_data($type, $scale, $photo_id)
4942 $user_info = api_get_user($a);
4944 if ($user_info === false) {
4945 throw new ForbiddenException();
4948 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4949 $data_sql = ($scale === false ? "" : "data, ");
4951 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4952 // clients needs to convert this in their way for further processing
4954 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4955 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4956 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4957 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4958 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4959 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4961 intval(local_user()),
4962 DBA::escape($photo_id),
4967 'image/jpeg' => 'jpg',
4968 'image/png' => 'png',
4969 'image/gif' => 'gif'
4972 // prepare output data for photo
4973 if (DBA::isResult($r)) {
4974 $data = ['photo' => $r[0]];
4975 $data['photo']['id'] = $data['photo']['resource-id'];
4976 if ($scale !== false) {
4977 $data['photo']['data'] = base64_encode($data['photo']['data']);
4979 unset($data['photo']['datasize']); //needed only with scale param
4981 if ($type == "xml") {
4982 $data['photo']['links'] = [];
4983 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4984 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4986 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4989 $data['photo']['link'] = [];
4990 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4992 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4993 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4997 unset($data['photo']['resource-id']);
4998 unset($data['photo']['minscale']);
4999 unset($data['photo']['maxscale']);
5001 throw new NotFoundException();
5004 // retrieve item element for getting activities (like, dislike etc.) related to photo
5005 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5006 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5008 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5010 // retrieve comments on photo
5011 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5012 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5014 $statuses = Item::selectForUser(api_user(), [], $condition);
5016 // prepare output of comments
5017 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5019 if ($type == "xml") {
5021 foreach ($commentData as $comment) {
5022 $comments[$k++ . ":comment"] = $comment;
5025 foreach ($commentData as $comment) {
5026 $comments[] = $comment;
5029 $data['photo']['friendica_comments'] = $comments;
5031 // include info if rights on photo and rights on item are mismatching
5032 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5033 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5034 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5035 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5036 $data['photo']['rights_mismatch'] = $rights_mismatch;
5043 * Similar as /mod/redir.php
5044 * redirect to 'url' after dfrn auth
5046 * Why this when there is mod/redir.php already?
5047 * This use api_user() and api_login()
5050 * c_url: url of remote contact to auth to
5051 * url: string, url to redirect after auth
5053 function api_friendica_remoteauth()
5055 $url = $_GET['url'] ?? '';
5056 $c_url = $_GET['c_url'] ?? '';
5058 if ($url === '' || $c_url === '') {
5059 throw new BadRequestException("Wrong parameters.");
5062 $c_url = Strings::normaliseLink($c_url);
5066 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5068 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5069 throw new BadRequestException("Unknown contact");
5072 $cid = $contact['id'];
5074 $dfrn_id = $contact['issued-id'] ?? $contact['dfrn-id'];
5076 if ($contact['duplex'] && $contact['issued-id']) {
5077 $orig_id = $contact['issued-id'];
5078 $dfrn_id = '1:' . $orig_id;
5080 if ($contact['duplex'] && $contact['dfrn-id']) {
5081 $orig_id = $contact['dfrn-id'];
5082 $dfrn_id = '0:' . $orig_id;
5085 $sec = Strings::getRandomHex();
5087 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5088 'sec' => $sec, 'expire' => time() + 45];
5089 DBA::insert('profile_check', $fields);
5091 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5092 $dest = ($url ? '&destination_url=' . $url : '');
5094 System::externalRedirect(
5095 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5096 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5097 . '&type=profile&sec=' . $sec . $dest
5100 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5103 * Return an item with announcer data if it had been announced
5105 * @param array $item Item array
5106 * @return array Item array with announce data
5108 function api_get_announce($item)
5110 // Quit if the item already has got a different owner and author
5111 if ($item['owner-id'] != $item['author-id']) {
5115 // Don't change original or Diaspora posts
5116 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5120 // Quit if we do now the original author and it had been a post from a native network
5121 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5125 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5126 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5127 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5128 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5129 if (!DBA::isResult($announce)) {
5133 return array_merge($item, $announce);
5137 * @brief Return the item shared, if the item contains only the [share] tag
5139 * @param array $item Sharer item
5140 * @return array|false Shared item or false if not a reshare
5141 * @throws ImagickException
5142 * @throws InternalServerErrorException
5144 function api_share_as_retweet(&$item)
5146 $body = trim($item["body"]);
5148 if (Diaspora::isReshare($body, false) === false) {
5149 if ($item['author-id'] == $item['owner-id']) {
5152 // Reshares from OStatus, ActivityPub and Twitter
5153 $reshared_item = $item;
5154 $reshared_item['owner-id'] = $reshared_item['author-id'];
5155 $reshared_item['owner-link'] = $reshared_item['author-link'];
5156 $reshared_item['owner-name'] = $reshared_item['author-name'];
5157 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5158 return $reshared_item;
5162 $reshared = Item::getShareArray($item);
5163 if (empty($reshared)) {
5167 $reshared_item = $item;
5169 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5173 if (!empty($reshared['comment'])) {
5174 $item['body'] = $reshared['comment'];
5177 $reshared_item["share-pre-body"] = $reshared['comment'];
5178 $reshared_item["body"] = $reshared['shared'];
5179 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5180 $reshared_item["author-name"] = $reshared['author'];
5181 $reshared_item["author-link"] = $reshared['profile'];
5182 $reshared_item["author-avatar"] = $reshared['avatar'];
5183 $reshared_item["plink"] = $reshared['link'] ?? '';
5184 $reshared_item["created"] = $reshared['posted'];
5185 $reshared_item["edited"] = $reshared['posted'];
5187 return $reshared_item;
5192 * @param string $profile
5194 * @return string|false
5195 * @throws InternalServerErrorException
5196 * @todo remove trailing junk from profile url
5197 * @todo pump.io check has to check the website
5199 function api_get_nick($profile)
5204 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5205 DBA::escape(Strings::normaliseLink($profile))
5208 if (DBA::isResult($r)) {
5209 $nick = $r[0]["nick"];
5214 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5215 DBA::escape(Strings::normaliseLink($profile))
5218 if (DBA::isResult($r)) {
5219 $nick = $r[0]["nick"];
5224 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5225 if ($friendica != $profile) {
5231 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5232 if ($diaspora != $profile) {
5238 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5239 if ($twitter != $profile) {
5246 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5247 if ($StatusnetHost != $profile) {
5248 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5249 if ($StatusnetUser != $profile) {
5250 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5251 $user = json_decode($UserData);
5253 $nick = $user->screen_name;
5259 // To-Do: look at the page if its really a pumpio site
5260 //if (!$nick == "") {
5261 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5262 // if ($pumpio != $profile)
5264 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5277 * @param array $item
5282 function api_in_reply_to($item)
5286 $in_reply_to['status_id'] = null;
5287 $in_reply_to['user_id'] = null;
5288 $in_reply_to['status_id_str'] = null;
5289 $in_reply_to['user_id_str'] = null;
5290 $in_reply_to['screen_name'] = null;
5292 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5293 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5294 if (DBA::isResult($parent)) {
5295 $in_reply_to['status_id'] = intval($parent['id']);
5297 $in_reply_to['status_id'] = intval($item['parent']);
5300 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5302 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5303 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5305 if (DBA::isResult($parent)) {
5306 if ($parent['author-nick'] == "") {
5307 $parent['author-nick'] = api_get_nick($parent['author-link']);
5310 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5311 $in_reply_to['user_id'] = intval($parent['author-id']);
5312 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5315 // There seems to be situation, where both fields are identical:
5316 // https://github.com/friendica/friendica/issues/1010
5317 // This is a bugfix for that.
5318 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5319 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']]);
5320 $in_reply_to['status_id'] = null;
5321 $in_reply_to['user_id'] = null;
5322 $in_reply_to['status_id_str'] = null;
5323 $in_reply_to['user_id_str'] = null;
5324 $in_reply_to['screen_name'] = null;
5328 return $in_reply_to;
5333 * @param string $text
5336 * @throws InternalServerErrorException
5338 function api_clean_plain_items($text)
5340 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5342 $text = BBCode::cleanPictureLinks($text);
5343 $URLSearchString = "^\[\]";
5345 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5347 if ($include_entities == "true") {
5348 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5351 // Simplify "attachment" element
5352 $text = BBCode::removeAttachment($text);
5359 * @param array $contacts
5363 function api_best_nickname(&$contacts)
5367 if (count($contacts) == 0) {
5371 foreach ($contacts as $contact) {
5372 if ($contact["network"] == "") {
5373 $contact["network"] = "dfrn";
5374 $best_contact = [$contact];
5378 if (sizeof($best_contact) == 0) {
5379 foreach ($contacts as $contact) {
5380 if ($contact["network"] == "dfrn") {
5381 $best_contact = [$contact];
5386 if (sizeof($best_contact) == 0) {
5387 foreach ($contacts as $contact) {
5388 if ($contact["network"] == "dspr") {
5389 $best_contact = [$contact];
5394 if (sizeof($best_contact) == 0) {
5395 foreach ($contacts as $contact) {
5396 if ($contact["network"] == "stat") {
5397 $best_contact = [$contact];
5402 if (sizeof($best_contact) == 0) {
5403 foreach ($contacts as $contact) {
5404 if ($contact["network"] == "pump") {
5405 $best_contact = [$contact];
5410 if (sizeof($best_contact) == 0) {
5411 foreach ($contacts as $contact) {
5412 if ($contact["network"] == "twit") {
5413 $best_contact = [$contact];
5418 if (sizeof($best_contact) == 1) {
5419 $contacts = $best_contact;
5421 $contacts = [$contacts[0]];
5426 * Return all or a specified group of the user with the containing contacts.
5428 * @param string $type Return type (atom, rss, xml, json)
5430 * @return array|string
5431 * @throws BadRequestException
5432 * @throws ForbiddenException
5433 * @throws ImagickException
5434 * @throws InternalServerErrorException
5435 * @throws UnauthorizedException
5437 function api_friendica_group_show($type)
5441 if (api_user() === false) {
5442 throw new ForbiddenException();
5446 $user_info = api_get_user($a);
5447 $gid = $_REQUEST['gid'] ?? 0;
5448 $uid = $user_info['uid'];
5450 // get data of the specified group id or all groups if not specified
5453 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5457 // error message if specified gid is not in database
5458 if (!DBA::isResult($r)) {
5459 throw new BadRequestException("gid not available");
5463 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5468 // loop through all groups and retrieve all members for adding data in the user array
5470 foreach ($r as $rr) {
5471 $members = Contact::getByGroupId($rr['id']);
5474 if ($type == "xml") {
5475 $user_element = "users";
5477 foreach ($members as $member) {
5478 $user = api_get_user($a, $member['nurl']);
5479 $users[$k++.":user"] = $user;
5482 $user_element = "user";
5483 foreach ($members as $member) {
5484 $user = api_get_user($a, $member['nurl']);
5488 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5490 return api_format_data("groups", $type, ['group' => $grps]);
5492 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5496 * Delete the specified group of the user.
5498 * @param string $type Return type (atom, rss, xml, json)
5500 * @return array|string
5501 * @throws BadRequestException
5502 * @throws ForbiddenException
5503 * @throws ImagickException
5504 * @throws InternalServerErrorException
5505 * @throws UnauthorizedException
5507 function api_friendica_group_delete($type)
5511 if (api_user() === false) {
5512 throw new ForbiddenException();
5516 $user_info = api_get_user($a);
5517 $gid = $_REQUEST['gid'] ?? 0;
5518 $name = $_REQUEST['name'] ?? '';
5519 $uid = $user_info['uid'];
5521 // error if no gid specified
5522 if ($gid == 0 || $name == "") {
5523 throw new BadRequestException('gid or name not specified');
5526 // get data of the specified group id
5528 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5532 // error message if specified gid is not in database
5533 if (!DBA::isResult($r)) {
5534 throw new BadRequestException('gid not available');
5537 // get data of the specified group id and group name
5539 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5544 // error message if specified gid is not in database
5545 if (!DBA::isResult($rname)) {
5546 throw new BadRequestException('wrong group name');
5550 $ret = Group::removeByName($uid, $name);
5553 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5554 return api_format_data("group_delete", $type, ['result' => $success]);
5556 throw new BadRequestException('other API error');
5559 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5564 * @param string $type Return type (atom, rss, xml, json)
5566 * @return array|string
5567 * @throws BadRequestException
5568 * @throws ForbiddenException
5569 * @throws ImagickException
5570 * @throws InternalServerErrorException
5571 * @throws UnauthorizedException
5572 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5574 function api_lists_destroy($type)
5578 if (api_user() === false) {
5579 throw new ForbiddenException();
5583 $user_info = api_get_user($a);
5584 $gid = $_REQUEST['list_id'] ?? 0;
5585 $uid = $user_info['uid'];
5587 // error if no gid specified
5589 throw new BadRequestException('gid not specified');
5592 // get data of the specified group id
5593 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5594 // error message if specified gid is not in database
5596 throw new BadRequestException('gid not available');
5599 if (Group::remove($gid)) {
5601 'name' => $group['name'],
5602 'id' => intval($gid),
5603 'id_str' => (string) $gid,
5604 'user' => $user_info
5607 return api_format_data("lists", $type, ['lists' => $list]);
5610 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5613 * Add a new group to the database.
5615 * @param string $name Group name
5616 * @param int $uid User ID
5617 * @param array $users List of users to add to the group
5620 * @throws BadRequestException
5622 function group_create($name, $uid, $users = [])
5624 // error if no name specified
5626 throw new BadRequestException('group name not specified');
5629 // get data of the specified group name
5631 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5635 // error message if specified group name already exists
5636 if (DBA::isResult($rname)) {
5637 throw new BadRequestException('group name already exists');
5640 // check if specified group name is a deleted group
5642 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5646 // error message if specified group name already exists
5647 if (DBA::isResult($rname)) {
5648 $reactivate_group = true;
5652 $ret = Group::create($uid, $name);
5654 $gid = Group::getIdByName($uid, $name);
5656 throw new BadRequestException('other API error');
5660 $erroraddinguser = false;
5662 foreach ($users as $user) {
5663 $cid = $user['cid'];
5664 // check if user really exists as contact
5666 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5670 if (count($contact)) {
5671 Group::addMember($gid, $cid);
5673 $erroraddinguser = true;
5674 $errorusers[] = $cid;
5678 // return success message incl. missing users in array
5679 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5681 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5685 * Create the specified group with the posted array of contacts.
5687 * @param string $type Return type (atom, rss, xml, json)
5689 * @return array|string
5690 * @throws BadRequestException
5691 * @throws ForbiddenException
5692 * @throws ImagickException
5693 * @throws InternalServerErrorException
5694 * @throws UnauthorizedException
5696 function api_friendica_group_create($type)
5700 if (api_user() === false) {
5701 throw new ForbiddenException();
5705 $user_info = api_get_user($a);
5706 $name = $_REQUEST['name'] ?? '';
5707 $uid = $user_info['uid'];
5708 $json = json_decode($_POST['json'], true);
5709 $users = $json['user'];
5711 $success = group_create($name, $uid, $users);
5713 return api_format_data("group_create", $type, ['result' => $success]);
5715 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5718 * Create a new group.
5720 * @param string $type Return type (atom, rss, xml, json)
5722 * @return array|string
5723 * @throws BadRequestException
5724 * @throws ForbiddenException
5725 * @throws ImagickException
5726 * @throws InternalServerErrorException
5727 * @throws UnauthorizedException
5728 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5730 function api_lists_create($type)
5734 if (api_user() === false) {
5735 throw new ForbiddenException();
5739 $user_info = api_get_user($a);
5740 $name = $_REQUEST['name'] ?? '';
5741 $uid = $user_info['uid'];
5743 $success = group_create($name, $uid);
5744 if ($success['success']) {
5746 'name' => $success['name'],
5747 'id' => intval($success['gid']),
5748 'id_str' => (string) $success['gid'],
5749 'user' => $user_info
5752 return api_format_data("lists", $type, ['lists'=>$grp]);
5755 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5758 * Update the specified group with the posted array of contacts.
5760 * @param string $type Return type (atom, rss, xml, json)
5762 * @return array|string
5763 * @throws BadRequestException
5764 * @throws ForbiddenException
5765 * @throws ImagickException
5766 * @throws InternalServerErrorException
5767 * @throws UnauthorizedException
5769 function api_friendica_group_update($type)
5773 if (api_user() === false) {
5774 throw new ForbiddenException();
5778 $user_info = api_get_user($a);
5779 $uid = $user_info['uid'];
5780 $gid = $_REQUEST['gid'] ?? 0;
5781 $name = $_REQUEST['name'] ?? '';
5782 $json = json_decode($_POST['json'], true);
5783 $users = $json['user'];
5785 // error if no name specified
5787 throw new BadRequestException('group name not specified');
5790 // error if no gid specified
5792 throw new BadRequestException('gid not specified');
5796 $members = Contact::getByGroupId($gid);
5797 foreach ($members as $member) {
5798 $cid = $member['id'];
5799 foreach ($users as $user) {
5800 $found = ($user['cid'] == $cid ? true : false);
5802 if (!isset($found) || !$found) {
5803 Group::removeMemberByName($uid, $name, $cid);
5808 $erroraddinguser = false;
5810 foreach ($users as $user) {
5811 $cid = $user['cid'];
5812 // check if user really exists as contact
5814 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5819 if (count($contact)) {
5820 Group::addMember($gid, $cid);
5822 $erroraddinguser = true;
5823 $errorusers[] = $cid;
5827 // return success message incl. missing users in array
5828 $status = ($erroraddinguser ? "missing user" : "ok");
5829 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5830 return api_format_data("group_update", $type, ['result' => $success]);
5833 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5836 * Update information about a group.
5838 * @param string $type Return type (atom, rss, xml, json)
5840 * @return array|string
5841 * @throws BadRequestException
5842 * @throws ForbiddenException
5843 * @throws ImagickException
5844 * @throws InternalServerErrorException
5845 * @throws UnauthorizedException
5846 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5848 function api_lists_update($type)
5852 if (api_user() === false) {
5853 throw new ForbiddenException();
5857 $user_info = api_get_user($a);
5858 $gid = $_REQUEST['list_id'] ?? 0;
5859 $name = $_REQUEST['name'] ?? '';
5860 $uid = $user_info['uid'];
5862 // error if no gid specified
5864 throw new BadRequestException('gid not specified');
5867 // get data of the specified group id
5868 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5869 // error message if specified gid is not in database
5871 throw new BadRequestException('gid not available');
5874 if (Group::update($gid, $name)) {
5877 'id' => intval($gid),
5878 'id_str' => (string) $gid,
5879 'user' => $user_info
5882 return api_format_data("lists", $type, ['lists' => $list]);
5886 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5890 * @param string $type Return type (atom, rss, xml, json)
5892 * @return array|string
5893 * @throws BadRequestException
5894 * @throws ForbiddenException
5895 * @throws ImagickException
5896 * @throws InternalServerErrorException
5898 function api_friendica_activity($type)
5902 if (api_user() === false) {
5903 throw new ForbiddenException();
5905 $verb = strtolower($a->argv[3]);
5906 $verb = preg_replace("|\..*$|", "", $verb);
5908 $id = $_REQUEST['id'] ?? 0;
5910 $res = Item::performLike($id, $verb);
5913 if ($type == "xml") {
5918 return api_format_data('ok', $type, ['ok' => $ok]);
5920 throw new BadRequestException('Error adding activity');
5924 /// @TODO move to top of file or somewhere better
5925 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5926 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5927 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5928 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5929 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5930 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5931 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5932 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5933 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5934 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5937 * @brief Returns notifications
5939 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5940 * @return string|array
5941 * @throws BadRequestException
5942 * @throws ForbiddenException
5943 * @throws InternalServerErrorException
5945 function api_friendica_notification($type)
5949 if (api_user() === false) {
5950 throw new ForbiddenException();
5953 throw new BadRequestException("Invalid argument count");
5955 /** @var Notify $nm */
5956 $nm = BaseObject::getClass(Notify::class);
5958 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
5960 if ($type == "xml") {
5962 if (!empty($notes)) {
5963 foreach ($notes as $note) {
5964 $xmlnotes[] = ["@attributes" => $note];
5970 return api_format_data("notes", $type, ['note' => $notes]);
5974 * POST request with 'id' param as notification id
5976 * @brief Set notification as seen and returns associated item (if possible)
5978 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5979 * @return string|array
5980 * @throws BadRequestException
5981 * @throws ForbiddenException
5982 * @throws ImagickException
5983 * @throws InternalServerErrorException
5984 * @throws UnauthorizedException
5986 function api_friendica_notification_seen($type)
5989 $user_info = api_get_user($a);
5991 if (api_user() === false || $user_info === false) {
5992 throw new ForbiddenException();
5995 throw new BadRequestException("Invalid argument count");
5998 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
6000 /** @var Notify $nm */
6001 $nm = BaseObject::getClass(Notify::class);
6002 $note = $nm->getByID($id);
6003 if (is_null($note)) {
6004 throw new BadRequestException("Invalid argument");
6007 $nm->setSeen($note);
6008 if ($note['otype']=='item') {
6009 // would be really better with an ItemsManager and $im->getByID() :-P
6010 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6011 if (DBA::isResult($item)) {
6012 // we found the item, return it to the user
6013 $ret = api_format_items([$item], $user_info, false, $type);
6014 $data = ['status' => $ret];
6015 return api_format_data("status", $type, $data);
6017 // the item can't be found, but we set the note as seen, so we count this as a success
6019 return api_format_data('result', $type, ['result' => "success"]);
6022 /// @TODO move to top of file or somewhere better
6023 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6024 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6027 * @brief update a direct_message to seen state
6029 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6030 * @return string|array (success result=ok, error result=error with error message)
6031 * @throws BadRequestException
6032 * @throws ForbiddenException
6033 * @throws ImagickException
6034 * @throws InternalServerErrorException
6035 * @throws UnauthorizedException
6037 function api_friendica_direct_messages_setseen($type)
6040 if (api_user() === false) {
6041 throw new ForbiddenException();
6045 $user_info = api_get_user($a);
6046 $uid = $user_info['uid'];
6047 $id = $_REQUEST['id'] ?? 0;
6049 // return error if id is zero
6051 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6052 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6055 // error message if specified id is not in database
6056 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6057 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6058 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6061 // update seen indicator
6062 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6066 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6067 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6069 $answer = ['result' => 'error', 'message' => 'unknown error'];
6070 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6074 /// @TODO move to top of file or somewhere better
6075 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6078 * @brief search for direct_messages containing a searchstring through api
6080 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6081 * @param string $box
6082 * @return string|array (success: success=true if found and search_result contains found messages,
6083 * success=false if nothing was found, search_result='nothing found',
6084 * error: result=error with error message)
6085 * @throws BadRequestException
6086 * @throws ForbiddenException
6087 * @throws ImagickException
6088 * @throws InternalServerErrorException
6089 * @throws UnauthorizedException
6091 function api_friendica_direct_messages_search($type, $box = "")
6095 if (api_user() === false) {
6096 throw new ForbiddenException();
6100 $user_info = api_get_user($a);
6101 $searchstring = $_REQUEST['searchstring'] ?? '';
6102 $uid = $user_info['uid'];
6104 // error if no searchstring specified
6105 if ($searchstring == "") {
6106 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6107 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6110 // get data for the specified searchstring
6112 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC",
6114 DBA::escape('%'.$searchstring.'%')
6117 $profile_url = $user_info["url"];
6119 // message if nothing was found
6120 if (!DBA::isResult($r)) {
6121 $success = ['success' => false, 'search_results' => 'problem with query'];
6122 } elseif (count($r) == 0) {
6123 $success = ['success' => false, 'search_results' => 'nothing found'];
6126 foreach ($r as $item) {
6127 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6128 $recipient = $user_info;
6129 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6130 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6131 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6132 $sender = $user_info;
6135 if (isset($recipient) && isset($sender)) {
6136 $ret[] = api_format_messages($item, $recipient, $sender);
6139 $success = ['success' => true, 'search_results' => $ret];
6142 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6145 /// @TODO move to top of file or somewhere better
6146 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6149 * @brief return data of all the profiles a user has to the client
6151 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6152 * @return string|array
6153 * @throws BadRequestException
6154 * @throws ForbiddenException
6155 * @throws ImagickException
6156 * @throws InternalServerErrorException
6157 * @throws UnauthorizedException
6159 function api_friendica_profile_show($type)
6163 if (api_user() === false) {
6164 throw new ForbiddenException();
6168 $profile_id = $_REQUEST['profile_id'] ?? 0;
6170 // retrieve general information about profiles for user
6171 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6172 $directory = Config::get('system', 'directory');
6174 // get data of the specified profile id or all profiles of the user if not specified
6175 if ($profile_id != 0) {
6176 $r = Profile::getById(api_user(), $profile_id);
6177 // error message if specified gid is not in database
6178 if (!DBA::isResult($r)) {
6179 throw new BadRequestException("profile_id not available");
6182 $r = Profile::getListByUser(api_user());
6184 // loop through all returned profiles and retrieve data and users
6187 if (DBA::isResult($r)) {
6188 foreach ($r as $rr) {
6189 $profile = api_format_items_profiles($rr);
6191 // select all users from contact table, loop and prepare standard return for user data
6193 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6194 foreach ($nurls as $nurl) {
6195 $user = api_get_user($a, $nurl['nurl']);
6196 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6198 $profile['users'] = $users;
6200 // add prepared profile data to array for final return
6201 if ($type == "xml") {
6202 $profiles[$k++ . ":profile"] = $profile;
6204 $profiles[] = $profile;
6209 // return settings, authenticated user and profiles data
6210 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6212 $result = ['multi_profiles' => $multi_profiles ? true : false,
6213 'global_dir' => $directory,
6214 'friendica_owner' => api_get_user($a, $self['nurl']),
6215 'profiles' => $profiles];
6216 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6218 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6221 * Returns a list of saved searches.
6223 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6225 * @param string $type Return format: json or xml
6227 * @return string|array
6230 function api_saved_searches_list($type)
6232 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6235 while ($term = DBA::fetch($terms)) {
6237 'created_at' => api_date(time()),
6238 'id' => intval($term['id']),
6239 'id_str' => $term['id'],
6240 'name' => $term['term'],
6242 'query' => $term['term']
6248 return api_format_data("terms", $type, ['terms' => $result]);
6251 /// @TODO move to top of file or somewhere better
6252 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6255 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6257 * @brief Number of comments
6259 * @param object $data [Status, Status]
6263 function bindComments(&$data)
6265 if (count($data) == 0) {
6271 foreach ($data as $item) {
6272 $ids[] = $item['id'];
6275 $idStr = DBA::escape(implode(', ', $ids));
6276 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6277 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6278 $itemsData = DBA::toArray($items);
6280 foreach ($itemsData as $item) {
6281 $comments[$item['parent']] = $item['comments'];
6284 foreach ($data as $idx => $item) {
6286 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6291 @TODO Maybe open to implement?
6293 [pagename] => api/1.1/statuses/lookup.json
6294 [id] => 605138389168451584
6295 [include_cards] => true
6296 [cards_platform] => Android-12
6297 [include_entities] => true
6298 [include_my_retweet] => 1
6300 [include_reply_count] => true
6301 [include_descendent_reply_count] => true
6305 Not implemented by now:
6306 statuses/retweets_of_me
6311 account/update_location
6312 account/update_profile_background_image
6315 friendica/profile/update
6316 friendica/profile/create
6317 friendica/profile/delete
6319 Not implemented in status.net:
6320 statuses/retweeted_to_me
6321 statuses/retweeted_by_me
6322 direct_messages/destroy
6324 account/update_delivery_device
6325 notifications/follow