3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Authentication;
15 use Friendica\Core\Config;
16 use Friendica\Core\Hook;
17 use Friendica\Core\L10n;
18 use Friendica\Core\Logger;
19 use Friendica\Core\NotificationsManager;
20 use Friendica\Core\PConfig;
21 use Friendica\Core\Protocol;
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\Photo;
30 use Friendica\Model\User;
31 use Friendica\Network\FKOAuth1;
32 use Friendica\Network\HTTPException;
33 use Friendica\Network\HTTPException\BadRequestException;
34 use Friendica\Network\HTTPException\ExpectationFailedException;
35 use Friendica\Network\HTTPException\ForbiddenException;
36 use Friendica\Network\HTTPException\InternalServerErrorException;
37 use Friendica\Network\HTTPException\MethodNotAllowedException;
38 use Friendica\Network\HTTPException\NotFoundException;
39 use Friendica\Network\HTTPException\NotImplementedException;
40 use Friendica\Network\HTTPException\TooManyRequestsException;
41 use Friendica\Network\HTTPException\UnauthorizedException;
42 use Friendica\Object\Image;
43 use Friendica\Protocol\Diaspora;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Network;
46 use Friendica\Util\Proxy as ProxyUtils;
47 use Friendica\Util\Strings;
48 use Friendica\Util\XML;
50 require_once 'mod/share.php';
51 require_once 'mod/item.php';
52 require_once 'mod/wall_upload.php';
54 define('API_METHOD_ANY', '*');
55 define('API_METHOD_GET', 'GET');
56 define('API_METHOD_POST', 'POST,PUT');
57 define('API_METHOD_DELETE', 'POST,DELETE');
59 define('API_LOG_PREFIX', 'API {action} - ');
65 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
66 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
67 * into a page, and visitors will post something without noticing it).
69 * @brief Auth API user
73 if (!empty($_SESSION['allow_api'])) {
81 * Clients can send 'source' parameter to be show in post metadata
82 * as "sent via <source>".
83 * Some clients doesn't send a source param, we support ones we know
86 * @brief Get source name from API client
89 * Client source name, default to "api" if unset/unknown
94 if (requestdata('source')) {
95 return requestdata('source');
98 // Support for known clients that doesn't send a source name
99 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
100 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
104 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
106 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
113 * @brief Format date for API
115 * @param string $str Source date, as UTC
116 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
119 function api_date($str)
121 // Wed May 23 06:01:13 +0000 2007
122 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
126 * Register a function to be the endpoint for defined API path.
128 * @brief Register API endpoint
130 * @param string $path API URL path, relative to System::baseUrl()
131 * @param string $func Function name to call on path request
132 * @param bool $auth API need logged user
133 * @param string $method HTTP method reqiured to call this endpoint.
134 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
135 * Default to API_METHOD_ANY
137 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
147 // Workaround for hotot
148 $path = str_replace("api/", "api/1.1/", $path);
158 * Log in user via OAuth1 or Simple HTTP Auth.
159 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
161 * @brief Login API user
164 * @throws InternalServerErrorException
165 * @throws UnauthorizedException
166 * @hook 'authenticate'
168 * 'username' => username from login form
169 * 'password' => password from login form
170 * 'authenticated' => return status,
171 * 'user_record' => return authenticated user record
173 * array $user logged user record
175 function api_login(App $a)
177 $oauth1 = new FKOAuth1();
180 $request = OAuthRequest::from_request();
181 list($consumer, $token) = $oauth1->verify_request($request);
182 if (!is_null($token)) {
183 $oauth1->loginUser($token->uid);
184 Hook::callAll('logged_in', $a->user);
187 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
188 var_dump($consumer, $token);
190 } catch (Exception $e) {
191 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
194 // workaround for HTTP-auth in CGI mode
195 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
196 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
197 if (strlen($userpass)) {
198 list($name, $password) = explode(':', $userpass);
199 $_SERVER['PHP_AUTH_USER'] = $name;
200 $_SERVER['PHP_AUTH_PW'] = $password;
204 if (empty($_SERVER['PHP_AUTH_USER'])) {
205 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
206 header('WWW-Authenticate: Basic realm="Friendica"');
207 throw new UnauthorizedException("This API requires login");
210 $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
211 $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
213 // allow "user@server" login (but ignore 'server' part)
214 $at = strstr($user, "@", true);
219 // next code from mod/auth.php. needs better solution
223 'username' => trim($user),
224 'password' => trim($password),
225 'authenticated' => 0,
226 'user_record' => null,
230 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
231 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
232 * and later addons should not interfere with an earlier one that succeeded.
234 Hook::callAll('authenticate', $addon_auth);
236 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
237 $record = $addon_auth['user_record'];
239 $user_id = User::authenticate(trim($user), trim($password));
240 if ($user_id !== false) {
241 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
245 if (!DBA::isResult($record)) {
246 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
247 header('WWW-Authenticate: Basic realm="Friendica"');
248 //header('HTTP/1.0 401 Unauthorized');
249 //die('This api requires login');
250 throw new UnauthorizedException("This API requires login");
253 Authentication::setAuthenticatedSessionForUser($record);
255 $_SESSION["allow_api"] = true;
257 Hook::callAll('logged_in', $a->user);
261 * API endpoints can define which HTTP method to accept when called.
262 * This function check the current HTTP method agains endpoint
265 * @brief Check HTTP method of called API
267 * @param string $method Required methods, uppercase, separated by comma
270 function api_check_method($method)
272 if ($method == "*") {
275 return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
279 * Authenticate user, call registered API function, set HTTP headers
281 * @brief Main API entry point
284 * @return string|array API call result
287 function api_call(App $a)
289 global $API, $called_api;
292 if (strpos($a->query_string, ".xml") > 0) {
295 if (strpos($a->query_string, ".json") > 0) {
298 if (strpos($a->query_string, ".rss") > 0) {
301 if (strpos($a->query_string, ".atom") > 0) {
306 foreach ($API as $p => $info) {
307 if (strpos($a->query_string, $p) === 0) {
308 if (!api_check_method($info['method'])) {
309 throw new MethodNotAllowedException();
312 $called_api = explode("/", $p);
313 //unset($_SERVER['PHP_AUTH_USER']);
315 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
316 if (!empty($info['auth']) && api_user() === false) {
320 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
321 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
323 $stamp = microtime(true);
324 $return = call_user_func($info['func'], $type);
325 $duration = (float) (microtime(true) - $stamp);
327 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
329 if (Config::get("system", "profiler")) {
330 $duration = microtime(true)-$a->performance["start"];
332 /// @TODO round() really everywhere?
334 API_LOG_PREFIX . 'performance',
338 'database_read' => round($a->performance["database"] - $a->performance["database_write"], 3),
339 'database_write' => round($a->performance["database_write"], 3),
340 'cache_read' => round($a->performance["cache"], 3),
341 'cache_write' => round($a->performance["cache_write"], 3),
342 'network_io' => round($a->performance["network"], 2),
343 'file_io' => round($a->performance["file"], 2),
344 'other_io' => round($duration - ($a->performance["database"]
345 + $a->performance["cache"] + $a->performance["cache_write"]
346 + $a->performance["network"] + $a->performance["file"]), 2),
347 'total' => round($duration, 2)
351 if (Config::get("rendertime", "callstack")) {
352 $o = "Database Read:\n";
353 foreach ($a->callstack["database"] as $func => $time) {
354 $time = round($time, 3);
356 $o .= $func . ": " . $time . "\n";
359 $o .= "\nDatabase Write:\n";
360 foreach ($a->callstack["database_write"] as $func => $time) {
361 $time = round($time, 3);
363 $o .= $func . ": " . $time . "\n";
367 $o = "Cache Read:\n";
368 foreach ($a->callstack["cache"] as $func => $time) {
369 $time = round($time, 3);
371 $o .= $func . ": " . $time . "\n";
374 $o .= "\nCache Write:\n";
375 foreach ($a->callstack["cache_write"] as $func => $time) {
376 $time = round($time, 3);
378 $o .= $func . ": " . $time . "\n";
382 $o .= "\nNetwork:\n";
383 foreach ($a->callstack["network"] as $func => $time) {
384 $time = round($time, 3);
386 $o .= $func . ": " . $time . "\n";
389 Logger::debug(API_LOG_PREFIX . $o, ['module' => 'api', 'action' => 'call']);
393 if (false === $return) {
395 * api function returned false withour throw an
396 * exception. This should not happend, throw a 500
398 throw new InternalServerErrorException();
403 header("Content-Type: text/xml");
406 header("Content-Type: application/json");
407 $json = json_encode(end($return));
408 if (!empty($_GET['callback'])) {
409 $json = $_GET['callback'] . "(" . $json . ")";
414 header("Content-Type: application/rss+xml");
415 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
418 header("Content-Type: application/atom+xml");
419 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
426 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call']);
427 throw new NotImplementedException();
428 } catch (HTTPException $e) {
429 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
430 return api_error($type, $e);
435 * @brief Format API error string
437 * @param string $type Return type (xml, json, rss, as)
438 * @param object $e HTTPException Error object
439 * @return string|array error message formatted as $type
441 function api_error($type, $e)
445 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
446 /// @TODO: https://dev.twitter.com/overview/api/response-codes
448 $error = ["error" => $error,
449 "code" => $e->httpcode . " " . $e->httpdesc,
450 "request" => $a->query_string];
452 $return = api_format_data('status', $type, ['status' => $error]);
456 header("Content-Type: text/xml");
459 header("Content-Type: application/json");
460 $return = json_encode($return);
463 header("Content-Type: application/rss+xml");
466 header("Content-Type: application/atom+xml");
474 * @brief Set values for RSS template
477 * @param array $arr Array to be passed to template
478 * @param array $user_info User info
480 * @throws BadRequestException
481 * @throws ImagickException
482 * @throws InternalServerErrorException
483 * @throws UnauthorizedException
484 * @todo find proper type-hints
486 function api_rss_extra(App $a, $arr, $user_info)
488 if (is_null($user_info)) {
489 $user_info = api_get_user($a);
492 $arr['$user'] = $user_info;
494 'alternate' => $user_info['url'],
495 'self' => System::baseUrl() . "/" . $a->query_string,
496 'base' => System::baseUrl(),
497 'updated' => api_date(null),
498 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
499 'language' => $user_info['lang'],
500 'logo' => System::baseUrl() . "/images/friendica-32.png",
508 * @brief Unique contact to contact url.
510 * @param int $id Contact id
511 * @return bool|string
512 * Contact url or False if contact id is unknown
515 function api_unique_id_to_nurl($id)
517 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
519 if (DBA::isResult($r)) {
527 * @brief Get user info array.
530 * @param int|string $contact_id Contact ID or URL
532 * @throws BadRequestException
533 * @throws ImagickException
534 * @throws InternalServerErrorException
535 * @throws UnauthorizedException
537 function api_get_user(App $a, $contact_id = null)
545 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
547 // Searching for contact URL
548 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
549 $user = DBA::escape(Strings::normaliseLink($contact_id));
551 $extra_query = "AND `contact`.`nurl` = '%s' ";
552 if (api_user() !== false) {
553 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
557 // Searching for contact id with uid = 0
558 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
559 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
562 throw new BadRequestException("User ID ".$contact_id." not found.");
566 $extra_query = "AND `contact`.`nurl` = '%s' ";
567 if (api_user() !== false) {
568 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
572 if (is_null($user) && !empty($_GET['user_id'])) {
573 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
576 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
580 $extra_query = "AND `contact`.`nurl` = '%s' ";
581 if (api_user() !== false) {
582 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
585 if (is_null($user) && !empty($_GET['screen_name'])) {
586 $user = DBA::escape($_GET['screen_name']);
587 $extra_query = "AND `contact`.`nick` = '%s' ";
588 if (api_user() !== false) {
589 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
593 if (is_null($user) && !empty($_GET['profileurl'])) {
594 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
595 $extra_query = "AND `contact`.`nurl` = '%s' ";
596 if (api_user() !== false) {
597 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
601 // $called_api is the API path exploded on / and is expected to have at least 2 elements
602 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
603 $argid = count($called_api);
604 if (!empty($a->argv[$argid])) {
605 $data = explode(".", $a->argv[$argid]);
606 if (count($data) > 1) {
607 list($user, $null) = $data;
610 if (is_numeric($user)) {
611 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
615 $extra_query = "AND `contact`.`nurl` = '%s' ";
616 if (api_user() !== false) {
617 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
621 $user = DBA::escape($user);
622 $extra_query = "AND `contact`.`nick` = '%s' ";
623 if (api_user() !== false) {
624 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
629 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
632 if (api_user() === false) {
636 $user = $_SESSION['uid'];
637 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
641 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
645 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
651 // Selecting the id by priority, friendica first
652 if (is_array($uinfo)) {
653 api_best_nickname($uinfo);
656 // if the contact wasn't found, fetch it from the contacts with uid = 0
657 if (!DBA::isResult($uinfo)) {
659 throw new BadRequestException("User not found.");
662 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
664 if (DBA::isResult($contact)) {
665 // If no nick where given, extract it from the address
666 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
667 $contact['nick'] = api_get_nick($contact["url"]);
671 'id' => $contact["id"],
672 'id_str' => (string) $contact["id"],
673 'name' => $contact["name"],
674 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
675 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
676 'description' => $contact["about"],
677 'profile_image_url' => $contact["micro"],
678 'profile_image_url_https' => $contact["micro"],
679 'profile_image_url_profile_size' => $contact["thumb"],
680 'profile_image_url_large' => $contact["photo"],
681 'url' => $contact["url"],
682 'protected' => false,
683 'followers_count' => 0,
684 'friends_count' => 0,
686 'created_at' => api_date($contact["created"]),
687 'favourites_count' => 0,
689 'time_zone' => 'UTC',
690 'geo_enabled' => false,
692 'statuses_count' => 0,
694 'contributors_enabled' => false,
695 'is_translator' => false,
696 'is_translation_enabled' => false,
697 'following' => false,
698 'follow_request_sent' => false,
699 'statusnet_blocking' => false,
700 'notifications' => false,
701 'statusnet_profile_url' => $contact["url"],
703 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
704 'pid' => Contact::getIdForURL($contact["url"], 0, true),
706 'network' => $contact["network"],
711 throw new BadRequestException("User ".$url." not found.");
715 if ($uinfo[0]['self']) {
716 if ($uinfo[0]['network'] == "") {
717 $uinfo[0]['network'] = Protocol::DFRN;
720 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
721 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
728 // Add a nick if it isn't present there
729 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
730 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
733 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
735 if (!empty($profile['about'])) {
736 $description = $profile['about'];
738 $description = $uinfo[0]["about"];
741 if (!empty($usr['default-location'])) {
742 $location = $usr['default-location'];
743 } elseif (!empty($uinfo[0]["location"])) {
744 $location = $uinfo[0]["location"];
746 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
750 'id' => intval($pcontact_id),
751 'id_str' => (string) intval($pcontact_id),
752 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
753 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
754 'location' => $location,
755 'description' => $description,
756 'profile_image_url' => $uinfo[0]['micro'],
757 'profile_image_url_https' => $uinfo[0]['micro'],
758 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
759 'profile_image_url_large' => $uinfo[0]["photo"],
760 'url' => $uinfo[0]['url'],
761 'protected' => false,
762 'followers_count' => intval($countfollowers),
763 'friends_count' => intval($countfriends),
765 'created_at' => api_date($uinfo[0]['created']),
766 'favourites_count' => intval($starred),
768 'time_zone' => 'UTC',
769 'geo_enabled' => false,
771 'statuses_count' => intval($countitems),
773 'contributors_enabled' => false,
774 'is_translator' => false,
775 'is_translation_enabled' => false,
776 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
777 'follow_request_sent' => false,
778 'statusnet_blocking' => false,
779 'notifications' => false,
781 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
782 'statusnet_profile_url' => $uinfo[0]['url'],
783 'uid' => intval($uinfo[0]['uid']),
784 'cid' => intval($uinfo[0]['cid']),
785 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
786 'self' => $uinfo[0]['self'],
787 'network' => $uinfo[0]['network'],
790 // If this is a local user and it uses Frio, we can get its color preferences.
792 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
793 if ($theme_info['theme'] === 'frio') {
794 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
796 if ($schema && ($schema != '---')) {
797 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
798 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
799 require_once $schemefile;
802 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
803 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
804 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
806 if (empty($nav_bg)) {
809 if (empty($link_color)) {
810 $link_color = "#6fdbe8";
812 if (empty($bgcolor)) {
813 $bgcolor = "#ededed";
816 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
817 $ret['profile_link_color'] = str_replace('#', '', $link_color);
818 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
826 * @brief return api-formatted array for item's author and owner
829 * @param array $item item from db
830 * @return array(array:author, array:owner)
831 * @throws BadRequestException
832 * @throws ImagickException
833 * @throws InternalServerErrorException
834 * @throws UnauthorizedException
836 function api_item_get_user(App $a, $item)
838 $status_user = api_get_user($a, defaults($item, 'author-id', null));
840 $status_user["protected"] = defaults($item, 'private', 0);
842 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
843 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
845 $owner_user = $status_user;
848 return ([$status_user, $owner_user]);
852 * @brief walks recursively through an array with the possibility to change value and key
854 * @param array $array The array to walk through
855 * @param callable $callback The callback function
857 * @return array the transformed array
859 function api_walk_recursive(array &$array, callable $callback)
863 foreach ($array as $k => $v) {
865 if ($callback($v, $k)) {
866 $new_array[$k] = api_walk_recursive($v, $callback);
869 if ($callback($v, $k)) {
880 * @brief Callback function to transform the array in an array that can be transformed in a XML file
882 * @param mixed $item Array item value
883 * @param string $key Array key
885 * @return boolean Should the array item be deleted?
887 function api_reformat_xml(&$item, &$key)
889 if (is_bool($item)) {
890 $item = ($item ? "true" : "false");
893 if (substr($key, 0, 10) == "statusnet_") {
894 $key = "statusnet:".substr($key, 10);
895 } elseif (substr($key, 0, 10) == "friendica_") {
896 $key = "friendica:".substr($key, 10);
898 /// @TODO old-lost code?
900 // $key = "default:".$key;
906 * @brief Creates the XML from a JSON style array
908 * @param array $data JSON style array
909 * @param string $root_element Name of the root element
911 * @return string The XML data
913 function api_create_xml(array $data, $root_element)
915 $childname = key($data);
916 $data2 = array_pop($data);
918 $namespaces = ["" => "http://api.twitter.com",
919 "statusnet" => "http://status.net/schema/api/1/",
920 "friendica" => "http://friendi.ca/schema/api/1/",
921 "georss" => "http://www.georss.org/georss"];
923 /// @todo Auto detection of needed namespaces
924 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
928 if (is_array($data2)) {
930 api_walk_recursive($data2, "api_reformat_xml");
936 foreach ($data2 as $item) {
937 $data4[$i++ . ":" . $childname] = $item;
944 $data3 = [$root_element => $data2];
946 $ret = XML::fromArray($data3, $xml, false, $namespaces);
951 * @brief Formats the data according to the data type
953 * @param string $root_element Name of the root element
954 * @param string $type Return type (atom, rss, xml, json)
955 * @param array $data JSON style array
957 * @return array|string (string|array) XML data or JSON data
959 function api_format_data($root_element, $type, $data)
965 $ret = api_create_xml($data, $root_element);
980 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
981 * returns a 401 status code and an error message if not.
983 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
985 * @param string $type Return type (atom, rss, xml, json)
986 * @return array|string
987 * @throws BadRequestException
988 * @throws ForbiddenException
989 * @throws ImagickException
990 * @throws InternalServerErrorException
991 * @throws UnauthorizedException
993 function api_account_verify_credentials($type)
998 if (api_user() === false) {
999 throw new ForbiddenException();
1002 unset($_REQUEST["user_id"]);
1003 unset($_GET["user_id"]);
1005 unset($_REQUEST["screen_name"]);
1006 unset($_GET["screen_name"]);
1008 $skip_status = defaults($_REQUEST, 'skip_status', false);
1010 $user_info = api_get_user($a);
1012 // "verified" isn't used here in the standard
1013 unset($user_info["verified"]);
1015 // - Adding last status
1016 if (!$skip_status) {
1017 $user_info["status"] = api_status_show("raw");
1018 if (!count($user_info["status"])) {
1019 unset($user_info["status"]);
1021 unset($user_info["status"]["user"]);
1025 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1026 unset($user_info["uid"]);
1027 unset($user_info["self"]);
1029 return api_format_data("user", $type, ['user' => $user_info]);
1032 /// @TODO move to top of file or somewhere better
1033 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1036 * Get data from $_POST or $_GET
1041 function requestdata($k)
1043 if (!empty($_POST[$k])) {
1046 if (!empty($_GET[$k])) {
1053 * Deprecated function to upload media.
1055 * @param string $type Return type (atom, rss, xml, json)
1057 * @return array|string
1058 * @throws BadRequestException
1059 * @throws ForbiddenException
1060 * @throws ImagickException
1061 * @throws InternalServerErrorException
1062 * @throws UnauthorizedException
1064 function api_statuses_mediap($type)
1068 if (api_user() === false) {
1069 Logger::log('api_statuses_update: no user');
1070 throw new ForbiddenException();
1072 $user_info = api_get_user($a);
1074 $_REQUEST['profile_uid'] = api_user();
1075 $_REQUEST['api_source'] = true;
1076 $txt = requestdata('status');
1077 /// @TODO old-lost code?
1078 //$txt = urldecode(requestdata('status'));
1080 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1081 $txt = HTML::toBBCodeVideo($txt);
1082 $config = HTMLPurifier_Config::createDefault();
1083 $config->set('Cache.DefinitionImpl', null);
1084 $purifier = new HTMLPurifier($config);
1085 $txt = $purifier->purify($txt);
1087 $txt = HTML::toBBCode($txt);
1089 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1091 $picture = wall_upload_post($a, false);
1093 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1094 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1095 $item_id = item_post($a);
1097 // output the post that we just posted.
1098 return api_status_show($type, $item_id);
1101 /// @TODO move this to top of file or somewhere better!
1102 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1105 * Updates the user’s current status.
1107 * @param string $type Return type (atom, rss, xml, json)
1109 * @return array|string
1110 * @throws BadRequestException
1111 * @throws ForbiddenException
1112 * @throws ImagickException
1113 * @throws InternalServerErrorException
1114 * @throws TooManyRequestsException
1115 * @throws UnauthorizedException
1116 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1118 function api_statuses_update($type)
1122 if (api_user() === false) {
1123 Logger::log('api_statuses_update: no user');
1124 throw new ForbiddenException();
1129 // convert $_POST array items to the form we use for web posts.
1130 if (requestdata('htmlstatus')) {
1131 $txt = requestdata('htmlstatus');
1132 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1133 $txt = HTML::toBBCodeVideo($txt);
1135 $config = HTMLPurifier_Config::createDefault();
1136 $config->set('Cache.DefinitionImpl', null);
1138 $purifier = new HTMLPurifier($config);
1139 $txt = $purifier->purify($txt);
1141 $_REQUEST['body'] = HTML::toBBCode($txt);
1144 $_REQUEST['body'] = requestdata('status');
1147 $_REQUEST['title'] = requestdata('title');
1149 $parent = requestdata('in_reply_to_status_id');
1151 // Twidere sends "-1" if it is no reply ...
1152 if ($parent == -1) {
1156 if (ctype_digit($parent)) {
1157 $_REQUEST['parent'] = $parent;
1159 $_REQUEST['parent_uri'] = $parent;
1162 if (requestdata('lat') && requestdata('long')) {
1163 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1165 $_REQUEST['profile_uid'] = api_user();
1168 // Check for throttling (maximum posts per day, week and month)
1169 $throttle_day = Config::get('system', 'throttle_limit_day');
1170 if ($throttle_day > 0) {
1171 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1173 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1174 $posts_day = DBA::count('thread', $condition);
1176 if ($posts_day > $throttle_day) {
1177 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1178 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1179 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));
1183 $throttle_week = Config::get('system', 'throttle_limit_week');
1184 if ($throttle_week > 0) {
1185 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1187 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1188 $posts_week = DBA::count('thread', $condition);
1190 if ($posts_week > $throttle_week) {
1191 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1192 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1193 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));
1197 $throttle_month = Config::get('system', 'throttle_limit_month');
1198 if ($throttle_month > 0) {
1199 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1201 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1202 $posts_month = DBA::count('thread', $condition);
1204 if ($posts_month > $throttle_month) {
1205 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1206 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1207 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));
1212 if (!empty($_FILES['media'])) {
1213 // upload the image if we have one
1214 $picture = wall_upload_post($a, false);
1215 if (is_array($picture)) {
1216 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1220 // To-Do: Multiple IDs
1221 if (requestdata('media_ids')) {
1223 "SELECT `resource-id`, `scale`, `nickname`, `type` 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",
1224 intval(requestdata('media_ids')),
1227 if (DBA::isResult($r)) {
1228 $phototypes = Image::supportedTypes();
1229 $ext = $phototypes[$r[0]['type']];
1230 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1231 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1235 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1237 $_REQUEST['api_source'] = true;
1239 if (empty($_REQUEST['source'])) {
1240 $_REQUEST["source"] = api_source();
1243 // call out normal post function
1244 $item_id = item_post($a);
1246 // output the post that we just posted.
1247 return api_status_show($type, $item_id);
1250 /// @TODO move to top of file or somewhere better
1251 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1252 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1255 * Uploads an image to Friendica.
1258 * @throws BadRequestException
1259 * @throws ForbiddenException
1260 * @throws ImagickException
1261 * @throws InternalServerErrorException
1262 * @throws UnauthorizedException
1263 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1265 function api_media_upload()
1269 if (api_user() === false) {
1270 Logger::log('no user');
1271 throw new ForbiddenException();
1276 if (empty($_FILES['media'])) {
1278 throw new BadRequestException("No media.");
1281 $media = wall_upload_post($a, false);
1284 throw new InternalServerErrorException();
1288 $returndata["media_id"] = $media["id"];
1289 $returndata["media_id_string"] = (string)$media["id"];
1290 $returndata["size"] = $media["size"];
1291 $returndata["image"] = ["w" => $media["width"],
1292 "h" => $media["height"],
1293 "image_type" => $media["type"],
1294 "friendica_preview_url" => $media["preview"]];
1296 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1298 return ["media" => $returndata];
1301 /// @TODO move to top of file or somewhere better
1302 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1306 * @param string $type Return type (atom, rss, xml, json)
1308 * @param int $item_id
1309 * @return array|string
1310 * @throws BadRequestException
1311 * @throws ImagickException
1312 * @throws InternalServerErrorException
1313 * @throws UnauthorizedException
1315 function api_status_show($type, $item_id = 0)
1319 $user_info = api_get_user($a);
1321 Logger::log('api_status_show: user_info: '.print_r($user_info, true), Logger::DEBUG);
1323 if (!empty($item_id)) {
1324 // Get the item with the given id
1325 $condition = ['id' => $item_id];
1327 // get last public wall message
1328 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1329 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1332 if ($type == "raw") {
1333 $condition['private'] = false;
1336 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1338 if (DBA::isResult($lastwall)) {
1339 $in_reply_to = api_in_reply_to($lastwall);
1341 $converted = api_convert_item($lastwall);
1343 if ($type == "xml") {
1344 $geo = "georss:point";
1350 'created_at' => api_date($lastwall['created']),
1351 'id' => intval($lastwall['id']),
1352 'id_str' => (string) $lastwall['id'],
1353 'text' => $converted["text"],
1354 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1355 'truncated' => false,
1356 'in_reply_to_status_id' => $in_reply_to['status_id'],
1357 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1358 'in_reply_to_user_id' => $in_reply_to['user_id'],
1359 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1360 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1361 'user' => $user_info,
1363 'coordinates' => '',
1365 'contributors' => '',
1366 'is_quote_status' => false,
1367 'retweet_count' => 0,
1368 'favorite_count' => 0,
1369 'favorited' => $lastwall['starred'] ? true : false,
1370 'retweeted' => false,
1371 'possibly_sensitive' => false,
1373 'statusnet_html' => $converted["html"],
1374 'statusnet_conversation_id' => $lastwall['parent'],
1375 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
1378 if (count($converted["attachments"]) > 0) {
1379 $status_info["attachments"] = $converted["attachments"];
1382 if (count($converted["entities"]) > 0) {
1383 $status_info["entities"] = $converted["entities"];
1386 if ($status_info["source"] == 'web') {
1387 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1388 } elseif (ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) != $status_info["source"]) {
1389 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']).')');
1392 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1393 unset($status_info["user"]["uid"]);
1394 unset($status_info["user"]["self"]);
1396 Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
1398 if ($type == "raw") {
1399 return $status_info;
1402 return api_format_data("statuses", $type, ['status' => $status_info]);
1407 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1408 * The author's most recent status will be returned inline.
1410 * @param string $type Return type (atom, rss, xml, json)
1411 * @return array|string
1412 * @throws BadRequestException
1413 * @throws ImagickException
1414 * @throws InternalServerErrorException
1415 * @throws UnauthorizedException
1416 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1418 function api_users_show($type)
1422 $user_info = api_get_user($a);
1424 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1425 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1426 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1428 if (DBA::isResult($lastwall)) {
1429 $in_reply_to = api_in_reply_to($lastwall);
1431 $converted = api_convert_item($lastwall);
1433 if ($type == "xml") {
1434 $geo = "georss:point";
1439 $user_info['status'] = [
1440 'text' => $converted["text"],
1441 'truncated' => false,
1442 'created_at' => api_date($lastwall['created']),
1443 'in_reply_to_status_id' => $in_reply_to['status_id'],
1444 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1445 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1446 'id' => intval($lastwall['contact-id']),
1447 'id_str' => (string) $lastwall['contact-id'],
1448 'in_reply_to_user_id' => $in_reply_to['user_id'],
1449 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1450 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1452 'favorited' => $lastwall['starred'] ? true : false,
1453 'statusnet_html' => $converted["html"],
1454 'statusnet_conversation_id' => $lastwall['parent'],
1455 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1458 if (count($converted["attachments"]) > 0) {
1459 $user_info["status"]["attachments"] = $converted["attachments"];
1462 if (count($converted["entities"]) > 0) {
1463 $user_info["status"]["entities"] = $converted["entities"];
1466 if ($user_info["status"]["source"] == 'web') {
1467 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1470 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1471 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) . ')');
1475 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1476 unset($user_info["uid"]);
1477 unset($user_info["self"]);
1479 return api_format_data("user", $type, ['user' => $user_info]);
1482 /// @TODO move to top of file or somewhere better
1483 api_register_func('api/users/show', 'api_users_show');
1484 api_register_func('api/externalprofile/show', 'api_users_show');
1487 * Search a public user account.
1489 * @param string $type Return type (atom, rss, xml, json)
1491 * @return array|string
1492 * @throws BadRequestException
1493 * @throws ImagickException
1494 * @throws InternalServerErrorException
1495 * @throws UnauthorizedException
1496 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1498 function api_users_search($type)
1504 if (!empty($_GET['q'])) {
1505 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1507 if (!DBA::isResult($r)) {
1508 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1511 if (DBA::isResult($r)) {
1513 foreach ($r as $user) {
1514 $user_info = api_get_user($a, $user["id"]);
1516 if ($type == "xml") {
1517 $userlist[$k++.":user"] = $user_info;
1519 $userlist[] = $user_info;
1522 $userlist = ["users" => $userlist];
1524 throw new BadRequestException("User ".$_GET["q"]." not found.");
1527 throw new BadRequestException("No user specified.");
1530 return api_format_data("users", $type, $userlist);
1533 /// @TODO move to top of file or somewhere better
1534 api_register_func('api/users/search', 'api_users_search');
1537 * Return user objects
1539 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1541 * @param string $type Return format: json or xml
1543 * @return array|string
1544 * @throws BadRequestException
1545 * @throws ImagickException
1546 * @throws InternalServerErrorException
1547 * @throws NotFoundException if the results are empty.
1548 * @throws UnauthorizedException
1550 function api_users_lookup($type)
1554 if (!empty($_REQUEST['user_id'])) {
1555 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1557 $users[] = api_get_user(get_app(), $id);
1562 if (empty($users)) {
1563 throw new NotFoundException;
1566 return api_format_data("users", $type, ['users' => $users]);
1569 /// @TODO move to top of file or somewhere better
1570 api_register_func('api/users/lookup', 'api_users_lookup', true);
1573 * Returns statuses that match a specified query.
1575 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1577 * @param string $type Return format: json, xml, atom, rss
1579 * @return array|string
1580 * @throws BadRequestException if the "q" parameter is missing.
1581 * @throws ForbiddenException
1582 * @throws ImagickException
1583 * @throws InternalServerErrorException
1584 * @throws UnauthorizedException
1586 function api_search($type)
1589 $user_info = api_get_user($a);
1591 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1593 if (empty($_REQUEST['q'])) { throw new BadRequestException('q parameter is required.'); }
1595 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1598 $data['status'] = [];
1600 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1601 if (!empty($_REQUEST['rpp'])) {
1602 $count = $_REQUEST['rpp'];
1603 } elseif (!empty($_REQUEST['count'])) {
1604 $count = $_REQUEST['count'];
1607 $since_id = defaults($_REQUEST, 'since_id', 0);
1608 $max_id = defaults($_REQUEST, 'max_id', 0);
1609 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1610 $start = $page * $count;
1611 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1612 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1613 $searchTerm = $matches[1];
1614 $condition = ["`oid` > ?
1615 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1616 AND `otype` = ? AND `type` = ? AND `term` = ?",
1617 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1619 $condition[0] .= ' AND `oid` <= ?';
1620 $condition[] = $max_id;
1622 $terms = DBA::select('term', ['oid'], $condition, []);
1624 while ($term = DBA::fetch($terms)) {
1625 $itemIds[] = $term['oid'];
1629 if (empty($itemIds)) {
1630 return api_format_data('statuses', $type, $data);
1633 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1634 if ($exclude_replies) {
1635 $preCondition[] = '`id` = `parent`';
1638 $condition = [implode(' AND ', $preCondition)];
1640 $condition = ["`id` > ?
1641 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1642 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1643 AND `body` LIKE CONCAT('%',?,'%')",
1644 $since_id, api_user(), $_REQUEST['q']];
1646 $condition[0] .= ' AND `id` <= ?';
1647 $condition[] = $max_id;
1651 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1653 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1655 bindComments($data['status']);
1657 return api_format_data('statuses', $type, $data);
1660 /// @TODO move to top of file or somewhere better
1661 api_register_func('api/search/tweets', 'api_search', true);
1662 api_register_func('api/search', 'api_search', true);
1665 * Returns the most recent statuses posted by the user and the users they follow.
1667 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1669 * @param string $type Return type (atom, rss, xml, json)
1671 * @return array|string
1672 * @throws BadRequestException
1673 * @throws ForbiddenException
1674 * @throws ImagickException
1675 * @throws InternalServerErrorException
1676 * @throws UnauthorizedException
1677 * @todo Optional parameters
1678 * @todo Add reply info
1680 function api_statuses_home_timeline($type)
1683 $user_info = api_get_user($a);
1685 if (api_user() === false || $user_info === false) {
1686 throw new ForbiddenException();
1689 unset($_REQUEST["user_id"]);
1690 unset($_GET["user_id"]);
1692 unset($_REQUEST["screen_name"]);
1693 unset($_GET["screen_name"]);
1695 // get last network messages
1698 $count = defaults($_REQUEST, 'count', 20);
1699 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1703 $since_id = defaults($_REQUEST, 'since_id', 0);
1704 $max_id = defaults($_REQUEST, 'max_id', 0);
1705 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1706 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1708 $start = $page * $count;
1710 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1711 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1714 $condition[0] .= " AND `item`.`id` <= ?";
1715 $condition[] = $max_id;
1717 if ($exclude_replies) {
1718 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1720 if ($conversation_id > 0) {
1721 $condition[0] .= " AND `item`.`parent` = ?";
1722 $condition[] = $conversation_id;
1725 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1726 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1728 $items = Item::inArray($statuses);
1730 $ret = api_format_items($items, $user_info, false, $type);
1732 // Set all posts from the query above to seen
1734 foreach ($items as $item) {
1735 $idarray[] = intval($item["id"]);
1738 if (!empty($idarray)) {
1739 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1741 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1747 $data = ['status' => $ret];
1752 $data = api_rss_extra($a, $data, $user_info);
1756 return api_format_data("statuses", $type, $data);
1760 /// @TODO move to top of file or somewhere better
1761 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1762 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1765 * Returns the most recent statuses from public users.
1767 * @param string $type Return type (atom, rss, xml, json)
1769 * @return array|string
1770 * @throws BadRequestException
1771 * @throws ForbiddenException
1772 * @throws ImagickException
1773 * @throws InternalServerErrorException
1774 * @throws UnauthorizedException
1776 function api_statuses_public_timeline($type)
1779 $user_info = api_get_user($a);
1781 if (api_user() === false || $user_info === false) {
1782 throw new ForbiddenException();
1785 // get last network messages
1788 $count = defaults($_REQUEST, 'count', 20);
1789 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1793 $since_id = defaults($_REQUEST, 'since_id', 0);
1794 $max_id = defaults($_REQUEST, 'max_id', 0);
1795 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1796 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1798 $start = $page * $count;
1800 if ($exclude_replies && !$conversation_id) {
1801 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1802 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1805 $condition[0] .= " AND `thread`.`iid` <= ?";
1806 $condition[] = $max_id;
1809 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1810 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1812 $r = Item::inArray($statuses);
1814 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1815 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1818 $condition[0] .= " AND `item`.`id` <= ?";
1819 $condition[] = $max_id;
1821 if ($conversation_id > 0) {
1822 $condition[0] .= " AND `item`.`parent` = ?";
1823 $condition[] = $conversation_id;
1826 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1827 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1829 $r = Item::inArray($statuses);
1832 $ret = api_format_items($r, $user_info, false, $type);
1836 $data = ['status' => $ret];
1841 $data = api_rss_extra($a, $data, $user_info);
1845 return api_format_data("statuses", $type, $data);
1848 /// @TODO move to top of file or somewhere better
1849 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1852 * Returns the most recent statuses posted by users this node knows about.
1854 * @brief Returns the list of public federated posts this node knows about
1856 * @param string $type Return format: json, xml, atom, rss
1857 * @return array|string
1858 * @throws BadRequestException
1859 * @throws ForbiddenException
1860 * @throws ImagickException
1861 * @throws InternalServerErrorException
1862 * @throws UnauthorizedException
1864 function api_statuses_networkpublic_timeline($type)
1867 $user_info = api_get_user($a);
1869 if (api_user() === false || $user_info === false) {
1870 throw new ForbiddenException();
1873 $since_id = defaults($_REQUEST, 'since_id', 0);
1874 $max_id = defaults($_REQUEST, 'max_id', 0);
1877 $count = defaults($_REQUEST, 'count', 20);
1878 $page = defaults($_REQUEST, 'page', 1);
1882 $start = ($page - 1) * $count;
1884 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1885 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1888 $condition[0] .= " AND `thread`.`iid` <= ?";
1889 $condition[] = $max_id;
1892 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1893 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1895 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1899 $data = ['status' => $ret];
1904 $data = api_rss_extra($a, $data, $user_info);
1908 return api_format_data("statuses", $type, $data);
1911 /// @TODO move to top of file or somewhere better
1912 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1915 * Returns a single status.
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 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1927 function api_statuses_show($type)
1930 $user_info = api_get_user($a);
1932 if (api_user() === false || $user_info === false) {
1933 throw new ForbiddenException();
1937 $id = intval(defaults($a->argv, 3, 0));
1940 $id = intval(defaults($_REQUEST, 'id', 0));
1945 $id = intval(defaults($a->argv, 4, 0));
1948 Logger::log('API: api_statuses_show: ' . $id);
1950 $conversation = !empty($_REQUEST['conversation']);
1952 // try to fetch the item for the local user - or the public item, if there is no local one
1953 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1954 if (!DBA::isResult($uri_item)) {
1955 throw new BadRequestException("There is no status with this id.");
1958 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1959 if (!DBA::isResult($item)) {
1960 throw new BadRequestException("There is no status with this id.");
1965 if ($conversation) {
1966 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1967 $params = ['order' => ['id' => true]];
1969 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1973 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1975 /// @TODO How about copying this to above methods which don't check $r ?
1976 if (!DBA::isResult($statuses)) {
1977 throw new BadRequestException("There is no status with this id.");
1980 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1982 if ($conversation) {
1983 $data = ['status' => $ret];
1984 return api_format_data("statuses", $type, $data);
1986 $data = ['status' => $ret[0]];
1987 return api_format_data("status", $type, $data);
1991 /// @TODO move to top of file or somewhere better
1992 api_register_func('api/statuses/show', 'api_statuses_show', true);
1996 * @param string $type Return type (atom, rss, xml, json)
1998 * @return array|string
1999 * @throws BadRequestException
2000 * @throws ForbiddenException
2001 * @throws ImagickException
2002 * @throws InternalServerErrorException
2003 * @throws UnauthorizedException
2004 * @todo nothing to say?
2006 function api_conversation_show($type)
2009 $user_info = api_get_user($a);
2011 if (api_user() === false || $user_info === false) {
2012 throw new ForbiddenException();
2016 $id = intval(defaults($a->argv , 3 , 0));
2017 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
2018 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
2019 $count = intval(defaults($_REQUEST, 'count' , 20));
2020 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
2025 $start = $page * $count;
2028 $id = intval(defaults($_REQUEST, 'id', 0));
2033 $id = intval(defaults($a->argv, 4, 0));
2036 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
2038 // try to fetch the item for the local user - or the public item, if there is no local one
2039 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
2040 if (!DBA::isResult($item)) {
2041 throw new BadRequestException("There is no status with this id.");
2044 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
2045 if (!DBA::isResult($parent)) {
2046 throw new BadRequestException("There is no status with this id.");
2049 $id = $parent['id'];
2051 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
2052 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2055 $condition[0] .= " AND `item`.`id` <= ?";
2056 $condition[] = $max_id;
2059 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2060 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2062 if (!DBA::isResult($statuses)) {
2063 throw new BadRequestException("There is no status with id $id.");
2066 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2068 $data = ['status' => $ret];
2069 return api_format_data("statuses", $type, $data);
2072 /// @TODO move to top of file or somewhere better
2073 api_register_func('api/conversation/show', 'api_conversation_show', true);
2074 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2079 * @param string $type Return type (atom, rss, xml, json)
2081 * @return array|string
2082 * @throws BadRequestException
2083 * @throws ForbiddenException
2084 * @throws ImagickException
2085 * @throws InternalServerErrorException
2086 * @throws UnauthorizedException
2087 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2089 function api_statuses_repeat($type)
2095 if (api_user() === false) {
2096 throw new ForbiddenException();
2102 $id = intval(defaults($a->argv, 3, 0));
2105 $id = intval(defaults($_REQUEST, 'id', 0));
2110 $id = intval(defaults($a->argv, 4, 0));
2113 Logger::log('API: api_statuses_repeat: '.$id);
2115 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2116 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2118 if (DBA::isResult($item) && $item['body'] != "") {
2119 if (strpos($item['body'], "[/share]") !== false) {
2120 $pos = strpos($item['body'], "[share");
2121 $post = substr($item['body'], $pos);
2123 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2125 $post .= $item['body'];
2126 $post .= "[/share]";
2128 $_REQUEST['body'] = $post;
2129 $_REQUEST['profile_uid'] = api_user();
2130 $_REQUEST['api_source'] = true;
2132 if (empty($_REQUEST['source'])) {
2133 $_REQUEST["source"] = api_source();
2136 $item_id = item_post($a);
2138 throw new ForbiddenException();
2141 // output the post that we just posted.
2143 return api_status_show($type, $item_id);
2146 /// @TODO move to top of file or somewhere better
2147 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2150 * Destroys a specific status.
2152 * @param string $type Return type (atom, rss, xml, json)
2154 * @return array|string
2155 * @throws BadRequestException
2156 * @throws ForbiddenException
2157 * @throws ImagickException
2158 * @throws InternalServerErrorException
2159 * @throws UnauthorizedException
2160 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2162 function api_statuses_destroy($type)
2166 if (api_user() === false) {
2167 throw new ForbiddenException();
2173 $id = intval(defaults($a->argv, 3, 0));
2176 $id = intval(defaults($_REQUEST, 'id', 0));
2181 $id = intval(defaults($a->argv, 4, 0));
2184 Logger::log('API: api_statuses_destroy: '.$id);
2186 $ret = api_statuses_show($type);
2188 Item::deleteForUser(['id' => $id], api_user());
2193 /// @TODO move to top of file or somewhere better
2194 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2197 * Returns the most recent mentions.
2199 * @param string $type Return type (atom, rss, xml, json)
2201 * @return array|string
2202 * @throws BadRequestException
2203 * @throws ForbiddenException
2204 * @throws ImagickException
2205 * @throws InternalServerErrorException
2206 * @throws UnauthorizedException
2207 * @see http://developer.twitter.com/doc/get/statuses/mentions
2209 function api_statuses_mentions($type)
2212 $user_info = api_get_user($a);
2214 if (api_user() === false || $user_info === false) {
2215 throw new ForbiddenException();
2218 unset($_REQUEST["user_id"]);
2219 unset($_GET["user_id"]);
2221 unset($_REQUEST["screen_name"]);
2222 unset($_GET["screen_name"]);
2224 // get last network messages
2227 $since_id = defaults($_REQUEST, 'since_id', 0);
2228 $max_id = defaults($_REQUEST, 'max_id' , 0);
2229 $count = defaults($_REQUEST, 'count' , 20);
2230 $page = defaults($_REQUEST, 'page' , 1);
2235 $start = ($page - 1) * $count;
2237 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2238 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2239 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2242 $condition[0] .= " AND `item`.`id` <= ?";
2243 $condition[] = $max_id;
2246 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2247 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2249 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2251 $data = ['status' => $ret];
2256 $data = api_rss_extra($a, $data, $user_info);
2260 return api_format_data("statuses", $type, $data);
2263 /// @TODO move to top of file or somewhere better
2264 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2265 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2268 * Returns the most recent statuses posted by the user.
2270 * @brief Returns a user's public timeline
2272 * @param string $type Either "json" or "xml"
2273 * @return string|array
2274 * @throws BadRequestException
2275 * @throws ForbiddenException
2276 * @throws ImagickException
2277 * @throws InternalServerErrorException
2278 * @throws UnauthorizedException
2279 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2281 function api_statuses_user_timeline($type)
2284 $user_info = api_get_user($a);
2286 if (api_user() === false || $user_info === false) {
2287 throw new ForbiddenException();
2291 "api_statuses_user_timeline: api_user: ". api_user() .
2292 "\nuser_info: ".print_r($user_info, true) .
2293 "\n_REQUEST: ".print_r($_REQUEST, true),
2297 $since_id = defaults($_REQUEST, 'since_id', 0);
2298 $max_id = defaults($_REQUEST, 'max_id', 0);
2299 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2300 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2303 $count = defaults($_REQUEST, 'count', 20);
2304 $page = defaults($_REQUEST, 'page', 1);
2308 $start = ($page - 1) * $count;
2310 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2311 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2313 if ($user_info['self'] == 1) {
2314 $condition[0] .= ' AND `item`.`wall` ';
2317 if ($exclude_replies) {
2318 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2321 if ($conversation_id > 0) {
2322 $condition[0] .= " AND `item`.`parent` = ?";
2323 $condition[] = $conversation_id;
2327 $condition[0] .= " AND `item`.`id` <= ?";
2328 $condition[] = $max_id;
2331 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2332 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2334 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2338 $data = ['status' => $ret];
2343 $data = api_rss_extra($a, $data, $user_info);
2347 return api_format_data("statuses", $type, $data);
2350 /// @TODO move to top of file or somewhere better
2351 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2354 * Star/unstar an item.
2355 * param: id : id of the item
2357 * @param string $type Return type (atom, rss, xml, json)
2359 * @return array|string
2360 * @throws BadRequestException
2361 * @throws ForbiddenException
2362 * @throws ImagickException
2363 * @throws InternalServerErrorException
2364 * @throws UnauthorizedException
2365 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2367 function api_favorites_create_destroy($type)
2371 if (api_user() === false) {
2372 throw new ForbiddenException();
2375 // for versioned api.
2376 /// @TODO We need a better global soluton
2377 $action_argv_id = 2;
2378 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2379 $action_argv_id = 3;
2382 if ($a->argc <= $action_argv_id) {
2383 throw new BadRequestException("Invalid request.");
2385 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2386 if ($a->argc == $action_argv_id + 2) {
2387 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2389 $itemid = intval(defaults($_REQUEST, 'id', 0));
2392 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2394 if (!DBA::isResult($item)) {
2395 throw new BadRequestException("Invalid item.");
2400 $item['starred'] = 1;
2403 $item['starred'] = 0;
2406 throw new BadRequestException("Invalid action ".$action);
2409 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2412 throw new InternalServerErrorException("DB error");
2416 $user_info = api_get_user($a);
2417 $rets = api_format_items([$item], $user_info, false, $type);
2420 $data = ['status' => $ret];
2425 $data = api_rss_extra($a, $data, $user_info);
2429 return api_format_data("status", $type, $data);
2432 /// @TODO move to top of file or somewhere better
2433 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2434 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2437 * Returns the most recent favorite statuses.
2439 * @param string $type Return type (atom, rss, xml, json)
2441 * @return string|array
2442 * @throws BadRequestException
2443 * @throws ForbiddenException
2444 * @throws ImagickException
2445 * @throws InternalServerErrorException
2446 * @throws UnauthorizedException
2448 function api_favorites($type)
2453 $user_info = api_get_user($a);
2455 if (api_user() === false || $user_info === false) {
2456 throw new ForbiddenException();
2461 // in friendica starred item are private
2462 // return favorites only for self
2463 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2465 if ($user_info['self'] == 0) {
2469 $since_id = defaults($_REQUEST, 'since_id', 0);
2470 $max_id = defaults($_REQUEST, 'max_id', 0);
2471 $count = defaults($_GET, 'count', 20);
2472 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2477 $start = $page*$count;
2479 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2480 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2482 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2485 $condition[0] .= " AND `item`.`id` <= ?";
2486 $condition[] = $max_id;
2489 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2491 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2496 $data = ['status' => $ret];
2501 $data = api_rss_extra($a, $data, $user_info);
2505 return api_format_data("statuses", $type, $data);
2508 /// @TODO move to top of file or somewhere better
2509 api_register_func('api/favorites', 'api_favorites', true);
2513 * @param array $item
2514 * @param array $recipient
2515 * @param array $sender
2518 * @throws InternalServerErrorException
2520 function api_format_messages($item, $recipient, $sender)
2522 // standard meta information
2524 'id' => $item['id'],
2525 'sender_id' => $sender['id'],
2527 'recipient_id' => $recipient['id'],
2528 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2529 'sender_screen_name' => $sender['screen_name'],
2530 'recipient_screen_name' => $recipient['screen_name'],
2531 'sender' => $sender,
2532 'recipient' => $recipient,
2534 'friendica_seen' => defaults($item, 'seen', 0),
2535 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2538 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2539 if (isset($ret['sender']['uid'])) {
2540 unset($ret['sender']['uid']);
2542 if (isset($ret['sender']['self'])) {
2543 unset($ret['sender']['self']);
2545 if (isset($ret['recipient']['uid'])) {
2546 unset($ret['recipient']['uid']);
2548 if (isset($ret['recipient']['self'])) {
2549 unset($ret['recipient']['self']);
2552 //don't send title to regular StatusNET requests to avoid confusing these apps
2553 if (!empty($_GET['getText'])) {
2554 $ret['title'] = $item['title'];
2555 if ($_GET['getText'] == 'html') {
2556 $ret['text'] = BBCode::convert($item['body'], false);
2557 } elseif ($_GET['getText'] == 'plain') {
2558 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2561 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2563 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2564 unset($ret['sender']);
2565 unset($ret['recipient']);
2573 * @param array $item
2576 * @throws InternalServerErrorException
2578 function api_convert_item($item)
2580 $body = $item['body'];
2581 $attachments = api_get_attachments($body);
2583 // Workaround for ostatus messages where the title is identically to the body
2584 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2585 $statusbody = trim(HTML::toPlaintext($html, 0));
2587 // handle data: images
2588 $statusbody = api_format_items_embeded_images($item, $statusbody);
2590 $statustitle = trim($item['title']);
2592 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2593 $statustext = trim($statusbody);
2595 $statustext = trim($statustitle."\n\n".$statusbody);
2598 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2599 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2602 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2604 // Workaround for clients with limited HTML parser functionality
2605 $search = ["<br>", "<blockquote>", "</blockquote>",
2606 "<h1>", "</h1>", "<h2>", "</h2>",
2607 "<h3>", "</h3>", "<h4>", "</h4>",
2608 "<h5>", "</h5>", "<h6>", "</h6>"];
2609 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2610 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2611 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2612 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2613 $statushtml = str_replace($search, $replace, $statushtml);
2615 if ($item['title'] != "") {
2616 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2620 $oldtext = $statushtml;
2621 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2622 } while ($oldtext != $statushtml);
2624 if (substr($statushtml, 0, 4) == '<br>') {
2625 $statushtml = substr($statushtml, 4);
2628 if (substr($statushtml, 0, -4) == '<br>') {
2629 $statushtml = substr($statushtml, -4);
2632 // feeds without body should contain the link
2633 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2634 $statushtml .= BBCode::convert($item['plink']);
2637 $entities = api_get_entitities($statustext, $body);
2640 "text" => $statustext,
2641 "html" => $statushtml,
2642 "attachments" => $attachments,
2643 "entities" => $entities
2649 * @param string $body
2652 * @throws InternalServerErrorException
2654 function api_get_attachments(&$body)
2657 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2659 $URLSearchString = "^\[\]";
2660 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2668 foreach ($images[1] as $image) {
2669 $imagedata = Image::getInfoFromURL($image);
2672 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2676 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2677 foreach ($images[0] as $orig) {
2678 $body = str_replace($orig, "", $body);
2682 return $attachments;
2687 * @param string $text
2688 * @param string $bbcode
2691 * @throws InternalServerErrorException
2692 * @todo Links at the first character of the post
2694 function api_get_entitities(&$text, $bbcode)
2696 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2698 if ($include_entities != "true") {
2699 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2701 foreach ($images[1] as $image) {
2702 $replace = ProxyUtils::proxifyUrl($image);
2703 $text = str_replace($image, $replace, $text);
2708 $bbcode = BBCode::cleanPictureLinks($bbcode);
2710 // Change pure links in text to bbcode uris
2711 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2714 $entities["hashtags"] = [];
2715 $entities["symbols"] = [];
2716 $entities["urls"] = [];
2717 $entities["user_mentions"] = [];
2719 $URLSearchString = "^\[\]";
2721 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2723 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2724 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2725 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2727 $bbcode = preg_replace(
2728 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2729 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2732 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2734 $bbcode = preg_replace(
2735 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2736 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2739 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2741 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2743 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2744 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2747 foreach ($urls[1] as $id => $url) {
2748 //$start = strpos($text, $url, $offset);
2749 $start = iconv_strpos($text, $url, 0, "UTF-8");
2750 if (!($start === false)) {
2751 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2755 ksort($ordered_urls);
2758 //foreach ($urls[1] AS $id=>$url) {
2759 foreach ($ordered_urls as $url) {
2760 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2761 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2763 $display_url = $url["title"];
2765 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2766 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2768 if (strlen($display_url) > 26) {
2769 $display_url = substr($display_url, 0, 25)."…";
2773 //$start = strpos($text, $url, $offset);
2774 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2775 if (!($start === false)) {
2776 $entities["urls"][] = ["url" => $url["url"],
2777 "expanded_url" => $url["url"],
2778 "display_url" => $display_url,
2779 "indices" => [$start, $start+strlen($url["url"])]];
2780 $offset = $start + 1;
2784 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2785 $ordered_images = [];
2786 foreach ($images[1] as $image) {
2787 //$start = strpos($text, $url, $offset);
2788 $start = iconv_strpos($text, $image, 0, "UTF-8");
2789 if (!($start === false)) {
2790 $ordered_images[$start] = $image;
2793 //$entities["media"] = array();
2796 foreach ($ordered_images as $url) {
2797 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2798 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2800 if (strlen($display_url) > 26) {
2801 $display_url = substr($display_url, 0, 25)."…";
2804 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2805 if (!($start === false)) {
2806 $image = Image::getInfoFromURL($url);
2808 // If image cache is activated, then use the following sizes:
2809 // thumb (150), small (340), medium (600) and large (1024)
2810 if (!Config::get("system", "proxy_disabled")) {
2811 $media_url = ProxyUtils::proxifyUrl($url);
2814 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2815 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2817 if (($image[0] > 150) || ($image[1] > 150)) {
2818 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2819 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2822 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2823 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2825 if (($image[0] > 600) || ($image[1] > 600)) {
2826 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2827 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2831 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2834 $entities["media"][] = [
2836 "id_str" => (string) ($start + 1),
2837 "indices" => [$start, $start+strlen($url)],
2838 "media_url" => Strings::normaliseLink($media_url),
2839 "media_url_https" => $media_url,
2841 "display_url" => $display_url,
2842 "expanded_url" => $url,
2846 $offset = $start + 1;
2855 * @param array $item
2856 * @param string $text
2860 function api_format_items_embeded_images($item, $text)
2862 $text = preg_replace_callback(
2863 '|data:image/([^;]+)[^=]+=*|m',
2864 function () use ($item) {
2865 return System::baseUrl() . '/display/' . $item['guid'];
2873 * @brief return <a href='url'>name</a> as array
2875 * @param string $txt text
2880 function api_contactlink_to_array($txt)
2883 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2884 if ($r && count($match)==3) {
2886 'name' => $match[2],
2900 * @brief return likes, dislikes and attend status for item
2902 * @param array $item array
2903 * @param string $type Return type (atom, rss, xml, json)
2906 * likes => int count,
2907 * dislikes => int count
2908 * @throws BadRequestException
2909 * @throws ImagickException
2910 * @throws InternalServerErrorException
2911 * @throws UnauthorizedException
2913 function api_format_items_activities($item, $type = "json")
2922 'attendmaybe' => [],
2925 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2926 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2928 while ($parent_item = Item::fetch($ret)) {
2929 // not used as result should be structured like other user data
2930 //builtin_activity_puller($i, $activities);
2932 // get user data and add it to the array of the activity
2933 $user = api_get_user($a, $parent_item['author-id']);
2934 switch ($parent_item['verb']) {
2936 $activities['like'][] = $user;
2938 case ACTIVITY_DISLIKE:
2939 $activities['dislike'][] = $user;
2941 case ACTIVITY_ATTEND:
2942 $activities['attendyes'][] = $user;
2944 case ACTIVITY_ATTENDNO:
2945 $activities['attendno'][] = $user;
2947 case ACTIVITY_ATTENDMAYBE:
2948 $activities['attendmaybe'][] = $user;
2957 if ($type == "xml") {
2958 $xml_activities = [];
2959 foreach ($activities as $k => $v) {
2960 // change xml element from "like" to "friendica:like"
2961 $xml_activities["friendica:".$k] = $v;
2962 // add user data into xml output
2964 foreach ($v as $user) {
2965 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2968 $activities = $xml_activities;
2976 * @brief return data from profiles
2978 * @param array $profile_row array containing data from db table 'profile'
2980 * @throws InternalServerErrorException
2982 function api_format_items_profiles($profile_row)
2985 'profile_id' => $profile_row['id'],
2986 'profile_name' => $profile_row['profile-name'],
2987 'is_default' => $profile_row['is-default'] ? true : false,
2988 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2989 'profile_photo' => $profile_row['photo'],
2990 'profile_thumb' => $profile_row['thumb'],
2991 'publish' => $profile_row['publish'] ? true : false,
2992 'net_publish' => $profile_row['net-publish'] ? true : false,
2993 'description' => $profile_row['pdesc'],
2994 'date_of_birth' => $profile_row['dob'],
2995 'address' => $profile_row['address'],
2996 'city' => $profile_row['locality'],
2997 'region' => $profile_row['region'],
2998 'postal_code' => $profile_row['postal-code'],
2999 'country' => $profile_row['country-name'],
3000 'hometown' => $profile_row['hometown'],
3001 'gender' => $profile_row['gender'],
3002 'marital' => $profile_row['marital'],
3003 'marital_with' => $profile_row['with'],
3004 'marital_since' => $profile_row['howlong'],
3005 'sexual' => $profile_row['sexual'],
3006 'politic' => $profile_row['politic'],
3007 'religion' => $profile_row['religion'],
3008 'public_keywords' => $profile_row['pub_keywords'],
3009 'private_keywords' => $profile_row['prv_keywords'],
3010 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
3011 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
3012 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
3013 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
3014 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
3015 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
3016 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
3017 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
3018 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
3019 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
3020 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
3021 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
3022 'homepage' => $profile_row['homepage'],
3029 * @brief format items to be returned by api
3031 * @param array $r array of items
3032 * @param array $user_info
3033 * @param bool $filter_user filter items by $user_info
3034 * @param string $type Return type (atom, rss, xml, json)
3036 * @throws BadRequestException
3037 * @throws ImagickException
3038 * @throws InternalServerErrorException
3039 * @throws UnauthorizedException
3041 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3047 foreach ((array)$r as $item) {
3048 localize_item($item);
3049 list($status_user, $owner_user) = api_item_get_user($a, $item);
3051 // Look if the posts are matching if they should be filtered by user id
3052 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3056 $in_reply_to = api_in_reply_to($item);
3058 $converted = api_convert_item($item);
3060 if ($type == "xml") {
3061 $geo = "georss:point";
3067 'text' => $converted["text"],
3068 'truncated' => false,
3069 'created_at'=> api_date($item['created']),
3070 'in_reply_to_status_id' => $in_reply_to['status_id'],
3071 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3072 'source' => (($item['app']) ? $item['app'] : 'web'),
3073 'id' => intval($item['id']),
3074 'id_str' => (string) intval($item['id']),
3075 'in_reply_to_user_id' => $in_reply_to['user_id'],
3076 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3077 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3079 'favorited' => $item['starred'] ? true : false,
3080 'user' => $status_user,
3081 'friendica_owner' => $owner_user,
3082 'friendica_private' => $item['private'] == 1,
3083 //'entities' => NULL,
3084 'statusnet_html' => $converted["html"],
3085 'statusnet_conversation_id' => $item['parent'],
3086 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3087 'friendica_activities' => api_format_items_activities($item, $type),
3090 if (count($converted["attachments"]) > 0) {
3091 $status["attachments"] = $converted["attachments"];
3094 if (count($converted["entities"]) > 0) {
3095 $status["entities"] = $converted["entities"];
3098 if ($status["source"] == 'web') {
3099 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3100 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3101 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3104 if ($item["id"] == $item["parent"]) {
3105 $retweeted_item = api_share_as_retweet($item);
3106 if ($retweeted_item !== false) {
3107 $retweeted_status = $status;
3108 $status['user'] = $status['friendica_owner'];
3110 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3111 } catch (BadRequestException $e) {
3112 // user not found. should be found?
3113 /// @todo check if the user should be always found
3114 $retweeted_status["user"] = [];
3117 $rt_converted = api_convert_item($retweeted_item);
3119 $retweeted_status['text'] = $rt_converted["text"];
3120 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3121 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3122 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3123 $status['retweeted_status'] = $retweeted_status;
3127 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3128 unset($status["user"]["uid"]);
3129 unset($status["user"]["self"]);
3131 if ($item["coord"] != "") {
3132 $coords = explode(' ', $item["coord"]);
3133 if (count($coords) == 2) {
3134 if ($type == "json") {
3135 $status["geo"] = ['type' => 'Point',
3136 'coordinates' => [(float) $coords[0],
3137 (float) $coords[1]]];
3138 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3139 $status["georss:point"] = $item["coord"];
3149 * Returns the remaining number of API requests available to the user before the API limit is reached.
3151 * @param string $type Return type (atom, rss, xml, json)
3153 * @return array|string
3156 function api_account_rate_limit_status($type)
3158 if ($type == "xml") {
3160 'remaining-hits' => '150',
3161 '@attributes' => ["type" => "integer"],
3162 'hourly-limit' => '150',
3163 '@attributes2' => ["type" => "integer"],
3164 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3165 '@attributes3' => ["type" => "datetime"],
3166 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3167 '@attributes4' => ["type" => "integer"],
3171 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3172 'remaining_hits' => '150',
3173 'hourly_limit' => '150',
3174 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3178 return api_format_data('hash', $type, ['hash' => $hash]);
3181 /// @TODO move to top of file or somewhere better
3182 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3185 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3187 * @param string $type Return type (atom, rss, xml, json)
3189 * @return array|string
3191 function api_help_test($type)
3193 if ($type == 'xml') {
3199 return api_format_data('ok', $type, ["ok" => $ok]);
3202 /// @TODO move to top of file or somewhere better
3203 api_register_func('api/help/test', 'api_help_test', false);
3206 * Returns all lists the user subscribes to.
3208 * @param string $type Return type (atom, rss, xml, json)
3210 * @return array|string
3211 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3213 function api_lists_list($type)
3216 /// @TODO $ret is not filled here?
3217 return api_format_data('lists', $type, ["lists_list" => $ret]);
3220 /// @TODO move to top of file or somewhere better
3221 api_register_func('api/lists/list', 'api_lists_list', true);
3222 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3225 * Returns all groups the user owns.
3227 * @param string $type Return type (atom, rss, xml, json)
3229 * @return array|string
3230 * @throws BadRequestException
3231 * @throws ForbiddenException
3232 * @throws ImagickException
3233 * @throws InternalServerErrorException
3234 * @throws UnauthorizedException
3235 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3237 function api_lists_ownerships($type)
3241 if (api_user() === false) {
3242 throw new ForbiddenException();
3246 $user_info = api_get_user($a);
3247 $uid = $user_info['uid'];
3249 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3251 // loop through all groups
3253 foreach ($groups as $group) {
3254 if ($group['visible']) {
3260 'name' => $group['name'],
3261 'id' => intval($group['id']),
3262 'id_str' => (string) $group['id'],
3263 'user' => $user_info,
3267 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3270 /// @TODO move to top of file or somewhere better
3271 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3274 * Returns recent statuses from users in the specified group.
3276 * @param string $type Return type (atom, rss, xml, json)
3278 * @return array|string
3279 * @throws BadRequestException
3280 * @throws ForbiddenException
3281 * @throws ImagickException
3282 * @throws InternalServerErrorException
3283 * @throws UnauthorizedException
3284 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3286 function api_lists_statuses($type)
3290 $user_info = api_get_user($a);
3291 if (api_user() === false || $user_info === false) {
3292 throw new ForbiddenException();
3295 unset($_REQUEST["user_id"]);
3296 unset($_GET["user_id"]);
3298 unset($_REQUEST["screen_name"]);
3299 unset($_GET["screen_name"]);
3301 if (empty($_REQUEST['list_id'])) {
3302 throw new BadRequestException('list_id not specified');
3306 $count = defaults($_REQUEST, 'count', 20);
3307 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3311 $since_id = defaults($_REQUEST, 'since_id', 0);
3312 $max_id = defaults($_REQUEST, 'max_id', 0);
3313 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3314 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3316 $start = $page * $count;
3318 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3319 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3322 $condition[0] .= " AND `item`.`id` <= ?";
3323 $condition[] = $max_id;
3325 if ($exclude_replies > 0) {
3326 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3328 if ($conversation_id > 0) {
3329 $condition[0] .= " AND `item`.`parent` = ?";
3330 $condition[] = $conversation_id;
3333 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3334 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3336 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3338 $data = ['status' => $items];
3343 $data = api_rss_extra($a, $data, $user_info);
3347 return api_format_data("statuses", $type, $data);
3350 /// @TODO move to top of file or somewhere better
3351 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3354 * Considers friends and followers lists to be private and won't return
3355 * anything if any user_id parameter is passed.
3357 * @brief Returns either the friends of the follower list
3359 * @param string $qtype Either "friends" or "followers"
3360 * @return boolean|array
3361 * @throws BadRequestException
3362 * @throws ForbiddenException
3363 * @throws ImagickException
3364 * @throws InternalServerErrorException
3365 * @throws UnauthorizedException
3367 function api_statuses_f($qtype)
3371 if (api_user() === false) {
3372 throw new ForbiddenException();
3376 $count = defaults($_GET, 'count', 20);
3377 $page = defaults($_GET, 'page', 1);
3381 $start = ($page - 1) * $count;
3383 $user_info = api_get_user($a);
3385 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3386 /* this is to stop Hotot to load friends multiple times
3387 * I'm not sure if I'm missing return something or
3388 * is a bug in hotot. Workaround, meantime
3392 return array('$users' => $ret);*/
3397 if ($qtype == 'friends') {
3398 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3399 } elseif ($qtype == 'followers') {
3400 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3403 // friends and followers only for self
3404 if ($user_info['self'] == 0) {
3405 $sql_extra = " AND false ";
3408 if ($qtype == 'blocks') {
3409 $sql_filter = 'AND `blocked` AND NOT `pending`';
3410 } elseif ($qtype == 'incoming') {
3411 $sql_filter = 'AND `pending`';
3413 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3431 foreach ($r as $cid) {
3432 $user = api_get_user($a, $cid['nurl']);
3433 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3434 unset($user["uid"]);
3435 unset($user["self"]);
3442 return ['user' => $ret];
3447 * Returns the user's friends.
3449 * @brief Returns the list of friends of the provided user
3451 * @deprecated By Twitter API in favor of friends/list
3453 * @param string $type Either "json" or "xml"
3454 * @return boolean|string|array
3455 * @throws BadRequestException
3456 * @throws ForbiddenException
3458 function api_statuses_friends($type)
3460 $data = api_statuses_f("friends");
3461 if ($data === false) {
3464 return api_format_data("users", $type, $data);
3468 * Returns the user's followers.
3470 * @brief Returns the list of followers of the provided user
3472 * @deprecated By Twitter API in favor of friends/list
3474 * @param string $type Either "json" or "xml"
3475 * @return boolean|string|array
3476 * @throws BadRequestException
3477 * @throws ForbiddenException
3479 function api_statuses_followers($type)
3481 $data = api_statuses_f("followers");
3482 if ($data === false) {
3485 return api_format_data("users", $type, $data);
3488 /// @TODO move to top of file or somewhere better
3489 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3490 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3493 * Returns the list of blocked users
3495 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3497 * @param string $type Either "json" or "xml"
3499 * @return boolean|string|array
3500 * @throws BadRequestException
3501 * @throws ForbiddenException
3503 function api_blocks_list($type)
3505 $data = api_statuses_f('blocks');
3506 if ($data === false) {
3509 return api_format_data("users", $type, $data);
3512 /// @TODO move to top of file or somewhere better
3513 api_register_func('api/blocks/list', 'api_blocks_list', true);
3516 * Returns the list of pending users IDs
3518 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3520 * @param string $type Either "json" or "xml"
3522 * @return boolean|string|array
3523 * @throws BadRequestException
3524 * @throws ForbiddenException
3526 function api_friendships_incoming($type)
3528 $data = api_statuses_f('incoming');
3529 if ($data === false) {
3534 foreach ($data['user'] as $user) {
3535 $ids[] = $user['id'];
3538 return api_format_data("ids", $type, ['id' => $ids]);
3541 /// @TODO move to top of file or somewhere better
3542 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3545 * Returns the instance's configuration information.
3547 * @param string $type Return type (atom, rss, xml, json)
3549 * @return array|string
3550 * @throws InternalServerErrorException
3552 function api_statusnet_config($type)
3556 $name = Config::get('config', 'sitename');
3557 $server = $a->getHostName();
3558 $logo = System::baseUrl() . '/images/friendica-64.png';
3559 $email = Config::get('config', 'admin_email');
3560 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3561 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3562 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3563 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3564 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3567 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3568 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3569 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3570 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3571 'shorturllength' => '30',
3573 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3574 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3575 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3576 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3581 return api_format_data('config', $type, ['config' => $config]);
3584 /// @TODO move to top of file or somewhere better
3585 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3586 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3590 * @param string $type Return type (atom, rss, xml, json)
3592 * @return array|string
3594 function api_statusnet_version($type)
3597 $fake_statusnet_version = "0.9.7";
3599 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3602 /// @TODO move to top of file or somewhere better
3603 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3604 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3608 * @param string $type Return type (atom, rss, xml, json)
3610 * @return array|string|void
3611 * @throws BadRequestException
3612 * @throws ForbiddenException
3613 * @throws ImagickException
3614 * @throws InternalServerErrorException
3615 * @throws UnauthorizedException
3616 * @todo use api_format_data() to return data
3618 function api_ff_ids($type)
3621 throw new ForbiddenException();
3628 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3631 "SELECT `pcontact`.`id` FROM `contact`
3632 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3633 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3636 if (!DBA::isResult($r)) {
3641 foreach ($r as $rr) {
3642 if ($stringify_ids) {
3645 $ids[] = intval($rr['id']);
3649 return api_format_data("ids", $type, ['id' => $ids]);
3653 * Returns the ID of every user the user is following.
3655 * @param string $type Return type (atom, rss, xml, json)
3657 * @return array|string
3658 * @throws BadRequestException
3659 * @throws ForbiddenException
3660 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3662 function api_friends_ids($type)
3664 return api_ff_ids($type);
3668 * Returns the ID of every user following the user.
3670 * @param string $type Return type (atom, rss, xml, json)
3672 * @return array|string
3673 * @throws BadRequestException
3674 * @throws ForbiddenException
3675 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3677 function api_followers_ids($type)
3679 return api_ff_ids($type);
3682 /// @TODO move to top of file or somewhere better
3683 api_register_func('api/friends/ids', 'api_friends_ids', true);
3684 api_register_func('api/followers/ids', 'api_followers_ids', true);
3687 * Sends a new direct message.
3689 * @param string $type Return type (atom, rss, xml, json)
3691 * @return array|string
3692 * @throws BadRequestException
3693 * @throws ForbiddenException
3694 * @throws ImagickException
3695 * @throws InternalServerErrorException
3696 * @throws NotFoundException
3697 * @throws UnauthorizedException
3698 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3700 function api_direct_messages_new($type)
3704 if (api_user() === false) {
3705 throw new ForbiddenException();
3708 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3712 $sender = api_get_user($a);
3715 if (!empty($_POST['screen_name'])) {
3717 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3719 DBA::escape($_POST['screen_name'])
3722 if (DBA::isResult($r)) {
3723 // Selecting the id by priority, friendica first
3724 api_best_nickname($r);
3726 $recipient = api_get_user($a, $r[0]['nurl']);
3729 $recipient = api_get_user($a, $_POST['user_id']);
3732 if (empty($recipient)) {
3733 throw new NotFoundException('Recipient not found');
3737 if (!empty($_REQUEST['replyto'])) {
3739 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3741 intval($_REQUEST['replyto'])
3743 $replyto = $r[0]['parent-uri'];
3744 $sub = $r[0]['title'];
3746 if (!empty($_REQUEST['title'])) {
3747 $sub = $_REQUEST['title'];
3749 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3753 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3756 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3757 $ret = api_format_messages($r[0], $recipient, $sender);
3759 $ret = ["error"=>$id];
3762 $data = ['direct_message'=>$ret];
3768 $data = api_rss_extra($a, $data, $sender);
3772 return api_format_data("direct-messages", $type, $data);
3775 /// @TODO move to top of file or somewhere better
3776 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3779 * Destroys a direct message.
3781 * @brief delete a direct_message from mail table through api
3783 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3784 * @return string|array
3785 * @throws BadRequestException
3786 * @throws ForbiddenException
3787 * @throws ImagickException
3788 * @throws InternalServerErrorException
3789 * @throws UnauthorizedException
3790 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3792 function api_direct_messages_destroy($type)
3796 if (api_user() === false) {
3797 throw new ForbiddenException();
3801 $user_info = api_get_user($a);
3803 $id = defaults($_REQUEST, 'id', 0);
3805 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3806 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3807 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3809 $uid = $user_info['uid'];
3810 // error if no id or parenturi specified (for clients posting parent-uri as well)
3811 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3812 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3813 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3816 // BadRequestException if no id specified (for clients using Twitter API)
3818 throw new BadRequestException('Message id not specified');
3821 // add parent-uri to sql command if specified by calling app
3822 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3824 // get data of the specified message id
3826 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3831 // error message if specified id is not in database
3832 if (!DBA::isResult($r)) {
3833 if ($verbose == "true") {
3834 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3835 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3837 /// @todo BadRequestException ok for Twitter API clients?
3838 throw new BadRequestException('message id not in database');
3843 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3848 if ($verbose == "true") {
3851 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3852 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3854 $answer = ['result' => 'error', 'message' => 'unknown error'];
3855 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3858 /// @todo return JSON data like Twitter API not yet implemented
3861 /// @TODO move to top of file or somewhere better
3862 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3867 * @brief unfollow contact
3869 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3870 * @return string|array
3871 * @throws BadRequestException
3872 * @throws ForbiddenException
3873 * @throws ImagickException
3874 * @throws InternalServerErrorException
3875 * @throws NotFoundException
3876 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3878 function api_friendships_destroy($type)
3882 if ($uid === false) {
3883 throw new ForbiddenException();
3886 $contact_id = defaults($_REQUEST, 'user_id');
3888 if (empty($contact_id)) {
3889 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3890 throw new BadRequestException("no user_id specified");
3893 // Get Contact by given id
3894 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3896 if(!DBA::isResult($contact)) {
3897 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3898 throw new NotFoundException("no contact found to given ID");
3901 $url = $contact["url"];
3903 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3904 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3905 Strings::normaliseLink($url), $url];
3906 $contact = DBA::selectFirst('contact', [], $condition);
3908 if (!DBA::isResult($contact)) {
3909 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3910 throw new NotFoundException("Not following Contact");
3913 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3914 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3915 throw new ExpectationFailedException("Not supported");
3918 $dissolve = ($contact['rel'] == Contact::SHARING);
3920 $owner = User::getOwnerDataById($uid);
3922 Contact::terminateFriendship($owner, $contact, $dissolve);
3925 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3926 throw new NotFoundException("Error Processing Request");
3929 // Sharing-only contacts get deleted as there no relationship any more
3931 Contact::remove($contact['id']);
3933 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3936 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3937 unset($contact["uid"]);
3938 unset($contact["self"]);
3940 // Set screen_name since Twidere requests it
3941 $contact["screen_name"] = $contact["nick"];
3943 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3945 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3949 * @param string $type Return type (atom, rss, xml, json)
3950 * @param string $box
3951 * @param string $verbose
3953 * @return array|string
3954 * @throws BadRequestException
3955 * @throws ForbiddenException
3956 * @throws ImagickException
3957 * @throws InternalServerErrorException
3958 * @throws UnauthorizedException
3960 function api_direct_messages_box($type, $box, $verbose)
3963 if (api_user() === false) {
3964 throw new ForbiddenException();
3967 $count = defaults($_GET, 'count', 20);
3968 $page = defaults($_REQUEST, 'page', 1) - 1;
3973 $since_id = defaults($_REQUEST, 'since_id', 0);
3974 $max_id = defaults($_REQUEST, 'max_id', 0);
3976 $user_id = defaults($_REQUEST, 'user_id', '');
3977 $screen_name = defaults($_REQUEST, 'screen_name', '');
3980 unset($_REQUEST["user_id"]);
3981 unset($_GET["user_id"]);
3983 unset($_REQUEST["screen_name"]);
3984 unset($_GET["screen_name"]);
3986 $user_info = api_get_user($a);
3987 if ($user_info === false) {
3988 throw new ForbiddenException();
3990 $profile_url = $user_info["url"];
3993 $start = $page * $count;
3998 if ($box=="sentbox") {
3999 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
4000 } elseif ($box == "conversation") {
4001 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
4002 } elseif ($box == "all") {
4003 $sql_extra = "true";
4004 } elseif ($box == "inbox") {
4005 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4009 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4012 if ($user_id != "") {
4013 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4014 } elseif ($screen_name !="") {
4015 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4019 "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",
4025 if ($verbose == "true" && !DBA::isResult($r)) {
4026 $answer = ['result' => 'error', 'message' => 'no mails available'];
4027 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4031 foreach ($r as $item) {
4032 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4033 $recipient = $user_info;
4034 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4035 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4036 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4037 $sender = $user_info;
4040 if (isset($recipient) && isset($sender)) {
4041 $ret[] = api_format_messages($item, $recipient, $sender);
4046 $data = ['direct_message' => $ret];
4051 $data = api_rss_extra($a, $data, $user_info);
4055 return api_format_data("direct-messages", $type, $data);
4059 * Returns the most recent direct messages sent by the user.
4061 * @param string $type Return type (atom, rss, xml, json)
4063 * @return array|string
4064 * @throws BadRequestException
4065 * @throws ForbiddenException
4066 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4068 function api_direct_messages_sentbox($type)
4070 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4071 return api_direct_messages_box($type, "sentbox", $verbose);
4075 * Returns the most recent direct messages sent to the user.
4077 * @param string $type Return type (atom, rss, xml, json)
4079 * @return array|string
4080 * @throws BadRequestException
4081 * @throws ForbiddenException
4082 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4084 function api_direct_messages_inbox($type)
4086 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4087 return api_direct_messages_box($type, "inbox", $verbose);
4092 * @param string $type Return type (atom, rss, xml, json)
4094 * @return array|string
4095 * @throws BadRequestException
4096 * @throws ForbiddenException
4098 function api_direct_messages_all($type)
4100 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4101 return api_direct_messages_box($type, "all", $verbose);
4106 * @param string $type Return type (atom, rss, xml, json)
4108 * @return array|string
4109 * @throws BadRequestException
4110 * @throws ForbiddenException
4112 function api_direct_messages_conversation($type)
4114 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4115 return api_direct_messages_box($type, "conversation", $verbose);
4118 /// @TODO move to top of file or somewhere better
4119 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4120 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4121 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4122 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4125 * Returns an OAuth Request Token.
4127 * @see https://oauth.net/core/1.0/#auth_step1
4129 function api_oauth_request_token()
4131 $oauth1 = new FKOAuth1();
4133 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4134 } catch (Exception $e) {
4135 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4143 * Returns an OAuth Access Token.
4145 * @return array|string
4146 * @see https://oauth.net/core/1.0/#auth_step3
4148 function api_oauth_access_token()
4150 $oauth1 = new FKOAuth1();
4152 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4153 } catch (Exception $e) {
4154 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4161 /// @TODO move to top of file or somewhere better
4162 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4163 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4167 * @brief delete a complete photoalbum with all containing photos from database through api
4169 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4170 * @return string|array
4171 * @throws BadRequestException
4172 * @throws ForbiddenException
4173 * @throws InternalServerErrorException
4175 function api_fr_photoalbum_delete($type)
4177 if (api_user() === false) {
4178 throw new ForbiddenException();
4181 $album = defaults($_REQUEST, 'album', "");
4183 // we do not allow calls without album string
4185 throw new BadRequestException("no albumname specified");
4187 // check if album is existing
4189 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4193 if (!DBA::isResult($r)) {
4194 throw new BadRequestException("album not available");
4197 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4198 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4199 foreach ($r as $rr) {
4200 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4201 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4203 if (!DBA::isResult($photo_item)) {
4204 throw new InternalServerErrorException("problem with deleting items occured");
4206 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4209 // now let's delete all photos from the album
4210 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4212 // return success of deletion or error message
4214 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4215 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4217 throw new InternalServerErrorException("unknown error - deleting from database failed");
4222 * @brief update the name of the album for all photos of an album
4224 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4225 * @return string|array
4226 * @throws BadRequestException
4227 * @throws ForbiddenException
4228 * @throws InternalServerErrorException
4230 function api_fr_photoalbum_update($type)
4232 if (api_user() === false) {
4233 throw new ForbiddenException();
4236 $album = defaults($_REQUEST, 'album', "");
4237 $album_new = defaults($_REQUEST, 'album_new', "");
4239 // we do not allow calls without album string
4241 throw new BadRequestException("no albumname specified");
4243 if ($album_new == "") {
4244 throw new BadRequestException("no new albumname specified");
4246 // check if album is existing
4247 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4248 throw new BadRequestException("album not available");
4250 // now let's update all photos to the albumname
4251 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4253 // return success of updating or error message
4255 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4256 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4258 throw new InternalServerErrorException("unknown error - updating in database failed");
4264 * @brief list all photos of the authenticated user
4266 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4267 * @return string|array
4268 * @throws ForbiddenException
4269 * @throws InternalServerErrorException
4271 function api_fr_photos_list($type)
4273 if (api_user() === false) {
4274 throw new ForbiddenException();
4277 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4278 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4279 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4280 intval(local_user())
4283 'image/jpeg' => 'jpg',
4284 'image/png' => 'png',
4285 'image/gif' => 'gif'
4287 $data = ['photo'=>[]];
4288 if (DBA::isResult($r)) {
4289 foreach ($r as $rr) {
4291 $photo['id'] = $rr['resource-id'];
4292 $photo['album'] = $rr['album'];
4293 $photo['filename'] = $rr['filename'];
4294 $photo['type'] = $rr['type'];
4295 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4296 $photo['created'] = $rr['created'];
4297 $photo['edited'] = $rr['edited'];
4298 $photo['desc'] = $rr['desc'];
4300 if ($type == "xml") {
4301 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4303 $photo['thumb'] = $thumb;
4304 $data['photo'][] = $photo;
4308 return api_format_data("photos", $type, $data);
4312 * @brief upload a new photo or change an existing photo
4314 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4315 * @return string|array
4316 * @throws BadRequestException
4317 * @throws ForbiddenException
4318 * @throws ImagickException
4319 * @throws InternalServerErrorException
4320 * @throws NotFoundException
4322 function api_fr_photo_create_update($type)
4324 if (api_user() === false) {
4325 throw new ForbiddenException();
4328 $photo_id = defaults($_REQUEST, 'photo_id', null);
4329 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4330 $album = defaults($_REQUEST, 'album', null);
4331 $album_new = defaults($_REQUEST, 'album_new', null);
4332 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4333 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4334 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4335 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4336 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4338 // do several checks on input parameters
4339 // we do not allow calls without album string
4340 if ($album == null) {
4341 throw new BadRequestException("no albumname specified");
4343 // if photo_id == null --> we are uploading a new photo
4344 if ($photo_id == null) {
4347 // error if no media posted in create-mode
4348 if (empty($_FILES['media'])) {
4350 throw new BadRequestException("no media data submitted");
4353 // album_new will be ignored in create-mode
4358 // check if photo is existing in databasei
4359 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4360 throw new BadRequestException("photo not available");
4364 // checks on acl strings provided by clients
4365 $acl_input_error = false;
4366 $acl_input_error |= check_acl_input($allow_cid);
4367 $acl_input_error |= check_acl_input($deny_cid);
4368 $acl_input_error |= check_acl_input($allow_gid);
4369 $acl_input_error |= check_acl_input($deny_gid);
4370 if ($acl_input_error) {
4371 throw new BadRequestException("acl data invalid");
4373 // now let's upload the new media in create-mode
4374 if ($mode == "create") {
4375 $media = $_FILES['media'];
4376 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4378 // return success of updating or error message
4379 if (!is_null($data)) {
4380 return api_format_data("photo_create", $type, $data);
4382 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4386 // now let's do the changes in update-mode
4387 if ($mode == "update") {
4388 $updated_fields = [];
4390 if (!is_null($desc)) {
4391 $updated_fields['desc'] = $desc;
4394 if (!is_null($album_new)) {
4395 $updated_fields['album'] = $album_new;
4398 if (!is_null($allow_cid)) {
4399 $allow_cid = trim($allow_cid);
4400 $updated_fields['allow_cid'] = $allow_cid;
4403 if (!is_null($deny_cid)) {
4404 $deny_cid = trim($deny_cid);
4405 $updated_fields['deny_cid'] = $deny_cid;
4408 if (!is_null($allow_gid)) {
4409 $allow_gid = trim($allow_gid);
4410 $updated_fields['allow_gid'] = $allow_gid;
4413 if (!is_null($deny_gid)) {
4414 $deny_gid = trim($deny_gid);
4415 $updated_fields['deny_gid'] = $deny_gid;
4419 if (count($updated_fields) > 0) {
4420 $nothingtodo = false;
4421 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4423 $nothingtodo = true;
4426 if (!empty($_FILES['media'])) {
4427 $nothingtodo = false;
4428 $media = $_FILES['media'];
4429 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4430 if (!is_null($data)) {
4431 return api_format_data("photo_update", $type, $data);
4435 // return success of updating or error message
4437 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4438 return api_format_data("photo_update", $type, ['$result' => $answer]);
4441 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4442 return api_format_data("photo_update", $type, ['$result' => $answer]);
4444 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4447 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4451 * @brief delete a single photo from the database through api
4453 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4454 * @return string|array
4455 * @throws BadRequestException
4456 * @throws ForbiddenException
4457 * @throws InternalServerErrorException
4459 function api_fr_photo_delete($type)
4461 if (api_user() === false) {
4462 throw new ForbiddenException();
4465 $photo_id = defaults($_REQUEST, 'photo_id', null);
4467 // do several checks on input parameters
4468 // we do not allow calls without photo id
4469 if ($photo_id == null) {
4470 throw new BadRequestException("no photo_id specified");
4472 // check if photo is existing in database
4473 $r = Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()]);
4475 throw new BadRequestException("photo not available");
4477 // now we can perform on the deletion of the photo
4478 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4480 // return success of deletion or error message
4482 // retrieve the id of the parent element (the photo element)
4483 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4484 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4486 if (!DBA::isResult($photo_item)) {
4487 throw new InternalServerErrorException("problem with deleting items occured");
4489 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4490 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4491 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4493 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4494 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4496 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4502 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4504 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4505 * @return string|array
4506 * @throws BadRequestException
4507 * @throws ForbiddenException
4508 * @throws InternalServerErrorException
4509 * @throws NotFoundException
4511 function api_fr_photo_detail($type)
4513 if (api_user() === false) {
4514 throw new ForbiddenException();
4516 if (empty($_REQUEST['photo_id'])) {
4517 throw new BadRequestException("No photo id.");
4520 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4521 $photo_id = $_REQUEST['photo_id'];
4523 // prepare json/xml output with data from database for the requested photo
4524 $data = prepare_photo_data($type, $scale, $photo_id);
4526 return api_format_data("photo_detail", $type, $data);
4531 * Updates the user’s profile image.
4533 * @brief updates the profile image for the user (either a specified profile or the default profile)
4535 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4537 * @return string|array
4538 * @throws BadRequestException
4539 * @throws ForbiddenException
4540 * @throws ImagickException
4541 * @throws InternalServerErrorException
4542 * @throws NotFoundException
4543 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4545 function api_account_update_profile_image($type)
4547 if (api_user() === false) {
4548 throw new ForbiddenException();
4551 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4553 // error if image data is missing
4554 if (empty($_FILES['image'])) {
4555 throw new BadRequestException("no media data submitted");
4558 // check if specified profile id is valid
4559 if ($profile_id != 0) {
4560 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4561 // error message if specified profile id is not in database
4562 if (!DBA::isResult($profile)) {
4563 throw new BadRequestException("profile_id not available");
4565 $is_default_profile = $profile['is-default'];
4567 $is_default_profile = 1;
4570 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4572 if (!empty($_FILES['image'])) {
4573 $media = $_FILES['image'];
4574 } elseif (!empty($_FILES['media'])) {
4575 $media = $_FILES['media'];
4577 // save new profile image
4578 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4581 if (is_array($media['type'])) {
4582 $filetype = $media['type'][0];
4584 $filetype = $media['type'];
4586 if ($filetype == "image/jpeg") {
4588 } elseif ($filetype == "image/png") {
4591 throw new InternalServerErrorException('Unsupported filetype');
4594 // change specified profile or all profiles to the new resource-id
4595 if ($is_default_profile) {
4596 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4597 Photo::update(['profile' => false], $condition);
4599 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4600 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4601 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4604 Contact::updateSelfFromUserID(api_user(), true);
4606 // Update global directory in background
4607 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4608 if ($url && strlen(Config::get('system', 'directory'))) {
4609 Worker::add(PRIORITY_LOW, "Directory", $url);
4612 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4614 // output for client
4616 return api_account_verify_credentials($type);
4618 // SaveMediaToDatabase failed for some reason
4619 throw new InternalServerErrorException("image upload failed");
4623 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4624 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4625 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4626 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4627 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4628 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4629 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4630 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4631 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4634 * Update user profile
4636 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4638 * @return array|string
4639 * @throws BadRequestException
4640 * @throws ForbiddenException
4641 * @throws ImagickException
4642 * @throws InternalServerErrorException
4643 * @throws UnauthorizedException
4645 function api_account_update_profile($type)
4647 $local_user = api_user();
4648 $api_user = api_get_user(get_app());
4650 if (!empty($_POST['name'])) {
4651 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4652 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4653 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4654 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4657 if (isset($_POST['description'])) {
4658 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4659 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4660 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4663 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4664 // Update global directory in background
4665 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4666 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4669 return api_account_verify_credentials($type);
4672 /// @TODO move to top of file or somewhere better
4673 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4677 * @param string $acl_string
4681 function check_acl_input($acl_string)
4683 if ($acl_string == null || $acl_string == " ") {
4686 $contact_not_found = false;
4688 // split <x><y><z> into array of cid's
4689 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4691 // check for each cid if it is available on server
4692 $cid_array = $array[0];
4693 foreach ($cid_array as $cid) {
4694 $cid = str_replace("<", "", $cid);
4695 $cid = str_replace(">", "", $cid);
4696 $condition = ['id' => $cid, 'uid' => api_user()];
4697 $contact_not_found |= !DBA::exists('contact', $condition);
4699 return $contact_not_found;
4704 * @param string $mediatype
4705 * @param array $media
4706 * @param string $type
4707 * @param string $album
4708 * @param string $allow_cid
4709 * @param string $deny_cid
4710 * @param string $allow_gid
4711 * @param string $deny_gid
4712 * @param string $desc
4713 * @param integer $profile
4714 * @param boolean $visibility
4715 * @param string $photo_id
4717 * @throws BadRequestException
4718 * @throws ForbiddenException
4719 * @throws ImagickException
4720 * @throws InternalServerErrorException
4721 * @throws NotFoundException
4723 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)
4731 if (is_array($media)) {
4732 if (is_array($media['tmp_name'])) {
4733 $src = $media['tmp_name'][0];
4735 $src = $media['tmp_name'];
4737 if (is_array($media['name'])) {
4738 $filename = basename($media['name'][0]);
4740 $filename = basename($media['name']);
4742 if (is_array($media['size'])) {
4743 $filesize = intval($media['size'][0]);
4745 $filesize = intval($media['size']);
4747 if (is_array($media['type'])) {
4748 $filetype = $media['type'][0];
4750 $filetype = $media['type'];
4754 if ($filetype == "") {
4755 $filetype=Image::guessType($filename);
4757 $imagedata = @getimagesize($src);
4759 $filetype = $imagedata['mime'];
4762 "File upload src: " . $src . " - filename: " . $filename .
4763 " - size: " . $filesize . " - type: " . $filetype,
4767 // check if there was a php upload error
4768 if ($filesize == 0 && $media['error'] == 1) {
4769 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4771 // check against max upload size within Friendica instance
4772 $maximagesize = Config::get('system', 'maximagesize');
4773 if ($maximagesize && ($filesize > $maximagesize)) {
4774 $formattedBytes = Strings::formatBytes($maximagesize);
4775 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4778 // create Photo instance with the data of the image
4779 $imagedata = @file_get_contents($src);
4780 $Image = new Image($imagedata, $filetype);
4781 if (!$Image->isValid()) {
4782 throw new InternalServerErrorException("unable to process image data");
4785 // check orientation of image
4786 $Image->orient($src);
4789 // check max length of images on server
4790 $max_length = Config::get('system', 'max_image_length');
4792 $max_length = MAX_IMAGE_LENGTH;
4794 if ($max_length > 0) {
4795 $Image->scaleDown($max_length);
4796 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4798 $width = $Image->getWidth();
4799 $height = $Image->getHeight();
4801 // create a new resource-id if not already provided
4802 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4804 if ($mediatype == "photo") {
4805 // upload normal image (scales 0, 1, 2)
4806 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4808 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4810 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4812 if ($width > 640 || $height > 640) {
4813 $Image->scaleDown(640);
4814 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4816 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4820 if ($width > 320 || $height > 320) {
4821 $Image->scaleDown(320);
4822 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4824 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4827 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4828 } elseif ($mediatype == "profileimage") {
4829 // upload profile image (scales 4, 5, 6)
4830 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4832 if ($width > 300 || $height > 300) {
4833 $Image->scaleDown(300);
4834 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4836 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4840 if ($width > 80 || $height > 80) {
4841 $Image->scaleDown(80);
4842 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4844 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4848 if ($width > 48 || $height > 48) {
4849 $Image->scaleDown(48);
4850 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4852 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4855 $Image->__destruct();
4856 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4859 if (isset($r) && $r) {
4860 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4861 if ($photo_id == null && $mediatype == "photo") {
4862 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4864 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4865 return prepare_photo_data($type, false, $hash);
4867 throw new InternalServerErrorException("image upload failed");
4873 * @param string $hash
4874 * @param string $allow_cid
4875 * @param string $deny_cid
4876 * @param string $allow_gid
4877 * @param string $deny_gid
4878 * @param string $filetype
4879 * @param boolean $visibility
4880 * @throws InternalServerErrorException
4882 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4884 // get data about the api authenticated user
4885 $uri = Item::newURI(intval(api_user()));
4886 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4889 $arr['guid'] = System::createUUID();
4890 $arr['uid'] = intval(api_user());
4892 $arr['parent-uri'] = $uri;
4893 $arr['type'] = 'photo';
4895 $arr['resource-id'] = $hash;
4896 $arr['contact-id'] = $owner_record['id'];
4897 $arr['owner-name'] = $owner_record['name'];
4898 $arr['owner-link'] = $owner_record['url'];
4899 $arr['owner-avatar'] = $owner_record['thumb'];
4900 $arr['author-name'] = $owner_record['name'];
4901 $arr['author-link'] = $owner_record['url'];
4902 $arr['author-avatar'] = $owner_record['thumb'];
4904 $arr['allow_cid'] = $allow_cid;
4905 $arr['allow_gid'] = $allow_gid;
4906 $arr['deny_cid'] = $deny_cid;
4907 $arr['deny_gid'] = $deny_gid;
4908 $arr['visible'] = $visibility;
4912 'image/jpeg' => 'jpg',
4913 'image/png' => 'png',
4914 'image/gif' => 'gif'
4917 // adds link to the thumbnail scale photo
4918 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4919 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4922 // do the magic for storing the item in the database and trigger the federation to other contacts
4928 * @param string $type
4930 * @param string $photo_id
4933 * @throws BadRequestException
4934 * @throws ForbiddenException
4935 * @throws ImagickException
4936 * @throws InternalServerErrorException
4937 * @throws NotFoundException
4938 * @throws UnauthorizedException
4940 function prepare_photo_data($type, $scale, $photo_id)
4943 $user_info = api_get_user($a);
4945 if ($user_info === false) {
4946 throw new ForbiddenException();
4949 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4950 $data_sql = ($scale === false ? "" : "data, ");
4952 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4953 // clients needs to convert this in their way for further processing
4955 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4956 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4957 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4958 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4960 intval(local_user()),
4961 DBA::escape($photo_id),
4966 'image/jpeg' => 'jpg',
4967 'image/png' => 'png',
4968 'image/gif' => 'gif'
4971 // prepare output data for photo
4972 if (DBA::isResult($r)) {
4973 $data = ['photo' => $r[0]];
4974 $data['photo']['id'] = $data['photo']['resource-id'];
4975 if ($scale !== false) {
4976 $data['photo']['data'] = base64_encode($data['photo']['data']);
4978 unset($data['photo']['datasize']); //needed only with scale param
4980 if ($type == "xml") {
4981 $data['photo']['links'] = [];
4982 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4983 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4985 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4988 $data['photo']['link'] = [];
4989 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4991 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4992 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4996 unset($data['photo']['resource-id']);
4997 unset($data['photo']['minscale']);
4998 unset($data['photo']['maxscale']);
5000 throw new NotFoundException();
5003 // retrieve item element for getting activities (like, dislike etc.) related to photo
5004 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5005 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5007 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5009 // retrieve comments on photo
5010 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5011 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5013 $statuses = Item::selectForUser(api_user(), [], $condition);
5015 // prepare output of comments
5016 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5018 if ($type == "xml") {
5020 foreach ($commentData as $comment) {
5021 $comments[$k++ . ":comment"] = $comment;
5024 foreach ($commentData as $comment) {
5025 $comments[] = $comment;
5028 $data['photo']['friendica_comments'] = $comments;
5030 // include info if rights on photo and rights on item are mismatching
5031 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5032 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5033 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5034 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5035 $data['photo']['rights_mismatch'] = $rights_mismatch;
5042 * Similar as /mod/redir.php
5043 * redirect to 'url' after dfrn auth
5045 * Why this when there is mod/redir.php already?
5046 * This use api_user() and api_login()
5049 * c_url: url of remote contact to auth to
5050 * url: string, url to redirect after auth
5052 function api_friendica_remoteauth()
5054 $url = defaults($_GET, 'url', '');
5055 $c_url = defaults($_GET, 'c_url', '');
5057 if ($url === '' || $c_url === '') {
5058 throw new BadRequestException("Wrong parameters.");
5061 $c_url = Strings::normaliseLink($c_url);
5065 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5067 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5068 throw new BadRequestException("Unknown contact");
5071 $cid = $contact['id'];
5073 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
5075 if ($contact['duplex'] && $contact['issued-id']) {
5076 $orig_id = $contact['issued-id'];
5077 $dfrn_id = '1:' . $orig_id;
5079 if ($contact['duplex'] && $contact['dfrn-id']) {
5080 $orig_id = $contact['dfrn-id'];
5081 $dfrn_id = '0:' . $orig_id;
5084 $sec = Strings::getRandomHex();
5086 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5087 'sec' => $sec, 'expire' => time() + 45];
5088 DBA::insert('profile_check', $fields);
5090 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5091 $dest = ($url ? '&destination_url=' . $url : '');
5093 System::externalRedirect(
5094 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5095 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5096 . '&type=profile&sec=' . $sec . $dest
5099 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5102 * @brief Return the item shared, if the item contains only the [share] tag
5104 * @param array $item Sharer item
5105 * @return array|false Shared item or false if not a reshare
5106 * @throws ImagickException
5107 * @throws InternalServerErrorException
5109 function api_share_as_retweet(&$item)
5111 $body = trim($item["body"]);
5113 if (Diaspora::isReshare($body, false) === false) {
5114 if ($item['author-id'] == $item['owner-id']) {
5117 // Reshares from OStatus, ActivityPub and Twitter
5118 $reshared_item = $item;
5119 $reshared_item['owner-id'] = $reshared_item['author-id'];
5120 $reshared_item['owner-link'] = $reshared_item['author-link'];
5121 $reshared_item['owner-name'] = $reshared_item['author-name'];
5122 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5123 return $reshared_item;
5127 /// @TODO "$1" should maybe mean '$1' ?
5128 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5130 * Skip if there is no shared message in there
5131 * we already checked this in diaspora::isReshare()
5132 * but better one more than one less...
5134 if (($body == $attributes) || empty($attributes)) {
5138 // build the fake reshared item
5139 $reshared_item = $item;
5142 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5143 if (!empty($matches[1])) {
5144 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5147 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5148 if (!empty($matches[1])) {
5149 $author = $matches[1];
5153 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5154 if (!empty($matches[1])) {
5155 $profile = $matches[1];
5158 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5159 if (!empty($matches[1])) {
5160 $profile = $matches[1];
5164 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5165 if (!empty($matches[1])) {
5166 $avatar = $matches[1];
5169 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5170 if (!empty($matches[1])) {
5171 $avatar = $matches[1];
5175 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5176 if (!empty($matches[1])) {
5177 $link = $matches[1];
5180 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5181 if (!empty($matches[1])) {
5182 $link = $matches[1];
5186 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5187 if (!empty($matches[1])) {
5188 $posted = $matches[1];
5191 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5192 if (!empty($matches[1])) {
5193 $posted = $matches[1];
5196 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5198 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5202 $reshared_item["body"] = $shared_body;
5203 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5204 $reshared_item["author-name"] = $author;
5205 $reshared_item["author-link"] = $profile;
5206 $reshared_item["author-avatar"] = $avatar;
5207 $reshared_item["plink"] = $link;
5208 $reshared_item["created"] = $posted;
5209 $reshared_item["edited"] = $posted;
5211 return $reshared_item;
5216 * @param string $profile
5218 * @return string|false
5219 * @throws InternalServerErrorException
5220 * @todo remove trailing junk from profile url
5221 * @todo pump.io check has to check the website
5223 function api_get_nick($profile)
5228 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5229 DBA::escape(Strings::normaliseLink($profile))
5232 if (DBA::isResult($r)) {
5233 $nick = $r[0]["nick"];
5238 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5239 DBA::escape(Strings::normaliseLink($profile))
5242 if (DBA::isResult($r)) {
5243 $nick = $r[0]["nick"];
5248 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5249 if ($friendica != $profile) {
5255 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5256 if ($diaspora != $profile) {
5262 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5263 if ($twitter != $profile) {
5270 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5271 if ($StatusnetHost != $profile) {
5272 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5273 if ($StatusnetUser != $profile) {
5274 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5275 $user = json_decode($UserData);
5277 $nick = $user->screen_name;
5283 // To-Do: look at the page if its really a pumpio site
5284 //if (!$nick == "") {
5285 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5286 // if ($pumpio != $profile)
5288 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5301 * @param array $item
5306 function api_in_reply_to($item)
5310 $in_reply_to['status_id'] = null;
5311 $in_reply_to['user_id'] = null;
5312 $in_reply_to['status_id_str'] = null;
5313 $in_reply_to['user_id_str'] = null;
5314 $in_reply_to['screen_name'] = null;
5316 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5317 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5318 if (DBA::isResult($parent)) {
5319 $in_reply_to['status_id'] = intval($parent['id']);
5321 $in_reply_to['status_id'] = intval($item['parent']);
5324 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5326 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5327 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5329 if (DBA::isResult($parent)) {
5330 if ($parent['author-nick'] == "") {
5331 $parent['author-nick'] = api_get_nick($parent['author-link']);
5334 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5335 $in_reply_to['user_id'] = intval($parent['author-id']);
5336 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5339 // There seems to be situation, where both fields are identical:
5340 // https://github.com/friendica/friendica/issues/1010
5341 // This is a bugfix for that.
5342 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5343 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']]);
5344 $in_reply_to['status_id'] = null;
5345 $in_reply_to['user_id'] = null;
5346 $in_reply_to['status_id_str'] = null;
5347 $in_reply_to['user_id_str'] = null;
5348 $in_reply_to['screen_name'] = null;
5352 return $in_reply_to;
5357 * @param string $text
5360 * @throws InternalServerErrorException
5362 function api_clean_plain_items($text)
5364 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5366 $text = BBCode::cleanPictureLinks($text);
5367 $URLSearchString = "^\[\]";
5369 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5371 if ($include_entities == "true") {
5372 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5375 // Simplify "attachment" element
5376 $text = api_clean_attachments($text);
5382 * @brief Removes most sharing information for API text export
5384 * @param string $body The original body
5386 * @return string Cleaned body
5387 * @throws InternalServerErrorException
5389 function api_clean_attachments($body)
5391 $data = BBCode::getAttachmentData($body);
5398 if (isset($data["text"])) {
5399 $body = $data["text"];
5401 if (($body == "") && isset($data["title"])) {
5402 $body = $data["title"];
5404 if (isset($data["url"])) {
5405 $body .= "\n".$data["url"];
5407 $body .= $data["after"];
5414 * @param array $contacts
5418 function api_best_nickname(&$contacts)
5422 if (count($contacts) == 0) {
5426 foreach ($contacts as $contact) {
5427 if ($contact["network"] == "") {
5428 $contact["network"] = "dfrn";
5429 $best_contact = [$contact];
5433 if (sizeof($best_contact) == 0) {
5434 foreach ($contacts as $contact) {
5435 if ($contact["network"] == "dfrn") {
5436 $best_contact = [$contact];
5441 if (sizeof($best_contact) == 0) {
5442 foreach ($contacts as $contact) {
5443 if ($contact["network"] == "dspr") {
5444 $best_contact = [$contact];
5449 if (sizeof($best_contact) == 0) {
5450 foreach ($contacts as $contact) {
5451 if ($contact["network"] == "stat") {
5452 $best_contact = [$contact];
5457 if (sizeof($best_contact) == 0) {
5458 foreach ($contacts as $contact) {
5459 if ($contact["network"] == "pump") {
5460 $best_contact = [$contact];
5465 if (sizeof($best_contact) == 0) {
5466 foreach ($contacts as $contact) {
5467 if ($contact["network"] == "twit") {
5468 $best_contact = [$contact];
5473 if (sizeof($best_contact) == 1) {
5474 $contacts = $best_contact;
5476 $contacts = [$contacts[0]];
5481 * Return all or a specified group of the user with the containing contacts.
5483 * @param string $type Return type (atom, rss, xml, json)
5485 * @return array|string
5486 * @throws BadRequestException
5487 * @throws ForbiddenException
5488 * @throws ImagickException
5489 * @throws InternalServerErrorException
5490 * @throws UnauthorizedException
5492 function api_friendica_group_show($type)
5496 if (api_user() === false) {
5497 throw new ForbiddenException();
5501 $user_info = api_get_user($a);
5502 $gid = defaults($_REQUEST, 'gid', 0);
5503 $uid = $user_info['uid'];
5505 // get data of the specified group id or all groups if not specified
5508 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5512 // error message if specified gid is not in database
5513 if (!DBA::isResult($r)) {
5514 throw new BadRequestException("gid not available");
5518 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5523 // loop through all groups and retrieve all members for adding data in the user array
5525 foreach ($r as $rr) {
5526 $members = Contact::getByGroupId($rr['id']);
5529 if ($type == "xml") {
5530 $user_element = "users";
5532 foreach ($members as $member) {
5533 $user = api_get_user($a, $member['nurl']);
5534 $users[$k++.":user"] = $user;
5537 $user_element = "user";
5538 foreach ($members as $member) {
5539 $user = api_get_user($a, $member['nurl']);
5543 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5545 return api_format_data("groups", $type, ['group' => $grps]);
5547 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5551 * Delete the specified group of the user.
5553 * @param string $type Return type (atom, rss, xml, json)
5555 * @return array|string
5556 * @throws BadRequestException
5557 * @throws ForbiddenException
5558 * @throws ImagickException
5559 * @throws InternalServerErrorException
5560 * @throws UnauthorizedException
5562 function api_friendica_group_delete($type)
5566 if (api_user() === false) {
5567 throw new ForbiddenException();
5571 $user_info = api_get_user($a);
5572 $gid = defaults($_REQUEST, 'gid', 0);
5573 $name = defaults($_REQUEST, 'name', "");
5574 $uid = $user_info['uid'];
5576 // error if no gid specified
5577 if ($gid == 0 || $name == "") {
5578 throw new BadRequestException('gid or name not specified');
5581 // get data of the specified group id
5583 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5587 // error message if specified gid is not in database
5588 if (!DBA::isResult($r)) {
5589 throw new BadRequestException('gid not available');
5592 // get data of the specified group id and group name
5594 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5599 // error message if specified gid is not in database
5600 if (!DBA::isResult($rname)) {
5601 throw new BadRequestException('wrong group name');
5605 $ret = Group::removeByName($uid, $name);
5608 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5609 return api_format_data("group_delete", $type, ['result' => $success]);
5611 throw new BadRequestException('other API error');
5614 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5619 * @param string $type Return type (atom, rss, xml, json)
5621 * @return array|string
5622 * @throws BadRequestException
5623 * @throws ForbiddenException
5624 * @throws ImagickException
5625 * @throws InternalServerErrorException
5626 * @throws UnauthorizedException
5627 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5629 function api_lists_destroy($type)
5633 if (api_user() === false) {
5634 throw new ForbiddenException();
5638 $user_info = api_get_user($a);
5639 $gid = defaults($_REQUEST, 'list_id', 0);
5640 $uid = $user_info['uid'];
5642 // error if no gid specified
5644 throw new BadRequestException('gid not specified');
5647 // get data of the specified group id
5648 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5649 // error message if specified gid is not in database
5651 throw new BadRequestException('gid not available');
5654 if (Group::remove($gid)) {
5656 'name' => $group['name'],
5657 'id' => intval($gid),
5658 'id_str' => (string) $gid,
5659 'user' => $user_info
5662 return api_format_data("lists", $type, ['lists' => $list]);
5665 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5668 * Add a new group to the database.
5670 * @param string $name Group name
5671 * @param int $uid User ID
5672 * @param array $users List of users to add to the group
5675 * @throws BadRequestException
5677 function group_create($name, $uid, $users = [])
5679 // error if no name specified
5681 throw new BadRequestException('group name not specified');
5684 // get data of the specified group name
5686 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5690 // error message if specified group name already exists
5691 if (DBA::isResult($rname)) {
5692 throw new BadRequestException('group name already exists');
5695 // check if specified group name is a deleted group
5697 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5701 // error message if specified group name already exists
5702 if (DBA::isResult($rname)) {
5703 $reactivate_group = true;
5707 $ret = Group::create($uid, $name);
5709 $gid = Group::getIdByName($uid, $name);
5711 throw new BadRequestException('other API error');
5715 $erroraddinguser = false;
5717 foreach ($users as $user) {
5718 $cid = $user['cid'];
5719 // check if user really exists as contact
5721 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5725 if (count($contact)) {
5726 Group::addMember($gid, $cid);
5728 $erroraddinguser = true;
5729 $errorusers[] = $cid;
5733 // return success message incl. missing users in array
5734 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5736 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5740 * Create the specified group with the posted array of contacts.
5742 * @param string $type Return type (atom, rss, xml, json)
5744 * @return array|string
5745 * @throws BadRequestException
5746 * @throws ForbiddenException
5747 * @throws ImagickException
5748 * @throws InternalServerErrorException
5749 * @throws UnauthorizedException
5751 function api_friendica_group_create($type)
5755 if (api_user() === false) {
5756 throw new ForbiddenException();
5760 $user_info = api_get_user($a);
5761 $name = defaults($_REQUEST, 'name', "");
5762 $uid = $user_info['uid'];
5763 $json = json_decode($_POST['json'], true);
5764 $users = $json['user'];
5766 $success = group_create($name, $uid, $users);
5768 return api_format_data("group_create", $type, ['result' => $success]);
5770 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5773 * Create a new group.
5775 * @param string $type Return type (atom, rss, xml, json)
5777 * @return array|string
5778 * @throws BadRequestException
5779 * @throws ForbiddenException
5780 * @throws ImagickException
5781 * @throws InternalServerErrorException
5782 * @throws UnauthorizedException
5783 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5785 function api_lists_create($type)
5789 if (api_user() === false) {
5790 throw new ForbiddenException();
5794 $user_info = api_get_user($a);
5795 $name = defaults($_REQUEST, 'name', "");
5796 $uid = $user_info['uid'];
5798 $success = group_create($name, $uid);
5799 if ($success['success']) {
5801 'name' => $success['name'],
5802 'id' => intval($success['gid']),
5803 'id_str' => (string) $success['gid'],
5804 'user' => $user_info
5807 return api_format_data("lists", $type, ['lists'=>$grp]);
5810 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5813 * Update the specified group with the posted array of contacts.
5815 * @param string $type Return type (atom, rss, xml, json)
5817 * @return array|string
5818 * @throws BadRequestException
5819 * @throws ForbiddenException
5820 * @throws ImagickException
5821 * @throws InternalServerErrorException
5822 * @throws UnauthorizedException
5824 function api_friendica_group_update($type)
5828 if (api_user() === false) {
5829 throw new ForbiddenException();
5833 $user_info = api_get_user($a);
5834 $uid = $user_info['uid'];
5835 $gid = defaults($_REQUEST, 'gid', 0);
5836 $name = defaults($_REQUEST, 'name', "");
5837 $json = json_decode($_POST['json'], true);
5838 $users = $json['user'];
5840 // error if no name specified
5842 throw new BadRequestException('group name not specified');
5845 // error if no gid specified
5847 throw new BadRequestException('gid not specified');
5851 $members = Contact::getByGroupId($gid);
5852 foreach ($members as $member) {
5853 $cid = $member['id'];
5854 foreach ($users as $user) {
5855 $found = ($user['cid'] == $cid ? true : false);
5857 if (!isset($found) || !$found) {
5858 Group::removeMemberByName($uid, $name, $cid);
5863 $erroraddinguser = false;
5865 foreach ($users as $user) {
5866 $cid = $user['cid'];
5867 // check if user really exists as contact
5869 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5874 if (count($contact)) {
5875 Group::addMember($gid, $cid);
5877 $erroraddinguser = true;
5878 $errorusers[] = $cid;
5882 // return success message incl. missing users in array
5883 $status = ($erroraddinguser ? "missing user" : "ok");
5884 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5885 return api_format_data("group_update", $type, ['result' => $success]);
5888 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5891 * Update information about a group.
5893 * @param string $type Return type (atom, rss, xml, json)
5895 * @return array|string
5896 * @throws BadRequestException
5897 * @throws ForbiddenException
5898 * @throws ImagickException
5899 * @throws InternalServerErrorException
5900 * @throws UnauthorizedException
5901 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5903 function api_lists_update($type)
5907 if (api_user() === false) {
5908 throw new ForbiddenException();
5912 $user_info = api_get_user($a);
5913 $gid = defaults($_REQUEST, 'list_id', 0);
5914 $name = defaults($_REQUEST, 'name', "");
5915 $uid = $user_info['uid'];
5917 // error if no gid specified
5919 throw new BadRequestException('gid not specified');
5922 // get data of the specified group id
5923 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5924 // error message if specified gid is not in database
5926 throw new BadRequestException('gid not available');
5929 if (Group::update($gid, $name)) {
5932 'id' => intval($gid),
5933 'id_str' => (string) $gid,
5934 'user' => $user_info
5937 return api_format_data("lists", $type, ['lists' => $list]);
5941 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5945 * @param string $type Return type (atom, rss, xml, json)
5947 * @return array|string
5948 * @throws BadRequestException
5949 * @throws ForbiddenException
5950 * @throws ImagickException
5951 * @throws InternalServerErrorException
5953 function api_friendica_activity($type)
5957 if (api_user() === false) {
5958 throw new ForbiddenException();
5960 $verb = strtolower($a->argv[3]);
5961 $verb = preg_replace("|\..*$|", "", $verb);
5963 $id = defaults($_REQUEST, 'id', 0);
5965 $res = Item::performLike($id, $verb);
5968 if ($type == "xml") {
5973 return api_format_data('ok', $type, ['ok' => $ok]);
5975 throw new BadRequestException('Error adding activity');
5979 /// @TODO move to top of file or somewhere better
5980 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5981 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5982 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5983 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5984 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5985 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5986 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5987 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5988 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5989 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5992 * @brief Returns notifications
5994 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5995 * @return string|array
5996 * @throws BadRequestException
5997 * @throws ForbiddenException
5998 * @throws InternalServerErrorException
6000 function api_friendica_notification($type)
6004 if (api_user() === false) {
6005 throw new ForbiddenException();
6008 throw new BadRequestException("Invalid argument count");
6010 $nm = new NotificationsManager();
6012 $notes = $nm->getAll([], "+seen -date", 50);
6014 if ($type == "xml") {
6016 if (!empty($notes)) {
6017 foreach ($notes as $note) {
6018 $xmlnotes[] = ["@attributes" => $note];
6024 return api_format_data("notes", $type, ['note' => $notes]);
6028 * POST request with 'id' param as notification id
6030 * @brief Set notification as seen and returns associated item (if possible)
6032 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6033 * @return string|array
6034 * @throws BadRequestException
6035 * @throws ForbiddenException
6036 * @throws ImagickException
6037 * @throws InternalServerErrorException
6038 * @throws UnauthorizedException
6040 function api_friendica_notification_seen($type)
6043 $user_info = api_get_user($a);
6045 if (api_user() === false || $user_info === false) {
6046 throw new ForbiddenException();
6049 throw new BadRequestException("Invalid argument count");
6052 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
6054 $nm = new NotificationsManager();
6055 $note = $nm->getByID($id);
6056 if (is_null($note)) {
6057 throw new BadRequestException("Invalid argument");
6060 $nm->setSeen($note);
6061 if ($note['otype']=='item') {
6062 // would be really better with an ItemsManager and $im->getByID() :-P
6063 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6064 if (DBA::isResult($item)) {
6065 // we found the item, return it to the user
6066 $ret = api_format_items([$item], $user_info, false, $type);
6067 $data = ['status' => $ret];
6068 return api_format_data("status", $type, $data);
6070 // the item can't be found, but we set the note as seen, so we count this as a success
6072 return api_format_data('result', $type, ['result' => "success"]);
6075 /// @TODO move to top of file or somewhere better
6076 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6077 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6080 * @brief update a direct_message to seen state
6082 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6083 * @return string|array (success result=ok, error result=error with error message)
6084 * @throws BadRequestException
6085 * @throws ForbiddenException
6086 * @throws ImagickException
6087 * @throws InternalServerErrorException
6088 * @throws UnauthorizedException
6090 function api_friendica_direct_messages_setseen($type)
6093 if (api_user() === false) {
6094 throw new ForbiddenException();
6098 $user_info = api_get_user($a);
6099 $uid = $user_info['uid'];
6100 $id = defaults($_REQUEST, 'id', 0);
6102 // return error if id is zero
6104 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6105 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6108 // error message if specified id is not in database
6109 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6110 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6111 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6114 // update seen indicator
6115 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6119 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6120 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6122 $answer = ['result' => 'error', 'message' => 'unknown error'];
6123 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6127 /// @TODO move to top of file or somewhere better
6128 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6131 * @brief search for direct_messages containing a searchstring through api
6133 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6134 * @param string $box
6135 * @return string|array (success: success=true if found and search_result contains found messages,
6136 * success=false if nothing was found, search_result='nothing found',
6137 * error: result=error with error message)
6138 * @throws BadRequestException
6139 * @throws ForbiddenException
6140 * @throws ImagickException
6141 * @throws InternalServerErrorException
6142 * @throws UnauthorizedException
6144 function api_friendica_direct_messages_search($type, $box = "")
6148 if (api_user() === false) {
6149 throw new ForbiddenException();
6153 $user_info = api_get_user($a);
6154 $searchstring = defaults($_REQUEST, 'searchstring', "");
6155 $uid = $user_info['uid'];
6157 // error if no searchstring specified
6158 if ($searchstring == "") {
6159 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6160 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6163 // get data for the specified searchstring
6165 "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",
6167 DBA::escape('%'.$searchstring.'%')
6170 $profile_url = $user_info["url"];
6172 // message if nothing was found
6173 if (!DBA::isResult($r)) {
6174 $success = ['success' => false, 'search_results' => 'problem with query'];
6175 } elseif (count($r) == 0) {
6176 $success = ['success' => false, 'search_results' => 'nothing found'];
6179 foreach ($r as $item) {
6180 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6181 $recipient = $user_info;
6182 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6183 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6184 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6185 $sender = $user_info;
6188 if (isset($recipient) && isset($sender)) {
6189 $ret[] = api_format_messages($item, $recipient, $sender);
6192 $success = ['success' => true, 'search_results' => $ret];
6195 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6198 /// @TODO move to top of file or somewhere better
6199 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6202 * @brief return data of all the profiles a user has to the client
6204 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6205 * @return string|array
6206 * @throws BadRequestException
6207 * @throws ForbiddenException
6208 * @throws ImagickException
6209 * @throws InternalServerErrorException
6210 * @throws UnauthorizedException
6212 function api_friendica_profile_show($type)
6216 if (api_user() === false) {
6217 throw new ForbiddenException();
6221 $profile_id = defaults($_REQUEST, 'profile_id', 0);
6223 // retrieve general information about profiles for user
6224 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6225 $directory = Config::get('system', 'directory');
6227 // get data of the specified profile id or all profiles of the user if not specified
6228 if ($profile_id != 0) {
6230 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
6235 // error message if specified gid is not in database
6236 if (!DBA::isResult($r)) {
6237 throw new BadRequestException("profile_id not available");
6241 "SELECT * FROM `profile` WHERE `uid` = %d",
6245 // loop through all returned profiles and retrieve data and users
6248 foreach ($r as $rr) {
6249 $profile = api_format_items_profiles($rr);
6251 // select all users from contact table, loop and prepare standard return for user data
6254 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
6259 foreach ($nurls as $nurl) {
6260 $user = api_get_user($a, $nurl['nurl']);
6261 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6263 $profile['users'] = $users;
6265 // add prepared profile data to array for final return
6266 if ($type == "xml") {
6267 $profiles[$k++ . ":profile"] = $profile;
6269 $profiles[] = $profile;
6273 // return settings, authenticated user and profiles data
6274 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6276 $result = ['multi_profiles' => $multi_profiles ? true : false,
6277 'global_dir' => $directory,
6278 'friendica_owner' => api_get_user($a, $self['nurl']),
6279 'profiles' => $profiles];
6280 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6282 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6285 * Returns a list of saved searches.
6287 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6289 * @param string $type Return format: json or xml
6291 * @return string|array
6294 function api_saved_searches_list($type)
6296 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6299 while ($term = $terms->fetch()) {
6301 'created_at' => api_date(time()),
6302 'id' => intval($term['id']),
6303 'id_str' => $term['id'],
6304 'name' => $term['term'],
6306 'query' => $term['term']
6312 return api_format_data("terms", $type, ['terms' => $result]);
6315 /// @TODO move to top of file or somewhere better
6316 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6319 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6321 * @brief Number of comments
6323 * @param object $data [Status, Status]
6327 function bindComments(&$data)
6329 if (count($data) == 0) {
6335 foreach ($data as $item) {
6336 $ids[] = $item['id'];
6339 $idStr = DBA::escape(implode(', ', $ids));
6340 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6341 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6342 $itemsData = DBA::toArray($items);
6344 foreach ($itemsData as $item) {
6345 $comments[$item['parent']] = $item['comments'];
6348 foreach ($data as $idx => $item) {
6350 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6355 @TODO Maybe open to implement?
6357 [pagename] => api/1.1/statuses/lookup.json
6358 [id] => 605138389168451584
6359 [include_cards] => true
6360 [cards_platform] => Android-12
6361 [include_entities] => true
6362 [include_my_retweet] => 1
6364 [include_reply_count] => true
6365 [include_descendent_reply_count] => true
6369 Not implemented by now:
6370 statuses/retweets_of_me
6375 account/update_location
6376 account/update_profile_background_image
6379 friendica/profile/update
6380 friendica/profile/create
6381 friendica/profile/delete
6383 Not implemented in status.net:
6384 statuses/retweeted_to_me
6385 statuses/retweeted_by_me
6386 direct_messages/destroy
6388 account/update_delivery_device
6389 notifications/follow