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 ($type == "raw") {
1324 $privacy_sql = "AND NOT `private`";
1329 if (!empty($item_id)) {
1330 // Get the item with the given id
1331 $condition = ['id' => $item_id];
1333 // get last public wall message
1334 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1335 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1337 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1339 if (DBA::isResult($lastwall)) {
1340 $in_reply_to = api_in_reply_to($lastwall);
1342 $converted = api_convert_item($lastwall);
1344 if ($type == "xml") {
1345 $geo = "georss:point";
1351 'created_at' => api_date($lastwall['created']),
1352 'id' => intval($lastwall['id']),
1353 'id_str' => (string) $lastwall['id'],
1354 'text' => $converted["text"],
1355 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1356 'truncated' => false,
1357 'in_reply_to_status_id' => $in_reply_to['status_id'],
1358 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1359 'in_reply_to_user_id' => $in_reply_to['user_id'],
1360 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1361 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1362 'user' => $user_info,
1364 'coordinates' => '',
1366 'contributors' => '',
1367 'is_quote_status' => false,
1368 'retweet_count' => 0,
1369 'favorite_count' => 0,
1370 'favorited' => $lastwall['starred'] ? true : false,
1371 'retweeted' => false,
1372 'possibly_sensitive' => false,
1374 'statusnet_html' => $converted["html"],
1375 'statusnet_conversation_id' => $lastwall['parent'],
1376 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
1379 if (count($converted["attachments"]) > 0) {
1380 $status_info["attachments"] = $converted["attachments"];
1383 if (count($converted["entities"]) > 0) {
1384 $status_info["entities"] = $converted["entities"];
1387 if ($status_info["source"] == 'web') {
1388 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1389 } elseif (ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) != $status_info["source"]) {
1390 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']).')');
1393 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1394 unset($status_info["user"]["uid"]);
1395 unset($status_info["user"]["self"]);
1397 Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
1399 if ($type == "raw") {
1400 return $status_info;
1403 return api_format_data("statuses", $type, ['status' => $status_info]);
1408 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1409 * The author's most recent status will be returned inline.
1411 * @param string $type Return type (atom, rss, xml, json)
1412 * @return array|string
1413 * @throws BadRequestException
1414 * @throws ImagickException
1415 * @throws InternalServerErrorException
1416 * @throws UnauthorizedException
1417 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1419 function api_users_show($type)
1423 $user_info = api_get_user($a);
1425 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1426 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1427 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1429 if (DBA::isResult($lastwall)) {
1430 $in_reply_to = api_in_reply_to($lastwall);
1432 $converted = api_convert_item($lastwall);
1434 if ($type == "xml") {
1435 $geo = "georss:point";
1440 $user_info['status'] = [
1441 'text' => $converted["text"],
1442 'truncated' => false,
1443 'created_at' => api_date($lastwall['created']),
1444 'in_reply_to_status_id' => $in_reply_to['status_id'],
1445 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1446 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1447 'id' => intval($lastwall['contact-id']),
1448 'id_str' => (string) $lastwall['contact-id'],
1449 'in_reply_to_user_id' => $in_reply_to['user_id'],
1450 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1451 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1453 'favorited' => $lastwall['starred'] ? true : false,
1454 'statusnet_html' => $converted["html"],
1455 'statusnet_conversation_id' => $lastwall['parent'],
1456 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1459 if (count($converted["attachments"]) > 0) {
1460 $user_info["status"]["attachments"] = $converted["attachments"];
1463 if (count($converted["entities"]) > 0) {
1464 $user_info["status"]["entities"] = $converted["entities"];
1467 if ($user_info["status"]["source"] == 'web') {
1468 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1471 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1472 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) . ')');
1476 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1477 unset($user_info["uid"]);
1478 unset($user_info["self"]);
1480 return api_format_data("user", $type, ['user' => $user_info]);
1483 /// @TODO move to top of file or somewhere better
1484 api_register_func('api/users/show', 'api_users_show');
1485 api_register_func('api/externalprofile/show', 'api_users_show');
1488 * Search a public user account.
1490 * @param string $type Return type (atom, rss, xml, json)
1492 * @return array|string
1493 * @throws BadRequestException
1494 * @throws ImagickException
1495 * @throws InternalServerErrorException
1496 * @throws UnauthorizedException
1497 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1499 function api_users_search($type)
1505 if (!empty($_GET['q'])) {
1506 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1508 if (!DBA::isResult($r)) {
1509 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1512 if (DBA::isResult($r)) {
1514 foreach ($r as $user) {
1515 $user_info = api_get_user($a, $user["id"]);
1517 if ($type == "xml") {
1518 $userlist[$k++.":user"] = $user_info;
1520 $userlist[] = $user_info;
1523 $userlist = ["users" => $userlist];
1525 throw new BadRequestException("User ".$_GET["q"]." not found.");
1528 throw new BadRequestException("No user specified.");
1531 return api_format_data("users", $type, $userlist);
1534 /// @TODO move to top of file or somewhere better
1535 api_register_func('api/users/search', 'api_users_search');
1538 * Return user objects
1540 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1542 * @param string $type Return format: json or xml
1544 * @return array|string
1545 * @throws BadRequestException
1546 * @throws ImagickException
1547 * @throws InternalServerErrorException
1548 * @throws NotFoundException if the results are empty.
1549 * @throws UnauthorizedException
1551 function api_users_lookup($type)
1555 if (!empty($_REQUEST['user_id'])) {
1556 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1558 $users[] = api_get_user(get_app(), $id);
1563 if (empty($users)) {
1564 throw new NotFoundException;
1567 return api_format_data("users", $type, ['users' => $users]);
1570 /// @TODO move to top of file or somewhere better
1571 api_register_func('api/users/lookup', 'api_users_lookup', true);
1574 * Returns statuses that match a specified query.
1576 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1578 * @param string $type Return format: json, xml, atom, rss
1580 * @return array|string
1581 * @throws BadRequestException if the "q" parameter is missing.
1582 * @throws ForbiddenException
1583 * @throws ImagickException
1584 * @throws InternalServerErrorException
1585 * @throws UnauthorizedException
1587 function api_search($type)
1590 $user_info = api_get_user($a);
1592 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1594 if (empty($_REQUEST['q'])) { throw new BadRequestException('q parameter is required.'); }
1596 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1599 $data['status'] = [];
1601 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1602 if (!empty($_REQUEST['rpp'])) {
1603 $count = $_REQUEST['rpp'];
1604 } elseif (!empty($_REQUEST['count'])) {
1605 $count = $_REQUEST['count'];
1608 $since_id = defaults($_REQUEST, 'since_id', 0);
1609 $max_id = defaults($_REQUEST, 'max_id', 0);
1610 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1611 $start = $page * $count;
1612 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1613 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1614 $searchTerm = $matches[1];
1615 $condition = ["`oid` > ?
1616 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1617 AND `otype` = ? AND `type` = ? AND `term` = ?",
1618 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1620 $condition[0] .= ' AND `oid` <= ?';
1621 $condition[] = $max_id;
1623 $terms = DBA::select('term', ['oid'], $condition, []);
1625 while ($term = DBA::fetch($terms)) {
1626 $itemIds[] = $term['oid'];
1630 if (empty($itemIds)) {
1631 return api_format_data('statuses', $type, $data);
1634 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1635 if ($exclude_replies) {
1636 $preCondition[] = '`id` = `parent`';
1639 $condition = [implode(' AND ', $preCondition)];
1641 $condition = ["`id` > ?
1642 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1643 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1644 AND `body` LIKE CONCAT('%',?,'%')",
1645 $since_id, api_user(), $_REQUEST['q']];
1647 $condition[0] .= ' AND `id` <= ?';
1648 $condition[] = $max_id;
1652 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1654 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1656 bindComments($data['status']);
1658 return api_format_data('statuses', $type, $data);
1661 /// @TODO move to top of file or somewhere better
1662 api_register_func('api/search/tweets', 'api_search', true);
1663 api_register_func('api/search', 'api_search', true);
1666 * Returns the most recent statuses posted by the user and the users they follow.
1668 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1670 * @param string $type Return type (atom, rss, xml, json)
1672 * @return array|string
1673 * @throws BadRequestException
1674 * @throws ForbiddenException
1675 * @throws ImagickException
1676 * @throws InternalServerErrorException
1677 * @throws UnauthorizedException
1678 * @todo Optional parameters
1679 * @todo Add reply info
1681 function api_statuses_home_timeline($type)
1684 $user_info = api_get_user($a);
1686 if (api_user() === false || $user_info === false) {
1687 throw new ForbiddenException();
1690 unset($_REQUEST["user_id"]);
1691 unset($_GET["user_id"]);
1693 unset($_REQUEST["screen_name"]);
1694 unset($_GET["screen_name"]);
1696 // get last network messages
1699 $count = defaults($_REQUEST, 'count', 20);
1700 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1704 $since_id = defaults($_REQUEST, 'since_id', 0);
1705 $max_id = defaults($_REQUEST, 'max_id', 0);
1706 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1707 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1709 $start = $page * $count;
1711 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1712 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1715 $condition[0] .= " AND `item`.`id` <= ?";
1716 $condition[] = $max_id;
1718 if ($exclude_replies) {
1719 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1721 if ($conversation_id > 0) {
1722 $condition[0] .= " AND `item`.`parent` = ?";
1723 $condition[] = $conversation_id;
1726 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1727 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1729 $items = Item::inArray($statuses);
1731 $ret = api_format_items($items, $user_info, false, $type);
1733 // Set all posts from the query above to seen
1735 foreach ($items as $item) {
1736 $idarray[] = intval($item["id"]);
1739 if (!empty($idarray)) {
1740 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1742 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1748 $data = ['status' => $ret];
1753 $data = api_rss_extra($a, $data, $user_info);
1757 return api_format_data("statuses", $type, $data);
1761 /// @TODO move to top of file or somewhere better
1762 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1763 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1766 * Returns the most recent statuses from public users.
1768 * @param string $type Return type (atom, rss, xml, json)
1770 * @return array|string
1771 * @throws BadRequestException
1772 * @throws ForbiddenException
1773 * @throws ImagickException
1774 * @throws InternalServerErrorException
1775 * @throws UnauthorizedException
1777 function api_statuses_public_timeline($type)
1780 $user_info = api_get_user($a);
1782 if (api_user() === false || $user_info === false) {
1783 throw new ForbiddenException();
1786 // get last network messages
1789 $count = defaults($_REQUEST, 'count', 20);
1790 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1794 $since_id = defaults($_REQUEST, 'since_id', 0);
1795 $max_id = defaults($_REQUEST, 'max_id', 0);
1796 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1797 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1799 $start = $page * $count;
1801 if ($exclude_replies && !$conversation_id) {
1802 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1803 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1806 $condition[0] .= " AND `thread`.`iid` <= ?";
1807 $condition[] = $max_id;
1810 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1811 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1813 $r = Item::inArray($statuses);
1815 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1816 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1819 $condition[0] .= " AND `item`.`id` <= ?";
1820 $condition[] = $max_id;
1822 if ($conversation_id > 0) {
1823 $condition[0] .= " AND `item`.`parent` = ?";
1824 $condition[] = $conversation_id;
1827 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1828 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1830 $r = Item::inArray($statuses);
1833 $ret = api_format_items($r, $user_info, false, $type);
1837 $data = ['status' => $ret];
1842 $data = api_rss_extra($a, $data, $user_info);
1846 return api_format_data("statuses", $type, $data);
1849 /// @TODO move to top of file or somewhere better
1850 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1853 * Returns the most recent statuses posted by users this node knows about.
1855 * @brief Returns the list of public federated posts this node knows about
1857 * @param string $type Return format: json, xml, atom, rss
1858 * @return array|string
1859 * @throws BadRequestException
1860 * @throws ForbiddenException
1861 * @throws ImagickException
1862 * @throws InternalServerErrorException
1863 * @throws UnauthorizedException
1865 function api_statuses_networkpublic_timeline($type)
1868 $user_info = api_get_user($a);
1870 if (api_user() === false || $user_info === false) {
1871 throw new ForbiddenException();
1874 $since_id = defaults($_REQUEST, 'since_id', 0);
1875 $max_id = defaults($_REQUEST, 'max_id', 0);
1878 $count = defaults($_REQUEST, 'count', 20);
1879 $page = defaults($_REQUEST, 'page', 1);
1883 $start = ($page - 1) * $count;
1885 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1886 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1889 $condition[0] .= " AND `thread`.`iid` <= ?";
1890 $condition[] = $max_id;
1893 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1894 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1896 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1900 $data = ['status' => $ret];
1905 $data = api_rss_extra($a, $data, $user_info);
1909 return api_format_data("statuses", $type, $data);
1912 /// @TODO move to top of file or somewhere better
1913 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1916 * Returns a single status.
1918 * @param string $type Return type (atom, rss, xml, json)
1920 * @return array|string
1921 * @throws BadRequestException
1922 * @throws ForbiddenException
1923 * @throws ImagickException
1924 * @throws InternalServerErrorException
1925 * @throws UnauthorizedException
1926 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1928 function api_statuses_show($type)
1931 $user_info = api_get_user($a);
1933 if (api_user() === false || $user_info === false) {
1934 throw new ForbiddenException();
1938 $id = intval(defaults($a->argv, 3, 0));
1941 $id = intval(defaults($_REQUEST, 'id', 0));
1946 $id = intval(defaults($a->argv, 4, 0));
1949 Logger::log('API: api_statuses_show: ' . $id);
1951 $conversation = !empty($_REQUEST['conversation']);
1953 // try to fetch the item for the local user - or the public item, if there is no local one
1954 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1955 if (!DBA::isResult($uri_item)) {
1956 throw new BadRequestException("There is no status with this id.");
1959 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1960 if (!DBA::isResult($item)) {
1961 throw new BadRequestException("There is no status with this id.");
1966 if ($conversation) {
1967 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1968 $params = ['order' => ['id' => true]];
1970 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1974 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1976 /// @TODO How about copying this to above methods which don't check $r ?
1977 if (!DBA::isResult($statuses)) {
1978 throw new BadRequestException("There is no status with this id.");
1981 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1983 if ($conversation) {
1984 $data = ['status' => $ret];
1985 return api_format_data("statuses", $type, $data);
1987 $data = ['status' => $ret[0]];
1988 return api_format_data("status", $type, $data);
1992 /// @TODO move to top of file or somewhere better
1993 api_register_func('api/statuses/show', 'api_statuses_show', true);
1997 * @param string $type Return type (atom, rss, xml, json)
1999 * @return array|string
2000 * @throws BadRequestException
2001 * @throws ForbiddenException
2002 * @throws ImagickException
2003 * @throws InternalServerErrorException
2004 * @throws UnauthorizedException
2005 * @todo nothing to say?
2007 function api_conversation_show($type)
2010 $user_info = api_get_user($a);
2012 if (api_user() === false || $user_info === false) {
2013 throw new ForbiddenException();
2017 $id = intval(defaults($a->argv , 3 , 0));
2018 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
2019 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
2020 $count = intval(defaults($_REQUEST, 'count' , 20));
2021 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
2026 $start = $page * $count;
2029 $id = intval(defaults($_REQUEST, 'id', 0));
2034 $id = intval(defaults($a->argv, 4, 0));
2037 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
2039 // try to fetch the item for the local user - or the public item, if there is no local one
2040 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
2041 if (!DBA::isResult($item)) {
2042 throw new BadRequestException("There is no status with this id.");
2045 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
2046 if (!DBA::isResult($parent)) {
2047 throw new BadRequestException("There is no status with this id.");
2050 $id = $parent['id'];
2052 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
2053 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2056 $condition[0] .= " AND `item`.`id` <= ?";
2057 $condition[] = $max_id;
2060 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2061 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2063 if (!DBA::isResult($statuses)) {
2064 throw new BadRequestException("There is no status with id $id.");
2067 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2069 $data = ['status' => $ret];
2070 return api_format_data("statuses", $type, $data);
2073 /// @TODO move to top of file or somewhere better
2074 api_register_func('api/conversation/show', 'api_conversation_show', true);
2075 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2080 * @param string $type Return type (atom, rss, xml, json)
2082 * @return array|string
2083 * @throws BadRequestException
2084 * @throws ForbiddenException
2085 * @throws ImagickException
2086 * @throws InternalServerErrorException
2087 * @throws UnauthorizedException
2088 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2090 function api_statuses_repeat($type)
2096 if (api_user() === false) {
2097 throw new ForbiddenException();
2103 $id = intval(defaults($a->argv, 3, 0));
2106 $id = intval(defaults($_REQUEST, 'id', 0));
2111 $id = intval(defaults($a->argv, 4, 0));
2114 Logger::log('API: api_statuses_repeat: '.$id);
2116 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2117 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2119 if (DBA::isResult($item) && $item['body'] != "") {
2120 if (strpos($item['body'], "[/share]") !== false) {
2121 $pos = strpos($item['body'], "[share");
2122 $post = substr($item['body'], $pos);
2124 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2126 $post .= $item['body'];
2127 $post .= "[/share]";
2129 $_REQUEST['body'] = $post;
2130 $_REQUEST['profile_uid'] = api_user();
2131 $_REQUEST['api_source'] = true;
2133 if (empty($_REQUEST['source'])) {
2134 $_REQUEST["source"] = api_source();
2137 $item_id = item_post($a);
2139 throw new ForbiddenException();
2142 // output the post that we just posted.
2144 return api_status_show($type, $item_id);
2147 /// @TODO move to top of file or somewhere better
2148 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2151 * Destroys a specific status.
2153 * @param string $type Return type (atom, rss, xml, json)
2155 * @return array|string
2156 * @throws BadRequestException
2157 * @throws ForbiddenException
2158 * @throws ImagickException
2159 * @throws InternalServerErrorException
2160 * @throws UnauthorizedException
2161 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2163 function api_statuses_destroy($type)
2167 if (api_user() === false) {
2168 throw new ForbiddenException();
2174 $id = intval(defaults($a->argv, 3, 0));
2177 $id = intval(defaults($_REQUEST, 'id', 0));
2182 $id = intval(defaults($a->argv, 4, 0));
2185 Logger::log('API: api_statuses_destroy: '.$id);
2187 $ret = api_statuses_show($type);
2189 Item::deleteForUser(['id' => $id], api_user());
2194 /// @TODO move to top of file or somewhere better
2195 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2198 * Returns the most recent mentions.
2200 * @param string $type Return type (atom, rss, xml, json)
2202 * @return array|string
2203 * @throws BadRequestException
2204 * @throws ForbiddenException
2205 * @throws ImagickException
2206 * @throws InternalServerErrorException
2207 * @throws UnauthorizedException
2208 * @see http://developer.twitter.com/doc/get/statuses/mentions
2210 function api_statuses_mentions($type)
2213 $user_info = api_get_user($a);
2215 if (api_user() === false || $user_info === false) {
2216 throw new ForbiddenException();
2219 unset($_REQUEST["user_id"]);
2220 unset($_GET["user_id"]);
2222 unset($_REQUEST["screen_name"]);
2223 unset($_GET["screen_name"]);
2225 // get last network messages
2228 $since_id = defaults($_REQUEST, 'since_id', 0);
2229 $max_id = defaults($_REQUEST, 'max_id' , 0);
2230 $count = defaults($_REQUEST, 'count' , 20);
2231 $page = defaults($_REQUEST, 'page' , 1);
2236 $start = ($page - 1) * $count;
2238 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2239 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2240 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2243 $condition[0] .= " AND `item`.`id` <= ?";
2244 $condition[] = $max_id;
2247 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2248 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2250 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2252 $data = ['status' => $ret];
2257 $data = api_rss_extra($a, $data, $user_info);
2261 return api_format_data("statuses", $type, $data);
2264 /// @TODO move to top of file or somewhere better
2265 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2266 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2269 * Returns the most recent statuses posted by the user.
2271 * @brief Returns a user's public timeline
2273 * @param string $type Either "json" or "xml"
2274 * @return string|array
2275 * @throws BadRequestException
2276 * @throws ForbiddenException
2277 * @throws ImagickException
2278 * @throws InternalServerErrorException
2279 * @throws UnauthorizedException
2280 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2282 function api_statuses_user_timeline($type)
2285 $user_info = api_get_user($a);
2287 if (api_user() === false || $user_info === false) {
2288 throw new ForbiddenException();
2292 "api_statuses_user_timeline: api_user: ". api_user() .
2293 "\nuser_info: ".print_r($user_info, true) .
2294 "\n_REQUEST: ".print_r($_REQUEST, true),
2298 $since_id = defaults($_REQUEST, 'since_id', 0);
2299 $max_id = defaults($_REQUEST, 'max_id', 0);
2300 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2301 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2304 $count = defaults($_REQUEST, 'count', 20);
2305 $page = defaults($_REQUEST, 'page', 1);
2309 $start = ($page - 1) * $count;
2311 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2312 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2314 if ($user_info['self'] == 1) {
2315 $condition[0] .= ' AND `item`.`wall` ';
2318 if ($exclude_replies) {
2319 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2322 if ($conversation_id > 0) {
2323 $condition[0] .= " AND `item`.`parent` = ?";
2324 $condition[] = $conversation_id;
2328 $condition[0] .= " AND `item`.`id` <= ?";
2329 $condition[] = $max_id;
2332 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2333 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2335 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2339 $data = ['status' => $ret];
2344 $data = api_rss_extra($a, $data, $user_info);
2348 return api_format_data("statuses", $type, $data);
2351 /// @TODO move to top of file or somewhere better
2352 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2355 * Star/unstar an item.
2356 * param: id : id of the item
2358 * @param string $type Return type (atom, rss, xml, json)
2360 * @return array|string
2361 * @throws BadRequestException
2362 * @throws ForbiddenException
2363 * @throws ImagickException
2364 * @throws InternalServerErrorException
2365 * @throws UnauthorizedException
2366 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2368 function api_favorites_create_destroy($type)
2372 if (api_user() === false) {
2373 throw new ForbiddenException();
2376 // for versioned api.
2377 /// @TODO We need a better global soluton
2378 $action_argv_id = 2;
2379 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2380 $action_argv_id = 3;
2383 if ($a->argc <= $action_argv_id) {
2384 throw new BadRequestException("Invalid request.");
2386 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2387 if ($a->argc == $action_argv_id + 2) {
2388 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2390 $itemid = intval(defaults($_REQUEST, 'id', 0));
2393 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2395 if (!DBA::isResult($item)) {
2396 throw new BadRequestException("Invalid item.");
2401 $item['starred'] = 1;
2404 $item['starred'] = 0;
2407 throw new BadRequestException("Invalid action ".$action);
2410 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2413 throw new InternalServerErrorException("DB error");
2417 $user_info = api_get_user($a);
2418 $rets = api_format_items([$item], $user_info, false, $type);
2421 $data = ['status' => $ret];
2426 $data = api_rss_extra($a, $data, $user_info);
2430 return api_format_data("status", $type, $data);
2433 /// @TODO move to top of file or somewhere better
2434 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2435 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2438 * Returns the most recent favorite statuses.
2440 * @param string $type Return type (atom, rss, xml, json)
2442 * @return string|array
2443 * @throws BadRequestException
2444 * @throws ForbiddenException
2445 * @throws ImagickException
2446 * @throws InternalServerErrorException
2447 * @throws UnauthorizedException
2449 function api_favorites($type)
2454 $user_info = api_get_user($a);
2456 if (api_user() === false || $user_info === false) {
2457 throw new ForbiddenException();
2462 // in friendica starred item are private
2463 // return favorites only for self
2464 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2466 if ($user_info['self'] == 0) {
2470 $since_id = defaults($_REQUEST, 'since_id', 0);
2471 $max_id = defaults($_REQUEST, 'max_id', 0);
2472 $count = defaults($_GET, 'count', 20);
2473 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2478 $start = $page*$count;
2480 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2481 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2483 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2486 $condition[0] .= " AND `item`.`id` <= ?";
2487 $condition[] = $max_id;
2490 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2492 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2497 $data = ['status' => $ret];
2502 $data = api_rss_extra($a, $data, $user_info);
2506 return api_format_data("statuses", $type, $data);
2509 /// @TODO move to top of file or somewhere better
2510 api_register_func('api/favorites', 'api_favorites', true);
2514 * @param array $item
2515 * @param array $recipient
2516 * @param array $sender
2519 * @throws InternalServerErrorException
2521 function api_format_messages($item, $recipient, $sender)
2523 // standard meta information
2525 'id' => $item['id'],
2526 'sender_id' => $sender['id'],
2528 'recipient_id' => $recipient['id'],
2529 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2530 'sender_screen_name' => $sender['screen_name'],
2531 'recipient_screen_name' => $recipient['screen_name'],
2532 'sender' => $sender,
2533 'recipient' => $recipient,
2535 'friendica_seen' => defaults($item, 'seen', 0),
2536 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2539 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2540 if (isset($ret['sender']['uid'])) {
2541 unset($ret['sender']['uid']);
2543 if (isset($ret['sender']['self'])) {
2544 unset($ret['sender']['self']);
2546 if (isset($ret['recipient']['uid'])) {
2547 unset($ret['recipient']['uid']);
2549 if (isset($ret['recipient']['self'])) {
2550 unset($ret['recipient']['self']);
2553 //don't send title to regular StatusNET requests to avoid confusing these apps
2554 if (!empty($_GET['getText'])) {
2555 $ret['title'] = $item['title'];
2556 if ($_GET['getText'] == 'html') {
2557 $ret['text'] = BBCode::convert($item['body'], false);
2558 } elseif ($_GET['getText'] == 'plain') {
2559 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2562 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2564 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2565 unset($ret['sender']);
2566 unset($ret['recipient']);
2574 * @param array $item
2577 * @throws InternalServerErrorException
2579 function api_convert_item($item)
2581 $body = $item['body'];
2582 $attachments = api_get_attachments($body);
2584 // Workaround for ostatus messages where the title is identically to the body
2585 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2586 $statusbody = trim(HTML::toPlaintext($html, 0));
2588 // handle data: images
2589 $statusbody = api_format_items_embeded_images($item, $statusbody);
2591 $statustitle = trim($item['title']);
2593 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2594 $statustext = trim($statusbody);
2596 $statustext = trim($statustitle."\n\n".$statusbody);
2599 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2600 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2603 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2605 // Workaround for clients with limited HTML parser functionality
2606 $search = ["<br>", "<blockquote>", "</blockquote>",
2607 "<h1>", "</h1>", "<h2>", "</h2>",
2608 "<h3>", "</h3>", "<h4>", "</h4>",
2609 "<h5>", "</h5>", "<h6>", "</h6>"];
2610 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2611 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2612 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2613 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2614 $statushtml = str_replace($search, $replace, $statushtml);
2616 if ($item['title'] != "") {
2617 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2621 $oldtext = $statushtml;
2622 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2623 } while ($oldtext != $statushtml);
2625 if (substr($statushtml, 0, 4) == '<br>') {
2626 $statushtml = substr($statushtml, 4);
2629 if (substr($statushtml, 0, -4) == '<br>') {
2630 $statushtml = substr($statushtml, -4);
2633 // feeds without body should contain the link
2634 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2635 $statushtml .= BBCode::convert($item['plink']);
2638 $entities = api_get_entitities($statustext, $body);
2641 "text" => $statustext,
2642 "html" => $statushtml,
2643 "attachments" => $attachments,
2644 "entities" => $entities
2650 * @param string $body
2653 * @throws InternalServerErrorException
2655 function api_get_attachments(&$body)
2658 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2660 $URLSearchString = "^\[\]";
2661 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2669 foreach ($images[1] as $image) {
2670 $imagedata = Image::getInfoFromURL($image);
2673 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2677 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2678 foreach ($images[0] as $orig) {
2679 $body = str_replace($orig, "", $body);
2683 return $attachments;
2688 * @param string $text
2689 * @param string $bbcode
2692 * @throws InternalServerErrorException
2693 * @todo Links at the first character of the post
2695 function api_get_entitities(&$text, $bbcode)
2697 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2699 if ($include_entities != "true") {
2700 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2702 foreach ($images[1] as $image) {
2703 $replace = ProxyUtils::proxifyUrl($image);
2704 $text = str_replace($image, $replace, $text);
2709 $bbcode = BBCode::cleanPictureLinks($bbcode);
2711 // Change pure links in text to bbcode uris
2712 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2715 $entities["hashtags"] = [];
2716 $entities["symbols"] = [];
2717 $entities["urls"] = [];
2718 $entities["user_mentions"] = [];
2720 $URLSearchString = "^\[\]";
2722 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2724 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2725 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2726 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2728 $bbcode = preg_replace(
2729 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2730 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2733 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2735 $bbcode = preg_replace(
2736 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2737 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2740 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2742 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2744 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2745 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2748 foreach ($urls[1] as $id => $url) {
2749 //$start = strpos($text, $url, $offset);
2750 $start = iconv_strpos($text, $url, 0, "UTF-8");
2751 if (!($start === false)) {
2752 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2756 ksort($ordered_urls);
2759 //foreach ($urls[1] AS $id=>$url) {
2760 foreach ($ordered_urls as $url) {
2761 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2762 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2764 $display_url = $url["title"];
2766 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2767 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2769 if (strlen($display_url) > 26) {
2770 $display_url = substr($display_url, 0, 25)."…";
2774 //$start = strpos($text, $url, $offset);
2775 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2776 if (!($start === false)) {
2777 $entities["urls"][] = ["url" => $url["url"],
2778 "expanded_url" => $url["url"],
2779 "display_url" => $display_url,
2780 "indices" => [$start, $start+strlen($url["url"])]];
2781 $offset = $start + 1;
2785 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2786 $ordered_images = [];
2787 foreach ($images[1] as $image) {
2788 //$start = strpos($text, $url, $offset);
2789 $start = iconv_strpos($text, $image, 0, "UTF-8");
2790 if (!($start === false)) {
2791 $ordered_images[$start] = $image;
2794 //$entities["media"] = array();
2797 foreach ($ordered_images as $url) {
2798 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2799 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2801 if (strlen($display_url) > 26) {
2802 $display_url = substr($display_url, 0, 25)."…";
2805 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2806 if (!($start === false)) {
2807 $image = Image::getInfoFromURL($url);
2809 // If image cache is activated, then use the following sizes:
2810 // thumb (150), small (340), medium (600) and large (1024)
2811 if (!Config::get("system", "proxy_disabled")) {
2812 $media_url = ProxyUtils::proxifyUrl($url);
2815 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2816 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2818 if (($image[0] > 150) || ($image[1] > 150)) {
2819 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2820 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2823 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2824 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2826 if (($image[0] > 600) || ($image[1] > 600)) {
2827 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2828 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2832 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2835 $entities["media"][] = [
2837 "id_str" => (string)$start+1,
2838 "indices" => [$start, $start+strlen($url)],
2839 "media_url" => Strings::normaliseLink($media_url),
2840 "media_url_https" => $media_url,
2842 "display_url" => $display_url,
2843 "expanded_url" => $url,
2847 $offset = $start + 1;
2856 * @param array $item
2857 * @param string $text
2861 function api_format_items_embeded_images($item, $text)
2863 $text = preg_replace_callback(
2864 '|data:image/([^;]+)[^=]+=*|m',
2865 function () use ($item) {
2866 return System::baseUrl() . '/display/' . $item['guid'];
2874 * @brief return <a href='url'>name</a> as array
2876 * @param string $txt text
2881 function api_contactlink_to_array($txt)
2884 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2885 if ($r && count($match)==3) {
2887 'name' => $match[2],
2901 * @brief return likes, dislikes and attend status for item
2903 * @param array $item array
2904 * @param string $type Return type (atom, rss, xml, json)
2907 * likes => int count,
2908 * dislikes => int count
2909 * @throws BadRequestException
2910 * @throws ImagickException
2911 * @throws InternalServerErrorException
2912 * @throws UnauthorizedException
2914 function api_format_items_activities($item, $type = "json")
2923 'attendmaybe' => [],
2926 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2927 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2929 while ($parent_item = Item::fetch($ret)) {
2930 // not used as result should be structured like other user data
2931 //builtin_activity_puller($i, $activities);
2933 // get user data and add it to the array of the activity
2934 $user = api_get_user($a, $parent_item['author-id']);
2935 switch ($parent_item['verb']) {
2937 $activities['like'][] = $user;
2939 case ACTIVITY_DISLIKE:
2940 $activities['dislike'][] = $user;
2942 case ACTIVITY_ATTEND:
2943 $activities['attendyes'][] = $user;
2945 case ACTIVITY_ATTENDNO:
2946 $activities['attendno'][] = $user;
2948 case ACTIVITY_ATTENDMAYBE:
2949 $activities['attendmaybe'][] = $user;
2958 if ($type == "xml") {
2959 $xml_activities = [];
2960 foreach ($activities as $k => $v) {
2961 // change xml element from "like" to "friendica:like"
2962 $xml_activities["friendica:".$k] = $v;
2963 // add user data into xml output
2965 foreach ($v as $user) {
2966 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2969 $activities = $xml_activities;
2977 * @brief return data from profiles
2979 * @param array $profile_row array containing data from db table 'profile'
2981 * @throws InternalServerErrorException
2983 function api_format_items_profiles($profile_row)
2986 'profile_id' => $profile_row['id'],
2987 'profile_name' => $profile_row['profile-name'],
2988 'is_default' => $profile_row['is-default'] ? true : false,
2989 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2990 'profile_photo' => $profile_row['photo'],
2991 'profile_thumb' => $profile_row['thumb'],
2992 'publish' => $profile_row['publish'] ? true : false,
2993 'net_publish' => $profile_row['net-publish'] ? true : false,
2994 'description' => $profile_row['pdesc'],
2995 'date_of_birth' => $profile_row['dob'],
2996 'address' => $profile_row['address'],
2997 'city' => $profile_row['locality'],
2998 'region' => $profile_row['region'],
2999 'postal_code' => $profile_row['postal-code'],
3000 'country' => $profile_row['country-name'],
3001 'hometown' => $profile_row['hometown'],
3002 'gender' => $profile_row['gender'],
3003 'marital' => $profile_row['marital'],
3004 'marital_with' => $profile_row['with'],
3005 'marital_since' => $profile_row['howlong'],
3006 'sexual' => $profile_row['sexual'],
3007 'politic' => $profile_row['politic'],
3008 'religion' => $profile_row['religion'],
3009 'public_keywords' => $profile_row['pub_keywords'],
3010 'private_keywords' => $profile_row['prv_keywords'],
3011 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
3012 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
3013 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
3014 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
3015 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
3016 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
3017 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
3018 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
3019 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
3020 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
3021 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
3022 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
3023 'homepage' => $profile_row['homepage'],
3030 * @brief format items to be returned by api
3032 * @param array $r array of items
3033 * @param array $user_info
3034 * @param bool $filter_user filter items by $user_info
3035 * @param string $type Return type (atom, rss, xml, json)
3037 * @throws BadRequestException
3038 * @throws ImagickException
3039 * @throws InternalServerErrorException
3040 * @throws UnauthorizedException
3042 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3048 foreach ((array)$r as $item) {
3049 localize_item($item);
3050 list($status_user, $owner_user) = api_item_get_user($a, $item);
3052 // Look if the posts are matching if they should be filtered by user id
3053 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3057 $in_reply_to = api_in_reply_to($item);
3059 $converted = api_convert_item($item);
3061 if ($type == "xml") {
3062 $geo = "georss:point";
3068 'text' => $converted["text"],
3069 'truncated' => false,
3070 'created_at'=> api_date($item['created']),
3071 'in_reply_to_status_id' => $in_reply_to['status_id'],
3072 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3073 'source' => (($item['app']) ? $item['app'] : 'web'),
3074 'id' => intval($item['id']),
3075 'id_str' => (string) intval($item['id']),
3076 'in_reply_to_user_id' => $in_reply_to['user_id'],
3077 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3078 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3080 'favorited' => $item['starred'] ? true : false,
3081 'user' => $status_user,
3082 'friendica_owner' => $owner_user,
3083 'friendica_private' => $item['private'] == 1,
3084 //'entities' => NULL,
3085 'statusnet_html' => $converted["html"],
3086 'statusnet_conversation_id' => $item['parent'],
3087 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3088 'friendica_activities' => api_format_items_activities($item, $type),
3091 if (count($converted["attachments"]) > 0) {
3092 $status["attachments"] = $converted["attachments"];
3095 if (count($converted["entities"]) > 0) {
3096 $status["entities"] = $converted["entities"];
3099 if ($status["source"] == 'web') {
3100 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3101 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3102 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3105 if ($item["id"] == $item["parent"]) {
3106 $retweeted_item = api_share_as_retweet($item);
3107 if ($retweeted_item !== false) {
3108 $retweeted_status = $status;
3109 $status['user'] = $status['friendica_owner'];
3111 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3112 } catch (BadRequestException $e) {
3113 // user not found. should be found?
3114 /// @todo check if the user should be always found
3115 $retweeted_status["user"] = [];
3118 $rt_converted = api_convert_item($retweeted_item);
3120 $retweeted_status['text'] = $rt_converted["text"];
3121 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3122 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3123 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3124 $status['retweeted_status'] = $retweeted_status;
3128 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3129 unset($status["user"]["uid"]);
3130 unset($status["user"]["self"]);
3132 if ($item["coord"] != "") {
3133 $coords = explode(' ', $item["coord"]);
3134 if (count($coords) == 2) {
3135 if ($type == "json") {
3136 $status["geo"] = ['type' => 'Point',
3137 'coordinates' => [(float) $coords[0],
3138 (float) $coords[1]]];
3139 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3140 $status["georss:point"] = $item["coord"];
3150 * Returns the remaining number of API requests available to the user before the API limit is reached.
3152 * @param string $type Return type (atom, rss, xml, json)
3154 * @return array|string
3157 function api_account_rate_limit_status($type)
3159 if ($type == "xml") {
3161 'remaining-hits' => '150',
3162 '@attributes' => ["type" => "integer"],
3163 'hourly-limit' => '150',
3164 '@attributes2' => ["type" => "integer"],
3165 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3166 '@attributes3' => ["type" => "datetime"],
3167 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3168 '@attributes4' => ["type" => "integer"],
3172 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3173 'remaining_hits' => '150',
3174 'hourly_limit' => '150',
3175 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3179 return api_format_data('hash', $type, ['hash' => $hash]);
3182 /// @TODO move to top of file or somewhere better
3183 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3186 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3188 * @param string $type Return type (atom, rss, xml, json)
3190 * @return array|string
3192 function api_help_test($type)
3194 if ($type == 'xml') {
3200 return api_format_data('ok', $type, ["ok" => $ok]);
3203 /// @TODO move to top of file or somewhere better
3204 api_register_func('api/help/test', 'api_help_test', false);
3207 * Returns all lists the user subscribes to.
3209 * @param string $type Return type (atom, rss, xml, json)
3211 * @return array|string
3212 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3214 function api_lists_list($type)
3217 /// @TODO $ret is not filled here?
3218 return api_format_data('lists', $type, ["lists_list" => $ret]);
3221 /// @TODO move to top of file or somewhere better
3222 api_register_func('api/lists/list', 'api_lists_list', true);
3223 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3226 * Returns all groups the user owns.
3228 * @param string $type Return type (atom, rss, xml, json)
3230 * @return array|string
3231 * @throws BadRequestException
3232 * @throws ForbiddenException
3233 * @throws ImagickException
3234 * @throws InternalServerErrorException
3235 * @throws UnauthorizedException
3236 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3238 function api_lists_ownerships($type)
3242 if (api_user() === false) {
3243 throw new ForbiddenException();
3247 $user_info = api_get_user($a);
3248 $uid = $user_info['uid'];
3250 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3252 // loop through all groups
3254 foreach ($groups as $group) {
3255 if ($group['visible']) {
3261 'name' => $group['name'],
3262 'id' => intval($group['id']),
3263 'id_str' => (string) $group['id'],
3264 'user' => $user_info,
3268 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3271 /// @TODO move to top of file or somewhere better
3272 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3275 * Returns recent statuses from users in the specified group.
3277 * @param string $type Return type (atom, rss, xml, json)
3279 * @return array|string
3280 * @throws BadRequestException
3281 * @throws ForbiddenException
3282 * @throws ImagickException
3283 * @throws InternalServerErrorException
3284 * @throws UnauthorizedException
3285 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3287 function api_lists_statuses($type)
3291 $user_info = api_get_user($a);
3292 if (api_user() === false || $user_info === false) {
3293 throw new ForbiddenException();
3296 unset($_REQUEST["user_id"]);
3297 unset($_GET["user_id"]);
3299 unset($_REQUEST["screen_name"]);
3300 unset($_GET["screen_name"]);
3302 if (empty($_REQUEST['list_id'])) {
3303 throw new BadRequestException('list_id not specified');
3307 $count = defaults($_REQUEST, 'count', 20);
3308 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3312 $since_id = defaults($_REQUEST, 'since_id', 0);
3313 $max_id = defaults($_REQUEST, 'max_id', 0);
3314 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3315 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3317 $start = $page * $count;
3319 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3320 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3323 $condition[0] .= " AND `item`.`id` <= ?";
3324 $condition[] = $max_id;
3326 if ($exclude_replies > 0) {
3327 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3329 if ($conversation_id > 0) {
3330 $condition[0] .= " AND `item`.`parent` = ?";
3331 $condition[] = $conversation_id;
3334 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3335 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3337 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3339 $data = ['status' => $items];
3344 $data = api_rss_extra($a, $data, $user_info);
3348 return api_format_data("statuses", $type, $data);
3351 /// @TODO move to top of file or somewhere better
3352 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3355 * Considers friends and followers lists to be private and won't return
3356 * anything if any user_id parameter is passed.
3358 * @brief Returns either the friends of the follower list
3360 * @param string $qtype Either "friends" or "followers"
3361 * @return boolean|array
3362 * @throws BadRequestException
3363 * @throws ForbiddenException
3364 * @throws ImagickException
3365 * @throws InternalServerErrorException
3366 * @throws UnauthorizedException
3368 function api_statuses_f($qtype)
3372 if (api_user() === false) {
3373 throw new ForbiddenException();
3377 $count = defaults($_GET, 'count', 20);
3378 $page = defaults($_GET, 'page', 1);
3382 $start = ($page - 1) * $count;
3384 $user_info = api_get_user($a);
3386 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3387 /* this is to stop Hotot to load friends multiple times
3388 * I'm not sure if I'm missing return something or
3389 * is a bug in hotot. Workaround, meantime
3393 return array('$users' => $ret);*/
3398 if ($qtype == 'friends') {
3399 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3400 } elseif ($qtype == 'followers') {
3401 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3404 // friends and followers only for self
3405 if ($user_info['self'] == 0) {
3406 $sql_extra = " AND false ";
3409 if ($qtype == 'blocks') {
3410 $sql_filter = 'AND `blocked` AND NOT `pending`';
3411 } elseif ($qtype == 'incoming') {
3412 $sql_filter = 'AND `pending`';
3414 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3432 foreach ($r as $cid) {
3433 $user = api_get_user($a, $cid['nurl']);
3434 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3435 unset($user["uid"]);
3436 unset($user["self"]);
3443 return ['user' => $ret];
3448 * Returns the user's friends.
3450 * @brief Returns the list of friends of the provided user
3452 * @deprecated By Twitter API in favor of friends/list
3454 * @param string $type Either "json" or "xml"
3455 * @return boolean|string|array
3456 * @throws BadRequestException
3457 * @throws ForbiddenException
3459 function api_statuses_friends($type)
3461 $data = api_statuses_f("friends");
3462 if ($data === false) {
3465 return api_format_data("users", $type, $data);
3469 * Returns the user's followers.
3471 * @brief Returns the list of followers of the provided user
3473 * @deprecated By Twitter API in favor of friends/list
3475 * @param string $type Either "json" or "xml"
3476 * @return boolean|string|array
3477 * @throws BadRequestException
3478 * @throws ForbiddenException
3480 function api_statuses_followers($type)
3482 $data = api_statuses_f("followers");
3483 if ($data === false) {
3486 return api_format_data("users", $type, $data);
3489 /// @TODO move to top of file or somewhere better
3490 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3491 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3494 * Returns the list of blocked users
3496 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3498 * @param string $type Either "json" or "xml"
3500 * @return boolean|string|array
3501 * @throws BadRequestException
3502 * @throws ForbiddenException
3504 function api_blocks_list($type)
3506 $data = api_statuses_f('blocks');
3507 if ($data === false) {
3510 return api_format_data("users", $type, $data);
3513 /// @TODO move to top of file or somewhere better
3514 api_register_func('api/blocks/list', 'api_blocks_list', true);
3517 * Returns the list of pending users IDs
3519 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3521 * @param string $type Either "json" or "xml"
3523 * @return boolean|string|array
3524 * @throws BadRequestException
3525 * @throws ForbiddenException
3527 function api_friendships_incoming($type)
3529 $data = api_statuses_f('incoming');
3530 if ($data === false) {
3535 foreach ($data['user'] as $user) {
3536 $ids[] = $user['id'];
3539 return api_format_data("ids", $type, ['id' => $ids]);
3542 /// @TODO move to top of file or somewhere better
3543 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3546 * Returns the instance's configuration information.
3548 * @param string $type Return type (atom, rss, xml, json)
3550 * @return array|string
3551 * @throws InternalServerErrorException
3553 function api_statusnet_config($type)
3557 $name = Config::get('config', 'sitename');
3558 $server = $a->getHostName();
3559 $logo = System::baseUrl() . '/images/friendica-64.png';
3560 $email = Config::get('config', 'admin_email');
3561 $closed = intval(Config::get('config', 'register_policy')) === REGISTER_CLOSED ? 'true' : 'false';
3562 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3563 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3564 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3565 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3568 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3569 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3570 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3571 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3572 'shorturllength' => '30',
3574 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3575 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3576 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3577 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3582 return api_format_data('config', $type, ['config' => $config]);
3585 /// @TODO move to top of file or somewhere better
3586 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3587 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3591 * @param string $type Return type (atom, rss, xml, json)
3593 * @return array|string
3595 function api_statusnet_version($type)
3598 $fake_statusnet_version = "0.9.7";
3600 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3603 /// @TODO move to top of file or somewhere better
3604 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3605 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3609 * @param string $type Return type (atom, rss, xml, json)
3611 * @return array|string|void
3612 * @throws BadRequestException
3613 * @throws ForbiddenException
3614 * @throws ImagickException
3615 * @throws InternalServerErrorException
3616 * @throws UnauthorizedException
3617 * @todo use api_format_data() to return data
3619 function api_ff_ids($type)
3622 throw new ForbiddenException();
3629 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3632 "SELECT `pcontact`.`id` FROM `contact`
3633 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3634 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3637 if (!DBA::isResult($r)) {
3642 foreach ($r as $rr) {
3643 if ($stringify_ids) {
3646 $ids[] = intval($rr['id']);
3650 return api_format_data("ids", $type, ['id' => $ids]);
3654 * Returns the ID of every user the user is following.
3656 * @param string $type Return type (atom, rss, xml, json)
3658 * @return array|string
3659 * @throws BadRequestException
3660 * @throws ForbiddenException
3661 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3663 function api_friends_ids($type)
3665 return api_ff_ids($type);
3669 * Returns the ID of every user following the user.
3671 * @param string $type Return type (atom, rss, xml, json)
3673 * @return array|string
3674 * @throws BadRequestException
3675 * @throws ForbiddenException
3676 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3678 function api_followers_ids($type)
3680 return api_ff_ids($type);
3683 /// @TODO move to top of file or somewhere better
3684 api_register_func('api/friends/ids', 'api_friends_ids', true);
3685 api_register_func('api/followers/ids', 'api_followers_ids', true);
3688 * Sends a new direct message.
3690 * @param string $type Return type (atom, rss, xml, json)
3692 * @return array|string
3693 * @throws BadRequestException
3694 * @throws ForbiddenException
3695 * @throws ImagickException
3696 * @throws InternalServerErrorException
3697 * @throws NotFoundException
3698 * @throws UnauthorizedException
3699 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3701 function api_direct_messages_new($type)
3705 if (api_user() === false) {
3706 throw new ForbiddenException();
3709 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3713 $sender = api_get_user($a);
3716 if (!empty($_POST['screen_name'])) {
3718 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3720 DBA::escape($_POST['screen_name'])
3723 if (DBA::isResult($r)) {
3724 // Selecting the id by priority, friendica first
3725 api_best_nickname($r);
3727 $recipient = api_get_user($a, $r[0]['nurl']);
3730 $recipient = api_get_user($a, $_POST['user_id']);
3733 if (empty($recipient)) {
3734 throw new NotFoundException('Recipient not found');
3738 if (!empty($_REQUEST['replyto'])) {
3740 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3742 intval($_REQUEST['replyto'])
3744 $replyto = $r[0]['parent-uri'];
3745 $sub = $r[0]['title'];
3747 if (!empty($_REQUEST['title'])) {
3748 $sub = $_REQUEST['title'];
3750 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3754 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3757 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3758 $ret = api_format_messages($r[0], $recipient, $sender);
3760 $ret = ["error"=>$id];
3763 $data = ['direct_message'=>$ret];
3769 $data = api_rss_extra($a, $data, $sender);
3773 return api_format_data("direct-messages", $type, $data);
3776 /// @TODO move to top of file or somewhere better
3777 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3780 * Destroys a direct message.
3782 * @brief delete a direct_message from mail table through api
3784 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3785 * @return string|array
3786 * @throws BadRequestException
3787 * @throws ForbiddenException
3788 * @throws ImagickException
3789 * @throws InternalServerErrorException
3790 * @throws UnauthorizedException
3791 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3793 function api_direct_messages_destroy($type)
3797 if (api_user() === false) {
3798 throw new ForbiddenException();
3802 $user_info = api_get_user($a);
3804 $id = defaults($_REQUEST, 'id', 0);
3806 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3807 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3808 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3810 $uid = $user_info['uid'];
3811 // error if no id or parenturi specified (for clients posting parent-uri as well)
3812 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3813 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3814 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3817 // BadRequestException if no id specified (for clients using Twitter API)
3819 throw new BadRequestException('Message id not specified');
3822 // add parent-uri to sql command if specified by calling app
3823 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3825 // get data of the specified message id
3827 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3832 // error message if specified id is not in database
3833 if (!DBA::isResult($r)) {
3834 if ($verbose == "true") {
3835 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3836 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3838 /// @todo BadRequestException ok for Twitter API clients?
3839 throw new BadRequestException('message id not in database');
3844 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3849 if ($verbose == "true") {
3852 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3853 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3855 $answer = ['result' => 'error', 'message' => 'unknown error'];
3856 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3859 /// @todo return JSON data like Twitter API not yet implemented
3862 /// @TODO move to top of file or somewhere better
3863 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3868 * @brief unfollow contact
3870 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3871 * @return string|array
3872 * @throws BadRequestException
3873 * @throws ForbiddenException
3874 * @throws ImagickException
3875 * @throws InternalServerErrorException
3876 * @throws NotFoundException
3877 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3879 function api_friendships_destroy($type)
3883 if ($uid === false) {
3884 throw new ForbiddenException();
3887 $contact_id = defaults($_REQUEST, 'user_id');
3889 if (empty($contact_id)) {
3890 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3891 throw new BadRequestException("no user_id specified");
3894 // Get Contact by given id
3895 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3897 if(!DBA::isResult($contact)) {
3898 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3899 throw new NotFoundException("no contact found to given ID");
3902 $url = $contact["url"];
3904 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3905 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3906 Strings::normaliseLink($url), $url];
3907 $contact = DBA::selectFirst('contact', [], $condition);
3909 if (!DBA::isResult($contact)) {
3910 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3911 throw new NotFoundException("Not following Contact");
3914 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3915 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3916 throw new ExpectationFailedException("Not supported");
3919 $dissolve = ($contact['rel'] == Contact::SHARING);
3921 $owner = User::getOwnerDataById($uid);
3923 Contact::terminateFriendship($owner, $contact, $dissolve);
3926 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3927 throw new NotFoundException("Error Processing Request");
3930 // Sharing-only contacts get deleted as there no relationship any more
3932 Contact::remove($contact['id']);
3934 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3937 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3938 unset($contact["uid"]);
3939 unset($contact["self"]);
3941 // Set screen_name since Twidere requests it
3942 $contact["screen_name"] = $contact["nick"];
3944 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3946 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3950 * @param string $type Return type (atom, rss, xml, json)
3951 * @param string $box
3952 * @param string $verbose
3954 * @return array|string
3955 * @throws BadRequestException
3956 * @throws ForbiddenException
3957 * @throws ImagickException
3958 * @throws InternalServerErrorException
3959 * @throws UnauthorizedException
3961 function api_direct_messages_box($type, $box, $verbose)
3964 if (api_user() === false) {
3965 throw new ForbiddenException();
3968 $count = defaults($_GET, 'count', 20);
3969 $page = defaults($_REQUEST, 'page', 1) - 1;
3974 $since_id = defaults($_REQUEST, 'since_id', 0);
3975 $max_id = defaults($_REQUEST, 'max_id', 0);
3977 $user_id = defaults($_REQUEST, 'user_id', '');
3978 $screen_name = defaults($_REQUEST, 'screen_name', '');
3981 unset($_REQUEST["user_id"]);
3982 unset($_GET["user_id"]);
3984 unset($_REQUEST["screen_name"]);
3985 unset($_GET["screen_name"]);
3987 $user_info = api_get_user($a);
3988 if ($user_info === false) {
3989 throw new ForbiddenException();
3991 $profile_url = $user_info["url"];
3994 $start = $page * $count;
3999 if ($box=="sentbox") {
4000 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
4001 } elseif ($box == "conversation") {
4002 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
4003 } elseif ($box == "all") {
4004 $sql_extra = "true";
4005 } elseif ($box == "inbox") {
4006 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4010 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4013 if ($user_id != "") {
4014 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4015 } elseif ($screen_name !="") {
4016 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4020 "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",
4026 if ($verbose == "true" && !DBA::isResult($r)) {
4027 $answer = ['result' => 'error', 'message' => 'no mails available'];
4028 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4032 foreach ($r as $item) {
4033 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4034 $recipient = $user_info;
4035 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4036 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4037 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4038 $sender = $user_info;
4041 if (isset($recipient) && isset($sender)) {
4042 $ret[] = api_format_messages($item, $recipient, $sender);
4047 $data = ['direct_message' => $ret];
4052 $data = api_rss_extra($a, $data, $user_info);
4056 return api_format_data("direct-messages", $type, $data);
4060 * Returns the most recent direct messages sent by the user.
4062 * @param string $type Return type (atom, rss, xml, json)
4064 * @return array|string
4065 * @throws BadRequestException
4066 * @throws ForbiddenException
4067 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4069 function api_direct_messages_sentbox($type)
4071 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4072 return api_direct_messages_box($type, "sentbox", $verbose);
4076 * Returns the most recent direct messages sent to the user.
4078 * @param string $type Return type (atom, rss, xml, json)
4080 * @return array|string
4081 * @throws BadRequestException
4082 * @throws ForbiddenException
4083 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4085 function api_direct_messages_inbox($type)
4087 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4088 return api_direct_messages_box($type, "inbox", $verbose);
4093 * @param string $type Return type (atom, rss, xml, json)
4095 * @return array|string
4096 * @throws BadRequestException
4097 * @throws ForbiddenException
4099 function api_direct_messages_all($type)
4101 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4102 return api_direct_messages_box($type, "all", $verbose);
4107 * @param string $type Return type (atom, rss, xml, json)
4109 * @return array|string
4110 * @throws BadRequestException
4111 * @throws ForbiddenException
4113 function api_direct_messages_conversation($type)
4115 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4116 return api_direct_messages_box($type, "conversation", $verbose);
4119 /// @TODO move to top of file or somewhere better
4120 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4121 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4122 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4123 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4126 * Returns an OAuth Request Token.
4128 * @see https://oauth.net/core/1.0/#auth_step1
4130 function api_oauth_request_token()
4132 $oauth1 = new FKOAuth1();
4134 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4135 } catch (Exception $e) {
4136 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4144 * Returns an OAuth Access Token.
4146 * @return array|string
4147 * @see https://oauth.net/core/1.0/#auth_step3
4149 function api_oauth_access_token()
4151 $oauth1 = new FKOAuth1();
4153 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4154 } catch (Exception $e) {
4155 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4162 /// @TODO move to top of file or somewhere better
4163 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4164 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4168 * @brief delete a complete photoalbum with all containing photos from database through api
4170 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4171 * @return string|array
4172 * @throws BadRequestException
4173 * @throws ForbiddenException
4174 * @throws InternalServerErrorException
4176 function api_fr_photoalbum_delete($type)
4178 if (api_user() === false) {
4179 throw new ForbiddenException();
4182 $album = defaults($_REQUEST, 'album', "");
4184 // we do not allow calls without album string
4186 throw new BadRequestException("no albumname specified");
4188 // check if album is existing
4190 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4194 if (!DBA::isResult($r)) {
4195 throw new BadRequestException("album not available");
4198 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4199 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4200 foreach ($r as $rr) {
4201 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4202 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4204 if (!DBA::isResult($photo_item)) {
4205 throw new InternalServerErrorException("problem with deleting items occured");
4207 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4210 // now let's delete all photos from the album
4211 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4213 // return success of deletion or error message
4215 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4216 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4218 throw new InternalServerErrorException("unknown error - deleting from database failed");
4223 * @brief update the name of the album for all photos of an album
4225 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4226 * @return string|array
4227 * @throws BadRequestException
4228 * @throws ForbiddenException
4229 * @throws InternalServerErrorException
4231 function api_fr_photoalbum_update($type)
4233 if (api_user() === false) {
4234 throw new ForbiddenException();
4237 $album = defaults($_REQUEST, 'album', "");
4238 $album_new = defaults($_REQUEST, 'album_new', "");
4240 // we do not allow calls without album string
4242 throw new BadRequestException("no albumname specified");
4244 if ($album_new == "") {
4245 throw new BadRequestException("no new albumname specified");
4247 // check if album is existing
4248 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4249 throw new BadRequestException("album not available");
4251 // now let's update all photos to the albumname
4252 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4254 // return success of updating or error message
4256 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4257 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4259 throw new InternalServerErrorException("unknown error - updating in database failed");
4265 * @brief list all photos of the authenticated user
4267 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4268 * @return string|array
4269 * @throws ForbiddenException
4270 * @throws InternalServerErrorException
4272 function api_fr_photos_list($type)
4274 if (api_user() === false) {
4275 throw new ForbiddenException();
4278 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4279 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4280 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4281 intval(local_user())
4284 'image/jpeg' => 'jpg',
4285 'image/png' => 'png',
4286 'image/gif' => 'gif'
4288 $data = ['photo'=>[]];
4289 if (DBA::isResult($r)) {
4290 foreach ($r as $rr) {
4292 $photo['id'] = $rr['resource-id'];
4293 $photo['album'] = $rr['album'];
4294 $photo['filename'] = $rr['filename'];
4295 $photo['type'] = $rr['type'];
4296 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4297 $photo['created'] = $rr['created'];
4298 $photo['edited'] = $rr['edited'];
4299 $photo['desc'] = $rr['desc'];
4301 if ($type == "xml") {
4302 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4304 $photo['thumb'] = $thumb;
4305 $data['photo'][] = $photo;
4309 return api_format_data("photos", $type, $data);
4313 * @brief upload a new photo or change an existing photo
4315 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4316 * @return string|array
4317 * @throws BadRequestException
4318 * @throws ForbiddenException
4319 * @throws ImagickException
4320 * @throws InternalServerErrorException
4321 * @throws NotFoundException
4323 function api_fr_photo_create_update($type)
4325 if (api_user() === false) {
4326 throw new ForbiddenException();
4329 $photo_id = defaults($_REQUEST, 'photo_id', null);
4330 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4331 $album = defaults($_REQUEST, 'album', null);
4332 $album_new = defaults($_REQUEST, 'album_new', null);
4333 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4334 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4335 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4336 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4337 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4339 // do several checks on input parameters
4340 // we do not allow calls without album string
4341 if ($album == null) {
4342 throw new BadRequestException("no albumname specified");
4344 // if photo_id == null --> we are uploading a new photo
4345 if ($photo_id == null) {
4348 // error if no media posted in create-mode
4349 if (empty($_FILES['media'])) {
4351 throw new BadRequestException("no media data submitted");
4354 // album_new will be ignored in create-mode
4359 // check if photo is existing in databasei
4360 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4361 throw new BadRequestException("photo not available");
4365 // checks on acl strings provided by clients
4366 $acl_input_error = false;
4367 $acl_input_error |= check_acl_input($allow_cid);
4368 $acl_input_error |= check_acl_input($deny_cid);
4369 $acl_input_error |= check_acl_input($allow_gid);
4370 $acl_input_error |= check_acl_input($deny_gid);
4371 if ($acl_input_error) {
4372 throw new BadRequestException("acl data invalid");
4374 // now let's upload the new media in create-mode
4375 if ($mode == "create") {
4376 $media = $_FILES['media'];
4377 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4379 // return success of updating or error message
4380 if (!is_null($data)) {
4381 return api_format_data("photo_create", $type, $data);
4383 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4387 // now let's do the changes in update-mode
4388 if ($mode == "update") {
4389 $updated_fields = [];
4391 if (!is_null($desc)) {
4392 $updated_fields['desc'] = $desc;
4395 if (!is_null($album_new)) {
4396 $updated_fields['album'] = $album_new;
4399 if (!is_null($allow_cid)) {
4400 $allow_cid = trim($allow_cid);
4401 $updated_fields['allow_cid'] = $allow_cid;
4404 if (!is_null($deny_cid)) {
4405 $deny_cid = trim($deny_cid);
4406 $updated_fields['deny_cid'] = $deny_cid;
4409 if (!is_null($allow_gid)) {
4410 $allow_gid = trim($allow_gid);
4411 $updated_fields['allow_gid'] = $allow_gid;
4414 if (!is_null($deny_gid)) {
4415 $deny_gid = trim($deny_gid);
4416 $updated_fields['deny_gid'] = $deny_gid;
4420 if (count($updated_fields) > 0) {
4421 $nothingtodo = false;
4422 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4424 $nothingtodo = true;
4427 if (!empty($_FILES['media'])) {
4428 $nothingtodo = false;
4429 $media = $_FILES['media'];
4430 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4431 if (!is_null($data)) {
4432 return api_format_data("photo_update", $type, $data);
4436 // return success of updating or error message
4438 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4439 return api_format_data("photo_update", $type, ['$result' => $answer]);
4442 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4443 return api_format_data("photo_update", $type, ['$result' => $answer]);
4445 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4448 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4452 * @brief delete a single photo from the database through api
4454 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4455 * @return string|array
4456 * @throws BadRequestException
4457 * @throws ForbiddenException
4458 * @throws InternalServerErrorException
4460 function api_fr_photo_delete($type)
4462 if (api_user() === false) {
4463 throw new ForbiddenException();
4466 $photo_id = defaults($_REQUEST, 'photo_id', null);
4468 // do several checks on input parameters
4469 // we do not allow calls without photo id
4470 if ($photo_id == null) {
4471 throw new BadRequestException("no photo_id specified");
4473 // check if photo is existing in database
4474 $r = Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()]);
4476 throw new BadRequestException("photo not available");
4478 // now we can perform on the deletion of the photo
4479 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4481 // return success of deletion or error message
4483 // retrieve the id of the parent element (the photo element)
4484 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4485 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4487 if (!DBA::isResult($photo_item)) {
4488 throw new InternalServerErrorException("problem with deleting items occured");
4490 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4491 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4492 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4494 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4495 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4497 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4503 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4505 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4506 * @return string|array
4507 * @throws BadRequestException
4508 * @throws ForbiddenException
4509 * @throws InternalServerErrorException
4510 * @throws NotFoundException
4512 function api_fr_photo_detail($type)
4514 if (api_user() === false) {
4515 throw new ForbiddenException();
4517 if (empty($_REQUEST['photo_id'])) {
4518 throw new BadRequestException("No photo id.");
4521 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4522 $photo_id = $_REQUEST['photo_id'];
4524 // prepare json/xml output with data from database for the requested photo
4525 $data = prepare_photo_data($type, $scale, $photo_id);
4527 return api_format_data("photo_detail", $type, $data);
4532 * Updates the user’s profile image.
4534 * @brief updates the profile image for the user (either a specified profile or the default profile)
4536 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4538 * @return string|array
4539 * @throws BadRequestException
4540 * @throws ForbiddenException
4541 * @throws ImagickException
4542 * @throws InternalServerErrorException
4543 * @throws NotFoundException
4544 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4546 function api_account_update_profile_image($type)
4548 if (api_user() === false) {
4549 throw new ForbiddenException();
4552 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4554 // error if image data is missing
4555 if (empty($_FILES['image'])) {
4556 throw new BadRequestException("no media data submitted");
4559 // check if specified profile id is valid
4560 if ($profile_id != 0) {
4561 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4562 // error message if specified profile id is not in database
4563 if (!DBA::isResult($profile)) {
4564 throw new BadRequestException("profile_id not available");
4566 $is_default_profile = $profile['is-default'];
4568 $is_default_profile = 1;
4571 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4573 if (!empty($_FILES['image'])) {
4574 $media = $_FILES['image'];
4575 } elseif (!empty($_FILES['media'])) {
4576 $media = $_FILES['media'];
4578 // save new profile image
4579 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4582 if (is_array($media['type'])) {
4583 $filetype = $media['type'][0];
4585 $filetype = $media['type'];
4587 if ($filetype == "image/jpeg") {
4589 } elseif ($filetype == "image/png") {
4592 throw new InternalServerErrorException('Unsupported filetype');
4595 // change specified profile or all profiles to the new resource-id
4596 if ($is_default_profile) {
4597 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4598 Photo::update(['profile' => false], $condition);
4600 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4601 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4602 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4605 Contact::updateSelfFromUserID(api_user(), true);
4607 // Update global directory in background
4608 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4609 if ($url && strlen(Config::get('system', 'directory'))) {
4610 Worker::add(PRIORITY_LOW, "Directory", $url);
4613 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4615 // output for client
4617 return api_account_verify_credentials($type);
4619 // SaveMediaToDatabase failed for some reason
4620 throw new InternalServerErrorException("image upload failed");
4624 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4625 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4626 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4627 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4628 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4629 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4630 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4631 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4632 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4635 * Update user profile
4637 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4639 * @return array|string
4640 * @throws BadRequestException
4641 * @throws ForbiddenException
4642 * @throws ImagickException
4643 * @throws InternalServerErrorException
4644 * @throws UnauthorizedException
4646 function api_account_update_profile($type)
4648 $local_user = api_user();
4649 $api_user = api_get_user(get_app());
4651 if (!empty($_POST['name'])) {
4652 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4653 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4654 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4655 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4658 if (isset($_POST['description'])) {
4659 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4660 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4661 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4664 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4665 // Update global directory in background
4666 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4667 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4670 return api_account_verify_credentials($type);
4673 /// @TODO move to top of file or somewhere better
4674 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4678 * @param string $acl_string
4682 function check_acl_input($acl_string)
4684 if ($acl_string == null || $acl_string == " ") {
4687 $contact_not_found = false;
4689 // split <x><y><z> into array of cid's
4690 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4692 // check for each cid if it is available on server
4693 $cid_array = $array[0];
4694 foreach ($cid_array as $cid) {
4695 $cid = str_replace("<", "", $cid);
4696 $cid = str_replace(">", "", $cid);
4697 $condition = ['id' => $cid, 'uid' => api_user()];
4698 $contact_not_found |= !DBA::exists('contact', $condition);
4700 return $contact_not_found;
4705 * @param string $mediatype
4706 * @param array $media
4707 * @param string $type
4708 * @param string $album
4709 * @param string $allow_cid
4710 * @param string $deny_cid
4711 * @param string $allow_gid
4712 * @param string $deny_gid
4713 * @param string $desc
4714 * @param integer $profile
4715 * @param boolean $visibility
4716 * @param string $photo_id
4718 * @throws BadRequestException
4719 * @throws ForbiddenException
4720 * @throws ImagickException
4721 * @throws InternalServerErrorException
4722 * @throws NotFoundException
4724 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)
4732 if (is_array($media)) {
4733 if (is_array($media['tmp_name'])) {
4734 $src = $media['tmp_name'][0];
4736 $src = $media['tmp_name'];
4738 if (is_array($media['name'])) {
4739 $filename = basename($media['name'][0]);
4741 $filename = basename($media['name']);
4743 if (is_array($media['size'])) {
4744 $filesize = intval($media['size'][0]);
4746 $filesize = intval($media['size']);
4748 if (is_array($media['type'])) {
4749 $filetype = $media['type'][0];
4751 $filetype = $media['type'];
4755 if ($filetype == "") {
4756 $filetype=Image::guessType($filename);
4758 $imagedata = @getimagesize($src);
4760 $filetype = $imagedata['mime'];
4763 "File upload src: " . $src . " - filename: " . $filename .
4764 " - size: " . $filesize . " - type: " . $filetype,
4768 // check if there was a php upload error
4769 if ($filesize == 0 && $media['error'] == 1) {
4770 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4772 // check against max upload size within Friendica instance
4773 $maximagesize = Config::get('system', 'maximagesize');
4774 if ($maximagesize && ($filesize > $maximagesize)) {
4775 $formattedBytes = Strings::formatBytes($maximagesize);
4776 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4779 // create Photo instance with the data of the image
4780 $imagedata = @file_get_contents($src);
4781 $Image = new Image($imagedata, $filetype);
4782 if (!$Image->isValid()) {
4783 throw new InternalServerErrorException("unable to process image data");
4786 // check orientation of image
4787 $Image->orient($src);
4790 // check max length of images on server
4791 $max_length = Config::get('system', 'max_image_length');
4793 $max_length = MAX_IMAGE_LENGTH;
4795 if ($max_length > 0) {
4796 $Image->scaleDown($max_length);
4797 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4799 $width = $Image->getWidth();
4800 $height = $Image->getHeight();
4802 // create a new resource-id if not already provided
4803 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4805 if ($mediatype == "photo") {
4806 // upload normal image (scales 0, 1, 2)
4807 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4809 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4811 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4813 if ($width > 640 || $height > 640) {
4814 $Image->scaleDown(640);
4815 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4817 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4821 if ($width > 320 || $height > 320) {
4822 $Image->scaleDown(320);
4823 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4825 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4828 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4829 } elseif ($mediatype == "profileimage") {
4830 // upload profile image (scales 4, 5, 6)
4831 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4833 if ($width > 300 || $height > 300) {
4834 $Image->scaleDown(300);
4835 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4837 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4841 if ($width > 80 || $height > 80) {
4842 $Image->scaleDown(80);
4843 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4845 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4849 if ($width > 48 || $height > 48) {
4850 $Image->scaleDown(48);
4851 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4853 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4856 $Image->__destruct();
4857 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4860 if (isset($r) && $r) {
4861 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4862 if ($photo_id == null && $mediatype == "photo") {
4863 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4865 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4866 return prepare_photo_data($type, false, $hash);
4868 throw new InternalServerErrorException("image upload failed");
4874 * @param string $hash
4875 * @param string $allow_cid
4876 * @param string $deny_cid
4877 * @param string $allow_gid
4878 * @param string $deny_gid
4879 * @param string $filetype
4880 * @param boolean $visibility
4881 * @throws InternalServerErrorException
4883 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4885 // get data about the api authenticated user
4886 $uri = Item::newURI(intval(api_user()));
4887 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4890 $arr['guid'] = System::createUUID();
4891 $arr['uid'] = intval(api_user());
4893 $arr['parent-uri'] = $uri;
4894 $arr['type'] = 'photo';
4896 $arr['resource-id'] = $hash;
4897 $arr['contact-id'] = $owner_record['id'];
4898 $arr['owner-name'] = $owner_record['name'];
4899 $arr['owner-link'] = $owner_record['url'];
4900 $arr['owner-avatar'] = $owner_record['thumb'];
4901 $arr['author-name'] = $owner_record['name'];
4902 $arr['author-link'] = $owner_record['url'];
4903 $arr['author-avatar'] = $owner_record['thumb'];
4905 $arr['allow_cid'] = $allow_cid;
4906 $arr['allow_gid'] = $allow_gid;
4907 $arr['deny_cid'] = $deny_cid;
4908 $arr['deny_gid'] = $deny_gid;
4909 $arr['visible'] = $visibility;
4913 'image/jpeg' => 'jpg',
4914 'image/png' => 'png',
4915 'image/gif' => 'gif'
4918 // adds link to the thumbnail scale photo
4919 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4920 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4923 // do the magic for storing the item in the database and trigger the federation to other contacts
4929 * @param string $type
4931 * @param string $photo_id
4934 * @throws BadRequestException
4935 * @throws ForbiddenException
4936 * @throws ImagickException
4937 * @throws InternalServerErrorException
4938 * @throws NotFoundException
4939 * @throws UnauthorizedException
4941 function prepare_photo_data($type, $scale, $photo_id)
4944 $user_info = api_get_user($a);
4946 if ($user_info === false) {
4947 throw new ForbiddenException();
4950 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4951 $data_sql = ($scale === false ? "" : "data, ");
4953 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4954 // clients needs to convert this in their way for further processing
4956 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4957 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4958 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4959 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4961 intval(local_user()),
4962 DBA::escape($photo_id),
4967 'image/jpeg' => 'jpg',
4968 'image/png' => 'png',
4969 'image/gif' => 'gif'
4972 // prepare output data for photo
4973 if (DBA::isResult($r)) {
4974 $data = ['photo' => $r[0]];
4975 $data['photo']['id'] = $data['photo']['resource-id'];
4976 if ($scale !== false) {
4977 $data['photo']['data'] = base64_encode($data['photo']['data']);
4979 unset($data['photo']['datasize']); //needed only with scale param
4981 if ($type == "xml") {
4982 $data['photo']['links'] = [];
4983 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4984 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4986 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4989 $data['photo']['link'] = [];
4990 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4992 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4993 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4997 unset($data['photo']['resource-id']);
4998 unset($data['photo']['minscale']);
4999 unset($data['photo']['maxscale']);
5001 throw new NotFoundException();
5004 // retrieve item element for getting activities (like, dislike etc.) related to photo
5005 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5006 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5008 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5010 // retrieve comments on photo
5011 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5012 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5014 $statuses = Item::selectForUser(api_user(), [], $condition);
5016 // prepare output of comments
5017 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5019 if ($type == "xml") {
5021 foreach ($commentData as $comment) {
5022 $comments[$k++ . ":comment"] = $comment;
5025 foreach ($commentData as $comment) {
5026 $comments[] = $comment;
5029 $data['photo']['friendica_comments'] = $comments;
5031 // include info if rights on photo and rights on item are mismatching
5032 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5033 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5034 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5035 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5036 $data['photo']['rights_mismatch'] = $rights_mismatch;
5043 * Similar as /mod/redir.php
5044 * redirect to 'url' after dfrn auth
5046 * Why this when there is mod/redir.php already?
5047 * This use api_user() and api_login()
5050 * c_url: url of remote contact to auth to
5051 * url: string, url to redirect after auth
5053 function api_friendica_remoteauth()
5055 $url = defaults($_GET, 'url', '');
5056 $c_url = defaults($_GET, 'c_url', '');
5058 if ($url === '' || $c_url === '') {
5059 throw new BadRequestException("Wrong parameters.");
5062 $c_url = Strings::normaliseLink($c_url);
5066 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5068 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5069 throw new BadRequestException("Unknown contact");
5072 $cid = $contact['id'];
5074 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
5076 if ($contact['duplex'] && $contact['issued-id']) {
5077 $orig_id = $contact['issued-id'];
5078 $dfrn_id = '1:' . $orig_id;
5080 if ($contact['duplex'] && $contact['dfrn-id']) {
5081 $orig_id = $contact['dfrn-id'];
5082 $dfrn_id = '0:' . $orig_id;
5085 $sec = Strings::getRandomHex();
5087 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5088 'sec' => $sec, 'expire' => time() + 45];
5089 DBA::insert('profile_check', $fields);
5091 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5092 $dest = ($url ? '&destination_url=' . $url : '');
5094 System::externalRedirect(
5095 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5096 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5097 . '&type=profile&sec=' . $sec . $dest
5100 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5103 * @brief Return the item shared, if the item contains only the [share] tag
5105 * @param array $item Sharer item
5106 * @return array|false Shared item or false if not a reshare
5107 * @throws ImagickException
5108 * @throws InternalServerErrorException
5110 function api_share_as_retweet(&$item)
5112 $body = trim($item["body"]);
5114 if (Diaspora::isReshare($body, false) === false) {
5115 if ($item['author-id'] == $item['owner-id']) {
5118 // Reshares from OStatus, ActivityPub and Twitter
5119 $reshared_item = $item;
5120 $reshared_item['owner-id'] = $reshared_item['author-id'];
5121 $reshared_item['owner-link'] = $reshared_item['author-link'];
5122 $reshared_item['owner-name'] = $reshared_item['author-name'];
5123 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5124 return $reshared_item;
5128 /// @TODO "$1" should maybe mean '$1' ?
5129 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5131 * Skip if there is no shared message in there
5132 * we already checked this in diaspora::isReshare()
5133 * but better one more than one less...
5135 if (($body == $attributes) || empty($attributes)) {
5139 // build the fake reshared item
5140 $reshared_item = $item;
5143 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5144 if (!empty($matches[1])) {
5145 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5148 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5149 if (!empty($matches[1])) {
5150 $author = $matches[1];
5154 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5155 if (!empty($matches[1])) {
5156 $profile = $matches[1];
5159 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5160 if (!empty($matches[1])) {
5161 $profile = $matches[1];
5165 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5166 if (!empty($matches[1])) {
5167 $avatar = $matches[1];
5170 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5171 if (!empty($matches[1])) {
5172 $avatar = $matches[1];
5176 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5177 if (!empty($matches[1])) {
5178 $link = $matches[1];
5181 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5182 if (!empty($matches[1])) {
5183 $link = $matches[1];
5187 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5188 if (!empty($matches[1])) {
5189 $posted = $matches[1];
5192 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5193 if (!empty($matches[1])) {
5194 $posted = $matches[1];
5197 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5199 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5203 $reshared_item["body"] = $shared_body;
5204 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5205 $reshared_item["author-name"] = $author;
5206 $reshared_item["author-link"] = $profile;
5207 $reshared_item["author-avatar"] = $avatar;
5208 $reshared_item["plink"] = $link;
5209 $reshared_item["created"] = $posted;
5210 $reshared_item["edited"] = $posted;
5212 return $reshared_item;
5217 * @param string $profile
5219 * @return string|false
5220 * @throws InternalServerErrorException
5221 * @todo remove trailing junk from profile url
5222 * @todo pump.io check has to check the website
5224 function api_get_nick($profile)
5229 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5230 DBA::escape(Strings::normaliseLink($profile))
5233 if (DBA::isResult($r)) {
5234 $nick = $r[0]["nick"];
5239 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5240 DBA::escape(Strings::normaliseLink($profile))
5243 if (DBA::isResult($r)) {
5244 $nick = $r[0]["nick"];
5249 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5250 if ($friendica != $profile) {
5256 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5257 if ($diaspora != $profile) {
5263 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5264 if ($twitter != $profile) {
5271 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5272 if ($StatusnetHost != $profile) {
5273 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5274 if ($StatusnetUser != $profile) {
5275 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5276 $user = json_decode($UserData);
5278 $nick = $user->screen_name;
5284 // To-Do: look at the page if its really a pumpio site
5285 //if (!$nick == "") {
5286 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5287 // if ($pumpio != $profile)
5289 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5302 * @param array $item
5307 function api_in_reply_to($item)
5311 $in_reply_to['status_id'] = null;
5312 $in_reply_to['user_id'] = null;
5313 $in_reply_to['status_id_str'] = null;
5314 $in_reply_to['user_id_str'] = null;
5315 $in_reply_to['screen_name'] = null;
5317 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5318 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5319 if (DBA::isResult($parent)) {
5320 $in_reply_to['status_id'] = intval($parent['id']);
5322 $in_reply_to['status_id'] = intval($item['parent']);
5325 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5327 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5328 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5330 if (DBA::isResult($parent)) {
5331 if ($parent['author-nick'] == "") {
5332 $parent['author-nick'] = api_get_nick($parent['author-link']);
5335 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5336 $in_reply_to['user_id'] = intval($parent['author-id']);
5337 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5340 // There seems to be situation, where both fields are identical:
5341 // https://github.com/friendica/friendica/issues/1010
5342 // This is a bugfix for that.
5343 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5344 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']]);
5345 $in_reply_to['status_id'] = null;
5346 $in_reply_to['user_id'] = null;
5347 $in_reply_to['status_id_str'] = null;
5348 $in_reply_to['user_id_str'] = null;
5349 $in_reply_to['screen_name'] = null;
5353 return $in_reply_to;
5358 * @param string $text
5361 * @throws InternalServerErrorException
5363 function api_clean_plain_items($text)
5365 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5367 $text = BBCode::cleanPictureLinks($text);
5368 $URLSearchString = "^\[\]";
5370 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5372 if ($include_entities == "true") {
5373 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5376 // Simplify "attachment" element
5377 $text = api_clean_attachments($text);
5383 * @brief Removes most sharing information for API text export
5385 * @param string $body The original body
5387 * @return string Cleaned body
5388 * @throws InternalServerErrorException
5390 function api_clean_attachments($body)
5392 $data = BBCode::getAttachmentData($body);
5399 if (isset($data["text"])) {
5400 $body = $data["text"];
5402 if (($body == "") && isset($data["title"])) {
5403 $body = $data["title"];
5405 if (isset($data["url"])) {
5406 $body .= "\n".$data["url"];
5408 $body .= $data["after"];
5415 * @param array $contacts
5419 function api_best_nickname(&$contacts)
5423 if (count($contacts) == 0) {
5427 foreach ($contacts as $contact) {
5428 if ($contact["network"] == "") {
5429 $contact["network"] = "dfrn";
5430 $best_contact = [$contact];
5434 if (sizeof($best_contact) == 0) {
5435 foreach ($contacts as $contact) {
5436 if ($contact["network"] == "dfrn") {
5437 $best_contact = [$contact];
5442 if (sizeof($best_contact) == 0) {
5443 foreach ($contacts as $contact) {
5444 if ($contact["network"] == "dspr") {
5445 $best_contact = [$contact];
5450 if (sizeof($best_contact) == 0) {
5451 foreach ($contacts as $contact) {
5452 if ($contact["network"] == "stat") {
5453 $best_contact = [$contact];
5458 if (sizeof($best_contact) == 0) {
5459 foreach ($contacts as $contact) {
5460 if ($contact["network"] == "pump") {
5461 $best_contact = [$contact];
5466 if (sizeof($best_contact) == 0) {
5467 foreach ($contacts as $contact) {
5468 if ($contact["network"] == "twit") {
5469 $best_contact = [$contact];
5474 if (sizeof($best_contact) == 1) {
5475 $contacts = $best_contact;
5477 $contacts = [$contacts[0]];
5482 * Return all or a specified group of the user with the containing contacts.
5484 * @param string $type Return type (atom, rss, xml, json)
5486 * @return array|string
5487 * @throws BadRequestException
5488 * @throws ForbiddenException
5489 * @throws ImagickException
5490 * @throws InternalServerErrorException
5491 * @throws UnauthorizedException
5493 function api_friendica_group_show($type)
5497 if (api_user() === false) {
5498 throw new ForbiddenException();
5502 $user_info = api_get_user($a);
5503 $gid = defaults($_REQUEST, 'gid', 0);
5504 $uid = $user_info['uid'];
5506 // get data of the specified group id or all groups if not specified
5509 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5513 // error message if specified gid is not in database
5514 if (!DBA::isResult($r)) {
5515 throw new BadRequestException("gid not available");
5519 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5524 // loop through all groups and retrieve all members for adding data in the user array
5526 foreach ($r as $rr) {
5527 $members = Contact::getByGroupId($rr['id']);
5530 if ($type == "xml") {
5531 $user_element = "users";
5533 foreach ($members as $member) {
5534 $user = api_get_user($a, $member['nurl']);
5535 $users[$k++.":user"] = $user;
5538 $user_element = "user";
5539 foreach ($members as $member) {
5540 $user = api_get_user($a, $member['nurl']);
5544 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5546 return api_format_data("groups", $type, ['group' => $grps]);
5548 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5552 * Delete the specified group of the user.
5554 * @param string $type Return type (atom, rss, xml, json)
5556 * @return array|string
5557 * @throws BadRequestException
5558 * @throws ForbiddenException
5559 * @throws ImagickException
5560 * @throws InternalServerErrorException
5561 * @throws UnauthorizedException
5563 function api_friendica_group_delete($type)
5567 if (api_user() === false) {
5568 throw new ForbiddenException();
5572 $user_info = api_get_user($a);
5573 $gid = defaults($_REQUEST, 'gid', 0);
5574 $name = defaults($_REQUEST, 'name', "");
5575 $uid = $user_info['uid'];
5577 // error if no gid specified
5578 if ($gid == 0 || $name == "") {
5579 throw new BadRequestException('gid or name not specified');
5582 // get data of the specified group id
5584 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5588 // error message if specified gid is not in database
5589 if (!DBA::isResult($r)) {
5590 throw new BadRequestException('gid not available');
5593 // get data of the specified group id and group name
5595 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5600 // error message if specified gid is not in database
5601 if (!DBA::isResult($rname)) {
5602 throw new BadRequestException('wrong group name');
5606 $ret = Group::removeByName($uid, $name);
5609 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5610 return api_format_data("group_delete", $type, ['result' => $success]);
5612 throw new BadRequestException('other API error');
5615 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5620 * @param string $type Return type (atom, rss, xml, json)
5622 * @return array|string
5623 * @throws BadRequestException
5624 * @throws ForbiddenException
5625 * @throws ImagickException
5626 * @throws InternalServerErrorException
5627 * @throws UnauthorizedException
5628 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5630 function api_lists_destroy($type)
5634 if (api_user() === false) {
5635 throw new ForbiddenException();
5639 $user_info = api_get_user($a);
5640 $gid = defaults($_REQUEST, 'list_id', 0);
5641 $uid = $user_info['uid'];
5643 // error if no gid specified
5645 throw new BadRequestException('gid not specified');
5648 // get data of the specified group id
5649 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5650 // error message if specified gid is not in database
5652 throw new BadRequestException('gid not available');
5655 if (Group::remove($gid)) {
5657 'name' => $group['name'],
5658 'id' => intval($gid),
5659 'id_str' => (string) $gid,
5660 'user' => $user_info
5663 return api_format_data("lists", $type, ['lists' => $list]);
5666 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5669 * Add a new group to the database.
5671 * @param string $name Group name
5672 * @param int $uid User ID
5673 * @param array $users List of users to add to the group
5676 * @throws BadRequestException
5678 function group_create($name, $uid, $users = [])
5680 // error if no name specified
5682 throw new BadRequestException('group name not specified');
5685 // get data of the specified group name
5687 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5691 // error message if specified group name already exists
5692 if (DBA::isResult($rname)) {
5693 throw new BadRequestException('group name already exists');
5696 // check if specified group name is a deleted group
5698 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5702 // error message if specified group name already exists
5703 if (DBA::isResult($rname)) {
5704 $reactivate_group = true;
5708 $ret = Group::create($uid, $name);
5710 $gid = Group::getIdByName($uid, $name);
5712 throw new BadRequestException('other API error');
5716 $erroraddinguser = false;
5718 foreach ($users as $user) {
5719 $cid = $user['cid'];
5720 // check if user really exists as contact
5722 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5726 if (count($contact)) {
5727 Group::addMember($gid, $cid);
5729 $erroraddinguser = true;
5730 $errorusers[] = $cid;
5734 // return success message incl. missing users in array
5735 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5737 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5741 * Create the specified group with the posted array of contacts.
5743 * @param string $type Return type (atom, rss, xml, json)
5745 * @return array|string
5746 * @throws BadRequestException
5747 * @throws ForbiddenException
5748 * @throws ImagickException
5749 * @throws InternalServerErrorException
5750 * @throws UnauthorizedException
5752 function api_friendica_group_create($type)
5756 if (api_user() === false) {
5757 throw new ForbiddenException();
5761 $user_info = api_get_user($a);
5762 $name = defaults($_REQUEST, 'name', "");
5763 $uid = $user_info['uid'];
5764 $json = json_decode($_POST['json'], true);
5765 $users = $json['user'];
5767 $success = group_create($name, $uid, $users);
5769 return api_format_data("group_create", $type, ['result' => $success]);
5771 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5774 * Create a new group.
5776 * @param string $type Return type (atom, rss, xml, json)
5778 * @return array|string
5779 * @throws BadRequestException
5780 * @throws ForbiddenException
5781 * @throws ImagickException
5782 * @throws InternalServerErrorException
5783 * @throws UnauthorizedException
5784 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5786 function api_lists_create($type)
5790 if (api_user() === false) {
5791 throw new ForbiddenException();
5795 $user_info = api_get_user($a);
5796 $name = defaults($_REQUEST, 'name', "");
5797 $uid = $user_info['uid'];
5799 $success = group_create($name, $uid);
5800 if ($success['success']) {
5802 'name' => $success['name'],
5803 'id' => intval($success['gid']),
5804 'id_str' => (string) $success['gid'],
5805 'user' => $user_info
5808 return api_format_data("lists", $type, ['lists'=>$grp]);
5811 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5814 * Update the specified group with the posted array of contacts.
5816 * @param string $type Return type (atom, rss, xml, json)
5818 * @return array|string
5819 * @throws BadRequestException
5820 * @throws ForbiddenException
5821 * @throws ImagickException
5822 * @throws InternalServerErrorException
5823 * @throws UnauthorizedException
5825 function api_friendica_group_update($type)
5829 if (api_user() === false) {
5830 throw new ForbiddenException();
5834 $user_info = api_get_user($a);
5835 $uid = $user_info['uid'];
5836 $gid = defaults($_REQUEST, 'gid', 0);
5837 $name = defaults($_REQUEST, 'name', "");
5838 $json = json_decode($_POST['json'], true);
5839 $users = $json['user'];
5841 // error if no name specified
5843 throw new BadRequestException('group name not specified');
5846 // error if no gid specified
5848 throw new BadRequestException('gid not specified');
5852 $members = Contact::getByGroupId($gid);
5853 foreach ($members as $member) {
5854 $cid = $member['id'];
5855 foreach ($users as $user) {
5856 $found = ($user['cid'] == $cid ? true : false);
5858 if (!isset($found) || !$found) {
5859 Group::removeMemberByName($uid, $name, $cid);
5864 $erroraddinguser = false;
5866 foreach ($users as $user) {
5867 $cid = $user['cid'];
5868 // check if user really exists as contact
5870 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5875 if (count($contact)) {
5876 Group::addMember($gid, $cid);
5878 $erroraddinguser = true;
5879 $errorusers[] = $cid;
5883 // return success message incl. missing users in array
5884 $status = ($erroraddinguser ? "missing user" : "ok");
5885 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5886 return api_format_data("group_update", $type, ['result' => $success]);
5889 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5892 * Update information about a group.
5894 * @param string $type Return type (atom, rss, xml, json)
5896 * @return array|string
5897 * @throws BadRequestException
5898 * @throws ForbiddenException
5899 * @throws ImagickException
5900 * @throws InternalServerErrorException
5901 * @throws UnauthorizedException
5902 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5904 function api_lists_update($type)
5908 if (api_user() === false) {
5909 throw new ForbiddenException();
5913 $user_info = api_get_user($a);
5914 $gid = defaults($_REQUEST, 'list_id', 0);
5915 $name = defaults($_REQUEST, 'name', "");
5916 $uid = $user_info['uid'];
5918 // error if no gid specified
5920 throw new BadRequestException('gid not specified');
5923 // get data of the specified group id
5924 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5925 // error message if specified gid is not in database
5927 throw new BadRequestException('gid not available');
5930 if (Group::update($gid, $name)) {
5933 'id' => intval($gid),
5934 'id_str' => (string) $gid,
5935 'user' => $user_info
5938 return api_format_data("lists", $type, ['lists' => $list]);
5942 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5946 * @param string $type Return type (atom, rss, xml, json)
5948 * @return array|string
5949 * @throws BadRequestException
5950 * @throws ForbiddenException
5951 * @throws ImagickException
5952 * @throws InternalServerErrorException
5954 function api_friendica_activity($type)
5958 if (api_user() === false) {
5959 throw new ForbiddenException();
5961 $verb = strtolower($a->argv[3]);
5962 $verb = preg_replace("|\..*$|", "", $verb);
5964 $id = defaults($_REQUEST, 'id', 0);
5966 $res = Item::performLike($id, $verb);
5969 if ($type == "xml") {
5974 return api_format_data('ok', $type, ['ok' => $ok]);
5976 throw new BadRequestException('Error adding activity');
5980 /// @TODO move to top of file or somewhere better
5981 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5982 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5983 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5984 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5985 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5986 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5987 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5988 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5989 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5990 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5993 * @brief Returns notifications
5995 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5996 * @return string|array
5997 * @throws BadRequestException
5998 * @throws ForbiddenException
5999 * @throws InternalServerErrorException
6001 function api_friendica_notification($type)
6005 if (api_user() === false) {
6006 throw new ForbiddenException();
6009 throw new BadRequestException("Invalid argument count");
6011 $nm = new NotificationsManager();
6013 $notes = $nm->getAll([], "+seen -date", 50);
6015 if ($type == "xml") {
6017 if (!empty($notes)) {
6018 foreach ($notes as $note) {
6019 $xmlnotes[] = ["@attributes" => $note];
6025 return api_format_data("notes", $type, ['note' => $notes]);
6029 * POST request with 'id' param as notification id
6031 * @brief Set notification as seen and returns associated item (if possible)
6033 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6034 * @return string|array
6035 * @throws BadRequestException
6036 * @throws ForbiddenException
6037 * @throws ImagickException
6038 * @throws InternalServerErrorException
6039 * @throws UnauthorizedException
6041 function api_friendica_notification_seen($type)
6044 $user_info = api_get_user($a);
6046 if (api_user() === false || $user_info === false) {
6047 throw new ForbiddenException();
6050 throw new BadRequestException("Invalid argument count");
6053 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
6055 $nm = new NotificationsManager();
6056 $note = $nm->getByID($id);
6057 if (is_null($note)) {
6058 throw new BadRequestException("Invalid argument");
6061 $nm->setSeen($note);
6062 if ($note['otype']=='item') {
6063 // would be really better with an ItemsManager and $im->getByID() :-P
6064 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6065 if (DBA::isResult($item)) {
6066 // we found the item, return it to the user
6067 $ret = api_format_items([$item], $user_info, false, $type);
6068 $data = ['status' => $ret];
6069 return api_format_data("status", $type, $data);
6071 // the item can't be found, but we set the note as seen, so we count this as a success
6073 return api_format_data('result', $type, ['result' => "success"]);
6076 /// @TODO move to top of file or somewhere better
6077 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6078 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6081 * @brief update a direct_message to seen state
6083 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6084 * @return string|array (success result=ok, error result=error with error message)
6085 * @throws BadRequestException
6086 * @throws ForbiddenException
6087 * @throws ImagickException
6088 * @throws InternalServerErrorException
6089 * @throws UnauthorizedException
6091 function api_friendica_direct_messages_setseen($type)
6094 if (api_user() === false) {
6095 throw new ForbiddenException();
6099 $user_info = api_get_user($a);
6100 $uid = $user_info['uid'];
6101 $id = defaults($_REQUEST, 'id', 0);
6103 // return error if id is zero
6105 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6106 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6109 // error message if specified id is not in database
6110 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6111 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6112 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6115 // update seen indicator
6116 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6120 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6121 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6123 $answer = ['result' => 'error', 'message' => 'unknown error'];
6124 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6128 /// @TODO move to top of file or somewhere better
6129 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6132 * @brief search for direct_messages containing a searchstring through api
6134 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6135 * @param string $box
6136 * @return string|array (success: success=true if found and search_result contains found messages,
6137 * success=false if nothing was found, search_result='nothing found',
6138 * error: result=error with error message)
6139 * @throws BadRequestException
6140 * @throws ForbiddenException
6141 * @throws ImagickException
6142 * @throws InternalServerErrorException
6143 * @throws UnauthorizedException
6145 function api_friendica_direct_messages_search($type, $box = "")
6149 if (api_user() === false) {
6150 throw new ForbiddenException();
6154 $user_info = api_get_user($a);
6155 $searchstring = defaults($_REQUEST, 'searchstring', "");
6156 $uid = $user_info['uid'];
6158 // error if no searchstring specified
6159 if ($searchstring == "") {
6160 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6161 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6164 // get data for the specified searchstring
6166 "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",
6168 DBA::escape('%'.$searchstring.'%')
6171 $profile_url = $user_info["url"];
6173 // message if nothing was found
6174 if (!DBA::isResult($r)) {
6175 $success = ['success' => false, 'search_results' => 'problem with query'];
6176 } elseif (count($r) == 0) {
6177 $success = ['success' => false, 'search_results' => 'nothing found'];
6180 foreach ($r as $item) {
6181 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6182 $recipient = $user_info;
6183 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6184 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6185 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6186 $sender = $user_info;
6189 if (isset($recipient) && isset($sender)) {
6190 $ret[] = api_format_messages($item, $recipient, $sender);
6193 $success = ['success' => true, 'search_results' => $ret];
6196 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6199 /// @TODO move to top of file or somewhere better
6200 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6203 * @brief return data of all the profiles a user has to the client
6205 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6206 * @return string|array
6207 * @throws BadRequestException
6208 * @throws ForbiddenException
6209 * @throws ImagickException
6210 * @throws InternalServerErrorException
6211 * @throws UnauthorizedException
6213 function api_friendica_profile_show($type)
6217 if (api_user() === false) {
6218 throw new ForbiddenException();
6222 $profile_id = defaults($_REQUEST, 'profile_id', 0);
6224 // retrieve general information about profiles for user
6225 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6226 $directory = Config::get('system', 'directory');
6228 // get data of the specified profile id or all profiles of the user if not specified
6229 if ($profile_id != 0) {
6231 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
6236 // error message if specified gid is not in database
6237 if (!DBA::isResult($r)) {
6238 throw new BadRequestException("profile_id not available");
6242 "SELECT * FROM `profile` WHERE `uid` = %d",
6246 // loop through all returned profiles and retrieve data and users
6249 foreach ($r as $rr) {
6250 $profile = api_format_items_profiles($rr);
6252 // select all users from contact table, loop and prepare standard return for user data
6255 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
6260 foreach ($nurls as $nurl) {
6261 $user = api_get_user($a, $nurl['nurl']);
6262 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6264 $profile['users'] = $users;
6266 // add prepared profile data to array for final return
6267 if ($type == "xml") {
6268 $profiles[$k++ . ":profile"] = $profile;
6270 $profiles[] = $profile;
6274 // return settings, authenticated user and profiles data
6275 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6277 $result = ['multi_profiles' => $multi_profiles ? true : false,
6278 'global_dir' => $directory,
6279 'friendica_owner' => api_get_user($a, $self['nurl']),
6280 'profiles' => $profiles];
6281 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6283 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6286 * Returns a list of saved searches.
6288 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6290 * @param string $type Return format: json or xml
6292 * @return string|array
6295 function api_saved_searches_list($type)
6297 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6300 while ($term = $terms->fetch()) {
6302 'created_at' => api_date(time()),
6303 'id' => intval($term['id']),
6304 'id_str' => $term['id'],
6305 'name' => $term['term'],
6307 'query' => $term['term']
6313 return api_format_data("terms", $type, ['terms' => $result]);
6316 /// @TODO move to top of file or somewhere better
6317 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6320 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6322 * @brief Number of comments
6324 * @param object $data [Status, Status]
6328 function bindComments(&$data)
6330 if (count($data) == 0) {
6336 foreach ($data as $item) {
6337 $ids[] = $item['id'];
6340 $idStr = DBA::escape(implode(', ', $ids));
6341 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6342 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6343 $itemsData = DBA::toArray($items);
6345 foreach ($itemsData as $item) {
6346 $comments[$item['parent']] = $item['comments'];
6349 foreach ($data as $idx => $item) {
6351 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6356 @TODO Maybe open to implement?
6358 [pagename] => api/1.1/statuses/lookup.json
6359 [id] => 605138389168451584
6360 [include_cards] => true
6361 [cards_platform] => Android-12
6362 [include_entities] => true
6363 [include_my_retweet] => 1
6365 [include_reply_count] => true
6366 [include_descendent_reply_count] => true
6370 Not implemented by now:
6371 statuses/retweets_of_me
6376 account/update_location
6377 account/update_profile_background_image
6380 friendica/profile/update
6381 friendica/profile/create
6382 friendica/profile/delete
6384 Not implemented in status.net:
6385 statuses/retweeted_to_me
6386 statuses/retweeted_by_me
6387 direct_messages/destroy
6389 account/update_delivery_device
6390 notifications/follow