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\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Protocol;
17 use Friendica\Core\Session;
18 use Friendica\Core\System;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBA;
22 use Friendica\Model\Contact;
23 use Friendica\Model\Group;
24 use Friendica\Model\Item;
25 use Friendica\Model\Mail;
26 use Friendica\Model\Notify;
27 use Friendica\Model\Photo;
28 use Friendica\Model\Profile;
29 use Friendica\Model\User;
30 use Friendica\Model\UserItem;
31 use Friendica\Network\FKOAuth1;
32 use Friendica\Network\HTTPException;
33 use Friendica\Network\HTTPException\BadRequestException;
34 use Friendica\Network\HTTPException\ExpectationFailedException;
35 use Friendica\Network\HTTPException\ForbiddenException;
36 use Friendica\Network\HTTPException\InternalServerErrorException;
37 use Friendica\Network\HTTPException\MethodNotAllowedException;
38 use Friendica\Network\HTTPException\NotFoundException;
39 use Friendica\Network\HTTPException\NotImplementedException;
40 use Friendica\Network\HTTPException\TooManyRequestsException;
41 use Friendica\Network\HTTPException\UnauthorizedException;
42 use Friendica\Object\Image;
43 use Friendica\Protocol\Activity;
44 use Friendica\Protocol\Diaspora;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Images;
47 use Friendica\Util\Network;
48 use Friendica\Util\Proxy as ProxyUtils;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
52 require_once __DIR__ . '/../mod/share.php';
53 require_once __DIR__ . '/../mod/item.php';
54 require_once __DIR__ . '/../mod/wall_upload.php';
56 define('API_METHOD_ANY', '*');
57 define('API_METHOD_GET', 'GET');
58 define('API_METHOD_POST', 'POST,PUT');
59 define('API_METHOD_DELETE', 'POST,DELETE');
61 define('API_LOG_PREFIX', 'API {action} - ');
69 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
70 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
71 * into a page, and visitors will post something without noticing it).
75 if (!empty($_SESSION['allow_api'])) {
83 * Get source name from API client
85 * Clients can send 'source' parameter to be show in post metadata
86 * as "sent via <source>".
87 * Some clients doesn't send a source param, we support ones we know
91 * Client source name, default to "api" if unset/unknown
96 if (requestdata('source')) {
97 return requestdata('source');
100 // Support for known clients that doesn't send a source name
101 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
102 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
106 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
108 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
115 * Format date for API
117 * @param string $str Source date, as UTC
118 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
121 function api_date($str)
123 // Wed May 23 06:01:13 +0000 2007
124 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
128 * Register a function to be the endpoint for defined API path.
130 * @param string $path API URL path, relative to DI::baseUrl()
131 * @param string $func Function name to call on path request
132 * @param bool $auth API need logged user
133 * @param string $method HTTP method reqiured to call this endpoint.
134 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
135 * Default to API_METHOD_ANY
137 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
147 // Workaround for hotot
148 $path = str_replace("api/", "api/1.1/", $path);
158 * Log in user via OAuth1 or Simple HTTP Auth.
159 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
162 * @throws ForbiddenException
163 * @throws InternalServerErrorException
164 * @throws UnauthorizedException
165 * @hook 'authenticate'
167 * 'username' => username from login form
168 * 'password' => password from login form
169 * 'authenticated' => return status,
170 * 'user_record' => return authenticated user record
172 function api_login(App $a)
174 $oauth1 = new FKOAuth1();
177 $request = OAuthRequest::from_request();
178 list($consumer, $token) = $oauth1->verify_request($request);
179 if (!is_null($token)) {
180 $oauth1->loginUser($token->uid);
181 Session::set('allow_api', true);
184 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
185 var_dump($consumer, $token);
187 } catch (Exception $e) {
188 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
191 // workaround for HTTP-auth in CGI mode
192 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
193 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
194 if (strlen($userpass)) {
195 list($name, $password) = explode(':', $userpass);
196 $_SERVER['PHP_AUTH_USER'] = $name;
197 $_SERVER['PHP_AUTH_PW'] = $password;
201 if (empty($_SERVER['PHP_AUTH_USER'])) {
202 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
203 header('WWW-Authenticate: Basic realm="Friendica"');
204 throw new UnauthorizedException("This API requires login");
207 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
208 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
210 // allow "user@server" login (but ignore 'server' part)
211 $at = strstr($user, "@", true);
216 // next code from mod/auth.php. needs better solution
220 'username' => trim($user),
221 'password' => trim($password),
222 'authenticated' => 0,
223 'user_record' => null,
227 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
228 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
229 * and later addons should not interfere with an earlier one that succeeded.
231 Hook::callAll('authenticate', $addon_auth);
233 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
234 $record = $addon_auth['user_record'];
236 $user_id = User::authenticate(trim($user), trim($password), true);
237 if ($user_id !== false) {
238 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
242 if (!DBA::isResult($record)) {
243 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
244 header('WWW-Authenticate: Basic realm="Friendica"');
245 //header('HTTP/1.0 401 Unauthorized');
246 //die('This api requires login');
247 throw new UnauthorizedException("This API requires login");
250 DI::auth()->setForUser($a, $record);
252 $_SESSION["allow_api"] = true;
254 Hook::callAll('logged_in', $a->user);
258 * Check HTTP method of called API
260 * API endpoints can define which HTTP method to accept when called.
261 * This function check the current HTTP method agains endpoint
264 * @param string $method Required methods, uppercase, separated by comma
267 function api_check_method($method)
269 if ($method == "*") {
272 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
276 * Main API entry point
278 * Authenticate user, call registered API function, set HTTP headers
281 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
282 * @return string|array API call result
285 function api_call(App $a, App\Arguments $args = null)
287 global $API, $called_api;
294 if (strpos($args->getQueryString(), ".xml") > 0) {
297 if (strpos($args->getQueryString(), ".json") > 0) {
300 if (strpos($args->getQueryString(), ".rss") > 0) {
303 if (strpos($args->getQueryString(), ".atom") > 0) {
308 foreach ($API as $p => $info) {
309 if (strpos($args->getQueryString(), $p) === 0) {
310 if (!api_check_method($info['method'])) {
311 throw new MethodNotAllowedException();
314 $called_api = explode("/", $p);
316 if (!empty($info['auth']) && api_user() === false) {
320 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
321 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
323 $stamp = microtime(true);
324 $return = call_user_func($info['func'], $type);
325 $duration = floatval(microtime(true) - $stamp);
327 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
329 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
331 if (false === $return) {
333 * api function returned false withour throw an
334 * exception. This should not happend, throw a 500
336 throw new InternalServerErrorException();
341 header("Content-Type: text/xml");
344 header("Content-Type: application/json");
345 if (!empty($return)) {
346 $json = json_encode(end($return));
347 if (!empty($_GET['callback'])) {
348 $json = $_GET['callback'] . "(" . $json . ")";
354 header("Content-Type: application/rss+xml");
355 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
358 header("Content-Type: application/atom+xml");
359 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
366 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
367 throw new NotImplementedException();
368 } catch (HTTPException $e) {
369 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
370 return api_error($type, $e, $args);
375 * Format API error string
377 * @param string $type Return type (xml, json, rss, as)
378 * @param object $e HTTPException Error object
379 * @param App\Arguments $args The App arguments
380 * @return string|array error message formatted as $type
382 function api_error($type, $e, App\Arguments $args)
384 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
385 /// @TODO: https://dev.twitter.com/overview/api/response-codes
387 $error = ["error" => $error,
388 "code" => $e->getCode() . " " . $e->httpdesc,
389 "request" => $args->getQueryString()];
391 $return = api_format_data('status', $type, ['status' => $error]);
395 header("Content-Type: text/xml");
398 header("Content-Type: application/json");
399 $return = json_encode($return);
402 header("Content-Type: application/rss+xml");
405 header("Content-Type: application/atom+xml");
413 * Set values for RSS template
416 * @param array $arr Array to be passed to template
417 * @param array $user_info User info
419 * @throws BadRequestException
420 * @throws ImagickException
421 * @throws InternalServerErrorException
422 * @throws UnauthorizedException
423 * @todo find proper type-hints
425 function api_rss_extra(App $a, $arr, $user_info)
427 if (is_null($user_info)) {
428 $user_info = api_get_user($a);
431 $arr['$user'] = $user_info;
433 'alternate' => $user_info['url'],
434 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
435 'base' => DI::baseUrl(),
436 'updated' => api_date(null),
437 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
438 'language' => $user_info['lang'],
439 'logo' => DI::baseUrl() . "/images/friendica-32.png",
447 * Unique contact to contact url.
449 * @param int $id Contact id
450 * @return bool|string
451 * Contact url or False if contact id is unknown
454 function api_unique_id_to_nurl($id)
456 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
458 if (DBA::isResult($r)) {
466 * Get user info array.
469 * @param int|string $contact_id Contact ID or URL
471 * @throws BadRequestException
472 * @throws ImagickException
473 * @throws InternalServerErrorException
474 * @throws UnauthorizedException
476 function api_get_user(App $a, $contact_id = null)
484 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
486 // Searching for contact URL
487 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
488 $user = DBA::escape(Strings::normaliseLink($contact_id));
490 $extra_query = "AND `contact`.`nurl` = '%s' ";
491 if (api_user() !== false) {
492 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
496 // Searching for contact id with uid = 0
497 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
498 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
501 throw new BadRequestException("User ID ".$contact_id." not found.");
505 $extra_query = "AND `contact`.`nurl` = '%s' ";
506 if (api_user() !== false) {
507 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
511 if (is_null($user) && !empty($_GET['user_id'])) {
512 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
515 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
519 $extra_query = "AND `contact`.`nurl` = '%s' ";
520 if (api_user() !== false) {
521 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
524 if (is_null($user) && !empty($_GET['screen_name'])) {
525 $user = DBA::escape($_GET['screen_name']);
526 $extra_query = "AND `contact`.`nick` = '%s' ";
527 if (api_user() !== false) {
528 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
532 if (is_null($user) && !empty($_GET['profileurl'])) {
533 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
534 $extra_query = "AND `contact`.`nurl` = '%s' ";
535 if (api_user() !== false) {
536 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
540 // $called_api is the API path exploded on / and is expected to have at least 2 elements
541 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
542 $argid = count($called_api);
543 if (!empty($a->argv[$argid])) {
544 $data = explode(".", $a->argv[$argid]);
545 if (count($data) > 1) {
546 list($user, $null) = $data;
549 if (is_numeric($user)) {
550 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
554 $extra_query = "AND `contact`.`nurl` = '%s' ";
555 if (api_user() !== false) {
556 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
560 $user = DBA::escape($user);
561 $extra_query = "AND `contact`.`nick` = '%s' ";
562 if (api_user() !== false) {
563 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
568 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
571 if (api_user() === false) {
575 $user = $_SESSION['uid'];
576 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
580 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
584 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
590 // Selecting the id by priority, friendica first
591 if (is_array($uinfo)) {
592 api_best_nickname($uinfo);
595 // if the contact wasn't found, fetch it from the contacts with uid = 0
596 if (!DBA::isResult($uinfo)) {
598 throw new BadRequestException("User not found.");
601 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
603 if (DBA::isResult($contact)) {
605 'id' => $contact["id"],
606 'id_str' => (string) $contact["id"],
607 'name' => $contact["name"],
608 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
609 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
610 'description' => BBCode::toPlaintext($contact["about"]),
611 'profile_image_url' => $contact["micro"],
612 'profile_image_url_https' => $contact["micro"],
613 'profile_image_url_profile_size' => $contact["thumb"],
614 'profile_image_url_large' => $contact["photo"],
615 'url' => $contact["url"],
616 'protected' => false,
617 'followers_count' => 0,
618 'friends_count' => 0,
620 'created_at' => api_date($contact["created"]),
621 'favourites_count' => 0,
623 'time_zone' => 'UTC',
624 'geo_enabled' => false,
626 'statuses_count' => 0,
628 'contributors_enabled' => false,
629 'is_translator' => false,
630 'is_translation_enabled' => false,
631 'following' => false,
632 'follow_request_sent' => false,
633 'statusnet_blocking' => false,
634 'notifications' => false,
635 'statusnet_profile_url' => $contact["url"],
637 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
638 'pid' => Contact::getIdForURL($contact["url"], 0, true),
640 'network' => $contact["network"],
645 throw new BadRequestException("User ".$url." not found.");
649 if ($uinfo[0]['self']) {
650 if ($uinfo[0]['network'] == "") {
651 $uinfo[0]['network'] = Protocol::DFRN;
654 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
655 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
662 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
664 if (!empty($profile['about'])) {
665 $description = $profile['about'];
667 $description = $uinfo[0]["about"];
670 if (!empty($usr['default-location'])) {
671 $location = $usr['default-location'];
672 } elseif (!empty($uinfo[0]["location"])) {
673 $location = $uinfo[0]["location"];
675 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
679 'id' => intval($pcontact_id),
680 'id_str' => (string) intval($pcontact_id),
681 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
682 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
683 'location' => $location,
684 'description' => BBCode::toPlaintext($description),
685 'profile_image_url' => $uinfo[0]['micro'],
686 'profile_image_url_https' => $uinfo[0]['micro'],
687 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
688 'profile_image_url_large' => $uinfo[0]["photo"],
689 'url' => $uinfo[0]['url'],
690 'protected' => false,
691 'followers_count' => intval($countfollowers),
692 'friends_count' => intval($countfriends),
694 'created_at' => api_date($uinfo[0]['created']),
695 'favourites_count' => intval($starred),
697 'time_zone' => 'UTC',
698 'geo_enabled' => false,
700 'statuses_count' => intval($countitems),
702 'contributors_enabled' => false,
703 'is_translator' => false,
704 'is_translation_enabled' => false,
705 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
706 'follow_request_sent' => false,
707 'statusnet_blocking' => false,
708 'notifications' => false,
710 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
711 'statusnet_profile_url' => $uinfo[0]['url'],
712 'uid' => intval($uinfo[0]['uid']),
713 'cid' => intval($uinfo[0]['cid']),
714 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
715 'self' => $uinfo[0]['self'],
716 'network' => $uinfo[0]['network'],
719 // If this is a local user and it uses Frio, we can get its color preferences.
721 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
722 if ($theme_info['theme'] === 'frio') {
723 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
725 if ($schema && ($schema != '---')) {
726 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
727 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
728 require_once $schemefile;
731 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
732 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
733 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
735 if (empty($nav_bg)) {
738 if (empty($link_color)) {
739 $link_color = "#6fdbe8";
741 if (empty($bgcolor)) {
742 $bgcolor = "#ededed";
745 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
746 $ret['profile_link_color'] = str_replace('#', '', $link_color);
747 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
755 * return api-formatted array for item's author and owner
758 * @param array $item item from db
759 * @return array(array:author, array:owner)
760 * @throws BadRequestException
761 * @throws ImagickException
762 * @throws InternalServerErrorException
763 * @throws UnauthorizedException
765 function api_item_get_user(App $a, $item)
767 $status_user = api_get_user($a, $item['author-id'] ?? null);
769 $author_user = $status_user;
771 $status_user["protected"] = $item['private'] ?? 0;
773 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
774 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
776 $owner_user = $author_user;
779 return ([$status_user, $author_user, $owner_user]);
783 * walks recursively through an array with the possibility to change value and key
785 * @param array $array The array to walk through
786 * @param callable $callback The callback function
788 * @return array the transformed array
790 function api_walk_recursive(array &$array, callable $callback)
794 foreach ($array as $k => $v) {
796 if ($callback($v, $k)) {
797 $new_array[$k] = api_walk_recursive($v, $callback);
800 if ($callback($v, $k)) {
811 * Callback function to transform the array in an array that can be transformed in a XML file
813 * @param mixed $item Array item value
814 * @param string $key Array key
816 * @return boolean Should the array item be deleted?
818 function api_reformat_xml(&$item, &$key)
820 if (is_bool($item)) {
821 $item = ($item ? "true" : "false");
824 if (substr($key, 0, 10) == "statusnet_") {
825 $key = "statusnet:".substr($key, 10);
826 } elseif (substr($key, 0, 10) == "friendica_") {
827 $key = "friendica:".substr($key, 10);
829 /// @TODO old-lost code?
831 // $key = "default:".$key;
837 * Creates the XML from a JSON style array
839 * @param array $data JSON style array
840 * @param string $root_element Name of the root element
842 * @return string The XML data
844 function api_create_xml(array $data, $root_element)
846 $childname = key($data);
847 $data2 = array_pop($data);
849 $namespaces = ["" => "http://api.twitter.com",
850 "statusnet" => "http://status.net/schema/api/1/",
851 "friendica" => "http://friendi.ca/schema/api/1/",
852 "georss" => "http://www.georss.org/georss"];
854 /// @todo Auto detection of needed namespaces
855 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
859 if (is_array($data2)) {
861 api_walk_recursive($data2, "api_reformat_xml");
867 foreach ($data2 as $item) {
868 $data4[$i++ . ":" . $childname] = $item;
875 $data3 = [$root_element => $data2];
877 $ret = XML::fromArray($data3, $xml, false, $namespaces);
882 * Formats the data according to the data type
884 * @param string $root_element Name of the root element
885 * @param string $type Return type (atom, rss, xml, json)
886 * @param array $data JSON style array
888 * @return array|string (string|array) XML data or JSON data
890 function api_format_data($root_element, $type, $data)
896 $ret = api_create_xml($data, $root_element);
911 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
912 * returns a 401 status code and an error message if not.
914 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
916 * @param string $type Return type (atom, rss, xml, json)
917 * @return array|string
918 * @throws BadRequestException
919 * @throws ForbiddenException
920 * @throws ImagickException
921 * @throws InternalServerErrorException
922 * @throws UnauthorizedException
924 function api_account_verify_credentials($type)
928 if (api_user() === false) {
929 throw new ForbiddenException();
932 unset($_REQUEST["user_id"]);
933 unset($_GET["user_id"]);
935 unset($_REQUEST["screen_name"]);
936 unset($_GET["screen_name"]);
938 $skip_status = $_REQUEST['skip_status'] ?? false;
940 $user_info = api_get_user($a);
942 // "verified" isn't used here in the standard
943 unset($user_info["verified"]);
945 // - Adding last status
947 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
949 $user_info['status'] = api_format_item($item, $type);
953 // "uid" and "self" are only needed for some internal stuff, so remove it from here
954 unset($user_info["uid"]);
955 unset($user_info["self"]);
957 return api_format_data("user", $type, ['user' => $user_info]);
960 /// @TODO move to top of file or somewhere better
961 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
964 * Get data from $_POST or $_GET
969 function requestdata($k)
971 if (!empty($_POST[$k])) {
974 if (!empty($_GET[$k])) {
981 * Deprecated function to upload media.
983 * @param string $type Return type (atom, rss, xml, json)
985 * @return array|string
986 * @throws BadRequestException
987 * @throws ForbiddenException
988 * @throws ImagickException
989 * @throws InternalServerErrorException
990 * @throws UnauthorizedException
992 function api_statuses_mediap($type)
996 if (api_user() === false) {
997 Logger::log('api_statuses_update: no user');
998 throw new ForbiddenException();
1000 $user_info = api_get_user($a);
1002 $_REQUEST['profile_uid'] = api_user();
1003 $_REQUEST['api_source'] = true;
1004 $txt = requestdata('status');
1005 /// @TODO old-lost code?
1006 //$txt = urldecode(requestdata('status'));
1008 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1009 $txt = HTML::toBBCodeVideo($txt);
1010 $config = HTMLPurifier_Config::createDefault();
1011 $config->set('Cache.DefinitionImpl', null);
1012 $purifier = new HTMLPurifier($config);
1013 $txt = $purifier->purify($txt);
1015 $txt = HTML::toBBCode($txt);
1017 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1019 $picture = wall_upload_post($a, false);
1021 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1022 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1023 $item_id = item_post($a);
1025 // output the post that we just posted.
1026 return api_status_show($type, $item_id);
1029 /// @TODO move this to top of file or somewhere better!
1030 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1033 * Updates the user’s current status.
1035 * @param string $type Return type (atom, rss, xml, json)
1037 * @return array|string
1038 * @throws BadRequestException
1039 * @throws ForbiddenException
1040 * @throws ImagickException
1041 * @throws InternalServerErrorException
1042 * @throws TooManyRequestsException
1043 * @throws UnauthorizedException
1044 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1046 function api_statuses_update($type)
1050 if (api_user() === false) {
1051 Logger::log('api_statuses_update: no user');
1052 throw new ForbiddenException();
1057 // convert $_POST array items to the form we use for web posts.
1058 if (requestdata('htmlstatus')) {
1059 $txt = requestdata('htmlstatus');
1060 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1061 $txt = HTML::toBBCodeVideo($txt);
1063 $config = HTMLPurifier_Config::createDefault();
1064 $config->set('Cache.DefinitionImpl', null);
1066 $purifier = new HTMLPurifier($config);
1067 $txt = $purifier->purify($txt);
1069 $_REQUEST['body'] = HTML::toBBCode($txt);
1072 $_REQUEST['body'] = requestdata('status');
1075 $_REQUEST['title'] = requestdata('title');
1077 $parent = requestdata('in_reply_to_status_id');
1079 // Twidere sends "-1" if it is no reply ...
1080 if ($parent == -1) {
1084 if (ctype_digit($parent)) {
1085 $_REQUEST['parent'] = $parent;
1087 $_REQUEST['parent_uri'] = $parent;
1090 if (requestdata('lat') && requestdata('long')) {
1091 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1093 $_REQUEST['profile_uid'] = api_user();
1096 // Check for throttling (maximum posts per day, week and month)
1097 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1098 if ($throttle_day > 0) {
1099 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1101 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1102 $posts_day = DBA::count('thread', $condition);
1104 if ($posts_day > $throttle_day) {
1105 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1106 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1107 throw new TooManyRequestsException(DI::l10n()->tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1111 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1112 if ($throttle_week > 0) {
1113 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1115 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1116 $posts_week = DBA::count('thread', $condition);
1118 if ($posts_week > $throttle_week) {
1119 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1120 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1121 throw new TooManyRequestsException(DI::l10n()->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
1125 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1126 if ($throttle_month > 0) {
1127 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1129 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1130 $posts_month = DBA::count('thread', $condition);
1132 if ($posts_month > $throttle_month) {
1133 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1134 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1135 throw new TooManyRequestsException(DI::l10n()->t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1140 if (!empty($_FILES['media'])) {
1141 // upload the image if we have one
1142 $picture = wall_upload_post($a, false);
1143 if (is_array($picture)) {
1144 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1148 if (requestdata('media_ids')) {
1149 $ids = explode(',', requestdata('media_ids'));
1150 foreach ($ids as $id) {
1152 "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",
1156 if (DBA::isResult($r)) {
1157 $phototypes = Images::supportedTypes();
1158 $ext = $phototypes[$r[0]['type']];
1159 $description = $r[0]['desc'] ?? '';
1160 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1161 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1166 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1168 $_REQUEST['api_source'] = true;
1170 if (empty($_REQUEST['source'])) {
1171 $_REQUEST["source"] = api_source();
1174 // call out normal post function
1175 $item_id = item_post($a);
1177 // output the post that we just posted.
1178 return api_status_show($type, $item_id);
1181 /// @TODO move to top of file or somewhere better
1182 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1183 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1186 * Uploads an image to Friendica.
1189 * @throws BadRequestException
1190 * @throws ForbiddenException
1191 * @throws ImagickException
1192 * @throws InternalServerErrorException
1193 * @throws UnauthorizedException
1194 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1196 function api_media_upload()
1200 if (api_user() === false) {
1201 Logger::log('no user');
1202 throw new ForbiddenException();
1207 if (empty($_FILES['media'])) {
1209 throw new BadRequestException("No media.");
1212 $media = wall_upload_post($a, false);
1215 throw new InternalServerErrorException();
1219 $returndata["media_id"] = $media["id"];
1220 $returndata["media_id_string"] = (string)$media["id"];
1221 $returndata["size"] = $media["size"];
1222 $returndata["image"] = ["w" => $media["width"],
1223 "h" => $media["height"],
1224 "image_type" => $media["type"],
1225 "friendica_preview_url" => $media["preview"]];
1227 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1229 return ["media" => $returndata];
1232 /// @TODO move to top of file or somewhere better
1233 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1236 * Updates media meta data (picture descriptions)
1238 * @param string $type Return type (atom, rss, xml, json)
1240 * @return array|string
1241 * @throws BadRequestException
1242 * @throws ForbiddenException
1243 * @throws ImagickException
1244 * @throws InternalServerErrorException
1245 * @throws TooManyRequestsException
1246 * @throws UnauthorizedException
1247 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1249 * @todo Compare the corresponding Twitter function for correct return values
1251 function api_media_metadata_create($type)
1255 if (api_user() === false) {
1256 Logger::info('no user');
1257 throw new ForbiddenException();
1262 $postdata = Network::postdata();
1264 if (empty($postdata)) {
1265 throw new BadRequestException("No post data");
1268 $data = json_decode($postdata, true);
1270 throw new BadRequestException("Invalid post data");
1273 if (empty($data['media_id']) || empty($data['alt_text'])) {
1274 throw new BadRequestException("Missing post data values");
1277 if (empty($data['alt_text']['text'])) {
1278 throw new BadRequestException("No alt text.");
1281 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1283 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1284 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1285 if (!DBA::isResult($photo)) {
1286 throw new BadRequestException("Metadata not found.");
1289 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1292 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1295 * @param string $type Return format (atom, rss, xml, json)
1296 * @param int $item_id
1300 function api_status_show($type, $item_id)
1302 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1306 $item = api_get_item(['id' => $item_id]);
1307 if (!empty($item)) {
1308 $status_info = api_format_item($item, $type);
1311 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1313 return api_format_data('statuses', $type, ['status' => $status_info]);
1317 * Retrieves the last public status of the provided user info
1319 * @param int $ownerId Public contact Id
1320 * @param int $uid User Id
1324 function api_get_last_status($ownerId, $uid)
1327 'author-id'=> $ownerId,
1329 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1333 $item = api_get_item($condition);
1339 * Retrieves a single item record based on the provided condition and converts it for API use.
1341 * @param array $condition Item table condition array
1345 function api_get_item(array $condition)
1347 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1353 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1354 * The author's most recent status will be returned inline.
1356 * @param string $type Return type (atom, rss, xml, json)
1357 * @return array|string
1358 * @throws BadRequestException
1359 * @throws ImagickException
1360 * @throws InternalServerErrorException
1361 * @throws UnauthorizedException
1362 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1364 function api_users_show($type)
1366 $a = Friendica\DI::app();
1368 $user_info = api_get_user($a);
1370 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1371 if (!empty($item)) {
1372 $user_info['status'] = api_format_item($item, $type);
1375 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1376 unset($user_info['uid']);
1377 unset($user_info['self']);
1379 return api_format_data('user', $type, ['user' => $user_info]);
1382 /// @TODO move to top of file or somewhere better
1383 api_register_func('api/users/show', 'api_users_show');
1384 api_register_func('api/externalprofile/show', 'api_users_show');
1387 * Search a public user account.
1389 * @param string $type Return type (atom, rss, xml, json)
1391 * @return array|string
1392 * @throws BadRequestException
1393 * @throws ImagickException
1394 * @throws InternalServerErrorException
1395 * @throws UnauthorizedException
1396 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1398 function api_users_search($type)
1404 if (!empty($_GET['q'])) {
1405 $contacts = Contact::selectToArray(
1408 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1416 if (DBA::isResult($contacts)) {
1418 foreach ($contacts as $contact) {
1419 $user_info = api_get_user($a, $contact['id']);
1421 if ($type == 'xml') {
1422 $userlist[$k++ . ':user'] = $user_info;
1424 $userlist[] = $user_info;
1427 $userlist = ['users' => $userlist];
1429 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1432 throw new BadRequestException('No search term specified.');
1435 return api_format_data('users', $type, $userlist);
1438 /// @TODO move to top of file or somewhere better
1439 api_register_func('api/users/search', 'api_users_search');
1442 * Return user objects
1444 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1446 * @param string $type Return format: json or xml
1448 * @return array|string
1449 * @throws BadRequestException
1450 * @throws ImagickException
1451 * @throws InternalServerErrorException
1452 * @throws NotFoundException if the results are empty.
1453 * @throws UnauthorizedException
1455 function api_users_lookup($type)
1459 if (!empty($_REQUEST['user_id'])) {
1460 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1462 $users[] = api_get_user(DI::app(), $id);
1467 if (empty($users)) {
1468 throw new NotFoundException;
1471 return api_format_data("users", $type, ['users' => $users]);
1474 /// @TODO move to top of file or somewhere better
1475 api_register_func('api/users/lookup', 'api_users_lookup', true);
1478 * Returns statuses that match a specified query.
1480 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1482 * @param string $type Return format: json, xml, atom, rss
1484 * @return array|string
1485 * @throws BadRequestException if the "q" parameter is missing.
1486 * @throws ForbiddenException
1487 * @throws ImagickException
1488 * @throws InternalServerErrorException
1489 * @throws UnauthorizedException
1491 function api_search($type)
1494 $user_info = api_get_user($a);
1496 if (api_user() === false || $user_info === false) {
1497 throw new ForbiddenException();
1500 if (empty($_REQUEST['q'])) {
1501 throw new BadRequestException('q parameter is required.');
1504 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1507 $data['status'] = [];
1509 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1510 if (!empty($_REQUEST['rpp'])) {
1511 $count = $_REQUEST['rpp'];
1512 } elseif (!empty($_REQUEST['count'])) {
1513 $count = $_REQUEST['count'];
1516 $since_id = $_REQUEST['since_id'] ?? 0;
1517 $max_id = $_REQUEST['max_id'] ?? 0;
1518 $page = $_REQUEST['page'] ?? 1;
1520 $start = max(0, ($page - 1) * $count);
1522 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1523 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1524 $searchTerm = $matches[1];
1525 $condition = ["`oid` > ?
1526 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1527 AND `otype` = ? AND `type` = ? AND `term` = ?",
1528 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1530 $condition[0] .= ' AND `oid` <= ?';
1531 $condition[] = $max_id;
1533 $terms = DBA::select('term', ['oid'], $condition, []);
1535 while ($term = DBA::fetch($terms)) {
1536 $itemIds[] = $term['oid'];
1540 if (empty($itemIds)) {
1541 return api_format_data('statuses', $type, $data);
1544 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1545 if ($exclude_replies) {
1546 $preCondition[] = '`id` = `parent`';
1549 $condition = [implode(' AND ', $preCondition)];
1551 $condition = ["`id` > ?
1552 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1553 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1554 AND `body` LIKE CONCAT('%',?,'%')",
1555 $since_id, api_user(), $_REQUEST['q']];
1557 $condition[0] .= ' AND `id` <= ?';
1558 $condition[] = $max_id;
1564 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1565 $id = Item::fetchByLink($searchTerm, api_user());
1568 $id = Item::fetchByLink($searchTerm);
1572 $statuses = Item::select([], ['id' => $id]);
1576 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1578 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1580 bindComments($data['status']);
1582 return api_format_data('statuses', $type, $data);
1585 /// @TODO move to top of file or somewhere better
1586 api_register_func('api/search/tweets', 'api_search', true);
1587 api_register_func('api/search', 'api_search', true);
1590 * Returns the most recent statuses posted by the user and the users they follow.
1592 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1594 * @param string $type Return type (atom, rss, xml, json)
1596 * @return array|string
1597 * @throws BadRequestException
1598 * @throws ForbiddenException
1599 * @throws ImagickException
1600 * @throws InternalServerErrorException
1601 * @throws UnauthorizedException
1602 * @todo Optional parameters
1603 * @todo Add reply info
1605 function api_statuses_home_timeline($type)
1608 $user_info = api_get_user($a);
1610 if (api_user() === false || $user_info === false) {
1611 throw new ForbiddenException();
1614 unset($_REQUEST["user_id"]);
1615 unset($_GET["user_id"]);
1617 unset($_REQUEST["screen_name"]);
1618 unset($_GET["screen_name"]);
1620 // get last network messages
1623 $count = $_REQUEST['count'] ?? 20;
1624 $page = $_REQUEST['page']?? 0;
1625 $since_id = $_REQUEST['since_id'] ?? 0;
1626 $max_id = $_REQUEST['max_id'] ?? 0;
1627 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1628 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1630 $start = max(0, ($page - 1) * $count);
1632 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1633 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1636 $condition[0] .= " AND `item`.`id` <= ?";
1637 $condition[] = $max_id;
1639 if ($exclude_replies) {
1640 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1642 if ($conversation_id > 0) {
1643 $condition[0] .= " AND `item`.`parent` = ?";
1644 $condition[] = $conversation_id;
1647 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1648 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1650 $items = Item::inArray($statuses);
1652 $ret = api_format_items($items, $user_info, false, $type);
1654 // Set all posts from the query above to seen
1656 foreach ($items as $item) {
1657 $idarray[] = intval($item["id"]);
1660 if (!empty($idarray)) {
1661 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1663 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1669 $data = ['status' => $ret];
1674 $data = api_rss_extra($a, $data, $user_info);
1678 return api_format_data("statuses", $type, $data);
1682 /// @TODO move to top of file or somewhere better
1683 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1684 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1687 * Returns the most recent statuses from public users.
1689 * @param string $type Return type (atom, rss, xml, json)
1691 * @return array|string
1692 * @throws BadRequestException
1693 * @throws ForbiddenException
1694 * @throws ImagickException
1695 * @throws InternalServerErrorException
1696 * @throws UnauthorizedException
1698 function api_statuses_public_timeline($type)
1701 $user_info = api_get_user($a);
1703 if (api_user() === false || $user_info === false) {
1704 throw new ForbiddenException();
1707 // get last network messages
1710 $count = $_REQUEST['count'] ?? 20;
1711 $page = $_REQUEST['page'] ?? 1;
1712 $since_id = $_REQUEST['since_id'] ?? 0;
1713 $max_id = $_REQUEST['max_id'] ?? 0;
1714 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1715 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1717 $start = max(0, ($page - 1) * $count);
1719 if ($exclude_replies && !$conversation_id) {
1720 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1721 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1724 $condition[0] .= " AND `thread`.`iid` <= ?";
1725 $condition[] = $max_id;
1728 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1729 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1731 $r = Item::inArray($statuses);
1733 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1734 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1737 $condition[0] .= " AND `item`.`id` <= ?";
1738 $condition[] = $max_id;
1740 if ($conversation_id > 0) {
1741 $condition[0] .= " AND `item`.`parent` = ?";
1742 $condition[] = $conversation_id;
1745 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1746 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1748 $r = Item::inArray($statuses);
1751 $ret = api_format_items($r, $user_info, false, $type);
1755 $data = ['status' => $ret];
1760 $data = api_rss_extra($a, $data, $user_info);
1764 return api_format_data("statuses", $type, $data);
1767 /// @TODO move to top of file or somewhere better
1768 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1771 * Returns the most recent statuses posted by users this node knows about.
1773 * @param string $type Return format: json, xml, atom, rss
1774 * @return array|string
1775 * @throws BadRequestException
1776 * @throws ForbiddenException
1777 * @throws ImagickException
1778 * @throws InternalServerErrorException
1779 * @throws UnauthorizedException
1781 function api_statuses_networkpublic_timeline($type)
1784 $user_info = api_get_user($a);
1786 if (api_user() === false || $user_info === false) {
1787 throw new ForbiddenException();
1790 $since_id = $_REQUEST['since_id'] ?? 0;
1791 $max_id = $_REQUEST['max_id'] ?? 0;
1794 $count = $_REQUEST['count'] ?? 20;
1795 $page = $_REQUEST['page'] ?? 1;
1797 $start = max(0, ($page - 1) * $count);
1799 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1800 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1803 $condition[0] .= " AND `thread`.`iid` <= ?";
1804 $condition[] = $max_id;
1807 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1808 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1810 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1814 $data = ['status' => $ret];
1819 $data = api_rss_extra($a, $data, $user_info);
1823 return api_format_data("statuses", $type, $data);
1826 /// @TODO move to top of file or somewhere better
1827 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1830 * Returns a single status.
1832 * @param string $type Return type (atom, rss, xml, json)
1834 * @return array|string
1835 * @throws BadRequestException
1836 * @throws ForbiddenException
1837 * @throws ImagickException
1838 * @throws InternalServerErrorException
1839 * @throws UnauthorizedException
1840 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1842 function api_statuses_show($type)
1845 $user_info = api_get_user($a);
1847 if (api_user() === false || $user_info === false) {
1848 throw new ForbiddenException();
1852 $id = intval($a->argv[3] ?? 0);
1855 $id = intval($_REQUEST['id'] ?? 0);
1860 $id = intval($a->argv[4] ?? 0);
1863 Logger::log('API: api_statuses_show: ' . $id);
1865 $conversation = !empty($_REQUEST['conversation']);
1867 // try to fetch the item for the local user - or the public item, if there is no local one
1868 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1869 if (!DBA::isResult($uri_item)) {
1870 throw new BadRequestException("There is no status with this id.");
1873 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1874 if (!DBA::isResult($item)) {
1875 throw new BadRequestException("There is no status with this id.");
1880 if ($conversation) {
1881 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1882 $params = ['order' => ['id' => true]];
1884 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1888 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1890 /// @TODO How about copying this to above methods which don't check $r ?
1891 if (!DBA::isResult($statuses)) {
1892 throw new BadRequestException("There is no status with this id.");
1895 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1897 if ($conversation) {
1898 $data = ['status' => $ret];
1899 return api_format_data("statuses", $type, $data);
1901 $data = ['status' => $ret[0]];
1902 return api_format_data("status", $type, $data);
1906 /// @TODO move to top of file or somewhere better
1907 api_register_func('api/statuses/show', 'api_statuses_show', true);
1911 * @param string $type Return type (atom, rss, xml, json)
1913 * @return array|string
1914 * @throws BadRequestException
1915 * @throws ForbiddenException
1916 * @throws ImagickException
1917 * @throws InternalServerErrorException
1918 * @throws UnauthorizedException
1919 * @todo nothing to say?
1921 function api_conversation_show($type)
1924 $user_info = api_get_user($a);
1926 if (api_user() === false || $user_info === false) {
1927 throw new ForbiddenException();
1931 $id = intval($a->argv[3] ?? 0);
1932 $since_id = intval($_REQUEST['since_id'] ?? 0);
1933 $max_id = intval($_REQUEST['max_id'] ?? 0);
1934 $count = intval($_REQUEST['count'] ?? 20);
1935 $page = intval($_REQUEST['page'] ?? 1);
1937 $start = max(0, ($page - 1) * $count);
1940 $id = intval($_REQUEST['id'] ?? 0);
1945 $id = intval($a->argv[4] ?? 0);
1948 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1950 // try to fetch the item for the local user - or the public item, if there is no local one
1951 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1952 if (!DBA::isResult($item)) {
1953 throw new BadRequestException("There is no status with this id.");
1956 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1957 if (!DBA::isResult($parent)) {
1958 throw new BadRequestException("There is no status with this id.");
1961 $id = $parent['id'];
1963 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1964 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1967 $condition[0] .= " AND `item`.`id` <= ?";
1968 $condition[] = $max_id;
1971 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1972 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1974 if (!DBA::isResult($statuses)) {
1975 throw new BadRequestException("There is no status with id $id.");
1978 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1980 $data = ['status' => $ret];
1981 return api_format_data("statuses", $type, $data);
1984 /// @TODO move to top of file or somewhere better
1985 api_register_func('api/conversation/show', 'api_conversation_show', true);
1986 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1991 * @param string $type Return type (atom, rss, xml, json)
1993 * @return array|string
1994 * @throws BadRequestException
1995 * @throws ForbiddenException
1996 * @throws ImagickException
1997 * @throws InternalServerErrorException
1998 * @throws UnauthorizedException
1999 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2001 function api_statuses_repeat($type)
2007 if (api_user() === false) {
2008 throw new ForbiddenException();
2014 $id = intval($a->argv[3] ?? 0);
2017 $id = intval($_REQUEST['id'] ?? 0);
2022 $id = intval($a->argv[4] ?? 0);
2025 Logger::log('API: api_statuses_repeat: '.$id);
2027 $fields = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2028 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2030 if (DBA::isResult($item) && $item['body'] != "") {
2031 if (strpos($item['body'], "[/share]") !== false) {
2032 $pos = strpos($item['body'], "[share");
2033 $post = substr($item['body'], $pos);
2035 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2037 if (!empty($item['title'])) {
2038 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2041 $post .= $item['body'];
2042 $post .= "[/share]";
2044 $_REQUEST['body'] = $post;
2045 $_REQUEST['tag'] = $item['tag'];
2046 $_REQUEST['attach'] = $item['attach'];
2047 $_REQUEST['profile_uid'] = api_user();
2048 $_REQUEST['api_source'] = true;
2050 if (empty($_REQUEST['source'])) {
2051 $_REQUEST["source"] = api_source();
2054 $item_id = item_post($a);
2056 throw new ForbiddenException();
2059 // output the post that we just posted.
2061 return api_status_show($type, $item_id);
2064 /// @TODO move to top of file or somewhere better
2065 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2068 * Destroys a specific status.
2070 * @param string $type Return type (atom, rss, xml, json)
2072 * @return array|string
2073 * @throws BadRequestException
2074 * @throws ForbiddenException
2075 * @throws ImagickException
2076 * @throws InternalServerErrorException
2077 * @throws UnauthorizedException
2078 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2080 function api_statuses_destroy($type)
2084 if (api_user() === false) {
2085 throw new ForbiddenException();
2091 $id = intval($a->argv[3] ?? 0);
2094 $id = intval($_REQUEST['id'] ?? 0);
2099 $id = intval($a->argv[4] ?? 0);
2102 Logger::log('API: api_statuses_destroy: '.$id);
2104 $ret = api_statuses_show($type);
2106 Item::deleteForUser(['id' => $id], api_user());
2111 /// @TODO move to top of file or somewhere better
2112 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2115 * Returns the most recent mentions.
2117 * @param string $type Return type (atom, rss, xml, json)
2119 * @return array|string
2120 * @throws BadRequestException
2121 * @throws ForbiddenException
2122 * @throws ImagickException
2123 * @throws InternalServerErrorException
2124 * @throws UnauthorizedException
2125 * @see http://developer.twitter.com/doc/get/statuses/mentions
2127 function api_statuses_mentions($type)
2130 $user_info = api_get_user($a);
2132 if (api_user() === false || $user_info === false) {
2133 throw new ForbiddenException();
2136 unset($_REQUEST["user_id"]);
2137 unset($_GET["user_id"]);
2139 unset($_REQUEST["screen_name"]);
2140 unset($_GET["screen_name"]);
2142 // get last network messages
2145 $since_id = $_REQUEST['since_id'] ?? 0;
2146 $max_id = $_REQUEST['max_id'] ?? 0;
2147 $count = $_REQUEST['count'] ?? 20;
2148 $page = $_REQUEST['page'] ?? 1;
2150 $start = max(0, ($page - 1) * $count);
2152 $query = "SELECT `item`.`id` FROM `user-item`
2153 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2154 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2155 `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2156 AND `user-item`.`iid` > ?";
2157 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2158 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2159 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
2160 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2164 $query .= " AND `item`.`id` <= ?";
2165 $condition[] = $max_id;
2168 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2169 $condition[] = $start;
2170 $condition[] = $count;
2172 $useritems = DBA::p($query, $condition);
2174 while ($useritem = DBA::fetch($useritems)) {
2175 $itemids[] = $useritem['id'];
2177 DBA::close($useritems);
2179 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2180 $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2182 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2184 $data = ['status' => $ret];
2189 $data = api_rss_extra($a, $data, $user_info);
2193 return api_format_data("statuses", $type, $data);
2196 /// @TODO move to top of file or somewhere better
2197 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2198 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2201 * Returns the most recent statuses posted by the user.
2203 * @param string $type Either "json" or "xml"
2204 * @return string|array
2205 * @throws BadRequestException
2206 * @throws ForbiddenException
2207 * @throws ImagickException
2208 * @throws InternalServerErrorException
2209 * @throws UnauthorizedException
2210 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2212 function api_statuses_user_timeline($type)
2215 $user_info = api_get_user($a);
2217 if (api_user() === false || $user_info === false) {
2218 throw new ForbiddenException();
2222 "api_statuses_user_timeline: api_user: ". api_user() .
2223 "\nuser_info: ".print_r($user_info, true) .
2224 "\n_REQUEST: ".print_r($_REQUEST, true),
2228 $since_id = $_REQUEST['since_id'] ?? 0;
2229 $max_id = $_REQUEST['max_id'] ?? 0;
2230 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2231 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2234 $count = $_REQUEST['count'] ?? 20;
2235 $page = $_REQUEST['page'] ?? 1;
2237 $start = max(0, ($page - 1) * $count);
2239 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2240 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2242 if ($user_info['self'] == 1) {
2243 $condition[0] .= ' AND `item`.`wall` ';
2246 if ($exclude_replies) {
2247 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2250 if ($conversation_id > 0) {
2251 $condition[0] .= " AND `item`.`parent` = ?";
2252 $condition[] = $conversation_id;
2256 $condition[0] .= " AND `item`.`id` <= ?";
2257 $condition[] = $max_id;
2260 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2261 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2263 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2267 $data = ['status' => $ret];
2272 $data = api_rss_extra($a, $data, $user_info);
2276 return api_format_data("statuses", $type, $data);
2279 /// @TODO move to top of file or somewhere better
2280 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2283 * Star/unstar an item.
2284 * param: id : id of the item
2286 * @param string $type Return type (atom, rss, xml, json)
2288 * @return array|string
2289 * @throws BadRequestException
2290 * @throws ForbiddenException
2291 * @throws ImagickException
2292 * @throws InternalServerErrorException
2293 * @throws UnauthorizedException
2294 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2296 function api_favorites_create_destroy($type)
2300 if (api_user() === false) {
2301 throw new ForbiddenException();
2304 // for versioned api.
2305 /// @TODO We need a better global soluton
2306 $action_argv_id = 2;
2307 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2308 $action_argv_id = 3;
2311 if ($a->argc <= $action_argv_id) {
2312 throw new BadRequestException("Invalid request.");
2314 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2315 if ($a->argc == $action_argv_id + 2) {
2316 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2318 $itemid = intval($_REQUEST['id'] ?? 0);
2321 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2323 if (!DBA::isResult($item)) {
2324 throw new BadRequestException("Invalid item.");
2329 $item['starred'] = 1;
2332 $item['starred'] = 0;
2335 throw new BadRequestException("Invalid action ".$action);
2338 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2341 throw new InternalServerErrorException("DB error");
2345 $user_info = api_get_user($a);
2346 $rets = api_format_items([$item], $user_info, false, $type);
2349 $data = ['status' => $ret];
2354 $data = api_rss_extra($a, $data, $user_info);
2358 return api_format_data("status", $type, $data);
2361 /// @TODO move to top of file or somewhere better
2362 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2363 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2366 * Returns the most recent favorite statuses.
2368 * @param string $type Return type (atom, rss, xml, json)
2370 * @return string|array
2371 * @throws BadRequestException
2372 * @throws ForbiddenException
2373 * @throws ImagickException
2374 * @throws InternalServerErrorException
2375 * @throws UnauthorizedException
2377 function api_favorites($type)
2382 $user_info = api_get_user($a);
2384 if (api_user() === false || $user_info === false) {
2385 throw new ForbiddenException();
2390 // in friendica starred item are private
2391 // return favorites only for self
2392 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2394 if ($user_info['self'] == 0) {
2398 $since_id = $_REQUEST['since_id'] ?? 0;
2399 $max_id = $_REQUEST['max_id'] ?? 0;
2400 $count = $_GET['count'] ?? 20;
2401 $page = $_REQUEST['page'] ?? 1;
2403 $start = max(0, ($page - 1) * $count);
2405 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2406 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2408 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2411 $condition[0] .= " AND `item`.`id` <= ?";
2412 $condition[] = $max_id;
2415 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2417 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2422 $data = ['status' => $ret];
2427 $data = api_rss_extra($a, $data, $user_info);
2431 return api_format_data("statuses", $type, $data);
2434 /// @TODO move to top of file or somewhere better
2435 api_register_func('api/favorites', 'api_favorites', true);
2439 * @param array $item
2440 * @param array $recipient
2441 * @param array $sender
2444 * @throws InternalServerErrorException
2446 function api_format_messages($item, $recipient, $sender)
2448 // standard meta information
2450 'id' => $item['id'],
2451 'sender_id' => $sender['id'],
2453 'recipient_id' => $recipient['id'],
2454 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2455 'sender_screen_name' => $sender['screen_name'],
2456 'recipient_screen_name' => $recipient['screen_name'],
2457 'sender' => $sender,
2458 'recipient' => $recipient,
2460 'friendica_seen' => $item['seen'] ?? 0,
2461 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2464 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2465 if (isset($ret['sender']['uid'])) {
2466 unset($ret['sender']['uid']);
2468 if (isset($ret['sender']['self'])) {
2469 unset($ret['sender']['self']);
2471 if (isset($ret['recipient']['uid'])) {
2472 unset($ret['recipient']['uid']);
2474 if (isset($ret['recipient']['self'])) {
2475 unset($ret['recipient']['self']);
2478 //don't send title to regular StatusNET requests to avoid confusing these apps
2479 if (!empty($_GET['getText'])) {
2480 $ret['title'] = $item['title'];
2481 if ($_GET['getText'] == 'html') {
2482 $ret['text'] = BBCode::convert($item['body'], false);
2483 } elseif ($_GET['getText'] == 'plain') {
2484 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2487 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2489 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2490 unset($ret['sender']);
2491 unset($ret['recipient']);
2499 * @param array $item
2502 * @throws InternalServerErrorException
2504 function api_convert_item($item)
2506 $body = $item['body'];
2507 $entities = api_get_entitities($statustext, $body);
2509 // Add pictures to the attachment array and remove them from the body
2510 $attachments = api_get_attachments($body);
2512 // Workaround for ostatus messages where the title is identically to the body
2513 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2514 $statusbody = trim(HTML::toPlaintext($html, 0));
2516 // handle data: images
2517 $statusbody = api_format_items_embeded_images($item, $statusbody);
2519 $statustitle = trim($item['title']);
2521 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2522 $statustext = trim($statusbody);
2524 $statustext = trim($statustitle."\n\n".$statusbody);
2527 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2528 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2531 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2533 // Workaround for clients with limited HTML parser functionality
2534 $search = ["<br>", "<blockquote>", "</blockquote>",
2535 "<h1>", "</h1>", "<h2>", "</h2>",
2536 "<h3>", "</h3>", "<h4>", "</h4>",
2537 "<h5>", "</h5>", "<h6>", "</h6>"];
2538 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2539 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2540 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2541 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2542 $statushtml = str_replace($search, $replace, $statushtml);
2544 if ($item['title'] != "") {
2545 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2549 $oldtext = $statushtml;
2550 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2551 } while ($oldtext != $statushtml);
2553 if (substr($statushtml, 0, 4) == '<br>') {
2554 $statushtml = substr($statushtml, 4);
2557 if (substr($statushtml, 0, -4) == '<br>') {
2558 $statushtml = substr($statushtml, -4);
2561 // feeds without body should contain the link
2562 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2563 $statushtml .= BBCode::convert($item['plink']);
2567 "text" => $statustext,
2568 "html" => $statushtml,
2569 "attachments" => $attachments,
2570 "entities" => $entities
2576 * @param string $body
2579 * @throws InternalServerErrorException
2581 function api_get_attachments(&$body)
2583 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2584 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2586 $URLSearchString = "^\[\]";
2587 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2591 // Remove all embedded pictures, since they are added as attachments
2592 foreach ($images[0] as $orig) {
2593 $body = str_replace($orig, '', $body);
2598 foreach ($images[1] as $image) {
2599 $imagedata = Images::getInfoFromURLCached($image);
2602 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2606 return $attachments;
2611 * @param string $text
2612 * @param string $bbcode
2615 * @throws InternalServerErrorException
2616 * @todo Links at the first character of the post
2618 function api_get_entitities(&$text, $bbcode)
2620 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2622 if ($include_entities != "true") {
2623 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2625 foreach ($images[1] as $image) {
2626 $replace = ProxyUtils::proxifyUrl($image);
2627 $text = str_replace($image, $replace, $text);
2632 $bbcode = BBCode::cleanPictureLinks($bbcode);
2634 // Change pure links in text to bbcode uris
2635 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2638 $entities["hashtags"] = [];
2639 $entities["symbols"] = [];
2640 $entities["urls"] = [];
2641 $entities["user_mentions"] = [];
2643 $URLSearchString = "^\[\]";
2645 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2647 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2648 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2650 $bbcode = preg_replace(
2651 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2652 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2655 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2657 $bbcode = preg_replace(
2658 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2659 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2662 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2664 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2666 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2669 foreach ($urls[1] as $id => $url) {
2670 $start = iconv_strpos($text, $url, 0, "UTF-8");
2671 if (!($start === false)) {
2672 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2676 ksort($ordered_urls);
2680 foreach ($ordered_urls as $url) {
2681 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2682 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2684 $display_url = $url["title"];
2686 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2687 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2689 if (strlen($display_url) > 26) {
2690 $display_url = substr($display_url, 0, 25)."…";
2694 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2695 if (!($start === false)) {
2696 $entities["urls"][] = ["url" => $url["url"],
2697 "expanded_url" => $url["url"],
2698 "display_url" => $display_url,
2699 "indices" => [$start, $start+strlen($url["url"])]];
2700 $offset = $start + 1;
2704 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2705 $ordered_images = [];
2706 foreach ($images as $image) {
2707 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2708 if (!($start === false)) {
2709 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2713 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2714 foreach ($images[1] as $image) {
2715 $start = iconv_strpos($text, $image, 0, "UTF-8");
2716 if (!($start === false)) {
2717 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2723 foreach ($ordered_images as $image) {
2724 $url = $image['url'];
2725 $ext_alt_text = $image['alt'];
2727 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2728 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2730 if (strlen($display_url) > 26) {
2731 $display_url = substr($display_url, 0, 25)."…";
2734 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2735 if (!($start === false)) {
2736 $image = Images::getInfoFromURLCached($url);
2738 // If image cache is activated, then use the following sizes:
2739 // thumb (150), small (340), medium (600) and large (1024)
2740 if (!DI::config()->get("system", "proxy_disabled")) {
2741 $media_url = ProxyUtils::proxifyUrl($url);
2744 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2745 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2747 if (($image[0] > 150) || ($image[1] > 150)) {
2748 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2749 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2752 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2753 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2755 if (($image[0] > 600) || ($image[1] > 600)) {
2756 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2757 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2761 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2764 $entities["media"][] = [
2766 "id_str" => (string) ($start + 1),
2767 "indices" => [$start, $start+strlen($url)],
2768 "media_url" => Strings::normaliseLink($media_url),
2769 "media_url_https" => $media_url,
2771 "display_url" => $display_url,
2772 "expanded_url" => $url,
2773 "ext_alt_text" => $ext_alt_text,
2777 $offset = $start + 1;
2786 * @param array $item
2787 * @param string $text
2791 function api_format_items_embeded_images($item, $text)
2793 $text = preg_replace_callback(
2794 '|data:image/([^;]+)[^=]+=*|m',
2795 function () use ($item) {
2796 return DI::baseUrl() . '/display/' . $item['guid'];
2804 * return <a href='url'>name</a> as array
2806 * @param string $txt text
2811 function api_contactlink_to_array($txt)
2814 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2815 if ($r && count($match)==3) {
2817 'name' => $match[2],
2831 * return likes, dislikes and attend status for item
2833 * @param array $item array
2834 * @param string $type Return type (atom, rss, xml, json)
2837 * likes => int count,
2838 * dislikes => int count
2839 * @throws BadRequestException
2840 * @throws ImagickException
2841 * @throws InternalServerErrorException
2842 * @throws UnauthorizedException
2844 function api_format_items_activities($item, $type = "json")
2853 'attendmaybe' => [],
2857 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2858 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2860 while ($parent_item = Item::fetch($ret)) {
2861 // not used as result should be structured like other user data
2862 //builtin_activity_puller($i, $activities);
2864 // get user data and add it to the array of the activity
2865 $user = api_get_user($a, $parent_item['author-id']);
2866 switch ($parent_item['verb']) {
2867 case Activity::LIKE:
2868 $activities['like'][] = $user;
2870 case Activity::DISLIKE:
2871 $activities['dislike'][] = $user;
2873 case Activity::ATTEND:
2874 $activities['attendyes'][] = $user;
2876 case Activity::ATTENDNO:
2877 $activities['attendno'][] = $user;
2879 case Activity::ATTENDMAYBE:
2880 $activities['attendmaybe'][] = $user;
2882 case Activity::ANNOUNCE:
2883 $activities['announce'][] = $user;
2892 if ($type == "xml") {
2893 $xml_activities = [];
2894 foreach ($activities as $k => $v) {
2895 // change xml element from "like" to "friendica:like"
2896 $xml_activities["friendica:".$k] = $v;
2897 // add user data into xml output
2899 foreach ($v as $user) {
2900 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2903 $activities = $xml_activities;
2911 * return data from profiles
2913 * @param array $profile_row array containing data from db table 'profile'
2915 * @throws InternalServerErrorException
2917 function api_format_items_profiles($profile_row)
2920 'profile_id' => $profile_row['id'],
2921 'profile_name' => $profile_row['profile-name'],
2922 'is_default' => $profile_row['is-default'] ? true : false,
2923 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2924 'profile_photo' => $profile_row['photo'],
2925 'profile_thumb' => $profile_row['thumb'],
2926 'publish' => $profile_row['publish'] ? true : false,
2927 'net_publish' => $profile_row['net-publish'] ? true : false,
2928 'description' => $profile_row['pdesc'],
2929 'date_of_birth' => $profile_row['dob'],
2930 'address' => $profile_row['address'],
2931 'city' => $profile_row['locality'],
2932 'region' => $profile_row['region'],
2933 'postal_code' => $profile_row['postal-code'],
2934 'country' => $profile_row['country-name'],
2935 'hometown' => $profile_row['hometown'],
2936 'gender' => $profile_row['gender'],
2937 'marital' => $profile_row['marital'],
2938 'marital_with' => $profile_row['with'],
2939 'marital_since' => $profile_row['howlong'],
2940 'sexual' => $profile_row['sexual'],
2941 'politic' => $profile_row['politic'],
2942 'religion' => $profile_row['religion'],
2943 'public_keywords' => $profile_row['pub_keywords'],
2944 'private_keywords' => $profile_row['prv_keywords'],
2945 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2946 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2947 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2948 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2949 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2950 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2951 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2952 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2953 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2954 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2955 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2956 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2957 'homepage' => $profile_row['homepage'],
2964 * format items to be returned by api
2966 * @param array $items array of items
2967 * @param array $user_info
2968 * @param bool $filter_user filter items by $user_info
2969 * @param string $type Return type (atom, rss, xml, json)
2971 * @throws BadRequestException
2972 * @throws ImagickException
2973 * @throws InternalServerErrorException
2974 * @throws UnauthorizedException
2976 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2978 $a = Friendica\DI::app();
2982 foreach ((array)$items as $item) {
2983 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2985 // Look if the posts are matching if they should be filtered by user id
2986 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2990 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2999 * @param array $item Item record
3000 * @param string $type Return format (atom, rss, xml, json)
3001 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3002 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3003 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3004 * @return array API-formatted status
3005 * @throws BadRequestException
3006 * @throws ImagickException
3007 * @throws InternalServerErrorException
3008 * @throws UnauthorizedException
3010 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3012 $a = Friendica\DI::app();
3014 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3015 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3018 localize_item($item);
3020 $in_reply_to = api_in_reply_to($item);
3022 $converted = api_convert_item($item);
3024 if ($type == "xml") {
3025 $geo = "georss:point";
3031 'text' => $converted["text"],
3032 'truncated' => false,
3033 'created_at'=> api_date($item['created']),
3034 'in_reply_to_status_id' => $in_reply_to['status_id'],
3035 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3036 'source' => (($item['app']) ? $item['app'] : 'web'),
3037 'id' => intval($item['id']),
3038 'id_str' => (string) intval($item['id']),
3039 'in_reply_to_user_id' => $in_reply_to['user_id'],
3040 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3041 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3043 'favorited' => $item['starred'] ? true : false,
3044 'user' => $status_user,
3045 'friendica_author' => $author_user,
3046 'friendica_owner' => $owner_user,
3047 'friendica_private' => $item['private'] == 1,
3048 //'entities' => NULL,
3049 'statusnet_html' => $converted["html"],
3050 'statusnet_conversation_id' => $item['parent'],
3051 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3052 'friendica_activities' => api_format_items_activities($item, $type),
3053 'friendica_title' => $item['title'],
3054 'friendica_html' => BBCode::convert($item['body'], false)
3057 if (count($converted["attachments"]) > 0) {
3058 $status["attachments"] = $converted["attachments"];
3061 if (count($converted["entities"]) > 0) {
3062 $status["entities"] = $converted["entities"];
3065 if ($status["source"] == 'web') {
3066 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3067 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3068 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3071 $retweeted_item = [];
3074 if ($item["id"] == $item["parent"]) {
3075 $body = $item['body'];
3076 $retweeted_item = api_share_as_retweet($item);
3077 if ($body != $item['body']) {
3078 $quoted_item = $retweeted_item;
3079 $retweeted_item = [];
3083 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3084 $announce = api_get_announce($item);
3085 if (!empty($announce)) {
3086 $retweeted_item = $item;
3088 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3092 if (!empty($quoted_item)) {
3093 if ($quoted_item['id'] != $item['id']) {
3094 $quoted_status = api_format_item($quoted_item);
3095 /// @todo Only remove the attachments that are also contained in the quotes status
3096 unset($status['attachments']);
3097 unset($status['entities']);
3099 $conv_quoted = api_convert_item($quoted_item);
3100 $quoted_status = $status;
3101 unset($quoted_status['attachments']);
3102 unset($quoted_status['entities']);
3103 unset($quoted_status['statusnet_conversation_id']);
3104 $quoted_status['text'] = $conv_quoted['text'];
3105 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3107 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3108 } catch (BadRequestException $e) {
3109 // user not found. should be found?
3110 /// @todo check if the user should be always found
3111 $quoted_status["user"] = [];
3114 unset($quoted_status['friendica_author']);
3115 unset($quoted_status['friendica_owner']);
3116 unset($quoted_status['friendica_activities']);
3117 unset($quoted_status['friendica_private']);
3120 if (!empty($retweeted_item)) {
3121 $retweeted_status = $status;
3122 unset($retweeted_status['friendica_author']);
3123 unset($retweeted_status['friendica_owner']);
3124 unset($retweeted_status['friendica_activities']);
3125 unset($retweeted_status['friendica_private']);
3126 unset($retweeted_status['statusnet_conversation_id']);
3127 $status['user'] = $status['friendica_owner'];
3129 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3130 } catch (BadRequestException $e) {
3131 // user not found. should be found?
3132 /// @todo check if the user should be always found
3133 $retweeted_status["user"] = [];
3136 $rt_converted = api_convert_item($retweeted_item);
3138 $retweeted_status['text'] = $rt_converted["text"];
3139 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3140 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3142 if (!empty($quoted_status)) {
3143 $retweeted_status['quoted_status'] = $quoted_status;
3146 $status['friendica_author'] = $retweeted_status['user'];
3147 $status['retweeted_status'] = $retweeted_status;
3148 } elseif (!empty($quoted_status)) {
3149 $root_status = api_convert_item($item);
3151 $status['text'] = $root_status["text"];
3152 $status['statusnet_html'] = $root_status["html"];
3153 $status['quoted_status'] = $quoted_status;
3156 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3157 unset($status["user"]["uid"]);
3158 unset($status["user"]["self"]);
3160 if ($item["coord"] != "") {
3161 $coords = explode(' ', $item["coord"]);
3162 if (count($coords) == 2) {
3163 if ($type == "json") {
3164 $status["geo"] = ['type' => 'Point',
3165 'coordinates' => [(float) $coords[0],
3166 (float) $coords[1]]];
3167 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3168 $status["georss:point"] = $item["coord"];
3177 * Returns the remaining number of API requests available to the user before the API limit is reached.
3179 * @param string $type Return type (atom, rss, xml, json)
3181 * @return array|string
3184 function api_account_rate_limit_status($type)
3186 if ($type == "xml") {
3188 'remaining-hits' => '150',
3189 '@attributes' => ["type" => "integer"],
3190 'hourly-limit' => '150',
3191 '@attributes2' => ["type" => "integer"],
3192 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3193 '@attributes3' => ["type" => "datetime"],
3194 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3195 '@attributes4' => ["type" => "integer"],
3199 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3200 'remaining_hits' => '150',
3201 'hourly_limit' => '150',
3202 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3206 return api_format_data('hash', $type, ['hash' => $hash]);
3209 /// @TODO move to top of file or somewhere better
3210 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3213 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3215 * @param string $type Return type (atom, rss, xml, json)
3217 * @return array|string
3219 function api_help_test($type)
3221 if ($type == 'xml') {
3227 return api_format_data('ok', $type, ["ok" => $ok]);
3230 /// @TODO move to top of file or somewhere better
3231 api_register_func('api/help/test', 'api_help_test', false);
3234 * Returns all lists the user subscribes to.
3236 * @param string $type Return type (atom, rss, xml, json)
3238 * @return array|string
3239 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3241 function api_lists_list($type)
3244 /// @TODO $ret is not filled here?
3245 return api_format_data('lists', $type, ["lists_list" => $ret]);
3248 /// @TODO move to top of file or somewhere better
3249 api_register_func('api/lists/list', 'api_lists_list', true);
3250 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3253 * Returns all groups the user owns.
3255 * @param string $type Return type (atom, rss, xml, json)
3257 * @return array|string
3258 * @throws BadRequestException
3259 * @throws ForbiddenException
3260 * @throws ImagickException
3261 * @throws InternalServerErrorException
3262 * @throws UnauthorizedException
3263 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3265 function api_lists_ownerships($type)
3269 if (api_user() === false) {
3270 throw new ForbiddenException();
3274 $user_info = api_get_user($a);
3275 $uid = $user_info['uid'];
3277 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3279 // loop through all groups
3281 foreach ($groups as $group) {
3282 if ($group['visible']) {
3288 'name' => $group['name'],
3289 'id' => intval($group['id']),
3290 'id_str' => (string) $group['id'],
3291 'user' => $user_info,
3295 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3298 /// @TODO move to top of file or somewhere better
3299 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3302 * Returns recent statuses from users in the specified group.
3304 * @param string $type Return type (atom, rss, xml, json)
3306 * @return array|string
3307 * @throws BadRequestException
3308 * @throws ForbiddenException
3309 * @throws ImagickException
3310 * @throws InternalServerErrorException
3311 * @throws UnauthorizedException
3312 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3314 function api_lists_statuses($type)
3318 $user_info = api_get_user($a);
3319 if (api_user() === false || $user_info === false) {
3320 throw new ForbiddenException();
3323 unset($_REQUEST["user_id"]);
3324 unset($_GET["user_id"]);
3326 unset($_REQUEST["screen_name"]);
3327 unset($_GET["screen_name"]);
3329 if (empty($_REQUEST['list_id'])) {
3330 throw new BadRequestException('list_id not specified');
3334 $count = $_REQUEST['count'] ?? 20;
3335 $page = $_REQUEST['page'] ?? 1;
3336 $since_id = $_REQUEST['since_id'] ?? 0;
3337 $max_id = $_REQUEST['max_id'] ?? 0;
3338 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3339 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3341 $start = max(0, ($page - 1) * $count);
3343 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3344 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3347 $condition[0] .= " AND `item`.`id` <= ?";
3348 $condition[] = $max_id;
3350 if ($exclude_replies > 0) {
3351 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3353 if ($conversation_id > 0) {
3354 $condition[0] .= " AND `item`.`parent` = ?";
3355 $condition[] = $conversation_id;
3358 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3359 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3361 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3363 $data = ['status' => $items];
3368 $data = api_rss_extra($a, $data, $user_info);
3372 return api_format_data("statuses", $type, $data);
3375 /// @TODO move to top of file or somewhere better
3376 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3379 * Returns either the friends of the follower list
3381 * Considers friends and followers lists to be private and won't return
3382 * anything if any user_id parameter is passed.
3384 * @param string $qtype Either "friends" or "followers"
3385 * @return boolean|array
3386 * @throws BadRequestException
3387 * @throws ForbiddenException
3388 * @throws ImagickException
3389 * @throws InternalServerErrorException
3390 * @throws UnauthorizedException
3392 function api_statuses_f($qtype)
3396 if (api_user() === false) {
3397 throw new ForbiddenException();
3401 $count = $_GET['count'] ?? 20;
3402 $page = $_GET['page'] ?? 1;
3404 $start = max(0, ($page - 1) * $count);
3406 $user_info = api_get_user($a);
3408 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3409 /* this is to stop Hotot to load friends multiple times
3410 * I'm not sure if I'm missing return something or
3411 * is a bug in hotot. Workaround, meantime
3415 return array('$users' => $ret);*/
3420 if ($qtype == 'friends') {
3421 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3422 } elseif ($qtype == 'followers') {
3423 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3426 // friends and followers only for self
3427 if ($user_info['self'] == 0) {
3428 $sql_extra = " AND false ";
3431 if ($qtype == 'blocks') {
3432 $sql_filter = 'AND `blocked` AND NOT `pending`';
3433 } elseif ($qtype == 'incoming') {
3434 $sql_filter = 'AND `pending`';
3436 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3454 foreach ($r as $cid) {
3455 $user = api_get_user($a, $cid['nurl']);
3456 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3457 unset($user["uid"]);
3458 unset($user["self"]);
3465 return ['user' => $ret];
3470 * Returns the list of friends of the provided user
3472 * @deprecated By Twitter API in favor of friends/list
3474 * @param string $type Either "json" or "xml"
3475 * @return boolean|string|array
3476 * @throws BadRequestException
3477 * @throws ForbiddenException
3479 function api_statuses_friends($type)
3481 $data = api_statuses_f("friends");
3482 if ($data === false) {
3485 return api_format_data("users", $type, $data);
3489 * Returns the list of followers of the provided user
3491 * @deprecated By Twitter API in favor of friends/list
3493 * @param string $type Either "json" or "xml"
3494 * @return boolean|string|array
3495 * @throws BadRequestException
3496 * @throws ForbiddenException
3498 function api_statuses_followers($type)
3500 $data = api_statuses_f("followers");
3501 if ($data === false) {
3504 return api_format_data("users", $type, $data);
3507 /// @TODO move to top of file or somewhere better
3508 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3509 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3512 * Returns the list of blocked users
3514 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3516 * @param string $type Either "json" or "xml"
3518 * @return boolean|string|array
3519 * @throws BadRequestException
3520 * @throws ForbiddenException
3522 function api_blocks_list($type)
3524 $data = api_statuses_f('blocks');
3525 if ($data === false) {
3528 return api_format_data("users", $type, $data);
3531 /// @TODO move to top of file or somewhere better
3532 api_register_func('api/blocks/list', 'api_blocks_list', true);
3535 * Returns the list of pending users IDs
3537 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3539 * @param string $type Either "json" or "xml"
3541 * @return boolean|string|array
3542 * @throws BadRequestException
3543 * @throws ForbiddenException
3545 function api_friendships_incoming($type)
3547 $data = api_statuses_f('incoming');
3548 if ($data === false) {
3553 foreach ($data['user'] as $user) {
3554 $ids[] = $user['id'];
3557 return api_format_data("ids", $type, ['id' => $ids]);
3560 /// @TODO move to top of file or somewhere better
3561 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3564 * Returns the instance's configuration information.
3566 * @param string $type Return type (atom, rss, xml, json)
3568 * @return array|string
3569 * @throws InternalServerErrorException
3571 function api_statusnet_config($type)
3573 $name = DI::config()->get('config', 'sitename');
3574 $server = DI::baseUrl()->getHostname();
3575 $logo = DI::baseUrl() . '/images/friendica-64.png';
3576 $email = DI::config()->get('config', 'admin_email');
3577 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3578 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3579 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3580 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3581 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3584 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3585 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3586 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3587 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3588 'shorturllength' => '30',
3590 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3591 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3592 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3593 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3598 return api_format_data('config', $type, ['config' => $config]);
3601 /// @TODO move to top of file or somewhere better
3602 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3603 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3607 * @param string $type Return type (atom, rss, xml, json)
3609 * @return array|string
3611 function api_statusnet_version($type)
3614 $fake_statusnet_version = "0.9.7";
3616 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3619 /// @TODO move to top of file or somewhere better
3620 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3621 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3625 * @param string $type Return type (atom, rss, xml, json)
3627 * @param int $rel A contact relationship constant
3628 * @return array|string|void
3629 * @throws BadRequestException
3630 * @throws ForbiddenException
3631 * @throws ImagickException
3632 * @throws InternalServerErrorException
3633 * @throws UnauthorizedException
3634 * @todo use api_format_data() to return data
3636 function api_ff_ids($type, int $rel)
3639 throw new ForbiddenException();
3646 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3648 $contacts = DBA::p("SELECT `pcontact`.`id`
3650 INNER JOIN `contact` AS `pcontact`
3651 ON `contact`.`nurl` = `pcontact`.`nurl`
3652 AND `pcontact`.`uid` = 0
3653 WHERE `contact`.`uid` = ?
3654 AND NOT `contact`.`self`
3655 AND `contact`.`rel` IN (?, ?)",
3662 foreach (DBA::toArray($contacts) as $contact) {
3663 if ($stringify_ids) {
3664 $ids[] = $contact['id'];
3666 $ids[] = intval($contact['id']);
3670 return api_format_data('ids', $type, ['id' => $ids]);
3674 * Returns the ID of every user the user is following.
3676 * @param string $type Return type (atom, rss, xml, json)
3678 * @return array|string
3679 * @throws BadRequestException
3680 * @throws ForbiddenException
3681 * @throws ImagickException
3682 * @throws InternalServerErrorException
3683 * @throws UnauthorizedException
3684 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3686 function api_friends_ids($type)
3688 return api_ff_ids($type, Contact::SHARING);
3692 * Returns the ID of every user following the user.
3694 * @param string $type Return type (atom, rss, xml, json)
3696 * @return array|string
3697 * @throws BadRequestException
3698 * @throws ForbiddenException
3699 * @throws ImagickException
3700 * @throws InternalServerErrorException
3701 * @throws UnauthorizedException
3702 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3704 function api_followers_ids($type)
3706 return api_ff_ids($type, Contact::FOLLOWER);
3709 /// @TODO move to top of file or somewhere better
3710 api_register_func('api/friends/ids', 'api_friends_ids', true);
3711 api_register_func('api/followers/ids', 'api_followers_ids', true);
3714 * Sends a new direct message.
3716 * @param string $type Return type (atom, rss, xml, json)
3718 * @return array|string
3719 * @throws BadRequestException
3720 * @throws ForbiddenException
3721 * @throws ImagickException
3722 * @throws InternalServerErrorException
3723 * @throws NotFoundException
3724 * @throws UnauthorizedException
3725 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3727 function api_direct_messages_new($type)
3731 if (api_user() === false) {
3732 throw new ForbiddenException();
3735 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3739 $sender = api_get_user($a);
3742 if (!empty($_POST['screen_name'])) {
3744 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3746 DBA::escape($_POST['screen_name'])
3749 if (DBA::isResult($r)) {
3750 // Selecting the id by priority, friendica first
3751 api_best_nickname($r);
3753 $recipient = api_get_user($a, $r[0]['nurl']);
3756 $recipient = api_get_user($a, $_POST['user_id']);
3759 if (empty($recipient)) {
3760 throw new NotFoundException('Recipient not found');
3764 if (!empty($_REQUEST['replyto'])) {
3766 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3768 intval($_REQUEST['replyto'])
3770 $replyto = $r[0]['parent-uri'];
3771 $sub = $r[0]['title'];
3773 if (!empty($_REQUEST['title'])) {
3774 $sub = $_REQUEST['title'];
3776 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3780 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3783 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3784 $ret = api_format_messages($r[0], $recipient, $sender);
3786 $ret = ["error"=>$id];
3789 $data = ['direct_message'=>$ret];
3795 $data = api_rss_extra($a, $data, $sender);
3799 return api_format_data("direct-messages", $type, $data);
3802 /// @TODO move to top of file or somewhere better
3803 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3806 * delete a direct_message from mail table through api
3808 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3809 * @return string|array
3810 * @throws BadRequestException
3811 * @throws ForbiddenException
3812 * @throws ImagickException
3813 * @throws InternalServerErrorException
3814 * @throws UnauthorizedException
3815 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3817 function api_direct_messages_destroy($type)
3821 if (api_user() === false) {
3822 throw new ForbiddenException();
3826 $user_info = api_get_user($a);
3828 $id = $_REQUEST['id'] ?? 0;
3830 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3831 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3832 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3834 $uid = $user_info['uid'];
3835 // error if no id or parenturi specified (for clients posting parent-uri as well)
3836 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3837 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3838 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3841 // BadRequestException if no id specified (for clients using Twitter API)
3843 throw new BadRequestException('Message id not specified');
3846 // add parent-uri to sql command if specified by calling app
3847 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3849 // get data of the specified message id
3851 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3856 // error message if specified id is not in database
3857 if (!DBA::isResult($r)) {
3858 if ($verbose == "true") {
3859 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3860 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3862 /// @todo BadRequestException ok for Twitter API clients?
3863 throw new BadRequestException('message id not in database');
3868 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3873 if ($verbose == "true") {
3876 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3877 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3879 $answer = ['result' => 'error', 'message' => 'unknown error'];
3880 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3883 /// @todo return JSON data like Twitter API not yet implemented
3886 /// @TODO move to top of file or somewhere better
3887 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3892 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3893 * @return string|array
3894 * @throws BadRequestException
3895 * @throws ForbiddenException
3896 * @throws ImagickException
3897 * @throws InternalServerErrorException
3898 * @throws NotFoundException
3899 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3901 function api_friendships_destroy($type)
3905 if ($uid === false) {
3906 throw new ForbiddenException();
3909 $contact_id = $_REQUEST['user_id'] ?? 0;
3911 if (empty($contact_id)) {
3912 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3913 throw new BadRequestException("no user_id specified");
3916 // Get Contact by given id
3917 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3919 if(!DBA::isResult($contact)) {
3920 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3921 throw new NotFoundException("no contact found to given ID");
3924 $url = $contact["url"];
3926 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3927 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3928 Strings::normaliseLink($url), $url];
3929 $contact = DBA::selectFirst('contact', [], $condition);
3931 if (!DBA::isResult($contact)) {
3932 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3933 throw new NotFoundException("Not following Contact");
3936 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3937 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3938 throw new ExpectationFailedException("Not supported");
3941 $dissolve = ($contact['rel'] == Contact::SHARING);
3943 $owner = User::getOwnerDataById($uid);
3945 Contact::terminateFriendship($owner, $contact, $dissolve);
3948 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3949 throw new NotFoundException("Error Processing Request");
3952 // Sharing-only contacts get deleted as there no relationship any more
3954 Contact::remove($contact['id']);
3956 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3959 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3960 unset($contact["uid"]);
3961 unset($contact["self"]);
3963 // Set screen_name since Twidere requests it
3964 $contact["screen_name"] = $contact["nick"];
3966 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3968 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3972 * @param string $type Return type (atom, rss, xml, json)
3973 * @param string $box
3974 * @param string $verbose
3976 * @return array|string
3977 * @throws BadRequestException
3978 * @throws ForbiddenException
3979 * @throws ImagickException
3980 * @throws InternalServerErrorException
3981 * @throws UnauthorizedException
3983 function api_direct_messages_box($type, $box, $verbose)
3986 if (api_user() === false) {
3987 throw new ForbiddenException();
3990 $count = $_GET['count'] ?? 20;
3991 $page = $_REQUEST['page'] ?? 1;
3993 $since_id = $_REQUEST['since_id'] ?? 0;
3994 $max_id = $_REQUEST['max_id'] ?? 0;
3996 $user_id = $_REQUEST['user_id'] ?? '';
3997 $screen_name = $_REQUEST['screen_name'] ?? '';
4000 unset($_REQUEST["user_id"]);
4001 unset($_GET["user_id"]);
4003 unset($_REQUEST["screen_name"]);
4004 unset($_GET["screen_name"]);
4006 $user_info = api_get_user($a);
4007 if ($user_info === false) {
4008 throw new ForbiddenException();
4010 $profile_url = $user_info["url"];
4013 $start = max(0, ($page - 1) * $count);
4018 if ($box=="sentbox") {
4019 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
4020 } elseif ($box == "conversation") {
4021 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
4022 } elseif ($box == "all") {
4023 $sql_extra = "true";
4024 } elseif ($box == "inbox") {
4025 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4029 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4032 if ($user_id != "") {
4033 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4034 } elseif ($screen_name !="") {
4035 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4039 "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",
4045 if ($verbose == "true" && !DBA::isResult($r)) {
4046 $answer = ['result' => 'error', 'message' => 'no mails available'];
4047 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4051 foreach ($r as $item) {
4052 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4053 $recipient = $user_info;
4054 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4055 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4056 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4057 $sender = $user_info;
4060 if (isset($recipient) && isset($sender)) {
4061 $ret[] = api_format_messages($item, $recipient, $sender);
4066 $data = ['direct_message' => $ret];
4071 $data = api_rss_extra($a, $data, $user_info);
4075 return api_format_data("direct-messages", $type, $data);
4079 * Returns the most recent direct messages sent by the user.
4081 * @param string $type Return type (atom, rss, xml, json)
4083 * @return array|string
4084 * @throws BadRequestException
4085 * @throws ForbiddenException
4086 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4088 function api_direct_messages_sentbox($type)
4090 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4091 return api_direct_messages_box($type, "sentbox", $verbose);
4095 * Returns the most recent direct messages sent to the user.
4097 * @param string $type Return type (atom, rss, xml, json)
4099 * @return array|string
4100 * @throws BadRequestException
4101 * @throws ForbiddenException
4102 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4104 function api_direct_messages_inbox($type)
4106 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4107 return api_direct_messages_box($type, "inbox", $verbose);
4112 * @param string $type Return type (atom, rss, xml, json)
4114 * @return array|string
4115 * @throws BadRequestException
4116 * @throws ForbiddenException
4118 function api_direct_messages_all($type)
4120 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4121 return api_direct_messages_box($type, "all", $verbose);
4126 * @param string $type Return type (atom, rss, xml, json)
4128 * @return array|string
4129 * @throws BadRequestException
4130 * @throws ForbiddenException
4132 function api_direct_messages_conversation($type)
4134 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4135 return api_direct_messages_box($type, "conversation", $verbose);
4138 /// @TODO move to top of file or somewhere better
4139 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4140 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4141 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4142 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4145 * Returns an OAuth Request Token.
4147 * @see https://oauth.net/core/1.0/#auth_step1
4149 function api_oauth_request_token()
4151 $oauth1 = new FKOAuth1();
4153 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4154 } catch (Exception $e) {
4155 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4163 * Returns an OAuth Access Token.
4165 * @return array|string
4166 * @see https://oauth.net/core/1.0/#auth_step3
4168 function api_oauth_access_token()
4170 $oauth1 = new FKOAuth1();
4172 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4173 } catch (Exception $e) {
4174 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4181 /// @TODO move to top of file or somewhere better
4182 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4183 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4187 * delete a complete photoalbum with all containing photos from database through api
4189 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4190 * @return string|array
4191 * @throws BadRequestException
4192 * @throws ForbiddenException
4193 * @throws InternalServerErrorException
4195 function api_fr_photoalbum_delete($type)
4197 if (api_user() === false) {
4198 throw new ForbiddenException();
4201 $album = $_REQUEST['album'] ?? '';
4203 // we do not allow calls without album string
4205 throw new BadRequestException("no albumname specified");
4207 // check if album is existing
4209 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4213 if (!DBA::isResult($r)) {
4214 throw new BadRequestException("album not available");
4217 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4218 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4219 foreach ($r as $rr) {
4220 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4221 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4223 if (!DBA::isResult($photo_item)) {
4224 throw new InternalServerErrorException("problem with deleting items occured");
4226 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4229 // now let's delete all photos from the album
4230 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4232 // return success of deletion or error message
4234 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4235 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4237 throw new InternalServerErrorException("unknown error - deleting from database failed");
4242 * update the name of the album for all photos of an album
4244 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4245 * @return string|array
4246 * @throws BadRequestException
4247 * @throws ForbiddenException
4248 * @throws InternalServerErrorException
4250 function api_fr_photoalbum_update($type)
4252 if (api_user() === false) {
4253 throw new ForbiddenException();
4256 $album = $_REQUEST['album'] ?? '';
4257 $album_new = $_REQUEST['album_new'] ?? '';
4259 // we do not allow calls without album string
4261 throw new BadRequestException("no albumname specified");
4263 if ($album_new == "") {
4264 throw new BadRequestException("no new albumname specified");
4266 // check if album is existing
4267 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4268 throw new BadRequestException("album not available");
4270 // now let's update all photos to the albumname
4271 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4273 // return success of updating or error message
4275 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4276 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4278 throw new InternalServerErrorException("unknown error - updating in database failed");
4284 * list all photos of the authenticated user
4286 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4287 * @return string|array
4288 * @throws ForbiddenException
4289 * @throws InternalServerErrorException
4291 function api_fr_photos_list($type)
4293 if (api_user() === false) {
4294 throw new ForbiddenException();
4297 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4298 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4299 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4300 intval(local_user())
4303 'image/jpeg' => 'jpg',
4304 'image/png' => 'png',
4305 'image/gif' => 'gif'
4307 $data = ['photo'=>[]];
4308 if (DBA::isResult($r)) {
4309 foreach ($r as $rr) {
4311 $photo['id'] = $rr['resource-id'];
4312 $photo['album'] = $rr['album'];
4313 $photo['filename'] = $rr['filename'];
4314 $photo['type'] = $rr['type'];
4315 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4316 $photo['created'] = $rr['created'];
4317 $photo['edited'] = $rr['edited'];
4318 $photo['desc'] = $rr['desc'];
4320 if ($type == "xml") {
4321 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4323 $photo['thumb'] = $thumb;
4324 $data['photo'][] = $photo;
4328 return api_format_data("photos", $type, $data);
4332 * upload a new photo or change an existing photo
4334 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4335 * @return string|array
4336 * @throws BadRequestException
4337 * @throws ForbiddenException
4338 * @throws ImagickException
4339 * @throws InternalServerErrorException
4340 * @throws NotFoundException
4342 function api_fr_photo_create_update($type)
4344 if (api_user() === false) {
4345 throw new ForbiddenException();
4348 $photo_id = $_REQUEST['photo_id'] ?? null;
4349 $desc = $_REQUEST['desc'] ?? null;
4350 $album = $_REQUEST['album'] ?? null;
4351 $album_new = $_REQUEST['album_new'] ?? null;
4352 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4353 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4354 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4355 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4356 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4358 // do several checks on input parameters
4359 // we do not allow calls without album string
4360 if ($album == null) {
4361 throw new BadRequestException("no albumname specified");
4363 // if photo_id == null --> we are uploading a new photo
4364 if ($photo_id == null) {
4367 // error if no media posted in create-mode
4368 if (empty($_FILES['media'])) {
4370 throw new BadRequestException("no media data submitted");
4373 // album_new will be ignored in create-mode
4378 // check if photo is existing in databasei
4379 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4380 throw new BadRequestException("photo not available");
4384 // checks on acl strings provided by clients
4385 $acl_input_error = false;
4386 $acl_input_error |= check_acl_input($allow_cid);
4387 $acl_input_error |= check_acl_input($deny_cid);
4388 $acl_input_error |= check_acl_input($allow_gid);
4389 $acl_input_error |= check_acl_input($deny_gid);
4390 if ($acl_input_error) {
4391 throw new BadRequestException("acl data invalid");
4393 // now let's upload the new media in create-mode
4394 if ($mode == "create") {
4395 $media = $_FILES['media'];
4396 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4398 // return success of updating or error message
4399 if (!is_null($data)) {
4400 return api_format_data("photo_create", $type, $data);
4402 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4406 // now let's do the changes in update-mode
4407 if ($mode == "update") {
4408 $updated_fields = [];
4410 if (!is_null($desc)) {
4411 $updated_fields['desc'] = $desc;
4414 if (!is_null($album_new)) {
4415 $updated_fields['album'] = $album_new;
4418 if (!is_null($allow_cid)) {
4419 $allow_cid = trim($allow_cid);
4420 $updated_fields['allow_cid'] = $allow_cid;
4423 if (!is_null($deny_cid)) {
4424 $deny_cid = trim($deny_cid);
4425 $updated_fields['deny_cid'] = $deny_cid;
4428 if (!is_null($allow_gid)) {
4429 $allow_gid = trim($allow_gid);
4430 $updated_fields['allow_gid'] = $allow_gid;
4433 if (!is_null($deny_gid)) {
4434 $deny_gid = trim($deny_gid);
4435 $updated_fields['deny_gid'] = $deny_gid;
4439 if (count($updated_fields) > 0) {
4440 $nothingtodo = false;
4441 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4443 $nothingtodo = true;
4446 if (!empty($_FILES['media'])) {
4447 $nothingtodo = false;
4448 $media = $_FILES['media'];
4449 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4450 if (!is_null($data)) {
4451 return api_format_data("photo_update", $type, $data);
4455 // return success of updating or error message
4457 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4458 return api_format_data("photo_update", $type, ['$result' => $answer]);
4461 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4462 return api_format_data("photo_update", $type, ['$result' => $answer]);
4464 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4467 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4471 * delete a single photo from the database through api
4473 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4474 * @return string|array
4475 * @throws BadRequestException
4476 * @throws ForbiddenException
4477 * @throws InternalServerErrorException
4479 function api_fr_photo_delete($type)
4481 if (api_user() === false) {
4482 throw new ForbiddenException();
4486 $photo_id = $_REQUEST['photo_id'] ?? null;
4488 // do several checks on input parameters
4489 // we do not allow calls without photo id
4490 if ($photo_id == null) {
4491 throw new BadRequestException("no photo_id specified");
4494 // check if photo is existing in database
4495 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4496 throw new BadRequestException("photo not available");
4499 // now we can perform on the deletion of the photo
4500 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4502 // return success of deletion or error message
4504 // retrieve the id of the parent element (the photo element)
4505 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4506 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4508 if (!DBA::isResult($photo_item)) {
4509 throw new InternalServerErrorException("problem with deleting items occured");
4511 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4512 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4513 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4515 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4516 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4518 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4524 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4526 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4527 * @return string|array
4528 * @throws BadRequestException
4529 * @throws ForbiddenException
4530 * @throws InternalServerErrorException
4531 * @throws NotFoundException
4533 function api_fr_photo_detail($type)
4535 if (api_user() === false) {
4536 throw new ForbiddenException();
4538 if (empty($_REQUEST['photo_id'])) {
4539 throw new BadRequestException("No photo id.");
4542 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4543 $photo_id = $_REQUEST['photo_id'];
4545 // prepare json/xml output with data from database for the requested photo
4546 $data = prepare_photo_data($type, $scale, $photo_id);
4548 return api_format_data("photo_detail", $type, $data);
4553 * updates the profile image for the user (either a specified profile or the default profile)
4555 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4557 * @return string|array
4558 * @throws BadRequestException
4559 * @throws ForbiddenException
4560 * @throws ImagickException
4561 * @throws InternalServerErrorException
4562 * @throws NotFoundException
4563 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4565 function api_account_update_profile_image($type)
4567 if (api_user() === false) {
4568 throw new ForbiddenException();
4571 $profile_id = $_REQUEST['profile_id'] ?? 0;
4573 // error if image data is missing
4574 if (empty($_FILES['image'])) {
4575 throw new BadRequestException("no media data submitted");
4578 // check if specified profile id is valid
4579 if ($profile_id != 0) {
4580 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4581 // error message if specified profile id is not in database
4582 if (!DBA::isResult($profile)) {
4583 throw new BadRequestException("profile_id not available");
4585 $is_default_profile = $profile['is-default'];
4587 $is_default_profile = 1;
4590 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4592 if (!empty($_FILES['image'])) {
4593 $media = $_FILES['image'];
4594 } elseif (!empty($_FILES['media'])) {
4595 $media = $_FILES['media'];
4597 // save new profile image
4598 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4601 if (is_array($media['type'])) {
4602 $filetype = $media['type'][0];
4604 $filetype = $media['type'];
4606 if ($filetype == "image/jpeg") {
4608 } elseif ($filetype == "image/png") {
4611 throw new InternalServerErrorException('Unsupported filetype');
4614 // change specified profile or all profiles to the new resource-id
4615 if ($is_default_profile) {
4616 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4617 Photo::update(['profile' => false], $condition);
4619 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4620 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4621 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4624 Contact::updateSelfFromUserID(api_user(), true);
4626 // Update global directory in background
4627 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4628 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4629 Worker::add(PRIORITY_LOW, "Directory", $url);
4632 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4634 // output for client
4636 return api_account_verify_credentials($type);
4638 // SaveMediaToDatabase failed for some reason
4639 throw new InternalServerErrorException("image upload failed");
4643 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4644 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4645 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4646 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4647 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4648 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4649 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4650 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4651 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4654 * Update user profile
4656 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4658 * @return array|string
4659 * @throws BadRequestException
4660 * @throws ForbiddenException
4661 * @throws ImagickException
4662 * @throws InternalServerErrorException
4663 * @throws UnauthorizedException
4665 function api_account_update_profile($type)
4667 $local_user = api_user();
4668 $api_user = api_get_user(DI::app());
4670 if (!empty($_POST['name'])) {
4671 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4672 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4673 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4674 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4677 if (isset($_POST['description'])) {
4678 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4679 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4680 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4683 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4684 // Update global directory in background
4685 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4686 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4689 return api_account_verify_credentials($type);
4692 /// @TODO move to top of file or somewhere better
4693 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4697 * @param string $acl_string
4701 function check_acl_input($acl_string)
4703 if (empty($acl_string)) {
4707 $contact_not_found = false;
4709 // split <x><y><z> into array of cid's
4710 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4712 // check for each cid if it is available on server
4713 $cid_array = $array[0];
4714 foreach ($cid_array as $cid) {
4715 $cid = str_replace("<", "", $cid);
4716 $cid = str_replace(">", "", $cid);
4717 $condition = ['id' => $cid, 'uid' => api_user()];
4718 $contact_not_found |= !DBA::exists('contact', $condition);
4720 return $contact_not_found;
4724 * @param string $mediatype
4725 * @param array $media
4726 * @param string $type
4727 * @param string $album
4728 * @param string $allow_cid
4729 * @param string $deny_cid
4730 * @param string $allow_gid
4731 * @param string $deny_gid
4732 * @param string $desc
4733 * @param integer $profile
4734 * @param boolean $visibility
4735 * @param string $photo_id
4737 * @throws BadRequestException
4738 * @throws ForbiddenException
4739 * @throws ImagickException
4740 * @throws InternalServerErrorException
4741 * @throws NotFoundException
4742 * @throws UnauthorizedException
4744 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)
4752 if (is_array($media)) {
4753 if (is_array($media['tmp_name'])) {
4754 $src = $media['tmp_name'][0];
4756 $src = $media['tmp_name'];
4758 if (is_array($media['name'])) {
4759 $filename = basename($media['name'][0]);
4761 $filename = basename($media['name']);
4763 if (is_array($media['size'])) {
4764 $filesize = intval($media['size'][0]);
4766 $filesize = intval($media['size']);
4768 if (is_array($media['type'])) {
4769 $filetype = $media['type'][0];
4771 $filetype = $media['type'];
4775 if ($filetype == "") {
4776 $filetype = Images::guessType($filename);
4778 $imagedata = @getimagesize($src);
4780 $filetype = $imagedata['mime'];
4783 "File upload src: " . $src . " - filename: " . $filename .
4784 " - size: " . $filesize . " - type: " . $filetype,
4788 // check if there was a php upload error
4789 if ($filesize == 0 && $media['error'] == 1) {
4790 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4792 // check against max upload size within Friendica instance
4793 $maximagesize = DI::config()->get('system', 'maximagesize');
4794 if ($maximagesize && ($filesize > $maximagesize)) {
4795 $formattedBytes = Strings::formatBytes($maximagesize);
4796 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4799 // create Photo instance with the data of the image
4800 $imagedata = @file_get_contents($src);
4801 $Image = new Image($imagedata, $filetype);
4802 if (!$Image->isValid()) {
4803 throw new InternalServerErrorException("unable to process image data");
4806 // check orientation of image
4807 $Image->orient($src);
4810 // check max length of images on server
4811 $max_length = DI::config()->get('system', 'max_image_length');
4813 $max_length = MAX_IMAGE_LENGTH;
4815 if ($max_length > 0) {
4816 $Image->scaleDown($max_length);
4817 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4819 $width = $Image->getWidth();
4820 $height = $Image->getHeight();
4822 // create a new resource-id if not already provided
4823 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4825 if ($mediatype == "photo") {
4826 // upload normal image (scales 0, 1, 2)
4827 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4829 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4831 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4833 if ($width > 640 || $height > 640) {
4834 $Image->scaleDown(640);
4835 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4837 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4841 if ($width > 320 || $height > 320) {
4842 $Image->scaleDown(320);
4843 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4845 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4848 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4849 } elseif ($mediatype == "profileimage") {
4850 // upload profile image (scales 4, 5, 6)
4851 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4853 if ($width > 300 || $height > 300) {
4854 $Image->scaleDown(300);
4855 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4857 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4861 if ($width > 80 || $height > 80) {
4862 $Image->scaleDown(80);
4863 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4865 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4869 if ($width > 48 || $height > 48) {
4870 $Image->scaleDown(48);
4871 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4873 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4876 $Image->__destruct();
4877 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4880 if (isset($r) && $r) {
4881 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4882 if ($photo_id == null && $mediatype == "photo") {
4883 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4885 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4886 return prepare_photo_data($type, false, $resource_id);
4888 throw new InternalServerErrorException("image upload failed");
4894 * @param string $hash
4895 * @param string $allow_cid
4896 * @param string $deny_cid
4897 * @param string $allow_gid
4898 * @param string $deny_gid
4899 * @param string $filetype
4900 * @param boolean $visibility
4901 * @throws InternalServerErrorException
4903 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4905 // get data about the api authenticated user
4906 $uri = Item::newURI(intval(api_user()));
4907 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4910 $arr['guid'] = System::createUUID();
4911 $arr['uid'] = intval(api_user());
4913 $arr['parent-uri'] = $uri;
4914 $arr['type'] = 'photo';
4916 $arr['resource-id'] = $hash;
4917 $arr['contact-id'] = $owner_record['id'];
4918 $arr['owner-name'] = $owner_record['name'];
4919 $arr['owner-link'] = $owner_record['url'];
4920 $arr['owner-avatar'] = $owner_record['thumb'];
4921 $arr['author-name'] = $owner_record['name'];
4922 $arr['author-link'] = $owner_record['url'];
4923 $arr['author-avatar'] = $owner_record['thumb'];
4925 $arr['allow_cid'] = $allow_cid;
4926 $arr['allow_gid'] = $allow_gid;
4927 $arr['deny_cid'] = $deny_cid;
4928 $arr['deny_gid'] = $deny_gid;
4929 $arr['visible'] = $visibility;
4933 'image/jpeg' => 'jpg',
4934 'image/png' => 'png',
4935 'image/gif' => 'gif'
4938 // adds link to the thumbnail scale photo
4939 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4940 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4943 // do the magic for storing the item in the database and trigger the federation to other contacts
4949 * @param string $type
4951 * @param string $photo_id
4954 * @throws BadRequestException
4955 * @throws ForbiddenException
4956 * @throws ImagickException
4957 * @throws InternalServerErrorException
4958 * @throws NotFoundException
4959 * @throws UnauthorizedException
4961 function prepare_photo_data($type, $scale, $photo_id)
4964 $user_info = api_get_user($a);
4966 if ($user_info === false) {
4967 throw new ForbiddenException();
4970 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4971 $data_sql = ($scale === false ? "" : "data, ");
4973 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4974 // clients needs to convert this in their way for further processing
4976 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4977 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4978 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4979 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4980 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4981 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4983 intval(local_user()),
4984 DBA::escape($photo_id),
4989 'image/jpeg' => 'jpg',
4990 'image/png' => 'png',
4991 'image/gif' => 'gif'
4994 // prepare output data for photo
4995 if (DBA::isResult($r)) {
4996 $data = ['photo' => $r[0]];
4997 $data['photo']['id'] = $data['photo']['resource-id'];
4998 if ($scale !== false) {
4999 $data['photo']['data'] = base64_encode($data['photo']['data']);
5001 unset($data['photo']['datasize']); //needed only with scale param
5003 if ($type == "xml") {
5004 $data['photo']['links'] = [];
5005 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5006 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
5008 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
5011 $data['photo']['link'] = [];
5012 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
5014 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5015 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
5019 unset($data['photo']['resource-id']);
5020 unset($data['photo']['minscale']);
5021 unset($data['photo']['maxscale']);
5023 throw new NotFoundException();
5026 // retrieve item element for getting activities (like, dislike etc.) related to photo
5027 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5028 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5029 if (!DBA::isResult($item)) {
5030 throw new NotFoundException('Photo-related item not found.');
5033 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5035 // retrieve comments on photo
5036 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5037 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5039 $statuses = Item::selectForUser(api_user(), [], $condition);
5041 // prepare output of comments
5042 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5044 if ($type == "xml") {
5046 foreach ($commentData as $comment) {
5047 $comments[$k++ . ":comment"] = $comment;
5050 foreach ($commentData as $comment) {
5051 $comments[] = $comment;
5054 $data['photo']['friendica_comments'] = $comments;
5056 // include info if rights on photo and rights on item are mismatching
5057 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5058 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5059 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5060 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5061 $data['photo']['rights_mismatch'] = $rights_mismatch;
5068 * Similar as /mod/redir.php
5069 * redirect to 'url' after dfrn auth
5071 * Why this when there is mod/redir.php already?
5072 * This use api_user() and api_login()
5075 * c_url: url of remote contact to auth to
5076 * url: string, url to redirect after auth
5078 function api_friendica_remoteauth()
5080 $url = $_GET['url'] ?? '';
5081 $c_url = $_GET['c_url'] ?? '';
5083 if ($url === '' || $c_url === '') {
5084 throw new BadRequestException("Wrong parameters.");
5087 $c_url = Strings::normaliseLink($c_url);
5091 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5092 if (!DBA::isResult($contact)) {
5093 throw new BadRequestException("Unknown contact");
5096 $cid = $contact['id'];
5098 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5100 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5101 System::externalRedirect($url ?: $c_url);
5104 if ($contact['duplex'] && $contact['issued-id']) {
5105 $orig_id = $contact['issued-id'];
5106 $dfrn_id = '1:' . $orig_id;
5108 if ($contact['duplex'] && $contact['dfrn-id']) {
5109 $orig_id = $contact['dfrn-id'];
5110 $dfrn_id = '0:' . $orig_id;
5113 $sec = Strings::getRandomHex();
5115 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5116 'sec' => $sec, 'expire' => time() + 45];
5117 DBA::insert('profile_check', $fields);
5119 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5120 $dest = ($url ? '&destination_url=' . $url : '');
5122 System::externalRedirect(
5123 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5124 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5125 . '&type=profile&sec=' . $sec . $dest
5128 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5131 * Return an item with announcer data if it had been announced
5133 * @param array $item Item array
5134 * @return array Item array with announce data
5136 function api_get_announce($item)
5138 // Quit if the item already has got a different owner and author
5139 if ($item['owner-id'] != $item['author-id']) {
5143 // Don't change original or Diaspora posts
5144 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5148 // Quit if we do now the original author and it had been a post from a native network
5149 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5153 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5154 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5155 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5156 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5157 if (!DBA::isResult($announce)) {
5161 return array_merge($item, $announce);
5165 * Return the item shared, if the item contains only the [share] tag
5167 * @param array $item Sharer item
5168 * @return array|false Shared item or false if not a reshare
5169 * @throws ImagickException
5170 * @throws InternalServerErrorException
5172 function api_share_as_retweet(&$item)
5174 $body = trim($item["body"]);
5176 if (Diaspora::isReshare($body, false) === false) {
5177 if ($item['author-id'] == $item['owner-id']) {
5180 // Reshares from OStatus, ActivityPub and Twitter
5181 $reshared_item = $item;
5182 $reshared_item['owner-id'] = $reshared_item['author-id'];
5183 $reshared_item['owner-link'] = $reshared_item['author-link'];
5184 $reshared_item['owner-name'] = $reshared_item['author-name'];
5185 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5186 return $reshared_item;
5190 $reshared = Item::getShareArray($item);
5191 if (empty($reshared)) {
5195 $reshared_item = $item;
5197 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5201 if (!empty($reshared['comment'])) {
5202 $item['body'] = $reshared['comment'];
5205 $reshared_item["share-pre-body"] = $reshared['comment'];
5206 $reshared_item["body"] = $reshared['shared'];
5207 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5208 $reshared_item["author-name"] = $reshared['author'];
5209 $reshared_item["author-link"] = $reshared['profile'];
5210 $reshared_item["author-avatar"] = $reshared['avatar'];
5211 $reshared_item["plink"] = $reshared['link'] ?? '';
5212 $reshared_item["created"] = $reshared['posted'];
5213 $reshared_item["edited"] = $reshared['posted'];
5215 // Try to fetch the original item
5216 if (!empty($reshared['guid'])) {
5217 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5218 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5219 $condition = ['id' => $original_id];
5224 if (!empty($condition)) {
5225 $original_item = Item::selectFirst([], $condition);
5226 if (DBA::isResult($original_item)) {
5227 $reshared_item = array_merge($reshared_item, $original_item);
5231 return $reshared_item;
5236 * @param array $item
5241 function api_in_reply_to($item)
5245 $in_reply_to['status_id'] = null;
5246 $in_reply_to['user_id'] = null;
5247 $in_reply_to['status_id_str'] = null;
5248 $in_reply_to['user_id_str'] = null;
5249 $in_reply_to['screen_name'] = null;
5251 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5252 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5253 if (DBA::isResult($parent)) {
5254 $in_reply_to['status_id'] = intval($parent['id']);
5256 $in_reply_to['status_id'] = intval($item['parent']);
5259 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5261 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5262 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5264 if (DBA::isResult($parent)) {
5265 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5266 $in_reply_to['user_id'] = intval($parent['author-id']);
5267 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5270 // There seems to be situation, where both fields are identical:
5271 // https://github.com/friendica/friendica/issues/1010
5272 // This is a bugfix for that.
5273 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5274 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']]);
5275 $in_reply_to['status_id'] = null;
5276 $in_reply_to['user_id'] = null;
5277 $in_reply_to['status_id_str'] = null;
5278 $in_reply_to['user_id_str'] = null;
5279 $in_reply_to['screen_name'] = null;
5283 return $in_reply_to;
5288 * @param string $text
5291 * @throws InternalServerErrorException
5293 function api_clean_plain_items($text)
5295 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5297 $text = BBCode::cleanPictureLinks($text);
5298 $URLSearchString = "^\[\]";
5300 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5302 if ($include_entities == "true") {
5303 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5306 // Simplify "attachment" element
5307 $text = BBCode::removeAttachment($text);
5314 * @param array $contacts
5318 function api_best_nickname(&$contacts)
5322 if (count($contacts) == 0) {
5326 foreach ($contacts as $contact) {
5327 if ($contact["network"] == "") {
5328 $contact["network"] = "dfrn";
5329 $best_contact = [$contact];
5333 if (sizeof($best_contact) == 0) {
5334 foreach ($contacts as $contact) {
5335 if ($contact["network"] == "dfrn") {
5336 $best_contact = [$contact];
5341 if (sizeof($best_contact) == 0) {
5342 foreach ($contacts as $contact) {
5343 if ($contact["network"] == "dspr") {
5344 $best_contact = [$contact];
5349 if (sizeof($best_contact) == 0) {
5350 foreach ($contacts as $contact) {
5351 if ($contact["network"] == "stat") {
5352 $best_contact = [$contact];
5357 if (sizeof($best_contact) == 0) {
5358 foreach ($contacts as $contact) {
5359 if ($contact["network"] == "pump") {
5360 $best_contact = [$contact];
5365 if (sizeof($best_contact) == 0) {
5366 foreach ($contacts as $contact) {
5367 if ($contact["network"] == "twit") {
5368 $best_contact = [$contact];
5373 if (sizeof($best_contact) == 1) {
5374 $contacts = $best_contact;
5376 $contacts = [$contacts[0]];
5381 * Return all or a specified group of the user with the containing contacts.
5383 * @param string $type Return type (atom, rss, xml, json)
5385 * @return array|string
5386 * @throws BadRequestException
5387 * @throws ForbiddenException
5388 * @throws ImagickException
5389 * @throws InternalServerErrorException
5390 * @throws UnauthorizedException
5392 function api_friendica_group_show($type)
5396 if (api_user() === false) {
5397 throw new ForbiddenException();
5401 $user_info = api_get_user($a);
5402 $gid = $_REQUEST['gid'] ?? 0;
5403 $uid = $user_info['uid'];
5405 // get data of the specified group id or all groups if not specified
5408 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5412 // error message if specified gid is not in database
5413 if (!DBA::isResult($r)) {
5414 throw new BadRequestException("gid not available");
5418 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5423 // loop through all groups and retrieve all members for adding data in the user array
5425 foreach ($r as $rr) {
5426 $members = Contact::getByGroupId($rr['id']);
5429 if ($type == "xml") {
5430 $user_element = "users";
5432 foreach ($members as $member) {
5433 $user = api_get_user($a, $member['nurl']);
5434 $users[$k++.":user"] = $user;
5437 $user_element = "user";
5438 foreach ($members as $member) {
5439 $user = api_get_user($a, $member['nurl']);
5443 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5445 return api_format_data("groups", $type, ['group' => $grps]);
5447 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5451 * Delete the specified group of the user.
5453 * @param string $type Return type (atom, rss, xml, json)
5455 * @return array|string
5456 * @throws BadRequestException
5457 * @throws ForbiddenException
5458 * @throws ImagickException
5459 * @throws InternalServerErrorException
5460 * @throws UnauthorizedException
5462 function api_friendica_group_delete($type)
5466 if (api_user() === false) {
5467 throw new ForbiddenException();
5471 $user_info = api_get_user($a);
5472 $gid = $_REQUEST['gid'] ?? 0;
5473 $name = $_REQUEST['name'] ?? '';
5474 $uid = $user_info['uid'];
5476 // error if no gid specified
5477 if ($gid == 0 || $name == "") {
5478 throw new BadRequestException('gid or name not specified');
5481 // get data of the specified group id
5483 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5487 // error message if specified gid is not in database
5488 if (!DBA::isResult($r)) {
5489 throw new BadRequestException('gid not available');
5492 // get data of the specified group id and group name
5494 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5499 // error message if specified gid is not in database
5500 if (!DBA::isResult($rname)) {
5501 throw new BadRequestException('wrong group name');
5505 $ret = Group::removeByName($uid, $name);
5508 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5509 return api_format_data("group_delete", $type, ['result' => $success]);
5511 throw new BadRequestException('other API error');
5514 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5519 * @param string $type Return type (atom, rss, xml, json)
5521 * @return array|string
5522 * @throws BadRequestException
5523 * @throws ForbiddenException
5524 * @throws ImagickException
5525 * @throws InternalServerErrorException
5526 * @throws UnauthorizedException
5527 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5529 function api_lists_destroy($type)
5533 if (api_user() === false) {
5534 throw new ForbiddenException();
5538 $user_info = api_get_user($a);
5539 $gid = $_REQUEST['list_id'] ?? 0;
5540 $uid = $user_info['uid'];
5542 // error if no gid specified
5544 throw new BadRequestException('gid not specified');
5547 // get data of the specified group id
5548 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5549 // error message if specified gid is not in database
5551 throw new BadRequestException('gid not available');
5554 if (Group::remove($gid)) {
5556 'name' => $group['name'],
5557 'id' => intval($gid),
5558 'id_str' => (string) $gid,
5559 'user' => $user_info
5562 return api_format_data("lists", $type, ['lists' => $list]);
5565 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5568 * Add a new group to the database.
5570 * @param string $name Group name
5571 * @param int $uid User ID
5572 * @param array $users List of users to add to the group
5575 * @throws BadRequestException
5577 function group_create($name, $uid, $users = [])
5579 // error if no name specified
5581 throw new BadRequestException('group name not specified');
5584 // get data of the specified group name
5586 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5590 // error message if specified group name already exists
5591 if (DBA::isResult($rname)) {
5592 throw new BadRequestException('group name already exists');
5595 // check if specified group name is a deleted group
5597 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5601 // error message if specified group name already exists
5602 if (DBA::isResult($rname)) {
5603 $reactivate_group = true;
5607 $ret = Group::create($uid, $name);
5609 $gid = Group::getIdByName($uid, $name);
5611 throw new BadRequestException('other API error');
5615 $erroraddinguser = false;
5617 foreach ($users as $user) {
5618 $cid = $user['cid'];
5619 // check if user really exists as contact
5621 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5625 if (count($contact)) {
5626 Group::addMember($gid, $cid);
5628 $erroraddinguser = true;
5629 $errorusers[] = $cid;
5633 // return success message incl. missing users in array
5634 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5636 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5640 * Create the specified group with the posted array of contacts.
5642 * @param string $type Return type (atom, rss, xml, json)
5644 * @return array|string
5645 * @throws BadRequestException
5646 * @throws ForbiddenException
5647 * @throws ImagickException
5648 * @throws InternalServerErrorException
5649 * @throws UnauthorizedException
5651 function api_friendica_group_create($type)
5655 if (api_user() === false) {
5656 throw new ForbiddenException();
5660 $user_info = api_get_user($a);
5661 $name = $_REQUEST['name'] ?? '';
5662 $uid = $user_info['uid'];
5663 $json = json_decode($_POST['json'], true);
5664 $users = $json['user'];
5666 $success = group_create($name, $uid, $users);
5668 return api_format_data("group_create", $type, ['result' => $success]);
5670 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5673 * Create a new group.
5675 * @param string $type Return type (atom, rss, xml, json)
5677 * @return array|string
5678 * @throws BadRequestException
5679 * @throws ForbiddenException
5680 * @throws ImagickException
5681 * @throws InternalServerErrorException
5682 * @throws UnauthorizedException
5683 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5685 function api_lists_create($type)
5689 if (api_user() === false) {
5690 throw new ForbiddenException();
5694 $user_info = api_get_user($a);
5695 $name = $_REQUEST['name'] ?? '';
5696 $uid = $user_info['uid'];
5698 $success = group_create($name, $uid);
5699 if ($success['success']) {
5701 'name' => $success['name'],
5702 'id' => intval($success['gid']),
5703 'id_str' => (string) $success['gid'],
5704 'user' => $user_info
5707 return api_format_data("lists", $type, ['lists'=>$grp]);
5710 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5713 * Update the specified group with the posted array of contacts.
5715 * @param string $type Return type (atom, rss, xml, json)
5717 * @return array|string
5718 * @throws BadRequestException
5719 * @throws ForbiddenException
5720 * @throws ImagickException
5721 * @throws InternalServerErrorException
5722 * @throws UnauthorizedException
5724 function api_friendica_group_update($type)
5728 if (api_user() === false) {
5729 throw new ForbiddenException();
5733 $user_info = api_get_user($a);
5734 $uid = $user_info['uid'];
5735 $gid = $_REQUEST['gid'] ?? 0;
5736 $name = $_REQUEST['name'] ?? '';
5737 $json = json_decode($_POST['json'], true);
5738 $users = $json['user'];
5740 // error if no name specified
5742 throw new BadRequestException('group name not specified');
5745 // error if no gid specified
5747 throw new BadRequestException('gid not specified');
5751 $members = Contact::getByGroupId($gid);
5752 foreach ($members as $member) {
5753 $cid = $member['id'];
5754 foreach ($users as $user) {
5755 $found = ($user['cid'] == $cid ? true : false);
5757 if (!isset($found) || !$found) {
5758 Group::removeMemberByName($uid, $name, $cid);
5763 $erroraddinguser = false;
5765 foreach ($users as $user) {
5766 $cid = $user['cid'];
5767 // check if user really exists as contact
5769 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5774 if (count($contact)) {
5775 Group::addMember($gid, $cid);
5777 $erroraddinguser = true;
5778 $errorusers[] = $cid;
5782 // return success message incl. missing users in array
5783 $status = ($erroraddinguser ? "missing user" : "ok");
5784 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5785 return api_format_data("group_update", $type, ['result' => $success]);
5788 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5791 * Update information about a group.
5793 * @param string $type Return type (atom, rss, xml, json)
5795 * @return array|string
5796 * @throws BadRequestException
5797 * @throws ForbiddenException
5798 * @throws ImagickException
5799 * @throws InternalServerErrorException
5800 * @throws UnauthorizedException
5801 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5803 function api_lists_update($type)
5807 if (api_user() === false) {
5808 throw new ForbiddenException();
5812 $user_info = api_get_user($a);
5813 $gid = $_REQUEST['list_id'] ?? 0;
5814 $name = $_REQUEST['name'] ?? '';
5815 $uid = $user_info['uid'];
5817 // error if no gid specified
5819 throw new BadRequestException('gid not specified');
5822 // get data of the specified group id
5823 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5824 // error message if specified gid is not in database
5826 throw new BadRequestException('gid not available');
5829 if (Group::update($gid, $name)) {
5832 'id' => intval($gid),
5833 'id_str' => (string) $gid,
5834 'user' => $user_info
5837 return api_format_data("lists", $type, ['lists' => $list]);
5841 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5845 * @param string $type Return type (atom, rss, xml, json)
5847 * @return array|string
5848 * @throws BadRequestException
5849 * @throws ForbiddenException
5850 * @throws ImagickException
5851 * @throws InternalServerErrorException
5853 function api_friendica_activity($type)
5857 if (api_user() === false) {
5858 throw new ForbiddenException();
5860 $verb = strtolower($a->argv[3]);
5861 $verb = preg_replace("|\..*$|", "", $verb);
5863 $id = $_REQUEST['id'] ?? 0;
5865 $res = Item::performLike($id, $verb);
5868 if ($type == "xml") {
5873 return api_format_data('ok', $type, ['ok' => $ok]);
5875 throw new BadRequestException('Error adding activity');
5879 /// @TODO move to top of file or somewhere better
5880 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5881 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5882 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5883 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5884 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5885 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5886 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5887 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5888 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5889 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5892 * Returns notifications
5894 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5895 * @return string|array
5896 * @throws BadRequestException
5897 * @throws ForbiddenException
5898 * @throws InternalServerErrorException
5900 function api_friendica_notification($type)
5904 if (api_user() === false) {
5905 throw new ForbiddenException();
5908 throw new BadRequestException("Invalid argument count");
5911 $notifications = DI::notify()->select(['uid' => api_user()], ['order' => ['seen' => 'ASC', 'date' => 'DESC'], 'limit' => 50]);
5913 if ($type == "xml") {
5915 if (!empty($notifications)) {
5916 foreach ($notifications as $notification) {
5917 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5921 $result = $xmlnotes;
5922 } elseif (count($notifications) > 0) {
5923 $result = $notifications->getArrayCopy();
5928 return api_format_data("notes", $type, ['note' => $result]);
5932 * Set notification as seen and returns associated item (if possible)
5934 * POST request with 'id' param as notification id
5936 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5937 * @return string|array
5938 * @throws BadRequestException
5939 * @throws ForbiddenException
5940 * @throws ImagickException
5941 * @throws InternalServerErrorException
5942 * @throws UnauthorizedException
5944 function api_friendica_notification_seen($type)
5947 $user_info = api_get_user($a);
5949 if (api_user() === false || $user_info === false) {
5950 throw new ForbiddenException();
5952 if ($a->argc !== 4) {
5953 throw new BadRequestException("Invalid argument count");
5956 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5959 $notification = DI::notify()->getByID($id);
5960 $notification->setSeen();
5962 if ($notification->otype === Notify::OTYPE_ITEM) {
5963 $item = Item::selectFirstForUser(api_user(), [], ['id' => $notification->iid, 'uid' => api_user()]);
5964 if (DBA::isResult($item)) {
5965 // we found the item, return it to the user
5966 $ret = api_format_items([$item], $user_info, false, $type);
5967 $data = ['status' => $ret];
5968 return api_format_data("status", $type, $data);
5970 // the item can't be found, but we set the notification as seen, so we count this as a success
5972 return api_format_data('result', $type, ['result' => "success"]);
5973 } catch (NotFoundException $e) {
5974 throw new BadRequestException('Invalid argument');
5978 /// @TODO move to top of file or somewhere better
5979 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5980 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5983 * update a direct_message to seen state
5985 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5986 * @return string|array (success result=ok, error result=error with error message)
5987 * @throws BadRequestException
5988 * @throws ForbiddenException
5989 * @throws ImagickException
5990 * @throws InternalServerErrorException
5991 * @throws UnauthorizedException
5993 function api_friendica_direct_messages_setseen($type)
5996 if (api_user() === false) {
5997 throw new ForbiddenException();
6001 $user_info = api_get_user($a);
6002 $uid = $user_info['uid'];
6003 $id = $_REQUEST['id'] ?? 0;
6005 // return error if id is zero
6007 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6008 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6011 // error message if specified id is not in database
6012 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6013 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6014 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6017 // update seen indicator
6018 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6022 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6023 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6025 $answer = ['result' => 'error', 'message' => 'unknown error'];
6026 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6030 /// @TODO move to top of file or somewhere better
6031 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6034 * search for direct_messages containing a searchstring through api
6036 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6037 * @param string $box
6038 * @return string|array (success: success=true if found and search_result contains found messages,
6039 * success=false if nothing was found, search_result='nothing found',
6040 * error: result=error with error message)
6041 * @throws BadRequestException
6042 * @throws ForbiddenException
6043 * @throws ImagickException
6044 * @throws InternalServerErrorException
6045 * @throws UnauthorizedException
6047 function api_friendica_direct_messages_search($type, $box = "")
6051 if (api_user() === false) {
6052 throw new ForbiddenException();
6056 $user_info = api_get_user($a);
6057 $searchstring = $_REQUEST['searchstring'] ?? '';
6058 $uid = $user_info['uid'];
6060 // error if no searchstring specified
6061 if ($searchstring == "") {
6062 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6063 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6066 // get data for the specified searchstring
6068 "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",
6070 DBA::escape('%'.$searchstring.'%')
6073 $profile_url = $user_info["url"];
6075 // message if nothing was found
6076 if (!DBA::isResult($r)) {
6077 $success = ['success' => false, 'search_results' => 'problem with query'];
6078 } elseif (count($r) == 0) {
6079 $success = ['success' => false, 'search_results' => 'nothing found'];
6082 foreach ($r as $item) {
6083 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6084 $recipient = $user_info;
6085 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6086 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6087 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6088 $sender = $user_info;
6091 if (isset($recipient) && isset($sender)) {
6092 $ret[] = api_format_messages($item, $recipient, $sender);
6095 $success = ['success' => true, 'search_results' => $ret];
6098 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6101 /// @TODO move to top of file or somewhere better
6102 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6105 * return data of all the profiles a user has to the client
6107 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6108 * @return string|array
6109 * @throws BadRequestException
6110 * @throws ForbiddenException
6111 * @throws ImagickException
6112 * @throws InternalServerErrorException
6113 * @throws UnauthorizedException
6115 function api_friendica_profile_show($type)
6119 if (api_user() === false) {
6120 throw new ForbiddenException();
6124 $profile_id = $_REQUEST['profile_id'] ?? 0;
6126 // retrieve general information about profiles for user
6127 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6128 $directory = DI::config()->get('system', 'directory');
6130 // get data of the specified profile id or all profiles of the user if not specified
6131 if ($profile_id != 0) {
6132 $r = Profile::getById(api_user(), $profile_id);
6133 // error message if specified gid is not in database
6134 if (!DBA::isResult($r)) {
6135 throw new BadRequestException("profile_id not available");
6138 $r = Profile::getListByUser(api_user());
6140 // loop through all returned profiles and retrieve data and users
6143 if (DBA::isResult($r)) {
6144 foreach ($r as $rr) {
6145 $profile = api_format_items_profiles($rr);
6147 // select all users from contact table, loop and prepare standard return for user data
6149 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6150 foreach ($nurls as $nurl) {
6151 $user = api_get_user($a, $nurl['nurl']);
6152 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6154 $profile['users'] = $users;
6156 // add prepared profile data to array for final return
6157 if ($type == "xml") {
6158 $profiles[$k++ . ":profile"] = $profile;
6160 $profiles[] = $profile;
6165 // return settings, authenticated user and profiles data
6166 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6168 $result = ['multi_profiles' => $multi_profiles ? true : false,
6169 'global_dir' => $directory,
6170 'friendica_owner' => api_get_user($a, $self['nurl']),
6171 'profiles' => $profiles];
6172 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6174 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6177 * Returns a list of saved searches.
6179 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6181 * @param string $type Return format: json or xml
6183 * @return string|array
6186 function api_saved_searches_list($type)
6188 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6191 while ($term = DBA::fetch($terms)) {
6193 'created_at' => api_date(time()),
6194 'id' => intval($term['id']),
6195 'id_str' => $term['id'],
6196 'name' => $term['term'],
6198 'query' => $term['term']
6204 return api_format_data("terms", $type, ['terms' => $result]);
6207 /// @TODO move to top of file or somewhere better
6208 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6211 * Number of comments
6213 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6215 * @param object $data [Status, Status]
6219 function bindComments(&$data)
6221 if (count($data) == 0) {
6227 foreach ($data as $item) {
6228 $ids[] = $item['id'];
6231 $idStr = DBA::escape(implode(', ', $ids));
6232 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6233 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6234 $itemsData = DBA::toArray($items);
6236 foreach ($itemsData as $item) {
6237 $comments[$item['parent']] = $item['comments'];
6240 foreach ($data as $idx => $item) {
6242 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6247 @TODO Maybe open to implement?
6249 [pagename] => api/1.1/statuses/lookup.json
6250 [id] => 605138389168451584
6251 [include_cards] => true
6252 [cards_platform] => Android-12
6253 [include_entities] => true
6254 [include_my_retweet] => 1
6256 [include_reply_count] => true
6257 [include_descendent_reply_count] => true
6261 Not implemented by now:
6262 statuses/retweets_of_me
6267 account/update_location
6268 account/update_profile_background_image
6271 friendica/profile/update
6272 friendica/profile/create
6273 friendica/profile/delete
6275 Not implemented in status.net:
6276 statuses/retweeted_to_me
6277 statuses/retweeted_by_me
6278 direct_messages/destroy
6280 account/update_delivery_device
6281 notifications/follow