3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\BaseObject;
11 use Friendica\Content\ContactSelector;
12 use Friendica\Content\Feature;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\HTML;
15 use Friendica\Core\Config;
16 use Friendica\Core\Hook;
17 use Friendica\Core\L10n;
18 use Friendica\Core\Logger;
19 use Friendica\Core\PConfig;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\Session;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Mail;
29 use Friendica\Model\Notify;
30 use Friendica\Model\Photo;
31 use Friendica\Model\Profile;
32 use Friendica\Model\User;
33 use Friendica\Network\FKOAuth1;
34 use Friendica\Network\HTTPException;
35 use Friendica\Network\HTTPException\BadRequestException;
36 use Friendica\Network\HTTPException\ExpectationFailedException;
37 use Friendica\Network\HTTPException\ForbiddenException;
38 use Friendica\Network\HTTPException\InternalServerErrorException;
39 use Friendica\Network\HTTPException\MethodNotAllowedException;
40 use Friendica\Network\HTTPException\NotFoundException;
41 use Friendica\Network\HTTPException\NotImplementedException;
42 use Friendica\Network\HTTPException\TooManyRequestsException;
43 use Friendica\Network\HTTPException\UnauthorizedException;
44 use Friendica\Object\Image;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\Diaspora;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Images;
49 use Friendica\Util\Network;
50 use Friendica\Util\Proxy as ProxyUtils;
51 use Friendica\Util\Strings;
52 use Friendica\Util\XML;
54 require_once __DIR__ . '/../mod/share.php';
55 require_once __DIR__ . '/../mod/item.php';
56 require_once __DIR__ . '/../mod/wall_upload.php';
58 define('API_METHOD_ANY', '*');
59 define('API_METHOD_GET', 'GET');
60 define('API_METHOD_POST', 'POST,PUT');
61 define('API_METHOD_DELETE', 'POST,DELETE');
63 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).
73 * @brief Auth API user
77 if (!empty($_SESSION['allow_api'])) {
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
90 * @brief Get source name from API client
93 * Client source name, default to "api" if unset/unknown
98 if (requestdata('source')) {
99 return requestdata('source');
102 // Support for known clients that doesn't send a source name
103 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
104 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
108 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
110 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
117 * @brief Format date for API
119 * @param string $str Source date, as UTC
120 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
123 function api_date($str)
125 // Wed May 23 06:01:13 +0000 2007
126 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
130 * Register a function to be the endpoint for defined API path.
132 * @brief Register API endpoint
134 * @param string $path API URL path, relative to System::baseUrl()
135 * @param string $func Function name to call on path request
136 * @param bool $auth API need logged user
137 * @param string $method HTTP method reqiured to call this endpoint.
138 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
139 * Default to API_METHOD_ANY
141 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
151 // Workaround for hotot
152 $path = str_replace("api/", "api/1.1/", $path);
162 * Log in user via OAuth1 or Simple HTTP Auth.
163 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
165 * @brief Login API user
168 * @throws ForbiddenException
169 * @throws InternalServerErrorException
170 * @throws UnauthorizedException
171 * @hook 'authenticate'
173 * 'username' => username from login form
174 * 'password' => password from login form
175 * 'authenticated' => return status,
176 * 'user_record' => return authenticated user record
178 function api_login(App $a)
180 $oauth1 = new FKOAuth1();
183 $request = OAuthRequest::from_request();
184 list($consumer, $token) = $oauth1->verify_request($request);
185 if (!is_null($token)) {
186 $oauth1->loginUser($token->uid);
187 Session::set('allow_api', true);
190 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
191 var_dump($consumer, $token);
193 } catch (Exception $e) {
194 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
197 // workaround for HTTP-auth in CGI mode
198 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
199 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
200 if (strlen($userpass)) {
201 list($name, $password) = explode(':', $userpass);
202 $_SERVER['PHP_AUTH_USER'] = $name;
203 $_SERVER['PHP_AUTH_PW'] = $password;
207 if (empty($_SERVER['PHP_AUTH_USER'])) {
208 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
209 header('WWW-Authenticate: Basic realm="Friendica"');
210 throw new UnauthorizedException("This API requires login");
213 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
214 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
216 // allow "user@server" login (but ignore 'server' part)
217 $at = strstr($user, "@", true);
222 // next code from mod/auth.php. needs better solution
226 'username' => trim($user),
227 'password' => trim($password),
228 'authenticated' => 0,
229 'user_record' => null,
233 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
234 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
235 * and later addons should not interfere with an earlier one that succeeded.
237 Hook::callAll('authenticate', $addon_auth);
239 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
240 $record = $addon_auth['user_record'];
242 $user_id = User::authenticate(trim($user), trim($password), true);
243 if ($user_id !== false) {
244 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
248 if (!DBA::isResult($record)) {
249 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
250 header('WWW-Authenticate: Basic realm="Friendica"');
251 //header('HTTP/1.0 401 Unauthorized');
252 //die('This api requires login');
253 throw new UnauthorizedException("This API requires login");
256 Session::setAuthenticatedForUser($a, $record);
258 $_SESSION["allow_api"] = true;
260 Hook::callAll('logged_in', $a->user);
264 * API endpoints can define which HTTP method to accept when called.
265 * This function check the current HTTP method agains endpoint
268 * @brief Check HTTP method of called API
270 * @param string $method Required methods, uppercase, separated by comma
273 function api_check_method($method)
275 if ($method == "*") {
278 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
282 * Authenticate user, call registered API function, set HTTP headers
284 * @brief Main API entry point
287 * @return string|array API call result
290 function api_call(App $a)
292 global $API, $called_api;
295 if (strpos($a->query_string, ".xml") > 0) {
298 if (strpos($a->query_string, ".json") > 0) {
301 if (strpos($a->query_string, ".rss") > 0) {
304 if (strpos($a->query_string, ".atom") > 0) {
309 foreach ($API as $p => $info) {
310 if (strpos($a->query_string, $p) === 0) {
311 if (!api_check_method($info['method'])) {
312 throw new MethodNotAllowedException();
315 $called_api = explode("/", $p);
316 //unset($_SERVER['PHP_AUTH_USER']);
318 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
319 if (!empty($info['auth']) && api_user() === false) {
323 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
324 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
326 $stamp = microtime(true);
327 $return = call_user_func($info['func'], $type);
328 $duration = floatval(microtime(true) - $stamp);
330 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
332 $a->getProfiler()->saveLog($a->getLogger(), API_LOG_PREFIX . 'performance');
334 if (false === $return) {
336 * api function returned false withour throw an
337 * exception. This should not happend, throw a 500
339 throw new InternalServerErrorException();
344 header("Content-Type: text/xml");
347 header("Content-Type: application/json");
348 if (!empty($return)) {
349 $json = json_encode(end($return));
350 if (!empty($_GET['callback'])) {
351 $json = $_GET['callback'] . "(" . $json . ")";
357 header("Content-Type: application/rss+xml");
358 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
361 header("Content-Type: application/atom+xml");
362 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
369 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => $a->query_string]);
370 throw new NotImplementedException();
371 } catch (HTTPException $e) {
372 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
373 return api_error($type, $e);
378 * @brief Format API error string
380 * @param string $type Return type (xml, json, rss, as)
381 * @param object $e HTTPException Error object
382 * @return string|array error message formatted as $type
384 function api_error($type, $e)
388 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
389 /// @TODO: https://dev.twitter.com/overview/api/response-codes
391 $error = ["error" => $error,
392 "code" => $e->getCode() . " " . $e->httpdesc,
393 "request" => $a->query_string];
395 $return = api_format_data('status', $type, ['status' => $error]);
399 header("Content-Type: text/xml");
402 header("Content-Type: application/json");
403 $return = json_encode($return);
406 header("Content-Type: application/rss+xml");
409 header("Content-Type: application/atom+xml");
417 * @brief Set values for RSS template
420 * @param array $arr Array to be passed to template
421 * @param array $user_info User info
423 * @throws BadRequestException
424 * @throws ImagickException
425 * @throws InternalServerErrorException
426 * @throws UnauthorizedException
427 * @todo find proper type-hints
429 function api_rss_extra(App $a, $arr, $user_info)
431 if (is_null($user_info)) {
432 $user_info = api_get_user($a);
435 $arr['$user'] = $user_info;
437 'alternate' => $user_info['url'],
438 'self' => System::baseUrl() . "/" . $a->query_string,
439 'base' => System::baseUrl(),
440 'updated' => api_date(null),
441 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
442 'language' => $user_info['lang'],
443 'logo' => System::baseUrl() . "/images/friendica-32.png",
451 * @brief Unique contact to contact url.
453 * @param int $id Contact id
454 * @return bool|string
455 * Contact url or False if contact id is unknown
458 function api_unique_id_to_nurl($id)
460 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
462 if (DBA::isResult($r)) {
470 * @brief Get user info array.
473 * @param int|string $contact_id Contact ID or URL
475 * @throws BadRequestException
476 * @throws ImagickException
477 * @throws InternalServerErrorException
478 * @throws UnauthorizedException
480 function api_get_user(App $a, $contact_id = null)
488 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
490 // Searching for contact URL
491 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
492 $user = DBA::escape(Strings::normaliseLink($contact_id));
494 $extra_query = "AND `contact`.`nurl` = '%s' ";
495 if (api_user() !== false) {
496 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
500 // Searching for contact id with uid = 0
501 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
502 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
505 throw new BadRequestException("User ID ".$contact_id." not found.");
509 $extra_query = "AND `contact`.`nurl` = '%s' ";
510 if (api_user() !== false) {
511 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
515 if (is_null($user) && !empty($_GET['user_id'])) {
516 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
519 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
523 $extra_query = "AND `contact`.`nurl` = '%s' ";
524 if (api_user() !== false) {
525 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
528 if (is_null($user) && !empty($_GET['screen_name'])) {
529 $user = DBA::escape($_GET['screen_name']);
530 $extra_query = "AND `contact`.`nick` = '%s' ";
531 if (api_user() !== false) {
532 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
536 if (is_null($user) && !empty($_GET['profileurl'])) {
537 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
538 $extra_query = "AND `contact`.`nurl` = '%s' ";
539 if (api_user() !== false) {
540 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
544 // $called_api is the API path exploded on / and is expected to have at least 2 elements
545 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
546 $argid = count($called_api);
547 if (!empty($a->argv[$argid])) {
548 $data = explode(".", $a->argv[$argid]);
549 if (count($data) > 1) {
550 list($user, $null) = $data;
553 if (is_numeric($user)) {
554 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
558 $extra_query = "AND `contact`.`nurl` = '%s' ";
559 if (api_user() !== false) {
560 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
564 $user = DBA::escape($user);
565 $extra_query = "AND `contact`.`nick` = '%s' ";
566 if (api_user() !== false) {
567 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
572 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
575 if (api_user() === false) {
579 $user = $_SESSION['uid'];
580 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
584 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
588 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
594 // Selecting the id by priority, friendica first
595 if (is_array($uinfo)) {
596 api_best_nickname($uinfo);
599 // if the contact wasn't found, fetch it from the contacts with uid = 0
600 if (!DBA::isResult($uinfo)) {
602 throw new BadRequestException("User not found.");
605 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
607 if (DBA::isResult($contact)) {
609 'id' => $contact["id"],
610 'id_str' => (string) $contact["id"],
611 'name' => $contact["name"],
612 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
613 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
614 'description' => BBCode::toPlaintext($contact["about"]),
615 'profile_image_url' => $contact["micro"],
616 'profile_image_url_https' => $contact["micro"],
617 'profile_image_url_profile_size' => $contact["thumb"],
618 'profile_image_url_large' => $contact["photo"],
619 'url' => $contact["url"],
620 'protected' => false,
621 'followers_count' => 0,
622 'friends_count' => 0,
624 'created_at' => api_date($contact["created"]),
625 'favourites_count' => 0,
627 'time_zone' => 'UTC',
628 'geo_enabled' => false,
630 'statuses_count' => 0,
632 'contributors_enabled' => false,
633 'is_translator' => false,
634 'is_translation_enabled' => false,
635 'following' => false,
636 'follow_request_sent' => false,
637 'statusnet_blocking' => false,
638 'notifications' => false,
639 'statusnet_profile_url' => $contact["url"],
641 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
642 'pid' => Contact::getIdForURL($contact["url"], 0, true),
644 'network' => $contact["network"],
649 throw new BadRequestException("User ".$url." not found.");
653 if ($uinfo[0]['self']) {
654 if ($uinfo[0]['network'] == "") {
655 $uinfo[0]['network'] = Protocol::DFRN;
658 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
659 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
666 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
668 if (!empty($profile['about'])) {
669 $description = $profile['about'];
671 $description = $uinfo[0]["about"];
674 if (!empty($usr['default-location'])) {
675 $location = $usr['default-location'];
676 } elseif (!empty($uinfo[0]["location"])) {
677 $location = $uinfo[0]["location"];
679 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
683 'id' => intval($pcontact_id),
684 'id_str' => (string) intval($pcontact_id),
685 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
686 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
687 'location' => $location,
688 'description' => BBCode::toPlaintext($description),
689 'profile_image_url' => $uinfo[0]['micro'],
690 'profile_image_url_https' => $uinfo[0]['micro'],
691 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
692 'profile_image_url_large' => $uinfo[0]["photo"],
693 'url' => $uinfo[0]['url'],
694 'protected' => false,
695 'followers_count' => intval($countfollowers),
696 'friends_count' => intval($countfriends),
698 'created_at' => api_date($uinfo[0]['created']),
699 'favourites_count' => intval($starred),
701 'time_zone' => 'UTC',
702 'geo_enabled' => false,
704 'statuses_count' => intval($countitems),
706 'contributors_enabled' => false,
707 'is_translator' => false,
708 'is_translation_enabled' => false,
709 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
710 'follow_request_sent' => false,
711 'statusnet_blocking' => false,
712 'notifications' => false,
714 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
715 'statusnet_profile_url' => $uinfo[0]['url'],
716 'uid' => intval($uinfo[0]['uid']),
717 'cid' => intval($uinfo[0]['cid']),
718 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
719 'self' => $uinfo[0]['self'],
720 'network' => $uinfo[0]['network'],
723 // If this is a local user and it uses Frio, we can get its color preferences.
725 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
726 if ($theme_info['theme'] === 'frio') {
727 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
729 if ($schema && ($schema != '---')) {
730 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
731 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
732 require_once $schemefile;
735 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
736 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
737 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
739 if (empty($nav_bg)) {
742 if (empty($link_color)) {
743 $link_color = "#6fdbe8";
745 if (empty($bgcolor)) {
746 $bgcolor = "#ededed";
749 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
750 $ret['profile_link_color'] = str_replace('#', '', $link_color);
751 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
759 * @brief return api-formatted array for item's author and owner
762 * @param array $item item from db
763 * @return array(array:author, array:owner)
764 * @throws BadRequestException
765 * @throws ImagickException
766 * @throws InternalServerErrorException
767 * @throws UnauthorizedException
769 function api_item_get_user(App $a, $item)
771 $status_user = api_get_user($a, $item['author-id'] ?? null);
773 $author_user = $status_user;
775 $status_user["protected"] = $item['private'] ?? 0;
777 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
778 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
780 $owner_user = $author_user;
783 return ([$status_user, $author_user, $owner_user]);
787 * @brief walks recursively through an array with the possibility to change value and key
789 * @param array $array The array to walk through
790 * @param callable $callback The callback function
792 * @return array the transformed array
794 function api_walk_recursive(array &$array, callable $callback)
798 foreach ($array as $k => $v) {
800 if ($callback($v, $k)) {
801 $new_array[$k] = api_walk_recursive($v, $callback);
804 if ($callback($v, $k)) {
815 * @brief Callback function to transform the array in an array that can be transformed in a XML file
817 * @param mixed $item Array item value
818 * @param string $key Array key
820 * @return boolean Should the array item be deleted?
822 function api_reformat_xml(&$item, &$key)
824 if (is_bool($item)) {
825 $item = ($item ? "true" : "false");
828 if (substr($key, 0, 10) == "statusnet_") {
829 $key = "statusnet:".substr($key, 10);
830 } elseif (substr($key, 0, 10) == "friendica_") {
831 $key = "friendica:".substr($key, 10);
833 /// @TODO old-lost code?
835 // $key = "default:".$key;
841 * @brief Creates the XML from a JSON style array
843 * @param array $data JSON style array
844 * @param string $root_element Name of the root element
846 * @return string The XML data
848 function api_create_xml(array $data, $root_element)
850 $childname = key($data);
851 $data2 = array_pop($data);
853 $namespaces = ["" => "http://api.twitter.com",
854 "statusnet" => "http://status.net/schema/api/1/",
855 "friendica" => "http://friendi.ca/schema/api/1/",
856 "georss" => "http://www.georss.org/georss"];
858 /// @todo Auto detection of needed namespaces
859 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
863 if (is_array($data2)) {
865 api_walk_recursive($data2, "api_reformat_xml");
871 foreach ($data2 as $item) {
872 $data4[$i++ . ":" . $childname] = $item;
879 $data3 = [$root_element => $data2];
881 $ret = XML::fromArray($data3, $xml, false, $namespaces);
886 * @brief Formats the data according to the data type
888 * @param string $root_element Name of the root element
889 * @param string $type Return type (atom, rss, xml, json)
890 * @param array $data JSON style array
892 * @return array|string (string|array) XML data or JSON data
894 function api_format_data($root_element, $type, $data)
900 $ret = api_create_xml($data, $root_element);
915 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
916 * returns a 401 status code and an error message if not.
918 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
920 * @param string $type Return type (atom, rss, xml, json)
921 * @return array|string
922 * @throws BadRequestException
923 * @throws ForbiddenException
924 * @throws ImagickException
925 * @throws InternalServerErrorException
926 * @throws UnauthorizedException
928 function api_account_verify_credentials($type)
932 if (api_user() === false) {
933 throw new ForbiddenException();
936 unset($_REQUEST["user_id"]);
937 unset($_GET["user_id"]);
939 unset($_REQUEST["screen_name"]);
940 unset($_GET["screen_name"]);
942 $skip_status = $_REQUEST['skip_status'] ?? false;
944 $user_info = api_get_user($a);
946 // "verified" isn't used here in the standard
947 unset($user_info["verified"]);
949 // - Adding last status
951 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
953 $user_info['status'] = api_format_item($item, $type);
957 // "uid" and "self" are only needed for some internal stuff, so remove it from here
958 unset($user_info["uid"]);
959 unset($user_info["self"]);
961 return api_format_data("user", $type, ['user' => $user_info]);
964 /// @TODO move to top of file or somewhere better
965 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
968 * Get data from $_POST or $_GET
973 function requestdata($k)
975 if (!empty($_POST[$k])) {
978 if (!empty($_GET[$k])) {
985 * Deprecated function to upload media.
987 * @param string $type Return type (atom, rss, xml, json)
989 * @return array|string
990 * @throws BadRequestException
991 * @throws ForbiddenException
992 * @throws ImagickException
993 * @throws InternalServerErrorException
994 * @throws UnauthorizedException
996 function api_statuses_mediap($type)
1000 if (api_user() === false) {
1001 Logger::log('api_statuses_update: no user');
1002 throw new ForbiddenException();
1004 $user_info = api_get_user($a);
1006 $_REQUEST['profile_uid'] = api_user();
1007 $_REQUEST['api_source'] = true;
1008 $txt = requestdata('status');
1009 /// @TODO old-lost code?
1010 //$txt = urldecode(requestdata('status'));
1012 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1013 $txt = HTML::toBBCodeVideo($txt);
1014 $config = HTMLPurifier_Config::createDefault();
1015 $config->set('Cache.DefinitionImpl', null);
1016 $purifier = new HTMLPurifier($config);
1017 $txt = $purifier->purify($txt);
1019 $txt = HTML::toBBCode($txt);
1021 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1023 $picture = wall_upload_post($a, false);
1025 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1026 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1027 $item_id = item_post($a);
1029 // output the post that we just posted.
1030 return api_status_show($type, $item_id);
1033 /// @TODO move this to top of file or somewhere better!
1034 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1037 * Updates the user’s current status.
1039 * @param string $type Return type (atom, rss, xml, json)
1041 * @return array|string
1042 * @throws BadRequestException
1043 * @throws ForbiddenException
1044 * @throws ImagickException
1045 * @throws InternalServerErrorException
1046 * @throws TooManyRequestsException
1047 * @throws UnauthorizedException
1048 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1050 function api_statuses_update($type)
1054 if (api_user() === false) {
1055 Logger::log('api_statuses_update: no user');
1056 throw new ForbiddenException();
1061 // convert $_POST array items to the form we use for web posts.
1062 if (requestdata('htmlstatus')) {
1063 $txt = requestdata('htmlstatus');
1064 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1065 $txt = HTML::toBBCodeVideo($txt);
1067 $config = HTMLPurifier_Config::createDefault();
1068 $config->set('Cache.DefinitionImpl', null);
1070 $purifier = new HTMLPurifier($config);
1071 $txt = $purifier->purify($txt);
1073 $_REQUEST['body'] = HTML::toBBCode($txt);
1076 $_REQUEST['body'] = requestdata('status');
1079 $_REQUEST['title'] = requestdata('title');
1081 $parent = requestdata('in_reply_to_status_id');
1083 // Twidere sends "-1" if it is no reply ...
1084 if ($parent == -1) {
1088 if (ctype_digit($parent)) {
1089 $_REQUEST['parent'] = $parent;
1091 $_REQUEST['parent_uri'] = $parent;
1094 if (requestdata('lat') && requestdata('long')) {
1095 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1097 $_REQUEST['profile_uid'] = api_user();
1100 // Check for throttling (maximum posts per day, week and month)
1101 $throttle_day = Config::get('system', 'throttle_limit_day');
1102 if ($throttle_day > 0) {
1103 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1105 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1106 $posts_day = DBA::count('thread', $condition);
1108 if ($posts_day > $throttle_day) {
1109 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1110 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1111 throw new TooManyRequestsException(L10n::tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1115 $throttle_week = Config::get('system', 'throttle_limit_week');
1116 if ($throttle_week > 0) {
1117 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1119 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1120 $posts_week = DBA::count('thread', $condition);
1122 if ($posts_week > $throttle_week) {
1123 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1124 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1125 throw new TooManyRequestsException(L10n::tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
1129 $throttle_month = Config::get('system', 'throttle_limit_month');
1130 if ($throttle_month > 0) {
1131 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1133 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1134 $posts_month = DBA::count('thread', $condition);
1136 if ($posts_month > $throttle_month) {
1137 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1138 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1139 throw new TooManyRequestsException(L10n::t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1144 if (!empty($_FILES['media'])) {
1145 // upload the image if we have one
1146 $picture = wall_upload_post($a, false);
1147 if (is_array($picture)) {
1148 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1152 if (requestdata('media_ids')) {
1153 $ids = explode(',', requestdata('media_ids'));
1154 foreach ($ids as $id) {
1156 "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",
1160 if (DBA::isResult($r)) {
1161 $phototypes = Images::supportedTypes();
1162 $ext = $phototypes[$r[0]['type']];
1163 $description = $r[0]['desc'] ?? '';
1164 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1165 $_REQUEST['body'] .= '[img=' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1170 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1172 $_REQUEST['api_source'] = true;
1174 if (empty($_REQUEST['source'])) {
1175 $_REQUEST["source"] = api_source();
1178 // call out normal post function
1179 $item_id = item_post($a);
1181 // output the post that we just posted.
1182 return api_status_show($type, $item_id);
1185 /// @TODO move to top of file or somewhere better
1186 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1187 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1190 * Uploads an image to Friendica.
1193 * @throws BadRequestException
1194 * @throws ForbiddenException
1195 * @throws ImagickException
1196 * @throws InternalServerErrorException
1197 * @throws UnauthorizedException
1198 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1200 function api_media_upload()
1204 if (api_user() === false) {
1205 Logger::log('no user');
1206 throw new ForbiddenException();
1211 if (empty($_FILES['media'])) {
1213 throw new BadRequestException("No media.");
1216 $media = wall_upload_post($a, false);
1219 throw new InternalServerErrorException();
1223 $returndata["media_id"] = $media["id"];
1224 $returndata["media_id_string"] = (string)$media["id"];
1225 $returndata["size"] = $media["size"];
1226 $returndata["image"] = ["w" => $media["width"],
1227 "h" => $media["height"],
1228 "image_type" => $media["type"],
1229 "friendica_preview_url" => $media["preview"]];
1231 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1233 return ["media" => $returndata];
1236 /// @TODO move to top of file or somewhere better
1237 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1240 * Updates media meta data (picture descriptions)
1242 * @param string $type Return type (atom, rss, xml, json)
1244 * @return array|string
1245 * @throws BadRequestException
1246 * @throws ForbiddenException
1247 * @throws ImagickException
1248 * @throws InternalServerErrorException
1249 * @throws TooManyRequestsException
1250 * @throws UnauthorizedException
1251 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1253 * @todo Compare the corresponding Twitter function for correct return values
1255 function api_media_metadata_create($type)
1259 if (api_user() === false) {
1260 Logger::info('no user');
1261 throw new ForbiddenException();
1266 $postdata = Network::postdata();
1268 if (empty($postdata)) {
1269 throw new BadRequestException("No post data");
1272 $data = json_decode($postdata, true);
1274 throw new BadRequestException("Invalid post data");
1277 if (empty($data['media_id']) || empty($data['alt_text'])) {
1278 throw new BadRequestException("Missing post data values");
1281 if (empty($data['alt_text']['text'])) {
1282 throw new BadRequestException("No alt text.");
1285 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1287 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1288 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1289 if (!DBA::isResult($photo)) {
1290 throw new BadRequestException("Metadata not found.");
1293 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1296 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1299 * @param string $type Return format (atom, rss, xml, json)
1300 * @param int $item_id
1304 function api_status_show($type, $item_id)
1306 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1310 $item = api_get_item(['id' => $item_id]);
1311 if (!empty($item)) {
1312 $status_info = api_format_item($item, $type);
1315 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1317 return api_format_data('statuses', $type, ['status' => $status_info]);
1321 * Retrieves the last public status of the provided user info
1323 * @param int $ownerId Public contact Id
1324 * @param int $uid User Id
1328 function api_get_last_status($ownerId, $uid)
1331 'author-id'=> $ownerId,
1333 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1337 $item = api_get_item($condition);
1343 * Retrieves a single item record based on the provided condition and converts it for API use.
1345 * @param array $condition Item table condition array
1349 function api_get_item(array $condition)
1351 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1357 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1358 * The author's most recent status will be returned inline.
1360 * @param string $type Return type (atom, rss, xml, json)
1361 * @return array|string
1362 * @throws BadRequestException
1363 * @throws ImagickException
1364 * @throws InternalServerErrorException
1365 * @throws UnauthorizedException
1366 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1368 function api_users_show($type)
1370 $a = BaseObject::getApp();
1372 $user_info = api_get_user($a);
1374 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1375 if (!empty($item)) {
1376 $user_info['status'] = api_format_item($item, $type);
1379 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1380 unset($user_info['uid']);
1381 unset($user_info['self']);
1383 return api_format_data('user', $type, ['user' => $user_info]);
1386 /// @TODO move to top of file or somewhere better
1387 api_register_func('api/users/show', 'api_users_show');
1388 api_register_func('api/externalprofile/show', 'api_users_show');
1391 * Search a public user account.
1393 * @param string $type Return type (atom, rss, xml, json)
1395 * @return array|string
1396 * @throws BadRequestException
1397 * @throws ImagickException
1398 * @throws InternalServerErrorException
1399 * @throws UnauthorizedException
1400 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1402 function api_users_search($type)
1408 if (!empty($_GET['q'])) {
1409 $contacts = Contact::selectToArray(
1412 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1420 if (DBA::isResult($contacts)) {
1422 foreach ($contacts as $contact) {
1423 $user_info = api_get_user($a, $contact['id']);
1425 if ($type == 'xml') {
1426 $userlist[$k++ . ':user'] = $user_info;
1428 $userlist[] = $user_info;
1431 $userlist = ['users' => $userlist];
1433 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1436 throw new BadRequestException('No search term specified.');
1439 return api_format_data('users', $type, $userlist);
1442 /// @TODO move to top of file or somewhere better
1443 api_register_func('api/users/search', 'api_users_search');
1446 * Return user objects
1448 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1450 * @param string $type Return format: json or xml
1452 * @return array|string
1453 * @throws BadRequestException
1454 * @throws ImagickException
1455 * @throws InternalServerErrorException
1456 * @throws NotFoundException if the results are empty.
1457 * @throws UnauthorizedException
1459 function api_users_lookup($type)
1463 if (!empty($_REQUEST['user_id'])) {
1464 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1466 $users[] = api_get_user(get_app(), $id);
1471 if (empty($users)) {
1472 throw new NotFoundException;
1475 return api_format_data("users", $type, ['users' => $users]);
1478 /// @TODO move to top of file or somewhere better
1479 api_register_func('api/users/lookup', 'api_users_lookup', true);
1482 * Returns statuses that match a specified query.
1484 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1486 * @param string $type Return format: json, xml, atom, rss
1488 * @return array|string
1489 * @throws BadRequestException if the "q" parameter is missing.
1490 * @throws ForbiddenException
1491 * @throws ImagickException
1492 * @throws InternalServerErrorException
1493 * @throws UnauthorizedException
1495 function api_search($type)
1498 $user_info = api_get_user($a);
1500 if (api_user() === false || $user_info === false) {
1501 throw new ForbiddenException();
1504 if (empty($_REQUEST['q'])) {
1505 throw new BadRequestException('q parameter is required.');
1508 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1511 $data['status'] = [];
1513 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1514 if (!empty($_REQUEST['rpp'])) {
1515 $count = $_REQUEST['rpp'];
1516 } elseif (!empty($_REQUEST['count'])) {
1517 $count = $_REQUEST['count'];
1520 $since_id = $_REQUEST['since_id'] ?? 0;
1521 $max_id = $_REQUEST['max_id'] ?? 0;
1522 $page = $_REQUEST['page'] ?? 1;
1524 $start = max(0, ($page - 1) * $count);
1526 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1527 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1528 $searchTerm = $matches[1];
1529 $condition = ["`oid` > ?
1530 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1531 AND `otype` = ? AND `type` = ? AND `term` = ?",
1532 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1534 $condition[0] .= ' AND `oid` <= ?';
1535 $condition[] = $max_id;
1537 $terms = DBA::select('term', ['oid'], $condition, []);
1539 while ($term = DBA::fetch($terms)) {
1540 $itemIds[] = $term['oid'];
1544 if (empty($itemIds)) {
1545 return api_format_data('statuses', $type, $data);
1548 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1549 if ($exclude_replies) {
1550 $preCondition[] = '`id` = `parent`';
1553 $condition = [implode(' AND ', $preCondition)];
1555 $condition = ["`id` > ?
1556 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1557 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1558 AND `body` LIKE CONCAT('%',?,'%')",
1559 $since_id, api_user(), $_REQUEST['q']];
1561 $condition[0] .= ' AND `id` <= ?';
1562 $condition[] = $max_id;
1568 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1569 $id = Item::fetchByLink($searchTerm, api_user());
1572 $id = Item::fetchByLink($searchTerm);
1576 $statuses = Item::select([], ['id' => $id]);
1580 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1582 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1584 bindComments($data['status']);
1586 return api_format_data('statuses', $type, $data);
1589 /// @TODO move to top of file or somewhere better
1590 api_register_func('api/search/tweets', 'api_search', true);
1591 api_register_func('api/search', 'api_search', true);
1594 * Returns the most recent statuses posted by the user and the users they follow.
1596 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1598 * @param string $type Return type (atom, rss, xml, json)
1600 * @return array|string
1601 * @throws BadRequestException
1602 * @throws ForbiddenException
1603 * @throws ImagickException
1604 * @throws InternalServerErrorException
1605 * @throws UnauthorizedException
1606 * @todo Optional parameters
1607 * @todo Add reply info
1609 function api_statuses_home_timeline($type)
1612 $user_info = api_get_user($a);
1614 if (api_user() === false || $user_info === false) {
1615 throw new ForbiddenException();
1618 unset($_REQUEST["user_id"]);
1619 unset($_GET["user_id"]);
1621 unset($_REQUEST["screen_name"]);
1622 unset($_GET["screen_name"]);
1624 // get last network messages
1627 $count = $_REQUEST['count'] ?? 20;
1628 $page = $_REQUEST['page']?? 0;
1629 $since_id = $_REQUEST['since_id'] ?? 0;
1630 $max_id = $_REQUEST['max_id'] ?? 0;
1631 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1632 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1634 $start = max(0, ($page - 1) * $count);
1636 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1637 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1640 $condition[0] .= " AND `item`.`id` <= ?";
1641 $condition[] = $max_id;
1643 if ($exclude_replies) {
1644 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1646 if ($conversation_id > 0) {
1647 $condition[0] .= " AND `item`.`parent` = ?";
1648 $condition[] = $conversation_id;
1651 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1652 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1654 $items = Item::inArray($statuses);
1656 $ret = api_format_items($items, $user_info, false, $type);
1658 // Set all posts from the query above to seen
1660 foreach ($items as $item) {
1661 $idarray[] = intval($item["id"]);
1664 if (!empty($idarray)) {
1665 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1667 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1673 $data = ['status' => $ret];
1678 $data = api_rss_extra($a, $data, $user_info);
1682 return api_format_data("statuses", $type, $data);
1686 /// @TODO move to top of file or somewhere better
1687 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1688 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1691 * Returns the most recent statuses from public users.
1693 * @param string $type Return type (atom, rss, xml, json)
1695 * @return array|string
1696 * @throws BadRequestException
1697 * @throws ForbiddenException
1698 * @throws ImagickException
1699 * @throws InternalServerErrorException
1700 * @throws UnauthorizedException
1702 function api_statuses_public_timeline($type)
1705 $user_info = api_get_user($a);
1707 if (api_user() === false || $user_info === false) {
1708 throw new ForbiddenException();
1711 // get last network messages
1714 $count = $_REQUEST['count'] ?? 20;
1715 $page = $_REQUEST['page'] ?? 1;
1716 $since_id = $_REQUEST['since_id'] ?? 0;
1717 $max_id = $_REQUEST['max_id'] ?? 0;
1718 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1719 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1721 $start = max(0, ($page - 1) * $count);
1723 if ($exclude_replies && !$conversation_id) {
1724 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1725 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1728 $condition[0] .= " AND `thread`.`iid` <= ?";
1729 $condition[] = $max_id;
1732 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1733 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1735 $r = Item::inArray($statuses);
1737 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1738 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1741 $condition[0] .= " AND `item`.`id` <= ?";
1742 $condition[] = $max_id;
1744 if ($conversation_id > 0) {
1745 $condition[0] .= " AND `item`.`parent` = ?";
1746 $condition[] = $conversation_id;
1749 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1750 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1752 $r = Item::inArray($statuses);
1755 $ret = api_format_items($r, $user_info, false, $type);
1759 $data = ['status' => $ret];
1764 $data = api_rss_extra($a, $data, $user_info);
1768 return api_format_data("statuses", $type, $data);
1771 /// @TODO move to top of file or somewhere better
1772 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1775 * Returns the most recent statuses posted by users this node knows about.
1777 * @brief Returns the list of public federated posts this node knows about
1779 * @param string $type Return format: json, xml, atom, rss
1780 * @return array|string
1781 * @throws BadRequestException
1782 * @throws ForbiddenException
1783 * @throws ImagickException
1784 * @throws InternalServerErrorException
1785 * @throws UnauthorizedException
1787 function api_statuses_networkpublic_timeline($type)
1790 $user_info = api_get_user($a);
1792 if (api_user() === false || $user_info === false) {
1793 throw new ForbiddenException();
1796 $since_id = $_REQUEST['since_id'] ?? 0;
1797 $max_id = $_REQUEST['max_id'] ?? 0;
1800 $count = $_REQUEST['count'] ?? 20;
1801 $page = $_REQUEST['page'] ?? 1;
1803 $start = max(0, ($page - 1) * $count);
1805 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1806 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1809 $condition[0] .= " AND `thread`.`iid` <= ?";
1810 $condition[] = $max_id;
1813 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1814 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1816 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1820 $data = ['status' => $ret];
1825 $data = api_rss_extra($a, $data, $user_info);
1829 return api_format_data("statuses", $type, $data);
1832 /// @TODO move to top of file or somewhere better
1833 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1836 * Returns a single status.
1838 * @param string $type Return type (atom, rss, xml, json)
1840 * @return array|string
1841 * @throws BadRequestException
1842 * @throws ForbiddenException
1843 * @throws ImagickException
1844 * @throws InternalServerErrorException
1845 * @throws UnauthorizedException
1846 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1848 function api_statuses_show($type)
1851 $user_info = api_get_user($a);
1853 if (api_user() === false || $user_info === false) {
1854 throw new ForbiddenException();
1858 $id = intval($a->argv[3] ?? 0);
1861 $id = intval($_REQUEST['id'] ?? 0);
1866 $id = intval($a->argv[4] ?? 0);
1869 Logger::log('API: api_statuses_show: ' . $id);
1871 $conversation = !empty($_REQUEST['conversation']);
1873 // try to fetch the item for the local user - or the public item, if there is no local one
1874 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1875 if (!DBA::isResult($uri_item)) {
1876 throw new BadRequestException("There is no status with this id.");
1879 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1880 if (!DBA::isResult($item)) {
1881 throw new BadRequestException("There is no status with this id.");
1886 if ($conversation) {
1887 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1888 $params = ['order' => ['id' => true]];
1890 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1894 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1896 /// @TODO How about copying this to above methods which don't check $r ?
1897 if (!DBA::isResult($statuses)) {
1898 throw new BadRequestException("There is no status with this id.");
1901 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1903 if ($conversation) {
1904 $data = ['status' => $ret];
1905 return api_format_data("statuses", $type, $data);
1907 $data = ['status' => $ret[0]];
1908 return api_format_data("status", $type, $data);
1912 /// @TODO move to top of file or somewhere better
1913 api_register_func('api/statuses/show', 'api_statuses_show', true);
1917 * @param string $type Return type (atom, rss, xml, json)
1919 * @return array|string
1920 * @throws BadRequestException
1921 * @throws ForbiddenException
1922 * @throws ImagickException
1923 * @throws InternalServerErrorException
1924 * @throws UnauthorizedException
1925 * @todo nothing to say?
1927 function api_conversation_show($type)
1930 $user_info = api_get_user($a);
1932 if (api_user() === false || $user_info === false) {
1933 throw new ForbiddenException();
1937 $id = intval($a->argv[3] ?? 0);
1938 $since_id = intval($_REQUEST['since_id'] ?? 0);
1939 $max_id = intval($_REQUEST['max_id'] ?? 0);
1940 $count = intval($_REQUEST['count'] ?? 20);
1941 $page = intval($_REQUEST['page'] ?? 1);
1943 $start = max(0, ($page - 1) * $count);
1946 $id = intval($_REQUEST['id'] ?? 0);
1951 $id = intval($a->argv[4] ?? 0);
1954 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1956 // try to fetch the item for the local user - or the public item, if there is no local one
1957 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1958 if (!DBA::isResult($item)) {
1959 throw new BadRequestException("There is no status with this id.");
1962 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1963 if (!DBA::isResult($parent)) {
1964 throw new BadRequestException("There is no status with this id.");
1967 $id = $parent['id'];
1969 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1970 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1973 $condition[0] .= " AND `item`.`id` <= ?";
1974 $condition[] = $max_id;
1977 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1978 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1980 if (!DBA::isResult($statuses)) {
1981 throw new BadRequestException("There is no status with id $id.");
1984 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1986 $data = ['status' => $ret];
1987 return api_format_data("statuses", $type, $data);
1990 /// @TODO move to top of file or somewhere better
1991 api_register_func('api/conversation/show', 'api_conversation_show', true);
1992 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1997 * @param string $type Return type (atom, rss, xml, json)
1999 * @return array|string
2000 * @throws BadRequestException
2001 * @throws ForbiddenException
2002 * @throws ImagickException
2003 * @throws InternalServerErrorException
2004 * @throws UnauthorizedException
2005 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2007 function api_statuses_repeat($type)
2013 if (api_user() === false) {
2014 throw new ForbiddenException();
2020 $id = intval($a->argv[3] ?? 0);
2023 $id = intval($_REQUEST['id'] ?? 0);
2028 $id = intval($a->argv[4] ?? 0);
2031 Logger::log('API: api_statuses_repeat: '.$id);
2033 $fields = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2034 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2036 if (DBA::isResult($item) && $item['body'] != "") {
2037 if (strpos($item['body'], "[/share]") !== false) {
2038 $pos = strpos($item['body'], "[share");
2039 $post = substr($item['body'], $pos);
2041 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2043 if (!empty($item['title'])) {
2044 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2047 $post .= $item['body'];
2048 $post .= "[/share]";
2050 $_REQUEST['body'] = $post;
2051 $_REQUEST['tag'] = $item['tag'];
2052 $_REQUEST['attach'] = $item['attach'];
2053 $_REQUEST['profile_uid'] = api_user();
2054 $_REQUEST['api_source'] = true;
2056 if (empty($_REQUEST['source'])) {
2057 $_REQUEST["source"] = api_source();
2060 $item_id = item_post($a);
2062 throw new ForbiddenException();
2065 // output the post that we just posted.
2067 return api_status_show($type, $item_id);
2070 /// @TODO move to top of file or somewhere better
2071 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2074 * Destroys a specific status.
2076 * @param string $type Return type (atom, rss, xml, json)
2078 * @return array|string
2079 * @throws BadRequestException
2080 * @throws ForbiddenException
2081 * @throws ImagickException
2082 * @throws InternalServerErrorException
2083 * @throws UnauthorizedException
2084 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2086 function api_statuses_destroy($type)
2090 if (api_user() === false) {
2091 throw new ForbiddenException();
2097 $id = intval($a->argv[3] ?? 0);
2100 $id = intval($_REQUEST['id'] ?? 0);
2105 $id = intval($a->argv[4] ?? 0);
2108 Logger::log('API: api_statuses_destroy: '.$id);
2110 $ret = api_statuses_show($type);
2112 Item::deleteForUser(['id' => $id], api_user());
2117 /// @TODO move to top of file or somewhere better
2118 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2121 * Returns the most recent mentions.
2123 * @param string $type Return type (atom, rss, xml, json)
2125 * @return array|string
2126 * @throws BadRequestException
2127 * @throws ForbiddenException
2128 * @throws ImagickException
2129 * @throws InternalServerErrorException
2130 * @throws UnauthorizedException
2131 * @see http://developer.twitter.com/doc/get/statuses/mentions
2133 function api_statuses_mentions($type)
2136 $user_info = api_get_user($a);
2138 if (api_user() === false || $user_info === false) {
2139 throw new ForbiddenException();
2142 unset($_REQUEST["user_id"]);
2143 unset($_GET["user_id"]);
2145 unset($_REQUEST["screen_name"]);
2146 unset($_GET["screen_name"]);
2148 // get last network messages
2151 $since_id = $_REQUEST['since_id'] ?? 0;
2152 $max_id = $_REQUEST['max_id'] ?? 0;
2153 $count = $_REQUEST['count'] ?? 20;
2154 $page = $_REQUEST['page'] ?? 1;
2156 $start = max(0, ($page - 1) * $count);
2158 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ? AND `mention`
2159 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND NOT `thread`.`ignored`)",
2160 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2163 $condition[0] .= " AND `item`.`id` <= ?";
2164 $condition[] = $max_id;
2167 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2168 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2170 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2172 $data = ['status' => $ret];
2177 $data = api_rss_extra($a, $data, $user_info);
2181 return api_format_data("statuses", $type, $data);
2184 /// @TODO move to top of file or somewhere better
2185 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2186 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2189 * Returns the most recent statuses posted by the user.
2191 * @brief Returns a user's public timeline
2193 * @param string $type Either "json" or "xml"
2194 * @return string|array
2195 * @throws BadRequestException
2196 * @throws ForbiddenException
2197 * @throws ImagickException
2198 * @throws InternalServerErrorException
2199 * @throws UnauthorizedException
2200 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2202 function api_statuses_user_timeline($type)
2205 $user_info = api_get_user($a);
2207 if (api_user() === false || $user_info === false) {
2208 throw new ForbiddenException();
2212 "api_statuses_user_timeline: api_user: ". api_user() .
2213 "\nuser_info: ".print_r($user_info, true) .
2214 "\n_REQUEST: ".print_r($_REQUEST, true),
2218 $since_id = $_REQUEST['since_id'] ?? 0;
2219 $max_id = $_REQUEST['max_id'] ?? 0;
2220 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2221 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2224 $count = $_REQUEST['count'] ?? 20;
2225 $page = $_REQUEST['page'] ?? 1;
2227 $start = max(0, ($page - 1) * $count);
2229 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2230 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2232 if ($user_info['self'] == 1) {
2233 $condition[0] .= ' AND `item`.`wall` ';
2236 if ($exclude_replies) {
2237 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2240 if ($conversation_id > 0) {
2241 $condition[0] .= " AND `item`.`parent` = ?";
2242 $condition[] = $conversation_id;
2246 $condition[0] .= " AND `item`.`id` <= ?";
2247 $condition[] = $max_id;
2250 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2251 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2253 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2257 $data = ['status' => $ret];
2262 $data = api_rss_extra($a, $data, $user_info);
2266 return api_format_data("statuses", $type, $data);
2269 /// @TODO move to top of file or somewhere better
2270 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2273 * Star/unstar an item.
2274 * param: id : id of the item
2276 * @param string $type Return type (atom, rss, xml, json)
2278 * @return array|string
2279 * @throws BadRequestException
2280 * @throws ForbiddenException
2281 * @throws ImagickException
2282 * @throws InternalServerErrorException
2283 * @throws UnauthorizedException
2284 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2286 function api_favorites_create_destroy($type)
2290 if (api_user() === false) {
2291 throw new ForbiddenException();
2294 // for versioned api.
2295 /// @TODO We need a better global soluton
2296 $action_argv_id = 2;
2297 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2298 $action_argv_id = 3;
2301 if ($a->argc <= $action_argv_id) {
2302 throw new BadRequestException("Invalid request.");
2304 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2305 if ($a->argc == $action_argv_id + 2) {
2306 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2308 $itemid = intval($_REQUEST['id'] ?? 0);
2311 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2313 if (!DBA::isResult($item)) {
2314 throw new BadRequestException("Invalid item.");
2319 $item['starred'] = 1;
2322 $item['starred'] = 0;
2325 throw new BadRequestException("Invalid action ".$action);
2328 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2331 throw new InternalServerErrorException("DB error");
2335 $user_info = api_get_user($a);
2336 $rets = api_format_items([$item], $user_info, false, $type);
2339 $data = ['status' => $ret];
2344 $data = api_rss_extra($a, $data, $user_info);
2348 return api_format_data("status", $type, $data);
2351 /// @TODO move to top of file or somewhere better
2352 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2353 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2356 * Returns the most recent favorite statuses.
2358 * @param string $type Return type (atom, rss, xml, json)
2360 * @return string|array
2361 * @throws BadRequestException
2362 * @throws ForbiddenException
2363 * @throws ImagickException
2364 * @throws InternalServerErrorException
2365 * @throws UnauthorizedException
2367 function api_favorites($type)
2372 $user_info = api_get_user($a);
2374 if (api_user() === false || $user_info === false) {
2375 throw new ForbiddenException();
2380 // in friendica starred item are private
2381 // return favorites only for self
2382 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2384 if ($user_info['self'] == 0) {
2388 $since_id = $_REQUEST['since_id'] ?? 0;
2389 $max_id = $_REQUEST['max_id'] ?? 0;
2390 $count = $_GET['count'] ?? 20;
2391 $page = $_REQUEST['page'] ?? 1;
2393 $start = max(0, ($page - 1) * $count);
2395 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2396 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2398 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2401 $condition[0] .= " AND `item`.`id` <= ?";
2402 $condition[] = $max_id;
2405 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2407 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2412 $data = ['status' => $ret];
2417 $data = api_rss_extra($a, $data, $user_info);
2421 return api_format_data("statuses", $type, $data);
2424 /// @TODO move to top of file or somewhere better
2425 api_register_func('api/favorites', 'api_favorites', true);
2429 * @param array $item
2430 * @param array $recipient
2431 * @param array $sender
2434 * @throws InternalServerErrorException
2436 function api_format_messages($item, $recipient, $sender)
2438 // standard meta information
2440 'id' => $item['id'],
2441 'sender_id' => $sender['id'],
2443 'recipient_id' => $recipient['id'],
2444 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2445 'sender_screen_name' => $sender['screen_name'],
2446 'recipient_screen_name' => $recipient['screen_name'],
2447 'sender' => $sender,
2448 'recipient' => $recipient,
2450 'friendica_seen' => $item['seen'] ?? 0,
2451 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2454 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2455 if (isset($ret['sender']['uid'])) {
2456 unset($ret['sender']['uid']);
2458 if (isset($ret['sender']['self'])) {
2459 unset($ret['sender']['self']);
2461 if (isset($ret['recipient']['uid'])) {
2462 unset($ret['recipient']['uid']);
2464 if (isset($ret['recipient']['self'])) {
2465 unset($ret['recipient']['self']);
2468 //don't send title to regular StatusNET requests to avoid confusing these apps
2469 if (!empty($_GET['getText'])) {
2470 $ret['title'] = $item['title'];
2471 if ($_GET['getText'] == 'html') {
2472 $ret['text'] = BBCode::convert($item['body'], false);
2473 } elseif ($_GET['getText'] == 'plain') {
2474 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2477 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2479 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2480 unset($ret['sender']);
2481 unset($ret['recipient']);
2489 * @param array $item
2492 * @throws InternalServerErrorException
2494 function api_convert_item($item)
2496 $body = $item['body'];
2497 $entities = api_get_entitities($statustext, $body);
2499 // Add pictures to the attachment array and remove them from the body
2500 $attachments = api_get_attachments($body);
2502 // Workaround for ostatus messages where the title is identically to the body
2503 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2504 $statusbody = trim(HTML::toPlaintext($html, 0));
2506 // handle data: images
2507 $statusbody = api_format_items_embeded_images($item, $statusbody);
2509 $statustitle = trim($item['title']);
2511 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2512 $statustext = trim($statusbody);
2514 $statustext = trim($statustitle."\n\n".$statusbody);
2517 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2518 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2521 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2523 // Workaround for clients with limited HTML parser functionality
2524 $search = ["<br>", "<blockquote>", "</blockquote>",
2525 "<h1>", "</h1>", "<h2>", "</h2>",
2526 "<h3>", "</h3>", "<h4>", "</h4>",
2527 "<h5>", "</h5>", "<h6>", "</h6>"];
2528 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2529 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2530 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2531 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2532 $statushtml = str_replace($search, $replace, $statushtml);
2534 if ($item['title'] != "") {
2535 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2539 $oldtext = $statushtml;
2540 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2541 } while ($oldtext != $statushtml);
2543 if (substr($statushtml, 0, 4) == '<br>') {
2544 $statushtml = substr($statushtml, 4);
2547 if (substr($statushtml, 0, -4) == '<br>') {
2548 $statushtml = substr($statushtml, -4);
2551 // feeds without body should contain the link
2552 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2553 $statushtml .= BBCode::convert($item['plink']);
2557 "text" => $statustext,
2558 "html" => $statushtml,
2559 "attachments" => $attachments,
2560 "entities" => $entities
2566 * @param string $body
2569 * @throws InternalServerErrorException
2571 function api_get_attachments(&$body)
2573 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2574 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2576 $URLSearchString = "^\[\]";
2577 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2581 // Remove all embedded pictures, since they are added as attachments
2582 foreach ($images[0] as $orig) {
2583 $body = str_replace($orig, '', $body);
2588 foreach ($images[1] as $image) {
2589 $imagedata = Images::getInfoFromURLCached($image);
2592 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2596 return $attachments;
2601 * @param string $text
2602 * @param string $bbcode
2605 * @throws InternalServerErrorException
2606 * @todo Links at the first character of the post
2608 function api_get_entitities(&$text, $bbcode)
2610 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2612 if ($include_entities != "true") {
2613 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2615 foreach ($images[1] as $image) {
2616 $replace = ProxyUtils::proxifyUrl($image);
2617 $text = str_replace($image, $replace, $text);
2622 $bbcode = BBCode::cleanPictureLinks($bbcode);
2624 // Change pure links in text to bbcode uris
2625 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2628 $entities["hashtags"] = [];
2629 $entities["symbols"] = [];
2630 $entities["urls"] = [];
2631 $entities["user_mentions"] = [];
2633 $URLSearchString = "^\[\]";
2635 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2637 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2638 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2640 $bbcode = preg_replace(
2641 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2642 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2645 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2647 $bbcode = preg_replace(
2648 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2649 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2652 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2654 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2656 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2659 foreach ($urls[1] as $id => $url) {
2660 $start = iconv_strpos($text, $url, 0, "UTF-8");
2661 if (!($start === false)) {
2662 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2666 ksort($ordered_urls);
2670 foreach ($ordered_urls as $url) {
2671 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2672 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2674 $display_url = $url["title"];
2676 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2677 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2679 if (strlen($display_url) > 26) {
2680 $display_url = substr($display_url, 0, 25)."…";
2684 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2685 if (!($start === false)) {
2686 $entities["urls"][] = ["url" => $url["url"],
2687 "expanded_url" => $url["url"],
2688 "display_url" => $display_url,
2689 "indices" => [$start, $start+strlen($url["url"])]];
2690 $offset = $start + 1;
2694 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2695 $ordered_images = [];
2696 foreach ($images as $image) {
2697 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2698 if (!($start === false)) {
2699 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2703 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2704 foreach ($images[1] as $image) {
2705 $start = iconv_strpos($text, $image, 0, "UTF-8");
2706 if (!($start === false)) {
2707 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2713 foreach ($ordered_images as $image) {
2714 $url = $image['url'];
2715 $ext_alt_text = $image['alt'];
2717 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2718 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2720 if (strlen($display_url) > 26) {
2721 $display_url = substr($display_url, 0, 25)."…";
2724 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2725 if (!($start === false)) {
2726 $image = Images::getInfoFromURLCached($url);
2728 // If image cache is activated, then use the following sizes:
2729 // thumb (150), small (340), medium (600) and large (1024)
2730 if (!Config::get("system", "proxy_disabled")) {
2731 $media_url = ProxyUtils::proxifyUrl($url);
2734 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2735 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2737 if (($image[0] > 150) || ($image[1] > 150)) {
2738 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2739 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2742 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2743 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2745 if (($image[0] > 600) || ($image[1] > 600)) {
2746 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2747 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2751 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2754 $entities["media"][] = [
2756 "id_str" => (string) ($start + 1),
2757 "indices" => [$start, $start+strlen($url)],
2758 "media_url" => Strings::normaliseLink($media_url),
2759 "media_url_https" => $media_url,
2761 "display_url" => $display_url,
2762 "expanded_url" => $url,
2763 "ext_alt_text" => $ext_alt_text,
2767 $offset = $start + 1;
2776 * @param array $item
2777 * @param string $text
2781 function api_format_items_embeded_images($item, $text)
2783 $text = preg_replace_callback(
2784 '|data:image/([^;]+)[^=]+=*|m',
2785 function () use ($item) {
2786 return System::baseUrl() . '/display/' . $item['guid'];
2794 * @brief return <a href='url'>name</a> as array
2796 * @param string $txt text
2801 function api_contactlink_to_array($txt)
2804 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2805 if ($r && count($match)==3) {
2807 'name' => $match[2],
2821 * @brief return likes, dislikes and attend status for item
2823 * @param array $item array
2824 * @param string $type Return type (atom, rss, xml, json)
2827 * likes => int count,
2828 * dislikes => int count
2829 * @throws BadRequestException
2830 * @throws ImagickException
2831 * @throws InternalServerErrorException
2832 * @throws UnauthorizedException
2834 function api_format_items_activities($item, $type = "json")
2843 'attendmaybe' => [],
2847 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2848 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2850 while ($parent_item = Item::fetch($ret)) {
2851 // not used as result should be structured like other user data
2852 //builtin_activity_puller($i, $activities);
2854 // get user data and add it to the array of the activity
2855 $user = api_get_user($a, $parent_item['author-id']);
2856 switch ($parent_item['verb']) {
2857 case Activity::LIKE:
2858 $activities['like'][] = $user;
2860 case Activity::DISLIKE:
2861 $activities['dislike'][] = $user;
2863 case Activity::ATTEND:
2864 $activities['attendyes'][] = $user;
2866 case Activity::ATTENDNO:
2867 $activities['attendno'][] = $user;
2869 case Activity::ATTENDMAYBE:
2870 $activities['attendmaybe'][] = $user;
2872 case Activity::ANNOUNCE:
2873 $activities['announce'][] = $user;
2882 if ($type == "xml") {
2883 $xml_activities = [];
2884 foreach ($activities as $k => $v) {
2885 // change xml element from "like" to "friendica:like"
2886 $xml_activities["friendica:".$k] = $v;
2887 // add user data into xml output
2889 foreach ($v as $user) {
2890 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2893 $activities = $xml_activities;
2901 * @brief return data from profiles
2903 * @param array $profile_row array containing data from db table 'profile'
2905 * @throws InternalServerErrorException
2907 function api_format_items_profiles($profile_row)
2910 'profile_id' => $profile_row['id'],
2911 'profile_name' => $profile_row['profile-name'],
2912 'is_default' => $profile_row['is-default'] ? true : false,
2913 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2914 'profile_photo' => $profile_row['photo'],
2915 'profile_thumb' => $profile_row['thumb'],
2916 'publish' => $profile_row['publish'] ? true : false,
2917 'net_publish' => $profile_row['net-publish'] ? true : false,
2918 'description' => $profile_row['pdesc'],
2919 'date_of_birth' => $profile_row['dob'],
2920 'address' => $profile_row['address'],
2921 'city' => $profile_row['locality'],
2922 'region' => $profile_row['region'],
2923 'postal_code' => $profile_row['postal-code'],
2924 'country' => $profile_row['country-name'],
2925 'hometown' => $profile_row['hometown'],
2926 'gender' => $profile_row['gender'],
2927 'marital' => $profile_row['marital'],
2928 'marital_with' => $profile_row['with'],
2929 'marital_since' => $profile_row['howlong'],
2930 'sexual' => $profile_row['sexual'],
2931 'politic' => $profile_row['politic'],
2932 'religion' => $profile_row['religion'],
2933 'public_keywords' => $profile_row['pub_keywords'],
2934 'private_keywords' => $profile_row['prv_keywords'],
2935 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2936 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2937 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2938 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2939 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2940 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2941 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2942 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2943 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2944 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2945 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2946 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2947 'homepage' => $profile_row['homepage'],
2954 * @brief format items to be returned by api
2956 * @param array $items array of items
2957 * @param array $user_info
2958 * @param bool $filter_user filter items by $user_info
2959 * @param string $type Return type (atom, rss, xml, json)
2961 * @throws BadRequestException
2962 * @throws ImagickException
2963 * @throws InternalServerErrorException
2964 * @throws UnauthorizedException
2966 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2968 $a = BaseObject::getApp();
2972 foreach ((array)$items as $item) {
2973 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2975 // Look if the posts are matching if they should be filtered by user id
2976 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2980 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2989 * @param array $item Item record
2990 * @param string $type Return format (atom, rss, xml, json)
2991 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2992 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2993 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2994 * @return array API-formatted status
2995 * @throws BadRequestException
2996 * @throws ImagickException
2997 * @throws InternalServerErrorException
2998 * @throws UnauthorizedException
3000 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3002 $a = BaseObject::getApp();
3004 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3005 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3008 localize_item($item);
3010 $in_reply_to = api_in_reply_to($item);
3012 $converted = api_convert_item($item);
3014 if ($type == "xml") {
3015 $geo = "georss:point";
3021 'text' => $converted["text"],
3022 'truncated' => false,
3023 'created_at'=> api_date($item['created']),
3024 'in_reply_to_status_id' => $in_reply_to['status_id'],
3025 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3026 'source' => (($item['app']) ? $item['app'] : 'web'),
3027 'id' => intval($item['id']),
3028 'id_str' => (string) intval($item['id']),
3029 'in_reply_to_user_id' => $in_reply_to['user_id'],
3030 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3031 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3033 'favorited' => $item['starred'] ? true : false,
3034 'user' => $status_user,
3035 'friendica_author' => $author_user,
3036 'friendica_owner' => $owner_user,
3037 'friendica_private' => $item['private'] == 1,
3038 //'entities' => NULL,
3039 'statusnet_html' => $converted["html"],
3040 'statusnet_conversation_id' => $item['parent'],
3041 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3042 'friendica_activities' => api_format_items_activities($item, $type),
3043 'friendica_title' => $item['title'],
3044 'friendica_html' => BBCode::convert($item['body'], false)
3047 if (count($converted["attachments"]) > 0) {
3048 $status["attachments"] = $converted["attachments"];
3051 if (count($converted["entities"]) > 0) {
3052 $status["entities"] = $converted["entities"];
3055 if ($status["source"] == 'web') {
3056 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3057 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3058 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3061 $retweeted_item = [];
3064 if ($item["id"] == $item["parent"]) {
3065 $body = $item['body'];
3066 $retweeted_item = api_share_as_retweet($item);
3067 if ($body != $item['body']) {
3068 $quoted_item = $retweeted_item;
3069 $retweeted_item = [];
3073 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3074 $announce = api_get_announce($item);
3075 if (!empty($announce)) {
3076 $retweeted_item = $item;
3078 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3082 if (!empty($quoted_item)) {
3083 if ($quoted_item['id'] != $item['id']) {
3084 $quoted_status = api_format_item($quoted_item);
3085 /// @todo Only remove the attachments that are also contained in the quotes status
3086 unset($status['attachments']);
3087 unset($status['entities']);
3089 $conv_quoted = api_convert_item($quoted_item);
3090 $quoted_status = $status;
3091 unset($quoted_status['attachments']);
3092 unset($quoted_status['entities']);
3093 unset($quoted_status['statusnet_conversation_id']);
3094 $quoted_status['text'] = $conv_quoted['text'];
3095 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3097 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3098 } catch (BadRequestException $e) {
3099 // user not found. should be found?
3100 /// @todo check if the user should be always found
3101 $quoted_status["user"] = [];
3104 unset($quoted_status['friendica_author']);
3105 unset($quoted_status['friendica_owner']);
3106 unset($quoted_status['friendica_activities']);
3107 unset($quoted_status['friendica_private']);
3110 if (!empty($retweeted_item)) {
3111 $retweeted_status = $status;
3112 unset($retweeted_status['friendica_author']);
3113 unset($retweeted_status['friendica_owner']);
3114 unset($retweeted_status['friendica_activities']);
3115 unset($retweeted_status['friendica_private']);
3116 unset($retweeted_status['statusnet_conversation_id']);
3117 $status['user'] = $status['friendica_owner'];
3119 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3120 } catch (BadRequestException $e) {
3121 // user not found. should be found?
3122 /// @todo check if the user should be always found
3123 $retweeted_status["user"] = [];
3126 $rt_converted = api_convert_item($retweeted_item);
3128 $retweeted_status['text'] = $rt_converted["text"];
3129 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3130 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3132 if (!empty($quoted_status)) {
3133 $retweeted_status['quoted_status'] = $quoted_status;
3136 $status['friendica_author'] = $retweeted_status['user'];
3137 $status['retweeted_status'] = $retweeted_status;
3138 } elseif (!empty($quoted_status)) {
3139 $root_status = api_convert_item($item);
3141 $status['text'] = $root_status["text"];
3142 $status['statusnet_html'] = $root_status["html"];
3143 $status['quoted_status'] = $quoted_status;
3146 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3147 unset($status["user"]["uid"]);
3148 unset($status["user"]["self"]);
3150 if ($item["coord"] != "") {
3151 $coords = explode(' ', $item["coord"]);
3152 if (count($coords) == 2) {
3153 if ($type == "json") {
3154 $status["geo"] = ['type' => 'Point',
3155 'coordinates' => [(float) $coords[0],
3156 (float) $coords[1]]];
3157 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3158 $status["georss:point"] = $item["coord"];
3167 * Returns the remaining number of API requests available to the user before the API limit is reached.
3169 * @param string $type Return type (atom, rss, xml, json)
3171 * @return array|string
3174 function api_account_rate_limit_status($type)
3176 if ($type == "xml") {
3178 'remaining-hits' => '150',
3179 '@attributes' => ["type" => "integer"],
3180 'hourly-limit' => '150',
3181 '@attributes2' => ["type" => "integer"],
3182 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3183 '@attributes3' => ["type" => "datetime"],
3184 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3185 '@attributes4' => ["type" => "integer"],
3189 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3190 'remaining_hits' => '150',
3191 'hourly_limit' => '150',
3192 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3196 return api_format_data('hash', $type, ['hash' => $hash]);
3199 /// @TODO move to top of file or somewhere better
3200 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3203 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3205 * @param string $type Return type (atom, rss, xml, json)
3207 * @return array|string
3209 function api_help_test($type)
3211 if ($type == 'xml') {
3217 return api_format_data('ok', $type, ["ok" => $ok]);
3220 /// @TODO move to top of file or somewhere better
3221 api_register_func('api/help/test', 'api_help_test', false);
3224 * Returns all lists the user subscribes to.
3226 * @param string $type Return type (atom, rss, xml, json)
3228 * @return array|string
3229 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3231 function api_lists_list($type)
3234 /// @TODO $ret is not filled here?
3235 return api_format_data('lists', $type, ["lists_list" => $ret]);
3238 /// @TODO move to top of file or somewhere better
3239 api_register_func('api/lists/list', 'api_lists_list', true);
3240 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3243 * Returns all groups the user owns.
3245 * @param string $type Return type (atom, rss, xml, json)
3247 * @return array|string
3248 * @throws BadRequestException
3249 * @throws ForbiddenException
3250 * @throws ImagickException
3251 * @throws InternalServerErrorException
3252 * @throws UnauthorizedException
3253 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3255 function api_lists_ownerships($type)
3259 if (api_user() === false) {
3260 throw new ForbiddenException();
3264 $user_info = api_get_user($a);
3265 $uid = $user_info['uid'];
3267 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3269 // loop through all groups
3271 foreach ($groups as $group) {
3272 if ($group['visible']) {
3278 'name' => $group['name'],
3279 'id' => intval($group['id']),
3280 'id_str' => (string) $group['id'],
3281 'user' => $user_info,
3285 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3288 /// @TODO move to top of file or somewhere better
3289 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3292 * Returns recent statuses from users in the specified group.
3294 * @param string $type Return type (atom, rss, xml, json)
3296 * @return array|string
3297 * @throws BadRequestException
3298 * @throws ForbiddenException
3299 * @throws ImagickException
3300 * @throws InternalServerErrorException
3301 * @throws UnauthorizedException
3302 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3304 function api_lists_statuses($type)
3308 $user_info = api_get_user($a);
3309 if (api_user() === false || $user_info === false) {
3310 throw new ForbiddenException();
3313 unset($_REQUEST["user_id"]);
3314 unset($_GET["user_id"]);
3316 unset($_REQUEST["screen_name"]);
3317 unset($_GET["screen_name"]);
3319 if (empty($_REQUEST['list_id'])) {
3320 throw new BadRequestException('list_id not specified');
3324 $count = $_REQUEST['count'] ?? 20;
3325 $page = $_REQUEST['page'] ?? 1;
3326 $since_id = $_REQUEST['since_id'] ?? 0;
3327 $max_id = $_REQUEST['max_id'] ?? 0;
3328 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3329 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3331 $start = max(0, ($page - 1) * $count);
3333 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3334 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3337 $condition[0] .= " AND `item`.`id` <= ?";
3338 $condition[] = $max_id;
3340 if ($exclude_replies > 0) {
3341 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3343 if ($conversation_id > 0) {
3344 $condition[0] .= " AND `item`.`parent` = ?";
3345 $condition[] = $conversation_id;
3348 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3349 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3351 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3353 $data = ['status' => $items];
3358 $data = api_rss_extra($a, $data, $user_info);
3362 return api_format_data("statuses", $type, $data);
3365 /// @TODO move to top of file or somewhere better
3366 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3369 * Considers friends and followers lists to be private and won't return
3370 * anything if any user_id parameter is passed.
3372 * @brief Returns either the friends of the follower list
3374 * @param string $qtype Either "friends" or "followers"
3375 * @return boolean|array
3376 * @throws BadRequestException
3377 * @throws ForbiddenException
3378 * @throws ImagickException
3379 * @throws InternalServerErrorException
3380 * @throws UnauthorizedException
3382 function api_statuses_f($qtype)
3386 if (api_user() === false) {
3387 throw new ForbiddenException();
3391 $count = $_GET['count'] ?? 20;
3392 $page = $_GET['page'] ?? 1;
3394 $start = max(0, ($page - 1) * $count);
3396 $user_info = api_get_user($a);
3398 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3399 /* this is to stop Hotot to load friends multiple times
3400 * I'm not sure if I'm missing return something or
3401 * is a bug in hotot. Workaround, meantime
3405 return array('$users' => $ret);*/
3410 if ($qtype == 'friends') {
3411 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3412 } elseif ($qtype == 'followers') {
3413 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3416 // friends and followers only for self
3417 if ($user_info['self'] == 0) {
3418 $sql_extra = " AND false ";
3421 if ($qtype == 'blocks') {
3422 $sql_filter = 'AND `blocked` AND NOT `pending`';
3423 } elseif ($qtype == 'incoming') {
3424 $sql_filter = 'AND `pending`';
3426 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3444 foreach ($r as $cid) {
3445 $user = api_get_user($a, $cid['nurl']);
3446 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3447 unset($user["uid"]);
3448 unset($user["self"]);
3455 return ['user' => $ret];
3460 * Returns the user's friends.
3462 * @brief Returns the list of friends of the provided user
3464 * @deprecated By Twitter API in favor of friends/list
3466 * @param string $type Either "json" or "xml"
3467 * @return boolean|string|array
3468 * @throws BadRequestException
3469 * @throws ForbiddenException
3471 function api_statuses_friends($type)
3473 $data = api_statuses_f("friends");
3474 if ($data === false) {
3477 return api_format_data("users", $type, $data);
3481 * Returns the user's followers.
3483 * @brief Returns the list of followers of the provided user
3485 * @deprecated By Twitter API in favor of friends/list
3487 * @param string $type Either "json" or "xml"
3488 * @return boolean|string|array
3489 * @throws BadRequestException
3490 * @throws ForbiddenException
3492 function api_statuses_followers($type)
3494 $data = api_statuses_f("followers");
3495 if ($data === false) {
3498 return api_format_data("users", $type, $data);
3501 /// @TODO move to top of file or somewhere better
3502 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3503 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3506 * Returns the list of blocked users
3508 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3510 * @param string $type Either "json" or "xml"
3512 * @return boolean|string|array
3513 * @throws BadRequestException
3514 * @throws ForbiddenException
3516 function api_blocks_list($type)
3518 $data = api_statuses_f('blocks');
3519 if ($data === false) {
3522 return api_format_data("users", $type, $data);
3525 /// @TODO move to top of file or somewhere better
3526 api_register_func('api/blocks/list', 'api_blocks_list', true);
3529 * Returns the list of pending users IDs
3531 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3533 * @param string $type Either "json" or "xml"
3535 * @return boolean|string|array
3536 * @throws BadRequestException
3537 * @throws ForbiddenException
3539 function api_friendships_incoming($type)
3541 $data = api_statuses_f('incoming');
3542 if ($data === false) {
3547 foreach ($data['user'] as $user) {
3548 $ids[] = $user['id'];
3551 return api_format_data("ids", $type, ['id' => $ids]);
3554 /// @TODO move to top of file or somewhere better
3555 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3558 * Returns the instance's configuration information.
3560 * @param string $type Return type (atom, rss, xml, json)
3562 * @return array|string
3563 * @throws InternalServerErrorException
3565 function api_statusnet_config($type)
3569 $name = Config::get('config', 'sitename');
3570 $server = $a->getHostName();
3571 $logo = System::baseUrl() . '/images/friendica-64.png';
3572 $email = Config::get('config', 'admin_email');
3573 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3574 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3575 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3576 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3577 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3580 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3581 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3582 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3583 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3584 'shorturllength' => '30',
3586 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3587 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3588 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3589 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3594 return api_format_data('config', $type, ['config' => $config]);
3597 /// @TODO move to top of file or somewhere better
3598 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3599 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3603 * @param string $type Return type (atom, rss, xml, json)
3605 * @return array|string
3607 function api_statusnet_version($type)
3610 $fake_statusnet_version = "0.9.7";
3612 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3615 /// @TODO move to top of file or somewhere better
3616 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3617 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3621 * @param string $type Return type (atom, rss, xml, json)
3623 * @param int $rel A contact relationship constant
3624 * @return array|string|void
3625 * @throws BadRequestException
3626 * @throws ForbiddenException
3627 * @throws ImagickException
3628 * @throws InternalServerErrorException
3629 * @throws UnauthorizedException
3630 * @todo use api_format_data() to return data
3632 function api_ff_ids($type, int $rel)
3635 throw new ForbiddenException();
3642 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3644 $contacts = DBA::p("SELECT `pcontact`.`id`
3646 INNER JOIN `contact` AS `pcontact`
3647 ON `contact`.`nurl` = `pcontact`.`nurl`
3648 AND `pcontact`.`uid` = 0
3649 WHERE `contact`.`uid` = ?
3650 AND NOT `contact`.`self`
3651 AND `contact`.`rel` IN (?, ?)",
3658 foreach (DBA::toArray($contacts) as $contact) {
3659 if ($stringify_ids) {
3660 $ids[] = $contact['id'];
3662 $ids[] = intval($contact['id']);
3666 return api_format_data('ids', $type, ['id' => $ids]);
3670 * Returns the ID of every user the user is following.
3672 * @param string $type Return type (atom, rss, xml, json)
3674 * @return array|string
3675 * @throws BadRequestException
3676 * @throws ForbiddenException
3677 * @throws ImagickException
3678 * @throws InternalServerErrorException
3679 * @throws UnauthorizedException
3680 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3682 function api_friends_ids($type)
3684 return api_ff_ids($type, Contact::SHARING);
3688 * Returns the ID of every user following the user.
3690 * @param string $type Return type (atom, rss, xml, json)
3692 * @return array|string
3693 * @throws BadRequestException
3694 * @throws ForbiddenException
3695 * @throws ImagickException
3696 * @throws InternalServerErrorException
3697 * @throws UnauthorizedException
3698 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3700 function api_followers_ids($type)
3702 return api_ff_ids($type, Contact::FOLLOWER);
3705 /// @TODO move to top of file or somewhere better
3706 api_register_func('api/friends/ids', 'api_friends_ids', true);
3707 api_register_func('api/followers/ids', 'api_followers_ids', true);
3710 * Sends a new direct message.
3712 * @param string $type Return type (atom, rss, xml, json)
3714 * @return array|string
3715 * @throws BadRequestException
3716 * @throws ForbiddenException
3717 * @throws ImagickException
3718 * @throws InternalServerErrorException
3719 * @throws NotFoundException
3720 * @throws UnauthorizedException
3721 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3723 function api_direct_messages_new($type)
3727 if (api_user() === false) {
3728 throw new ForbiddenException();
3731 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3735 $sender = api_get_user($a);
3738 if (!empty($_POST['screen_name'])) {
3740 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3742 DBA::escape($_POST['screen_name'])
3745 if (DBA::isResult($r)) {
3746 // Selecting the id by priority, friendica first
3747 api_best_nickname($r);
3749 $recipient = api_get_user($a, $r[0]['nurl']);
3752 $recipient = api_get_user($a, $_POST['user_id']);
3755 if (empty($recipient)) {
3756 throw new NotFoundException('Recipient not found');
3760 if (!empty($_REQUEST['replyto'])) {
3762 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3764 intval($_REQUEST['replyto'])
3766 $replyto = $r[0]['parent-uri'];
3767 $sub = $r[0]['title'];
3769 if (!empty($_REQUEST['title'])) {
3770 $sub = $_REQUEST['title'];
3772 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3776 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3779 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3780 $ret = api_format_messages($r[0], $recipient, $sender);
3782 $ret = ["error"=>$id];
3785 $data = ['direct_message'=>$ret];
3791 $data = api_rss_extra($a, $data, $sender);
3795 return api_format_data("direct-messages", $type, $data);
3798 /// @TODO move to top of file or somewhere better
3799 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3802 * Destroys a direct message.
3804 * @brief delete a direct_message from mail table through api
3806 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3807 * @return string|array
3808 * @throws BadRequestException
3809 * @throws ForbiddenException
3810 * @throws ImagickException
3811 * @throws InternalServerErrorException
3812 * @throws UnauthorizedException
3813 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3815 function api_direct_messages_destroy($type)
3819 if (api_user() === false) {
3820 throw new ForbiddenException();
3824 $user_info = api_get_user($a);
3826 $id = $_REQUEST['id'] ?? 0;
3828 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3829 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3830 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3832 $uid = $user_info['uid'];
3833 // error if no id or parenturi specified (for clients posting parent-uri as well)
3834 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3835 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3836 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3839 // BadRequestException if no id specified (for clients using Twitter API)
3841 throw new BadRequestException('Message id not specified');
3844 // add parent-uri to sql command if specified by calling app
3845 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3847 // get data of the specified message id
3849 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3854 // error message if specified id is not in database
3855 if (!DBA::isResult($r)) {
3856 if ($verbose == "true") {
3857 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3858 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3860 /// @todo BadRequestException ok for Twitter API clients?
3861 throw new BadRequestException('message id not in database');
3866 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3871 if ($verbose == "true") {
3874 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3875 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3877 $answer = ['result' => 'error', 'message' => 'unknown error'];
3878 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3881 /// @todo return JSON data like Twitter API not yet implemented
3884 /// @TODO move to top of file or somewhere better
3885 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3890 * @brief unfollow contact
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 * @brief 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 * @brief 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 * @brief 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 = System::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 * @brief 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 * @brief 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 * @brief 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 user’s profile image.
4555 * @brief updates the profile image for the user (either a specified profile or the default profile)
4557 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4559 * @return string|array
4560 * @throws BadRequestException
4561 * @throws ForbiddenException
4562 * @throws ImagickException
4563 * @throws InternalServerErrorException
4564 * @throws NotFoundException
4565 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4567 function api_account_update_profile_image($type)
4569 if (api_user() === false) {
4570 throw new ForbiddenException();
4573 $profile_id = $_REQUEST['profile_id'] ?? 0;
4575 // error if image data is missing
4576 if (empty($_FILES['image'])) {
4577 throw new BadRequestException("no media data submitted");
4580 // check if specified profile id is valid
4581 if ($profile_id != 0) {
4582 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4583 // error message if specified profile id is not in database
4584 if (!DBA::isResult($profile)) {
4585 throw new BadRequestException("profile_id not available");
4587 $is_default_profile = $profile['is-default'];
4589 $is_default_profile = 1;
4592 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4594 if (!empty($_FILES['image'])) {
4595 $media = $_FILES['image'];
4596 } elseif (!empty($_FILES['media'])) {
4597 $media = $_FILES['media'];
4599 // save new profile image
4600 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4603 if (is_array($media['type'])) {
4604 $filetype = $media['type'][0];
4606 $filetype = $media['type'];
4608 if ($filetype == "image/jpeg") {
4610 } elseif ($filetype == "image/png") {
4613 throw new InternalServerErrorException('Unsupported filetype');
4616 // change specified profile or all profiles to the new resource-id
4617 if ($is_default_profile) {
4618 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4619 Photo::update(['profile' => false], $condition);
4621 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4622 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4623 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4626 Contact::updateSelfFromUserID(api_user(), true);
4628 // Update global directory in background
4629 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4630 if ($url && strlen(Config::get('system', 'directory'))) {
4631 Worker::add(PRIORITY_LOW, "Directory", $url);
4634 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4636 // output for client
4638 return api_account_verify_credentials($type);
4640 // SaveMediaToDatabase failed for some reason
4641 throw new InternalServerErrorException("image upload failed");
4645 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4646 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4647 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4648 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4649 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4650 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4651 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4652 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4653 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4656 * Update user profile
4658 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4660 * @return array|string
4661 * @throws BadRequestException
4662 * @throws ForbiddenException
4663 * @throws ImagickException
4664 * @throws InternalServerErrorException
4665 * @throws UnauthorizedException
4667 function api_account_update_profile($type)
4669 $local_user = api_user();
4670 $api_user = api_get_user(get_app());
4672 if (!empty($_POST['name'])) {
4673 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4674 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4675 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4676 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4679 if (isset($_POST['description'])) {
4680 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4681 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4682 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4685 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4686 // Update global directory in background
4687 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4688 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4691 return api_account_verify_credentials($type);
4694 /// @TODO move to top of file or somewhere better
4695 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4699 * @param string $acl_string
4703 function check_acl_input($acl_string)
4705 if (empty($acl_string)) {
4709 $contact_not_found = false;
4711 // split <x><y><z> into array of cid's
4712 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4714 // check for each cid if it is available on server
4715 $cid_array = $array[0];
4716 foreach ($cid_array as $cid) {
4717 $cid = str_replace("<", "", $cid);
4718 $cid = str_replace(">", "", $cid);
4719 $condition = ['id' => $cid, 'uid' => api_user()];
4720 $contact_not_found |= !DBA::exists('contact', $condition);
4722 return $contact_not_found;
4726 * @param string $mediatype
4727 * @param array $media
4728 * @param string $type
4729 * @param string $album
4730 * @param string $allow_cid
4731 * @param string $deny_cid
4732 * @param string $allow_gid
4733 * @param string $deny_gid
4734 * @param string $desc
4735 * @param integer $profile
4736 * @param boolean $visibility
4737 * @param string $photo_id
4739 * @throws BadRequestException
4740 * @throws ForbiddenException
4741 * @throws ImagickException
4742 * @throws InternalServerErrorException
4743 * @throws NotFoundException
4744 * @throws UnauthorizedException
4746 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)
4754 if (is_array($media)) {
4755 if (is_array($media['tmp_name'])) {
4756 $src = $media['tmp_name'][0];
4758 $src = $media['tmp_name'];
4760 if (is_array($media['name'])) {
4761 $filename = basename($media['name'][0]);
4763 $filename = basename($media['name']);
4765 if (is_array($media['size'])) {
4766 $filesize = intval($media['size'][0]);
4768 $filesize = intval($media['size']);
4770 if (is_array($media['type'])) {
4771 $filetype = $media['type'][0];
4773 $filetype = $media['type'];
4777 if ($filetype == "") {
4778 $filetype = Images::guessType($filename);
4780 $imagedata = @getimagesize($src);
4782 $filetype = $imagedata['mime'];
4785 "File upload src: " . $src . " - filename: " . $filename .
4786 " - size: " . $filesize . " - type: " . $filetype,
4790 // check if there was a php upload error
4791 if ($filesize == 0 && $media['error'] == 1) {
4792 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4794 // check against max upload size within Friendica instance
4795 $maximagesize = Config::get('system', 'maximagesize');
4796 if ($maximagesize && ($filesize > $maximagesize)) {
4797 $formattedBytes = Strings::formatBytes($maximagesize);
4798 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4801 // create Photo instance with the data of the image
4802 $imagedata = @file_get_contents($src);
4803 $Image = new Image($imagedata, $filetype);
4804 if (!$Image->isValid()) {
4805 throw new InternalServerErrorException("unable to process image data");
4808 // check orientation of image
4809 $Image->orient($src);
4812 // check max length of images on server
4813 $max_length = Config::get('system', 'max_image_length');
4815 $max_length = MAX_IMAGE_LENGTH;
4817 if ($max_length > 0) {
4818 $Image->scaleDown($max_length);
4819 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4821 $width = $Image->getWidth();
4822 $height = $Image->getHeight();
4824 // create a new resource-id if not already provided
4825 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4827 if ($mediatype == "photo") {
4828 // upload normal image (scales 0, 1, 2)
4829 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4831 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4833 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4835 if ($width > 640 || $height > 640) {
4836 $Image->scaleDown(640);
4837 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4839 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4843 if ($width > 320 || $height > 320) {
4844 $Image->scaleDown(320);
4845 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4847 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4850 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4851 } elseif ($mediatype == "profileimage") {
4852 // upload profile image (scales 4, 5, 6)
4853 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4855 if ($width > 300 || $height > 300) {
4856 $Image->scaleDown(300);
4857 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4859 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4863 if ($width > 80 || $height > 80) {
4864 $Image->scaleDown(80);
4865 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4867 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4871 if ($width > 48 || $height > 48) {
4872 $Image->scaleDown(48);
4873 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4875 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4878 $Image->__destruct();
4879 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4882 if (isset($r) && $r) {
4883 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4884 if ($photo_id == null && $mediatype == "photo") {
4885 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4887 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4888 return prepare_photo_data($type, false, $resource_id);
4890 throw new InternalServerErrorException("image upload failed");
4896 * @param string $hash
4897 * @param string $allow_cid
4898 * @param string $deny_cid
4899 * @param string $allow_gid
4900 * @param string $deny_gid
4901 * @param string $filetype
4902 * @param boolean $visibility
4903 * @throws InternalServerErrorException
4905 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4907 // get data about the api authenticated user
4908 $uri = Item::newURI(intval(api_user()));
4909 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4912 $arr['guid'] = System::createUUID();
4913 $arr['uid'] = intval(api_user());
4915 $arr['parent-uri'] = $uri;
4916 $arr['type'] = 'photo';
4918 $arr['resource-id'] = $hash;
4919 $arr['contact-id'] = $owner_record['id'];
4920 $arr['owner-name'] = $owner_record['name'];
4921 $arr['owner-link'] = $owner_record['url'];
4922 $arr['owner-avatar'] = $owner_record['thumb'];
4923 $arr['author-name'] = $owner_record['name'];
4924 $arr['author-link'] = $owner_record['url'];
4925 $arr['author-avatar'] = $owner_record['thumb'];
4927 $arr['allow_cid'] = $allow_cid;
4928 $arr['allow_gid'] = $allow_gid;
4929 $arr['deny_cid'] = $deny_cid;
4930 $arr['deny_gid'] = $deny_gid;
4931 $arr['visible'] = $visibility;
4935 'image/jpeg' => 'jpg',
4936 'image/png' => 'png',
4937 'image/gif' => 'gif'
4940 // adds link to the thumbnail scale photo
4941 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4942 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4945 // do the magic for storing the item in the database and trigger the federation to other contacts
4951 * @param string $type
4953 * @param string $photo_id
4956 * @throws BadRequestException
4957 * @throws ForbiddenException
4958 * @throws ImagickException
4959 * @throws InternalServerErrorException
4960 * @throws NotFoundException
4961 * @throws UnauthorizedException
4963 function prepare_photo_data($type, $scale, $photo_id)
4966 $user_info = api_get_user($a);
4968 if ($user_info === false) {
4969 throw new ForbiddenException();
4972 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4973 $data_sql = ($scale === false ? "" : "data, ");
4975 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4976 // clients needs to convert this in their way for further processing
4978 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4979 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4980 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4981 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4982 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4983 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4985 intval(local_user()),
4986 DBA::escape($photo_id),
4991 'image/jpeg' => 'jpg',
4992 'image/png' => 'png',
4993 'image/gif' => 'gif'
4996 // prepare output data for photo
4997 if (DBA::isResult($r)) {
4998 $data = ['photo' => $r[0]];
4999 $data['photo']['id'] = $data['photo']['resource-id'];
5000 if ($scale !== false) {
5001 $data['photo']['data'] = base64_encode($data['photo']['data']);
5003 unset($data['photo']['datasize']); //needed only with scale param
5005 if ($type == "xml") {
5006 $data['photo']['links'] = [];
5007 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5008 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
5010 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
5013 $data['photo']['link'] = [];
5014 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
5016 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5017 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
5021 unset($data['photo']['resource-id']);
5022 unset($data['photo']['minscale']);
5023 unset($data['photo']['maxscale']);
5025 throw new NotFoundException();
5028 // retrieve item element for getting activities (like, dislike etc.) related to photo
5029 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5030 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5032 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5034 // retrieve comments on photo
5035 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5036 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5038 $statuses = Item::selectForUser(api_user(), [], $condition);
5040 // prepare output of comments
5041 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5043 if ($type == "xml") {
5045 foreach ($commentData as $comment) {
5046 $comments[$k++ . ":comment"] = $comment;
5049 foreach ($commentData as $comment) {
5050 $comments[] = $comment;
5053 $data['photo']['friendica_comments'] = $comments;
5055 // include info if rights on photo and rights on item are mismatching
5056 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5057 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5058 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5059 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5060 $data['photo']['rights_mismatch'] = $rights_mismatch;
5067 * Similar as /mod/redir.php
5068 * redirect to 'url' after dfrn auth
5070 * Why this when there is mod/redir.php already?
5071 * This use api_user() and api_login()
5074 * c_url: url of remote contact to auth to
5075 * url: string, url to redirect after auth
5077 function api_friendica_remoteauth()
5079 $url = $_GET['url'] ?? '';
5080 $c_url = $_GET['c_url'] ?? '';
5082 if ($url === '' || $c_url === '') {
5083 throw new BadRequestException("Wrong parameters.");
5086 $c_url = Strings::normaliseLink($c_url);
5090 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5091 if (!DBA::isResult($contact)) {
5092 throw new BadRequestException("Unknown contact");
5095 $cid = $contact['id'];
5097 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5099 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5100 System::externalRedirect($url ?: $c_url);
5103 if ($contact['duplex'] && $contact['issued-id']) {
5104 $orig_id = $contact['issued-id'];
5105 $dfrn_id = '1:' . $orig_id;
5107 if ($contact['duplex'] && $contact['dfrn-id']) {
5108 $orig_id = $contact['dfrn-id'];
5109 $dfrn_id = '0:' . $orig_id;
5112 $sec = Strings::getRandomHex();
5114 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5115 'sec' => $sec, 'expire' => time() + 45];
5116 DBA::insert('profile_check', $fields);
5118 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5119 $dest = ($url ? '&destination_url=' . $url : '');
5121 System::externalRedirect(
5122 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5123 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5124 . '&type=profile&sec=' . $sec . $dest
5127 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5130 * Return an item with announcer data if it had been announced
5132 * @param array $item Item array
5133 * @return array Item array with announce data
5135 function api_get_announce($item)
5137 // Quit if the item already has got a different owner and author
5138 if ($item['owner-id'] != $item['author-id']) {
5142 // Don't change original or Diaspora posts
5143 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5147 // Quit if we do now the original author and it had been a post from a native network
5148 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5152 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5153 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5154 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5155 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5156 if (!DBA::isResult($announce)) {
5160 return array_merge($item, $announce);
5164 * @brief Return the item shared, if the item contains only the [share] tag
5166 * @param array $item Sharer item
5167 * @return array|false Shared item or false if not a reshare
5168 * @throws ImagickException
5169 * @throws InternalServerErrorException
5171 function api_share_as_retweet(&$item)
5173 $body = trim($item["body"]);
5175 if (Diaspora::isReshare($body, false) === false) {
5176 if ($item['author-id'] == $item['owner-id']) {
5179 // Reshares from OStatus, ActivityPub and Twitter
5180 $reshared_item = $item;
5181 $reshared_item['owner-id'] = $reshared_item['author-id'];
5182 $reshared_item['owner-link'] = $reshared_item['author-link'];
5183 $reshared_item['owner-name'] = $reshared_item['author-name'];
5184 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5185 return $reshared_item;
5189 $reshared = Item::getShareArray($item);
5190 if (empty($reshared)) {
5194 $reshared_item = $item;
5196 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5200 if (!empty($reshared['comment'])) {
5201 $item['body'] = $reshared['comment'];
5204 $reshared_item["share-pre-body"] = $reshared['comment'];
5205 $reshared_item["body"] = $reshared['shared'];
5206 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5207 $reshared_item["author-name"] = $reshared['author'];
5208 $reshared_item["author-link"] = $reshared['profile'];
5209 $reshared_item["author-avatar"] = $reshared['avatar'];
5210 $reshared_item["plink"] = $reshared['link'] ?? '';
5211 $reshared_item["created"] = $reshared['posted'];
5212 $reshared_item["edited"] = $reshared['posted'];
5214 // Try to fetch the original item
5215 if (!empty($reshared['guid'])) {
5216 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5217 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5218 $condition = ['id' => $original_id];
5223 if (!empty($condition)) {
5224 $original_item = Item::selectFirst([], $condition);
5225 if (DBA::isResult($original_item)) {
5226 $reshared_item = array_merge($reshared_item, $original_item);
5230 return $reshared_item;
5235 * @param array $item
5240 function api_in_reply_to($item)
5244 $in_reply_to['status_id'] = null;
5245 $in_reply_to['user_id'] = null;
5246 $in_reply_to['status_id_str'] = null;
5247 $in_reply_to['user_id_str'] = null;
5248 $in_reply_to['screen_name'] = null;
5250 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5251 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5252 if (DBA::isResult($parent)) {
5253 $in_reply_to['status_id'] = intval($parent['id']);
5255 $in_reply_to['status_id'] = intval($item['parent']);
5258 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5260 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5261 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5263 if (DBA::isResult($parent)) {
5264 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5265 $in_reply_to['user_id'] = intval($parent['author-id']);
5266 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5269 // There seems to be situation, where both fields are identical:
5270 // https://github.com/friendica/friendica/issues/1010
5271 // This is a bugfix for that.
5272 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5273 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']]);
5274 $in_reply_to['status_id'] = null;
5275 $in_reply_to['user_id'] = null;
5276 $in_reply_to['status_id_str'] = null;
5277 $in_reply_to['user_id_str'] = null;
5278 $in_reply_to['screen_name'] = null;
5282 return $in_reply_to;
5287 * @param string $text
5290 * @throws InternalServerErrorException
5292 function api_clean_plain_items($text)
5294 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5296 $text = BBCode::cleanPictureLinks($text);
5297 $URLSearchString = "^\[\]";
5299 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5301 if ($include_entities == "true") {
5302 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5305 // Simplify "attachment" element
5306 $text = BBCode::removeAttachment($text);
5313 * @param array $contacts
5317 function api_best_nickname(&$contacts)
5321 if (count($contacts) == 0) {
5325 foreach ($contacts as $contact) {
5326 if ($contact["network"] == "") {
5327 $contact["network"] = "dfrn";
5328 $best_contact = [$contact];
5332 if (sizeof($best_contact) == 0) {
5333 foreach ($contacts as $contact) {
5334 if ($contact["network"] == "dfrn") {
5335 $best_contact = [$contact];
5340 if (sizeof($best_contact) == 0) {
5341 foreach ($contacts as $contact) {
5342 if ($contact["network"] == "dspr") {
5343 $best_contact = [$contact];
5348 if (sizeof($best_contact) == 0) {
5349 foreach ($contacts as $contact) {
5350 if ($contact["network"] == "stat") {
5351 $best_contact = [$contact];
5356 if (sizeof($best_contact) == 0) {
5357 foreach ($contacts as $contact) {
5358 if ($contact["network"] == "pump") {
5359 $best_contact = [$contact];
5364 if (sizeof($best_contact) == 0) {
5365 foreach ($contacts as $contact) {
5366 if ($contact["network"] == "twit") {
5367 $best_contact = [$contact];
5372 if (sizeof($best_contact) == 1) {
5373 $contacts = $best_contact;
5375 $contacts = [$contacts[0]];
5380 * Return all or a specified group of the user with the containing contacts.
5382 * @param string $type Return type (atom, rss, xml, json)
5384 * @return array|string
5385 * @throws BadRequestException
5386 * @throws ForbiddenException
5387 * @throws ImagickException
5388 * @throws InternalServerErrorException
5389 * @throws UnauthorizedException
5391 function api_friendica_group_show($type)
5395 if (api_user() === false) {
5396 throw new ForbiddenException();
5400 $user_info = api_get_user($a);
5401 $gid = $_REQUEST['gid'] ?? 0;
5402 $uid = $user_info['uid'];
5404 // get data of the specified group id or all groups if not specified
5407 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5411 // error message if specified gid is not in database
5412 if (!DBA::isResult($r)) {
5413 throw new BadRequestException("gid not available");
5417 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5422 // loop through all groups and retrieve all members for adding data in the user array
5424 foreach ($r as $rr) {
5425 $members = Contact::getByGroupId($rr['id']);
5428 if ($type == "xml") {
5429 $user_element = "users";
5431 foreach ($members as $member) {
5432 $user = api_get_user($a, $member['nurl']);
5433 $users[$k++.":user"] = $user;
5436 $user_element = "user";
5437 foreach ($members as $member) {
5438 $user = api_get_user($a, $member['nurl']);
5442 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5444 return api_format_data("groups", $type, ['group' => $grps]);
5446 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5450 * Delete the specified group of the user.
5452 * @param string $type Return type (atom, rss, xml, json)
5454 * @return array|string
5455 * @throws BadRequestException
5456 * @throws ForbiddenException
5457 * @throws ImagickException
5458 * @throws InternalServerErrorException
5459 * @throws UnauthorizedException
5461 function api_friendica_group_delete($type)
5465 if (api_user() === false) {
5466 throw new ForbiddenException();
5470 $user_info = api_get_user($a);
5471 $gid = $_REQUEST['gid'] ?? 0;
5472 $name = $_REQUEST['name'] ?? '';
5473 $uid = $user_info['uid'];
5475 // error if no gid specified
5476 if ($gid == 0 || $name == "") {
5477 throw new BadRequestException('gid or name not specified');
5480 // get data of the specified group id
5482 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5486 // error message if specified gid is not in database
5487 if (!DBA::isResult($r)) {
5488 throw new BadRequestException('gid not available');
5491 // get data of the specified group id and group name
5493 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5498 // error message if specified gid is not in database
5499 if (!DBA::isResult($rname)) {
5500 throw new BadRequestException('wrong group name');
5504 $ret = Group::removeByName($uid, $name);
5507 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5508 return api_format_data("group_delete", $type, ['result' => $success]);
5510 throw new BadRequestException('other API error');
5513 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5518 * @param string $type Return type (atom, rss, xml, json)
5520 * @return array|string
5521 * @throws BadRequestException
5522 * @throws ForbiddenException
5523 * @throws ImagickException
5524 * @throws InternalServerErrorException
5525 * @throws UnauthorizedException
5526 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5528 function api_lists_destroy($type)
5532 if (api_user() === false) {
5533 throw new ForbiddenException();
5537 $user_info = api_get_user($a);
5538 $gid = $_REQUEST['list_id'] ?? 0;
5539 $uid = $user_info['uid'];
5541 // error if no gid specified
5543 throw new BadRequestException('gid not specified');
5546 // get data of the specified group id
5547 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5548 // error message if specified gid is not in database
5550 throw new BadRequestException('gid not available');
5553 if (Group::remove($gid)) {
5555 'name' => $group['name'],
5556 'id' => intval($gid),
5557 'id_str' => (string) $gid,
5558 'user' => $user_info
5561 return api_format_data("lists", $type, ['lists' => $list]);
5564 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5567 * Add a new group to the database.
5569 * @param string $name Group name
5570 * @param int $uid User ID
5571 * @param array $users List of users to add to the group
5574 * @throws BadRequestException
5576 function group_create($name, $uid, $users = [])
5578 // error if no name specified
5580 throw new BadRequestException('group name not specified');
5583 // get data of the specified group name
5585 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5589 // error message if specified group name already exists
5590 if (DBA::isResult($rname)) {
5591 throw new BadRequestException('group name already exists');
5594 // check if specified group name is a deleted group
5596 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5600 // error message if specified group name already exists
5601 if (DBA::isResult($rname)) {
5602 $reactivate_group = true;
5606 $ret = Group::create($uid, $name);
5608 $gid = Group::getIdByName($uid, $name);
5610 throw new BadRequestException('other API error');
5614 $erroraddinguser = false;
5616 foreach ($users as $user) {
5617 $cid = $user['cid'];
5618 // check if user really exists as contact
5620 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5624 if (count($contact)) {
5625 Group::addMember($gid, $cid);
5627 $erroraddinguser = true;
5628 $errorusers[] = $cid;
5632 // return success message incl. missing users in array
5633 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5635 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5639 * Create the specified group with the posted array of contacts.
5641 * @param string $type Return type (atom, rss, xml, json)
5643 * @return array|string
5644 * @throws BadRequestException
5645 * @throws ForbiddenException
5646 * @throws ImagickException
5647 * @throws InternalServerErrorException
5648 * @throws UnauthorizedException
5650 function api_friendica_group_create($type)
5654 if (api_user() === false) {
5655 throw new ForbiddenException();
5659 $user_info = api_get_user($a);
5660 $name = $_REQUEST['name'] ?? '';
5661 $uid = $user_info['uid'];
5662 $json = json_decode($_POST['json'], true);
5663 $users = $json['user'];
5665 $success = group_create($name, $uid, $users);
5667 return api_format_data("group_create", $type, ['result' => $success]);
5669 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5672 * Create a new group.
5674 * @param string $type Return type (atom, rss, xml, json)
5676 * @return array|string
5677 * @throws BadRequestException
5678 * @throws ForbiddenException
5679 * @throws ImagickException
5680 * @throws InternalServerErrorException
5681 * @throws UnauthorizedException
5682 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5684 function api_lists_create($type)
5688 if (api_user() === false) {
5689 throw new ForbiddenException();
5693 $user_info = api_get_user($a);
5694 $name = $_REQUEST['name'] ?? '';
5695 $uid = $user_info['uid'];
5697 $success = group_create($name, $uid);
5698 if ($success['success']) {
5700 'name' => $success['name'],
5701 'id' => intval($success['gid']),
5702 'id_str' => (string) $success['gid'],
5703 'user' => $user_info
5706 return api_format_data("lists", $type, ['lists'=>$grp]);
5709 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5712 * Update the specified group with the posted array of contacts.
5714 * @param string $type Return type (atom, rss, xml, json)
5716 * @return array|string
5717 * @throws BadRequestException
5718 * @throws ForbiddenException
5719 * @throws ImagickException
5720 * @throws InternalServerErrorException
5721 * @throws UnauthorizedException
5723 function api_friendica_group_update($type)
5727 if (api_user() === false) {
5728 throw new ForbiddenException();
5732 $user_info = api_get_user($a);
5733 $uid = $user_info['uid'];
5734 $gid = $_REQUEST['gid'] ?? 0;
5735 $name = $_REQUEST['name'] ?? '';
5736 $json = json_decode($_POST['json'], true);
5737 $users = $json['user'];
5739 // error if no name specified
5741 throw new BadRequestException('group name not specified');
5744 // error if no gid specified
5746 throw new BadRequestException('gid not specified');
5750 $members = Contact::getByGroupId($gid);
5751 foreach ($members as $member) {
5752 $cid = $member['id'];
5753 foreach ($users as $user) {
5754 $found = ($user['cid'] == $cid ? true : false);
5756 if (!isset($found) || !$found) {
5757 Group::removeMemberByName($uid, $name, $cid);
5762 $erroraddinguser = false;
5764 foreach ($users as $user) {
5765 $cid = $user['cid'];
5766 // check if user really exists as contact
5768 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5773 if (count($contact)) {
5774 Group::addMember($gid, $cid);
5776 $erroraddinguser = true;
5777 $errorusers[] = $cid;
5781 // return success message incl. missing users in array
5782 $status = ($erroraddinguser ? "missing user" : "ok");
5783 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5784 return api_format_data("group_update", $type, ['result' => $success]);
5787 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5790 * Update information about a group.
5792 * @param string $type Return type (atom, rss, xml, json)
5794 * @return array|string
5795 * @throws BadRequestException
5796 * @throws ForbiddenException
5797 * @throws ImagickException
5798 * @throws InternalServerErrorException
5799 * @throws UnauthorizedException
5800 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5802 function api_lists_update($type)
5806 if (api_user() === false) {
5807 throw new ForbiddenException();
5811 $user_info = api_get_user($a);
5812 $gid = $_REQUEST['list_id'] ?? 0;
5813 $name = $_REQUEST['name'] ?? '';
5814 $uid = $user_info['uid'];
5816 // error if no gid specified
5818 throw new BadRequestException('gid not specified');
5821 // get data of the specified group id
5822 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5823 // error message if specified gid is not in database
5825 throw new BadRequestException('gid not available');
5828 if (Group::update($gid, $name)) {
5831 'id' => intval($gid),
5832 'id_str' => (string) $gid,
5833 'user' => $user_info
5836 return api_format_data("lists", $type, ['lists' => $list]);
5840 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5844 * @param string $type Return type (atom, rss, xml, json)
5846 * @return array|string
5847 * @throws BadRequestException
5848 * @throws ForbiddenException
5849 * @throws ImagickException
5850 * @throws InternalServerErrorException
5852 function api_friendica_activity($type)
5856 if (api_user() === false) {
5857 throw new ForbiddenException();
5859 $verb = strtolower($a->argv[3]);
5860 $verb = preg_replace("|\..*$|", "", $verb);
5862 $id = $_REQUEST['id'] ?? 0;
5864 $res = Item::performLike($id, $verb);
5867 if ($type == "xml") {
5872 return api_format_data('ok', $type, ['ok' => $ok]);
5874 throw new BadRequestException('Error adding activity');
5878 /// @TODO move to top of file or somewhere better
5879 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5880 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5881 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5882 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5883 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5884 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5885 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5886 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5887 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5888 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5891 * @brief Returns notifications
5893 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5894 * @return string|array
5895 * @throws BadRequestException
5896 * @throws ForbiddenException
5897 * @throws InternalServerErrorException
5899 function api_friendica_notification($type)
5903 if (api_user() === false) {
5904 throw new ForbiddenException();
5907 throw new BadRequestException("Invalid argument count");
5909 /** @var Notify $nm */
5910 $nm = BaseObject::getClass(Notify::class);
5912 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
5914 if ($type == "xml") {
5916 if (!empty($notes)) {
5917 foreach ($notes as $note) {
5918 $xmlnotes[] = ["@attributes" => $note];
5924 return api_format_data("notes", $type, ['note' => $notes]);
5928 * POST request with 'id' param as notification id
5930 * @brief Set notification as seen and returns associated item (if possible)
5932 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5933 * @return string|array
5934 * @throws BadRequestException
5935 * @throws ForbiddenException
5936 * @throws ImagickException
5937 * @throws InternalServerErrorException
5938 * @throws UnauthorizedException
5940 function api_friendica_notification_seen($type)
5943 $user_info = api_get_user($a);
5945 if (api_user() === false || $user_info === false) {
5946 throw new ForbiddenException();
5949 throw new BadRequestException("Invalid argument count");
5952 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5954 /** @var Notify $nm */
5955 $nm = BaseObject::getClass(Notify::class);
5956 $note = $nm->getByID($id);
5957 if (is_null($note)) {
5958 throw new BadRequestException("Invalid argument");
5961 $nm->setSeen($note);
5962 if ($note['otype']=='item') {
5963 // would be really better with an ItemsManager and $im->getByID() :-P
5964 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5965 if (DBA::isResult($item)) {
5966 // we found the item, return it to the user
5967 $ret = api_format_items([$item], $user_info, false, $type);
5968 $data = ['status' => $ret];
5969 return api_format_data("status", $type, $data);
5971 // the item can't be found, but we set the note as seen, so we count this as a success
5973 return api_format_data('result', $type, ['result' => "success"]);
5976 /// @TODO move to top of file or somewhere better
5977 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5978 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5981 * @brief update a direct_message to seen state
5983 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5984 * @return string|array (success result=ok, error result=error with error message)
5985 * @throws BadRequestException
5986 * @throws ForbiddenException
5987 * @throws ImagickException
5988 * @throws InternalServerErrorException
5989 * @throws UnauthorizedException
5991 function api_friendica_direct_messages_setseen($type)
5994 if (api_user() === false) {
5995 throw new ForbiddenException();
5999 $user_info = api_get_user($a);
6000 $uid = $user_info['uid'];
6001 $id = $_REQUEST['id'] ?? 0;
6003 // return error if id is zero
6005 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6006 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6009 // error message if specified id is not in database
6010 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6011 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6012 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6015 // update seen indicator
6016 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6020 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6021 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6023 $answer = ['result' => 'error', 'message' => 'unknown error'];
6024 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6028 /// @TODO move to top of file or somewhere better
6029 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6032 * @brief search for direct_messages containing a searchstring through api
6034 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6035 * @param string $box
6036 * @return string|array (success: success=true if found and search_result contains found messages,
6037 * success=false if nothing was found, search_result='nothing found',
6038 * error: result=error with error message)
6039 * @throws BadRequestException
6040 * @throws ForbiddenException
6041 * @throws ImagickException
6042 * @throws InternalServerErrorException
6043 * @throws UnauthorizedException
6045 function api_friendica_direct_messages_search($type, $box = "")
6049 if (api_user() === false) {
6050 throw new ForbiddenException();
6054 $user_info = api_get_user($a);
6055 $searchstring = $_REQUEST['searchstring'] ?? '';
6056 $uid = $user_info['uid'];
6058 // error if no searchstring specified
6059 if ($searchstring == "") {
6060 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6061 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6064 // get data for the specified searchstring
6066 "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",
6068 DBA::escape('%'.$searchstring.'%')
6071 $profile_url = $user_info["url"];
6073 // message if nothing was found
6074 if (!DBA::isResult($r)) {
6075 $success = ['success' => false, 'search_results' => 'problem with query'];
6076 } elseif (count($r) == 0) {
6077 $success = ['success' => false, 'search_results' => 'nothing found'];
6080 foreach ($r as $item) {
6081 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6082 $recipient = $user_info;
6083 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6084 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6085 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6086 $sender = $user_info;
6089 if (isset($recipient) && isset($sender)) {
6090 $ret[] = api_format_messages($item, $recipient, $sender);
6093 $success = ['success' => true, 'search_results' => $ret];
6096 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6099 /// @TODO move to top of file or somewhere better
6100 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6103 * @brief return data of all the profiles a user has to the client
6105 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6106 * @return string|array
6107 * @throws BadRequestException
6108 * @throws ForbiddenException
6109 * @throws ImagickException
6110 * @throws InternalServerErrorException
6111 * @throws UnauthorizedException
6113 function api_friendica_profile_show($type)
6117 if (api_user() === false) {
6118 throw new ForbiddenException();
6122 $profile_id = $_REQUEST['profile_id'] ?? 0;
6124 // retrieve general information about profiles for user
6125 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6126 $directory = Config::get('system', 'directory');
6128 // get data of the specified profile id or all profiles of the user if not specified
6129 if ($profile_id != 0) {
6130 $r = Profile::getById(api_user(), $profile_id);
6131 // error message if specified gid is not in database
6132 if (!DBA::isResult($r)) {
6133 throw new BadRequestException("profile_id not available");
6136 $r = Profile::getListByUser(api_user());
6138 // loop through all returned profiles and retrieve data and users
6141 if (DBA::isResult($r)) {
6142 foreach ($r as $rr) {
6143 $profile = api_format_items_profiles($rr);
6145 // select all users from contact table, loop and prepare standard return for user data
6147 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6148 foreach ($nurls as $nurl) {
6149 $user = api_get_user($a, $nurl['nurl']);
6150 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6152 $profile['users'] = $users;
6154 // add prepared profile data to array for final return
6155 if ($type == "xml") {
6156 $profiles[$k++ . ":profile"] = $profile;
6158 $profiles[] = $profile;
6163 // return settings, authenticated user and profiles data
6164 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6166 $result = ['multi_profiles' => $multi_profiles ? true : false,
6167 'global_dir' => $directory,
6168 'friendica_owner' => api_get_user($a, $self['nurl']),
6169 'profiles' => $profiles];
6170 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6172 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6175 * Returns a list of saved searches.
6177 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6179 * @param string $type Return format: json or xml
6181 * @return string|array
6184 function api_saved_searches_list($type)
6186 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6189 while ($term = DBA::fetch($terms)) {
6191 'created_at' => api_date(time()),
6192 'id' => intval($term['id']),
6193 'id_str' => $term['id'],
6194 'name' => $term['term'],
6196 'query' => $term['term']
6202 return api_format_data("terms", $type, ['terms' => $result]);
6205 /// @TODO move to top of file or somewhere better
6206 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6209 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6211 * @brief Number of comments
6213 * @param object $data [Status, Status]
6217 function bindComments(&$data)
6219 if (count($data) == 0) {
6225 foreach ($data as $item) {
6226 $ids[] = $item['id'];
6229 $idStr = DBA::escape(implode(', ', $ids));
6230 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6231 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6232 $itemsData = DBA::toArray($items);
6234 foreach ($itemsData as $item) {
6235 $comments[$item['parent']] = $item['comments'];
6238 foreach ($data as $idx => $item) {
6240 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6245 @TODO Maybe open to implement?
6247 [pagename] => api/1.1/statuses/lookup.json
6248 [id] => 605138389168451584
6249 [include_cards] => true
6250 [cards_platform] => Android-12
6251 [include_entities] => true
6252 [include_my_retweet] => 1
6254 [include_reply_count] => true
6255 [include_descendent_reply_count] => true
6259 Not implemented by now:
6260 statuses/retweets_of_me
6265 account/update_location
6266 account/update_profile_background_image
6269 friendica/profile/update
6270 friendica/profile/create
6271 friendica/profile/delete
6273 Not implemented in status.net:
6274 statuses/retweeted_to_me
6275 statuses/retweeted_by_me
6276 direct_messages/destroy
6278 account/update_delivery_device
6279 notifications/follow