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 $a->getProfiler()->saveLog($a->getLogger(), API_LOG_PREFIX . 'performance');
331 if (false === $return) {
333 * api function returned false withour throw an
334 * exception. This should not happend, throw a 500
336 throw new InternalServerErrorException();
341 header("Content-Type: text/xml");
344 header("Content-Type: application/json");
345 $json = json_encode(end($return));
346 if (!empty($_GET['callback'])) {
347 $json = $_GET['callback'] . "(" . $json . ")";
352 header("Content-Type: application/rss+xml");
353 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
356 header("Content-Type: application/atom+xml");
357 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
364 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call']);
365 throw new NotImplementedException();
366 } catch (HTTPException $e) {
367 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
368 return api_error($type, $e);
373 * @brief Format API error string
375 * @param string $type Return type (xml, json, rss, as)
376 * @param object $e HTTPException Error object
377 * @return string|array error message formatted as $type
379 function api_error($type, $e)
383 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
384 /// @TODO: https://dev.twitter.com/overview/api/response-codes
386 $error = ["error" => $error,
387 "code" => $e->httpcode . " " . $e->httpdesc,
388 "request" => $a->query_string];
390 $return = api_format_data('status', $type, ['status' => $error]);
394 header("Content-Type: text/xml");
397 header("Content-Type: application/json");
398 $return = json_encode($return);
401 header("Content-Type: application/rss+xml");
404 header("Content-Type: application/atom+xml");
412 * @brief Set values for RSS template
415 * @param array $arr Array to be passed to template
416 * @param array $user_info User info
418 * @throws BadRequestException
419 * @throws ImagickException
420 * @throws InternalServerErrorException
421 * @throws UnauthorizedException
422 * @todo find proper type-hints
424 function api_rss_extra(App $a, $arr, $user_info)
426 if (is_null($user_info)) {
427 $user_info = api_get_user($a);
430 $arr['$user'] = $user_info;
432 'alternate' => $user_info['url'],
433 'self' => System::baseUrl() . "/" . $a->query_string,
434 'base' => System::baseUrl(),
435 'updated' => api_date(null),
436 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
437 'language' => $user_info['lang'],
438 'logo' => System::baseUrl() . "/images/friendica-32.png",
446 * @brief Unique contact to contact url.
448 * @param int $id Contact id
449 * @return bool|string
450 * Contact url or False if contact id is unknown
453 function api_unique_id_to_nurl($id)
455 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
457 if (DBA::isResult($r)) {
465 * @brief Get user info array.
468 * @param int|string $contact_id Contact ID or URL
470 * @throws BadRequestException
471 * @throws ImagickException
472 * @throws InternalServerErrorException
473 * @throws UnauthorizedException
475 function api_get_user(App $a, $contact_id = null)
483 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
485 // Searching for contact URL
486 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
487 $user = DBA::escape(Strings::normaliseLink($contact_id));
489 $extra_query = "AND `contact`.`nurl` = '%s' ";
490 if (api_user() !== false) {
491 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
495 // Searching for contact id with uid = 0
496 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
497 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
500 throw new BadRequestException("User ID ".$contact_id." not found.");
504 $extra_query = "AND `contact`.`nurl` = '%s' ";
505 if (api_user() !== false) {
506 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
510 if (is_null($user) && !empty($_GET['user_id'])) {
511 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
514 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
518 $extra_query = "AND `contact`.`nurl` = '%s' ";
519 if (api_user() !== false) {
520 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
523 if (is_null($user) && !empty($_GET['screen_name'])) {
524 $user = DBA::escape($_GET['screen_name']);
525 $extra_query = "AND `contact`.`nick` = '%s' ";
526 if (api_user() !== false) {
527 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
531 if (is_null($user) && !empty($_GET['profileurl'])) {
532 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
533 $extra_query = "AND `contact`.`nurl` = '%s' ";
534 if (api_user() !== false) {
535 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
539 // $called_api is the API path exploded on / and is expected to have at least 2 elements
540 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
541 $argid = count($called_api);
542 if (!empty($a->argv[$argid])) {
543 $data = explode(".", $a->argv[$argid]);
544 if (count($data) > 1) {
545 list($user, $null) = $data;
548 if (is_numeric($user)) {
549 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
553 $extra_query = "AND `contact`.`nurl` = '%s' ";
554 if (api_user() !== false) {
555 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
559 $user = DBA::escape($user);
560 $extra_query = "AND `contact`.`nick` = '%s' ";
561 if (api_user() !== false) {
562 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
567 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
570 if (api_user() === false) {
574 $user = $_SESSION['uid'];
575 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
579 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
583 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
589 // Selecting the id by priority, friendica first
590 if (is_array($uinfo)) {
591 api_best_nickname($uinfo);
594 // if the contact wasn't found, fetch it from the contacts with uid = 0
595 if (!DBA::isResult($uinfo)) {
597 throw new BadRequestException("User not found.");
600 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
602 if (DBA::isResult($contact)) {
603 // If no nick where given, extract it from the address
604 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
605 $contact['nick'] = api_get_nick($contact["url"]);
609 'id' => $contact["id"],
610 'id_str' => (string) $contact["id"],
611 'name' => $contact["name"],
612 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
613 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
614 'description' => $contact["about"],
615 'profile_image_url' => $contact["micro"],
616 'profile_image_url_https' => $contact["micro"],
617 'profile_image_url_profile_size' => $contact["thumb"],
618 'profile_image_url_large' => $contact["photo"],
619 'url' => $contact["url"],
620 'protected' => false,
621 'followers_count' => 0,
622 'friends_count' => 0,
624 'created_at' => api_date($contact["created"]),
625 'favourites_count' => 0,
627 'time_zone' => 'UTC',
628 'geo_enabled' => false,
630 'statuses_count' => 0,
632 'contributors_enabled' => false,
633 'is_translator' => false,
634 'is_translation_enabled' => false,
635 'following' => false,
636 'follow_request_sent' => false,
637 'statusnet_blocking' => false,
638 'notifications' => false,
639 'statusnet_profile_url' => $contact["url"],
641 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
642 'pid' => Contact::getIdForURL($contact["url"], 0, true),
644 'network' => $contact["network"],
649 throw new BadRequestException("User ".$url." not found.");
653 if ($uinfo[0]['self']) {
654 if ($uinfo[0]['network'] == "") {
655 $uinfo[0]['network'] = Protocol::DFRN;
658 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
659 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
666 // Add a nick if it isn't present there
667 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
668 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
671 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
673 if (!empty($profile['about'])) {
674 $description = $profile['about'];
676 $description = $uinfo[0]["about"];
679 if (!empty($usr['default-location'])) {
680 $location = $usr['default-location'];
681 } elseif (!empty($uinfo[0]["location"])) {
682 $location = $uinfo[0]["location"];
684 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
688 'id' => intval($pcontact_id),
689 'id_str' => (string) intval($pcontact_id),
690 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
691 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
692 'location' => $location,
693 'description' => $description,
694 'profile_image_url' => $uinfo[0]['micro'],
695 'profile_image_url_https' => $uinfo[0]['micro'],
696 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
697 'profile_image_url_large' => $uinfo[0]["photo"],
698 'url' => $uinfo[0]['url'],
699 'protected' => false,
700 'followers_count' => intval($countfollowers),
701 'friends_count' => intval($countfriends),
703 'created_at' => api_date($uinfo[0]['created']),
704 'favourites_count' => intval($starred),
706 'time_zone' => 'UTC',
707 'geo_enabled' => false,
709 'statuses_count' => intval($countitems),
711 'contributors_enabled' => false,
712 'is_translator' => false,
713 'is_translation_enabled' => false,
714 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
715 'follow_request_sent' => false,
716 'statusnet_blocking' => false,
717 'notifications' => false,
719 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
720 'statusnet_profile_url' => $uinfo[0]['url'],
721 'uid' => intval($uinfo[0]['uid']),
722 'cid' => intval($uinfo[0]['cid']),
723 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
724 'self' => $uinfo[0]['self'],
725 'network' => $uinfo[0]['network'],
728 // If this is a local user and it uses Frio, we can get its color preferences.
730 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
731 if ($theme_info['theme'] === 'frio') {
732 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
734 if ($schema && ($schema != '---')) {
735 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
736 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
737 require_once $schemefile;
740 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
741 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
742 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
744 if (empty($nav_bg)) {
747 if (empty($link_color)) {
748 $link_color = "#6fdbe8";
750 if (empty($bgcolor)) {
751 $bgcolor = "#ededed";
754 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
755 $ret['profile_link_color'] = str_replace('#', '', $link_color);
756 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
764 * @brief return api-formatted array for item's author and owner
767 * @param array $item item from db
768 * @return array(array:author, array:owner)
769 * @throws BadRequestException
770 * @throws ImagickException
771 * @throws InternalServerErrorException
772 * @throws UnauthorizedException
774 function api_item_get_user(App $a, $item)
776 $status_user = api_get_user($a, defaults($item, 'author-id', null));
778 $status_user["protected"] = defaults($item, 'private', 0);
780 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
781 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
783 $owner_user = $status_user;
786 return ([$status_user, $owner_user]);
790 * @brief walks recursively through an array with the possibility to change value and key
792 * @param array $array The array to walk through
793 * @param callable $callback The callback function
795 * @return array the transformed array
797 function api_walk_recursive(array &$array, callable $callback)
801 foreach ($array as $k => $v) {
803 if ($callback($v, $k)) {
804 $new_array[$k] = api_walk_recursive($v, $callback);
807 if ($callback($v, $k)) {
818 * @brief Callback function to transform the array in an array that can be transformed in a XML file
820 * @param mixed $item Array item value
821 * @param string $key Array key
823 * @return boolean Should the array item be deleted?
825 function api_reformat_xml(&$item, &$key)
827 if (is_bool($item)) {
828 $item = ($item ? "true" : "false");
831 if (substr($key, 0, 10) == "statusnet_") {
832 $key = "statusnet:".substr($key, 10);
833 } elseif (substr($key, 0, 10) == "friendica_") {
834 $key = "friendica:".substr($key, 10);
836 /// @TODO old-lost code?
838 // $key = "default:".$key;
844 * @brief Creates the XML from a JSON style array
846 * @param array $data JSON style array
847 * @param string $root_element Name of the root element
849 * @return string The XML data
851 function api_create_xml(array $data, $root_element)
853 $childname = key($data);
854 $data2 = array_pop($data);
856 $namespaces = ["" => "http://api.twitter.com",
857 "statusnet" => "http://status.net/schema/api/1/",
858 "friendica" => "http://friendi.ca/schema/api/1/",
859 "georss" => "http://www.georss.org/georss"];
861 /// @todo Auto detection of needed namespaces
862 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
866 if (is_array($data2)) {
868 api_walk_recursive($data2, "api_reformat_xml");
874 foreach ($data2 as $item) {
875 $data4[$i++ . ":" . $childname] = $item;
882 $data3 = [$root_element => $data2];
884 $ret = XML::fromArray($data3, $xml, false, $namespaces);
889 * @brief Formats the data according to the data type
891 * @param string $root_element Name of the root element
892 * @param string $type Return type (atom, rss, xml, json)
893 * @param array $data JSON style array
895 * @return array|string (string|array) XML data or JSON data
897 function api_format_data($root_element, $type, $data)
903 $ret = api_create_xml($data, $root_element);
918 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
919 * returns a 401 status code and an error message if not.
921 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
923 * @param string $type Return type (atom, rss, xml, json)
924 * @return array|string
925 * @throws BadRequestException
926 * @throws ForbiddenException
927 * @throws ImagickException
928 * @throws InternalServerErrorException
929 * @throws UnauthorizedException
931 function api_account_verify_credentials($type)
936 if (api_user() === false) {
937 throw new ForbiddenException();
940 unset($_REQUEST["user_id"]);
941 unset($_GET["user_id"]);
943 unset($_REQUEST["screen_name"]);
944 unset($_GET["screen_name"]);
946 $skip_status = defaults($_REQUEST, 'skip_status', false);
948 $user_info = api_get_user($a);
950 // "verified" isn't used here in the standard
951 unset($user_info["verified"]);
953 // - Adding last status
955 $user_info["status"] = api_status_show("raw");
956 if (!count($user_info["status"])) {
957 unset($user_info["status"]);
959 unset($user_info["status"]["user"]);
963 // "uid" and "self" are only needed for some internal stuff, so remove it from here
964 unset($user_info["uid"]);
965 unset($user_info["self"]);
967 return api_format_data("user", $type, ['user' => $user_info]);
970 /// @TODO move to top of file or somewhere better
971 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
974 * Get data from $_POST or $_GET
979 function requestdata($k)
981 if (!empty($_POST[$k])) {
984 if (!empty($_GET[$k])) {
991 * Deprecated function to upload media.
993 * @param string $type Return type (atom, rss, xml, json)
995 * @return array|string
996 * @throws BadRequestException
997 * @throws ForbiddenException
998 * @throws ImagickException
999 * @throws InternalServerErrorException
1000 * @throws UnauthorizedException
1002 function api_statuses_mediap($type)
1006 if (api_user() === false) {
1007 Logger::log('api_statuses_update: no user');
1008 throw new ForbiddenException();
1010 $user_info = api_get_user($a);
1012 $_REQUEST['profile_uid'] = api_user();
1013 $_REQUEST['api_source'] = true;
1014 $txt = requestdata('status');
1015 /// @TODO old-lost code?
1016 //$txt = urldecode(requestdata('status'));
1018 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1019 $txt = HTML::toBBCodeVideo($txt);
1020 $config = HTMLPurifier_Config::createDefault();
1021 $config->set('Cache.DefinitionImpl', null);
1022 $purifier = new HTMLPurifier($config);
1023 $txt = $purifier->purify($txt);
1025 $txt = HTML::toBBCode($txt);
1027 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1029 $picture = wall_upload_post($a, false);
1031 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1032 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1033 $item_id = item_post($a);
1035 // output the post that we just posted.
1036 return api_status_show($type, $item_id);
1039 /// @TODO move this to top of file or somewhere better!
1040 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1043 * Updates the user’s current status.
1045 * @param string $type Return type (atom, rss, xml, json)
1047 * @return array|string
1048 * @throws BadRequestException
1049 * @throws ForbiddenException
1050 * @throws ImagickException
1051 * @throws InternalServerErrorException
1052 * @throws TooManyRequestsException
1053 * @throws UnauthorizedException
1054 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1056 function api_statuses_update($type)
1060 if (api_user() === false) {
1061 Logger::log('api_statuses_update: no user');
1062 throw new ForbiddenException();
1067 // convert $_POST array items to the form we use for web posts.
1068 if (requestdata('htmlstatus')) {
1069 $txt = requestdata('htmlstatus');
1070 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1071 $txt = HTML::toBBCodeVideo($txt);
1073 $config = HTMLPurifier_Config::createDefault();
1074 $config->set('Cache.DefinitionImpl', null);
1076 $purifier = new HTMLPurifier($config);
1077 $txt = $purifier->purify($txt);
1079 $_REQUEST['body'] = HTML::toBBCode($txt);
1082 $_REQUEST['body'] = requestdata('status');
1085 $_REQUEST['title'] = requestdata('title');
1087 $parent = requestdata('in_reply_to_status_id');
1089 // Twidere sends "-1" if it is no reply ...
1090 if ($parent == -1) {
1094 if (ctype_digit($parent)) {
1095 $_REQUEST['parent'] = $parent;
1097 $_REQUEST['parent_uri'] = $parent;
1100 if (requestdata('lat') && requestdata('long')) {
1101 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1103 $_REQUEST['profile_uid'] = api_user();
1106 // Check for throttling (maximum posts per day, week and month)
1107 $throttle_day = Config::get('system', 'throttle_limit_day');
1108 if ($throttle_day > 0) {
1109 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1111 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1112 $posts_day = DBA::count('thread', $condition);
1114 if ($posts_day > $throttle_day) {
1115 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1116 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1117 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));
1121 $throttle_week = Config::get('system', 'throttle_limit_week');
1122 if ($throttle_week > 0) {
1123 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1125 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1126 $posts_week = DBA::count('thread', $condition);
1128 if ($posts_week > $throttle_week) {
1129 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1130 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1131 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));
1135 $throttle_month = Config::get('system', 'throttle_limit_month');
1136 if ($throttle_month > 0) {
1137 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1139 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1140 $posts_month = DBA::count('thread', $condition);
1142 if ($posts_month > $throttle_month) {
1143 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1144 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1145 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));
1150 if (!empty($_FILES['media'])) {
1151 // upload the image if we have one
1152 $picture = wall_upload_post($a, false);
1153 if (is_array($picture)) {
1154 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1158 // To-Do: Multiple IDs
1159 if (requestdata('media_ids')) {
1161 "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",
1162 intval(requestdata('media_ids')),
1165 if (DBA::isResult($r)) {
1166 $phototypes = Image::supportedTypes();
1167 $ext = $phototypes[$r[0]['type']];
1168 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1169 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1173 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1175 $_REQUEST['api_source'] = true;
1177 if (empty($_REQUEST['source'])) {
1178 $_REQUEST["source"] = api_source();
1181 // call out normal post function
1182 $item_id = item_post($a);
1184 // output the post that we just posted.
1185 return api_status_show($type, $item_id);
1188 /// @TODO move to top of file or somewhere better
1189 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1190 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1193 * Uploads an image to Friendica.
1196 * @throws BadRequestException
1197 * @throws ForbiddenException
1198 * @throws ImagickException
1199 * @throws InternalServerErrorException
1200 * @throws UnauthorizedException
1201 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1203 function api_media_upload()
1207 if (api_user() === false) {
1208 Logger::log('no user');
1209 throw new ForbiddenException();
1214 if (empty($_FILES['media'])) {
1216 throw new BadRequestException("No media.");
1219 $media = wall_upload_post($a, false);
1222 throw new InternalServerErrorException();
1226 $returndata["media_id"] = $media["id"];
1227 $returndata["media_id_string"] = (string)$media["id"];
1228 $returndata["size"] = $media["size"];
1229 $returndata["image"] = ["w" => $media["width"],
1230 "h" => $media["height"],
1231 "image_type" => $media["type"],
1232 "friendica_preview_url" => $media["preview"]];
1234 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1236 return ["media" => $returndata];
1239 /// @TODO move to top of file or somewhere better
1240 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1244 * @param string $type Return type (atom, rss, xml, json)
1246 * @param int $item_id
1247 * @return array|string
1248 * @throws BadRequestException
1249 * @throws ImagickException
1250 * @throws InternalServerErrorException
1251 * @throws UnauthorizedException
1253 function api_status_show($type, $item_id = 0)
1257 $user_info = api_get_user($a);
1259 Logger::log('api_status_show: user_info: '.print_r($user_info, true), Logger::DEBUG);
1261 if (!empty($item_id)) {
1262 // Get the item with the given id
1263 $condition = ['id' => $item_id];
1265 // get last public wall message
1266 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1267 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1270 if ($type == "raw") {
1271 $condition['private'] = false;
1274 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1276 if (DBA::isResult($lastwall)) {
1277 $in_reply_to = api_in_reply_to($lastwall);
1279 $converted = api_convert_item($lastwall);
1281 if ($type == "xml") {
1282 $geo = "georss:point";
1288 'created_at' => api_date($lastwall['created']),
1289 'id' => intval($lastwall['id']),
1290 'id_str' => (string) $lastwall['id'],
1291 'text' => $converted["text"],
1292 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1293 'truncated' => false,
1294 'in_reply_to_status_id' => $in_reply_to['status_id'],
1295 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1296 'in_reply_to_user_id' => $in_reply_to['user_id'],
1297 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1298 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1299 'user' => $user_info,
1301 'coordinates' => '',
1303 'contributors' => '',
1304 'is_quote_status' => false,
1305 'retweet_count' => 0,
1306 'favorite_count' => 0,
1307 'favorited' => $lastwall['starred'] ? true : false,
1308 'retweeted' => false,
1309 'possibly_sensitive' => false,
1311 'statusnet_html' => $converted["html"],
1312 'statusnet_conversation_id' => $lastwall['parent'],
1313 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
1316 if (count($converted["attachments"]) > 0) {
1317 $status_info["attachments"] = $converted["attachments"];
1320 if (count($converted["entities"]) > 0) {
1321 $status_info["entities"] = $converted["entities"];
1324 if ($status_info["source"] == 'web') {
1325 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1326 } elseif (ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) != $status_info["source"]) {
1327 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']).')');
1330 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1331 unset($status_info["user"]["uid"]);
1332 unset($status_info["user"]["self"]);
1334 Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
1336 if ($type == "raw") {
1337 return $status_info;
1340 return api_format_data("statuses", $type, ['status' => $status_info]);
1345 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1346 * The author's most recent status will be returned inline.
1348 * @param string $type Return type (atom, rss, xml, json)
1349 * @return array|string
1350 * @throws BadRequestException
1351 * @throws ImagickException
1352 * @throws InternalServerErrorException
1353 * @throws UnauthorizedException
1354 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1356 function api_users_show($type)
1360 $user_info = api_get_user($a);
1362 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1363 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1364 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1366 if (DBA::isResult($lastwall)) {
1367 $in_reply_to = api_in_reply_to($lastwall);
1369 $converted = api_convert_item($lastwall);
1371 if ($type == "xml") {
1372 $geo = "georss:point";
1377 $user_info['status'] = [
1378 'text' => $converted["text"],
1379 'truncated' => false,
1380 'created_at' => api_date($lastwall['created']),
1381 'in_reply_to_status_id' => $in_reply_to['status_id'],
1382 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1383 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1384 'id' => intval($lastwall['contact-id']),
1385 'id_str' => (string) $lastwall['contact-id'],
1386 'in_reply_to_user_id' => $in_reply_to['user_id'],
1387 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1388 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1390 'favorited' => $lastwall['starred'] ? true : false,
1391 'statusnet_html' => $converted["html"],
1392 'statusnet_conversation_id' => $lastwall['parent'],
1393 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1396 if (count($converted["attachments"]) > 0) {
1397 $user_info["status"]["attachments"] = $converted["attachments"];
1400 if (count($converted["entities"]) > 0) {
1401 $user_info["status"]["entities"] = $converted["entities"];
1404 if ($user_info["status"]["source"] == 'web') {
1405 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1408 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1409 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) . ')');
1413 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1414 unset($user_info["uid"]);
1415 unset($user_info["self"]);
1417 return api_format_data("user", $type, ['user' => $user_info]);
1420 /// @TODO move to top of file or somewhere better
1421 api_register_func('api/users/show', 'api_users_show');
1422 api_register_func('api/externalprofile/show', 'api_users_show');
1425 * Search a public user account.
1427 * @param string $type Return type (atom, rss, xml, json)
1429 * @return array|string
1430 * @throws BadRequestException
1431 * @throws ImagickException
1432 * @throws InternalServerErrorException
1433 * @throws UnauthorizedException
1434 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1436 function api_users_search($type)
1442 if (!empty($_GET['q'])) {
1443 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1445 if (!DBA::isResult($r)) {
1446 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1449 if (DBA::isResult($r)) {
1451 foreach ($r as $user) {
1452 $user_info = api_get_user($a, $user["id"]);
1454 if ($type == "xml") {
1455 $userlist[$k++.":user"] = $user_info;
1457 $userlist[] = $user_info;
1460 $userlist = ["users" => $userlist];
1462 throw new BadRequestException("User ".$_GET["q"]." not found.");
1465 throw new BadRequestException("No user specified.");
1468 return api_format_data("users", $type, $userlist);
1471 /// @TODO move to top of file or somewhere better
1472 api_register_func('api/users/search', 'api_users_search');
1475 * Return user objects
1477 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1479 * @param string $type Return format: json or xml
1481 * @return array|string
1482 * @throws BadRequestException
1483 * @throws ImagickException
1484 * @throws InternalServerErrorException
1485 * @throws NotFoundException if the results are empty.
1486 * @throws UnauthorizedException
1488 function api_users_lookup($type)
1492 if (!empty($_REQUEST['user_id'])) {
1493 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1495 $users[] = api_get_user(get_app(), $id);
1500 if (empty($users)) {
1501 throw new NotFoundException;
1504 return api_format_data("users", $type, ['users' => $users]);
1507 /// @TODO move to top of file or somewhere better
1508 api_register_func('api/users/lookup', 'api_users_lookup', true);
1511 * Returns statuses that match a specified query.
1513 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1515 * @param string $type Return format: json, xml, atom, rss
1517 * @return array|string
1518 * @throws BadRequestException if the "q" parameter is missing.
1519 * @throws ForbiddenException
1520 * @throws ImagickException
1521 * @throws InternalServerErrorException
1522 * @throws UnauthorizedException
1524 function api_search($type)
1527 $user_info = api_get_user($a);
1529 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1531 if (empty($_REQUEST['q'])) {
1532 throw new BadRequestException('q parameter is required.');
1535 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1538 $data['status'] = [];
1540 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1541 if (!empty($_REQUEST['rpp'])) {
1542 $count = $_REQUEST['rpp'];
1543 } elseif (!empty($_REQUEST['count'])) {
1544 $count = $_REQUEST['count'];
1547 $since_id = defaults($_REQUEST, 'since_id', 0);
1548 $max_id = defaults($_REQUEST, 'max_id', 0);
1549 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1550 $start = $page * $count;
1551 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1552 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1553 $searchTerm = $matches[1];
1554 $condition = ["`oid` > ?
1555 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1556 AND `otype` = ? AND `type` = ? AND `term` = ?",
1557 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1559 $condition[0] .= ' AND `oid` <= ?';
1560 $condition[] = $max_id;
1562 $terms = DBA::select('term', ['oid'], $condition, []);
1564 while ($term = DBA::fetch($terms)) {
1565 $itemIds[] = $term['oid'];
1569 if (empty($itemIds)) {
1570 return api_format_data('statuses', $type, $data);
1573 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1574 if ($exclude_replies) {
1575 $preCondition[] = '`id` = `parent`';
1578 $condition = [implode(' AND ', $preCondition)];
1580 $condition = ["`id` > ?
1581 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1582 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1583 AND `body` LIKE CONCAT('%',?,'%')",
1584 $since_id, api_user(), $_REQUEST['q']];
1586 $condition[0] .= ' AND `id` <= ?';
1587 $condition[] = $max_id;
1591 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1593 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1595 bindComments($data['status']);
1597 return api_format_data('statuses', $type, $data);
1600 /// @TODO move to top of file or somewhere better
1601 api_register_func('api/search/tweets', 'api_search', true);
1602 api_register_func('api/search', 'api_search', true);
1605 * Returns the most recent statuses posted by the user and the users they follow.
1607 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1609 * @param string $type Return type (atom, rss, xml, json)
1611 * @return array|string
1612 * @throws BadRequestException
1613 * @throws ForbiddenException
1614 * @throws ImagickException
1615 * @throws InternalServerErrorException
1616 * @throws UnauthorizedException
1617 * @todo Optional parameters
1618 * @todo Add reply info
1620 function api_statuses_home_timeline($type)
1623 $user_info = api_get_user($a);
1625 if (api_user() === false || $user_info === false) {
1626 throw new ForbiddenException();
1629 unset($_REQUEST["user_id"]);
1630 unset($_GET["user_id"]);
1632 unset($_REQUEST["screen_name"]);
1633 unset($_GET["screen_name"]);
1635 // get last network messages
1638 $count = defaults($_REQUEST, 'count', 20);
1639 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1643 $since_id = defaults($_REQUEST, 'since_id', 0);
1644 $max_id = defaults($_REQUEST, 'max_id', 0);
1645 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1646 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1648 $start = $page * $count;
1650 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1651 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1654 $condition[0] .= " AND `item`.`id` <= ?";
1655 $condition[] = $max_id;
1657 if ($exclude_replies) {
1658 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1660 if ($conversation_id > 0) {
1661 $condition[0] .= " AND `item`.`parent` = ?";
1662 $condition[] = $conversation_id;
1665 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1666 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1668 $items = Item::inArray($statuses);
1670 $ret = api_format_items($items, $user_info, false, $type);
1672 // Set all posts from the query above to seen
1674 foreach ($items as $item) {
1675 $idarray[] = intval($item["id"]);
1678 if (!empty($idarray)) {
1679 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1681 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1687 $data = ['status' => $ret];
1692 $data = api_rss_extra($a, $data, $user_info);
1696 return api_format_data("statuses", $type, $data);
1700 /// @TODO move to top of file or somewhere better
1701 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1702 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1705 * Returns the most recent statuses from public users.
1707 * @param string $type Return type (atom, rss, xml, json)
1709 * @return array|string
1710 * @throws BadRequestException
1711 * @throws ForbiddenException
1712 * @throws ImagickException
1713 * @throws InternalServerErrorException
1714 * @throws UnauthorizedException
1716 function api_statuses_public_timeline($type)
1719 $user_info = api_get_user($a);
1721 if (api_user() === false || $user_info === false) {
1722 throw new ForbiddenException();
1725 // get last network messages
1728 $count = defaults($_REQUEST, 'count', 20);
1729 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1733 $since_id = defaults($_REQUEST, 'since_id', 0);
1734 $max_id = defaults($_REQUEST, 'max_id', 0);
1735 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1736 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1738 $start = $page * $count;
1740 if ($exclude_replies && !$conversation_id) {
1741 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1742 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1745 $condition[0] .= " AND `thread`.`iid` <= ?";
1746 $condition[] = $max_id;
1749 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1750 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1752 $r = Item::inArray($statuses);
1754 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1755 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1758 $condition[0] .= " AND `item`.`id` <= ?";
1759 $condition[] = $max_id;
1761 if ($conversation_id > 0) {
1762 $condition[0] .= " AND `item`.`parent` = ?";
1763 $condition[] = $conversation_id;
1766 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1767 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1769 $r = Item::inArray($statuses);
1772 $ret = api_format_items($r, $user_info, false, $type);
1776 $data = ['status' => $ret];
1781 $data = api_rss_extra($a, $data, $user_info);
1785 return api_format_data("statuses", $type, $data);
1788 /// @TODO move to top of file or somewhere better
1789 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1792 * Returns the most recent statuses posted by users this node knows about.
1794 * @brief Returns the list of public federated posts this node knows about
1796 * @param string $type Return format: json, xml, atom, rss
1797 * @return array|string
1798 * @throws BadRequestException
1799 * @throws ForbiddenException
1800 * @throws ImagickException
1801 * @throws InternalServerErrorException
1802 * @throws UnauthorizedException
1804 function api_statuses_networkpublic_timeline($type)
1807 $user_info = api_get_user($a);
1809 if (api_user() === false || $user_info === false) {
1810 throw new ForbiddenException();
1813 $since_id = defaults($_REQUEST, 'since_id', 0);
1814 $max_id = defaults($_REQUEST, 'max_id', 0);
1817 $count = defaults($_REQUEST, 'count', 20);
1818 $page = defaults($_REQUEST, 'page', 1);
1822 $start = ($page - 1) * $count;
1824 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1825 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1828 $condition[0] .= " AND `thread`.`iid` <= ?";
1829 $condition[] = $max_id;
1832 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1833 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1835 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1839 $data = ['status' => $ret];
1844 $data = api_rss_extra($a, $data, $user_info);
1848 return api_format_data("statuses", $type, $data);
1851 /// @TODO move to top of file or somewhere better
1852 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1855 * Returns a single status.
1857 * @param string $type Return type (atom, rss, xml, json)
1859 * @return array|string
1860 * @throws BadRequestException
1861 * @throws ForbiddenException
1862 * @throws ImagickException
1863 * @throws InternalServerErrorException
1864 * @throws UnauthorizedException
1865 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1867 function api_statuses_show($type)
1870 $user_info = api_get_user($a);
1872 if (api_user() === false || $user_info === false) {
1873 throw new ForbiddenException();
1877 $id = intval(defaults($a->argv, 3, 0));
1880 $id = intval(defaults($_REQUEST, 'id', 0));
1885 $id = intval(defaults($a->argv, 4, 0));
1888 Logger::log('API: api_statuses_show: ' . $id);
1890 $conversation = !empty($_REQUEST['conversation']);
1892 // try to fetch the item for the local user - or the public item, if there is no local one
1893 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1894 if (!DBA::isResult($uri_item)) {
1895 throw new BadRequestException("There is no status with this id.");
1898 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1899 if (!DBA::isResult($item)) {
1900 throw new BadRequestException("There is no status with this id.");
1905 if ($conversation) {
1906 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1907 $params = ['order' => ['id' => true]];
1909 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1913 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1915 /// @TODO How about copying this to above methods which don't check $r ?
1916 if (!DBA::isResult($statuses)) {
1917 throw new BadRequestException("There is no status with this id.");
1920 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1922 if ($conversation) {
1923 $data = ['status' => $ret];
1924 return api_format_data("statuses", $type, $data);
1926 $data = ['status' => $ret[0]];
1927 return api_format_data("status", $type, $data);
1931 /// @TODO move to top of file or somewhere better
1932 api_register_func('api/statuses/show', 'api_statuses_show', true);
1936 * @param string $type Return type (atom, rss, xml, json)
1938 * @return array|string
1939 * @throws BadRequestException
1940 * @throws ForbiddenException
1941 * @throws ImagickException
1942 * @throws InternalServerErrorException
1943 * @throws UnauthorizedException
1944 * @todo nothing to say?
1946 function api_conversation_show($type)
1949 $user_info = api_get_user($a);
1951 if (api_user() === false || $user_info === false) {
1952 throw new ForbiddenException();
1956 $id = intval(defaults($a->argv , 3 , 0));
1957 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1958 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1959 $count = intval(defaults($_REQUEST, 'count' , 20));
1960 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1965 $start = $page * $count;
1968 $id = intval(defaults($_REQUEST, 'id', 0));
1973 $id = intval(defaults($a->argv, 4, 0));
1976 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1978 // try to fetch the item for the local user - or the public item, if there is no local one
1979 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1980 if (!DBA::isResult($item)) {
1981 throw new BadRequestException("There is no status with this id.");
1984 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1985 if (!DBA::isResult($parent)) {
1986 throw new BadRequestException("There is no status with this id.");
1989 $id = $parent['id'];
1991 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1992 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1995 $condition[0] .= " AND `item`.`id` <= ?";
1996 $condition[] = $max_id;
1999 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2000 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2002 if (!DBA::isResult($statuses)) {
2003 throw new BadRequestException("There is no status with id $id.");
2006 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2008 $data = ['status' => $ret];
2009 return api_format_data("statuses", $type, $data);
2012 /// @TODO move to top of file or somewhere better
2013 api_register_func('api/conversation/show', 'api_conversation_show', true);
2014 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2019 * @param string $type Return type (atom, rss, xml, json)
2021 * @return array|string
2022 * @throws BadRequestException
2023 * @throws ForbiddenException
2024 * @throws ImagickException
2025 * @throws InternalServerErrorException
2026 * @throws UnauthorizedException
2027 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2029 function api_statuses_repeat($type)
2035 if (api_user() === false) {
2036 throw new ForbiddenException();
2042 $id = intval(defaults($a->argv, 3, 0));
2045 $id = intval(defaults($_REQUEST, 'id', 0));
2050 $id = intval(defaults($a->argv, 4, 0));
2053 Logger::log('API: api_statuses_repeat: '.$id);
2055 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2056 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2058 if (DBA::isResult($item) && $item['body'] != "") {
2059 if (strpos($item['body'], "[/share]") !== false) {
2060 $pos = strpos($item['body'], "[share");
2061 $post = substr($item['body'], $pos);
2063 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2065 $post .= $item['body'];
2066 $post .= "[/share]";
2068 $_REQUEST['body'] = $post;
2069 $_REQUEST['profile_uid'] = api_user();
2070 $_REQUEST['api_source'] = true;
2072 if (empty($_REQUEST['source'])) {
2073 $_REQUEST["source"] = api_source();
2076 $item_id = item_post($a);
2078 throw new ForbiddenException();
2081 // output the post that we just posted.
2083 return api_status_show($type, $item_id);
2086 /// @TODO move to top of file or somewhere better
2087 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2090 * Destroys a specific status.
2092 * @param string $type Return type (atom, rss, xml, json)
2094 * @return array|string
2095 * @throws BadRequestException
2096 * @throws ForbiddenException
2097 * @throws ImagickException
2098 * @throws InternalServerErrorException
2099 * @throws UnauthorizedException
2100 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2102 function api_statuses_destroy($type)
2106 if (api_user() === false) {
2107 throw new ForbiddenException();
2113 $id = intval(defaults($a->argv, 3, 0));
2116 $id = intval(defaults($_REQUEST, 'id', 0));
2121 $id = intval(defaults($a->argv, 4, 0));
2124 Logger::log('API: api_statuses_destroy: '.$id);
2126 $ret = api_statuses_show($type);
2128 Item::deleteForUser(['id' => $id], api_user());
2133 /// @TODO move to top of file or somewhere better
2134 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2137 * Returns the most recent mentions.
2139 * @param string $type Return type (atom, rss, xml, json)
2141 * @return array|string
2142 * @throws BadRequestException
2143 * @throws ForbiddenException
2144 * @throws ImagickException
2145 * @throws InternalServerErrorException
2146 * @throws UnauthorizedException
2147 * @see http://developer.twitter.com/doc/get/statuses/mentions
2149 function api_statuses_mentions($type)
2152 $user_info = api_get_user($a);
2154 if (api_user() === false || $user_info === false) {
2155 throw new ForbiddenException();
2158 unset($_REQUEST["user_id"]);
2159 unset($_GET["user_id"]);
2161 unset($_REQUEST["screen_name"]);
2162 unset($_GET["screen_name"]);
2164 // get last network messages
2167 $since_id = defaults($_REQUEST, 'since_id', 0);
2168 $max_id = defaults($_REQUEST, 'max_id' , 0);
2169 $count = defaults($_REQUEST, 'count' , 20);
2170 $page = defaults($_REQUEST, 'page' , 1);
2175 $start = ($page - 1) * $count;
2177 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2178 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2179 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2182 $condition[0] .= " AND `item`.`id` <= ?";
2183 $condition[] = $max_id;
2186 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2187 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2189 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2191 $data = ['status' => $ret];
2196 $data = api_rss_extra($a, $data, $user_info);
2200 return api_format_data("statuses", $type, $data);
2203 /// @TODO move to top of file or somewhere better
2204 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2205 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2208 * Returns the most recent statuses posted by the user.
2210 * @brief Returns a user's public timeline
2212 * @param string $type Either "json" or "xml"
2213 * @return string|array
2214 * @throws BadRequestException
2215 * @throws ForbiddenException
2216 * @throws ImagickException
2217 * @throws InternalServerErrorException
2218 * @throws UnauthorizedException
2219 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2221 function api_statuses_user_timeline($type)
2224 $user_info = api_get_user($a);
2226 if (api_user() === false || $user_info === false) {
2227 throw new ForbiddenException();
2231 "api_statuses_user_timeline: api_user: ". api_user() .
2232 "\nuser_info: ".print_r($user_info, true) .
2233 "\n_REQUEST: ".print_r($_REQUEST, true),
2237 $since_id = defaults($_REQUEST, 'since_id', 0);
2238 $max_id = defaults($_REQUEST, 'max_id', 0);
2239 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2240 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2243 $count = defaults($_REQUEST, 'count', 20);
2244 $page = defaults($_REQUEST, 'page', 1);
2248 $start = ($page - 1) * $count;
2250 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2251 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2253 if ($user_info['self'] == 1) {
2254 $condition[0] .= ' AND `item`.`wall` ';
2257 if ($exclude_replies) {
2258 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2261 if ($conversation_id > 0) {
2262 $condition[0] .= " AND `item`.`parent` = ?";
2263 $condition[] = $conversation_id;
2267 $condition[0] .= " AND `item`.`id` <= ?";
2268 $condition[] = $max_id;
2271 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2272 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2274 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2278 $data = ['status' => $ret];
2283 $data = api_rss_extra($a, $data, $user_info);
2287 return api_format_data("statuses", $type, $data);
2290 /// @TODO move to top of file or somewhere better
2291 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2294 * Star/unstar an item.
2295 * param: id : id of the item
2297 * @param string $type Return type (atom, rss, xml, json)
2299 * @return array|string
2300 * @throws BadRequestException
2301 * @throws ForbiddenException
2302 * @throws ImagickException
2303 * @throws InternalServerErrorException
2304 * @throws UnauthorizedException
2305 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2307 function api_favorites_create_destroy($type)
2311 if (api_user() === false) {
2312 throw new ForbiddenException();
2315 // for versioned api.
2316 /// @TODO We need a better global soluton
2317 $action_argv_id = 2;
2318 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2319 $action_argv_id = 3;
2322 if ($a->argc <= $action_argv_id) {
2323 throw new BadRequestException("Invalid request.");
2325 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2326 if ($a->argc == $action_argv_id + 2) {
2327 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2329 $itemid = intval(defaults($_REQUEST, 'id', 0));
2332 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2334 if (!DBA::isResult($item)) {
2335 throw new BadRequestException("Invalid item.");
2340 $item['starred'] = 1;
2343 $item['starred'] = 0;
2346 throw new BadRequestException("Invalid action ".$action);
2349 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2352 throw new InternalServerErrorException("DB error");
2356 $user_info = api_get_user($a);
2357 $rets = api_format_items([$item], $user_info, false, $type);
2360 $data = ['status' => $ret];
2365 $data = api_rss_extra($a, $data, $user_info);
2369 return api_format_data("status", $type, $data);
2372 /// @TODO move to top of file or somewhere better
2373 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2374 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2377 * Returns the most recent favorite statuses.
2379 * @param string $type Return type (atom, rss, xml, json)
2381 * @return string|array
2382 * @throws BadRequestException
2383 * @throws ForbiddenException
2384 * @throws ImagickException
2385 * @throws InternalServerErrorException
2386 * @throws UnauthorizedException
2388 function api_favorites($type)
2393 $user_info = api_get_user($a);
2395 if (api_user() === false || $user_info === false) {
2396 throw new ForbiddenException();
2401 // in friendica starred item are private
2402 // return favorites only for self
2403 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2405 if ($user_info['self'] == 0) {
2409 $since_id = defaults($_REQUEST, 'since_id', 0);
2410 $max_id = defaults($_REQUEST, 'max_id', 0);
2411 $count = defaults($_GET, 'count', 20);
2412 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2417 $start = $page*$count;
2419 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2420 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2422 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2425 $condition[0] .= " AND `item`.`id` <= ?";
2426 $condition[] = $max_id;
2429 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2431 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2436 $data = ['status' => $ret];
2441 $data = api_rss_extra($a, $data, $user_info);
2445 return api_format_data("statuses", $type, $data);
2448 /// @TODO move to top of file or somewhere better
2449 api_register_func('api/favorites', 'api_favorites', true);
2453 * @param array $item
2454 * @param array $recipient
2455 * @param array $sender
2458 * @throws InternalServerErrorException
2460 function api_format_messages($item, $recipient, $sender)
2462 // standard meta information
2464 'id' => $item['id'],
2465 'sender_id' => $sender['id'],
2467 'recipient_id' => $recipient['id'],
2468 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2469 'sender_screen_name' => $sender['screen_name'],
2470 'recipient_screen_name' => $recipient['screen_name'],
2471 'sender' => $sender,
2472 'recipient' => $recipient,
2474 'friendica_seen' => defaults($item, 'seen', 0),
2475 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2478 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2479 if (isset($ret['sender']['uid'])) {
2480 unset($ret['sender']['uid']);
2482 if (isset($ret['sender']['self'])) {
2483 unset($ret['sender']['self']);
2485 if (isset($ret['recipient']['uid'])) {
2486 unset($ret['recipient']['uid']);
2488 if (isset($ret['recipient']['self'])) {
2489 unset($ret['recipient']['self']);
2492 //don't send title to regular StatusNET requests to avoid confusing these apps
2493 if (!empty($_GET['getText'])) {
2494 $ret['title'] = $item['title'];
2495 if ($_GET['getText'] == 'html') {
2496 $ret['text'] = BBCode::convert($item['body'], false);
2497 } elseif ($_GET['getText'] == 'plain') {
2498 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2501 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2503 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2504 unset($ret['sender']);
2505 unset($ret['recipient']);
2513 * @param array $item
2516 * @throws InternalServerErrorException
2518 function api_convert_item($item)
2520 $body = $item['body'];
2521 $attachments = api_get_attachments($body);
2523 // Workaround for ostatus messages where the title is identically to the body
2524 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2525 $statusbody = trim(HTML::toPlaintext($html, 0));
2527 // handle data: images
2528 $statusbody = api_format_items_embeded_images($item, $statusbody);
2530 $statustitle = trim($item['title']);
2532 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2533 $statustext = trim($statusbody);
2535 $statustext = trim($statustitle."\n\n".$statusbody);
2538 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2539 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2542 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2544 // Workaround for clients with limited HTML parser functionality
2545 $search = ["<br>", "<blockquote>", "</blockquote>",
2546 "<h1>", "</h1>", "<h2>", "</h2>",
2547 "<h3>", "</h3>", "<h4>", "</h4>",
2548 "<h5>", "</h5>", "<h6>", "</h6>"];
2549 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2550 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2551 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2552 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2553 $statushtml = str_replace($search, $replace, $statushtml);
2555 if ($item['title'] != "") {
2556 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2560 $oldtext = $statushtml;
2561 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2562 } while ($oldtext != $statushtml);
2564 if (substr($statushtml, 0, 4) == '<br>') {
2565 $statushtml = substr($statushtml, 4);
2568 if (substr($statushtml, 0, -4) == '<br>') {
2569 $statushtml = substr($statushtml, -4);
2572 // feeds without body should contain the link
2573 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2574 $statushtml .= BBCode::convert($item['plink']);
2577 $entities = api_get_entitities($statustext, $body);
2580 "text" => $statustext,
2581 "html" => $statushtml,
2582 "attachments" => $attachments,
2583 "entities" => $entities
2589 * @param string $body
2592 * @throws InternalServerErrorException
2594 function api_get_attachments(&$body)
2597 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2599 $URLSearchString = "^\[\]";
2600 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2608 foreach ($images[1] as $image) {
2609 $imagedata = Image::getInfoFromURL($image);
2612 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2616 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2617 foreach ($images[0] as $orig) {
2618 $body = str_replace($orig, "", $body);
2622 return $attachments;
2627 * @param string $text
2628 * @param string $bbcode
2631 * @throws InternalServerErrorException
2632 * @todo Links at the first character of the post
2634 function api_get_entitities(&$text, $bbcode)
2636 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2638 if ($include_entities != "true") {
2639 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2641 foreach ($images[1] as $image) {
2642 $replace = ProxyUtils::proxifyUrl($image);
2643 $text = str_replace($image, $replace, $text);
2648 $bbcode = BBCode::cleanPictureLinks($bbcode);
2650 // Change pure links in text to bbcode uris
2651 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2654 $entities["hashtags"] = [];
2655 $entities["symbols"] = [];
2656 $entities["urls"] = [];
2657 $entities["user_mentions"] = [];
2659 $URLSearchString = "^\[\]";
2661 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2663 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2664 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2665 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2667 $bbcode = preg_replace(
2668 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2669 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2672 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2674 $bbcode = preg_replace(
2675 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2676 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2679 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2681 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2683 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2684 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2687 foreach ($urls[1] as $id => $url) {
2688 //$start = strpos($text, $url, $offset);
2689 $start = iconv_strpos($text, $url, 0, "UTF-8");
2690 if (!($start === false)) {
2691 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2695 ksort($ordered_urls);
2698 //foreach ($urls[1] AS $id=>$url) {
2699 foreach ($ordered_urls as $url) {
2700 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2701 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2703 $display_url = $url["title"];
2705 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2706 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2708 if (strlen($display_url) > 26) {
2709 $display_url = substr($display_url, 0, 25)."…";
2713 //$start = strpos($text, $url, $offset);
2714 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2715 if (!($start === false)) {
2716 $entities["urls"][] = ["url" => $url["url"],
2717 "expanded_url" => $url["url"],
2718 "display_url" => $display_url,
2719 "indices" => [$start, $start+strlen($url["url"])]];
2720 $offset = $start + 1;
2724 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2725 $ordered_images = [];
2726 foreach ($images[1] as $image) {
2727 //$start = strpos($text, $url, $offset);
2728 $start = iconv_strpos($text, $image, 0, "UTF-8");
2729 if (!($start === false)) {
2730 $ordered_images[$start] = $image;
2733 //$entities["media"] = array();
2736 foreach ($ordered_images as $url) {
2737 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2738 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2740 if (strlen($display_url) > 26) {
2741 $display_url = substr($display_url, 0, 25)."…";
2744 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2745 if (!($start === false)) {
2746 $image = Image::getInfoFromURL($url);
2748 // If image cache is activated, then use the following sizes:
2749 // thumb (150), small (340), medium (600) and large (1024)
2750 if (!Config::get("system", "proxy_disabled")) {
2751 $media_url = ProxyUtils::proxifyUrl($url);
2754 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2755 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2757 if (($image[0] > 150) || ($image[1] > 150)) {
2758 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2759 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2762 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2763 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2765 if (($image[0] > 600) || ($image[1] > 600)) {
2766 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2767 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2771 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2774 $entities["media"][] = [
2776 "id_str" => (string) ($start + 1),
2777 "indices" => [$start, $start+strlen($url)],
2778 "media_url" => Strings::normaliseLink($media_url),
2779 "media_url_https" => $media_url,
2781 "display_url" => $display_url,
2782 "expanded_url" => $url,
2786 $offset = $start + 1;
2795 * @param array $item
2796 * @param string $text
2800 function api_format_items_embeded_images($item, $text)
2802 $text = preg_replace_callback(
2803 '|data:image/([^;]+)[^=]+=*|m',
2804 function () use ($item) {
2805 return System::baseUrl() . '/display/' . $item['guid'];
2813 * @brief return <a href='url'>name</a> as array
2815 * @param string $txt text
2820 function api_contactlink_to_array($txt)
2823 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2824 if ($r && count($match)==3) {
2826 'name' => $match[2],
2840 * @brief return likes, dislikes and attend status for item
2842 * @param array $item array
2843 * @param string $type Return type (atom, rss, xml, json)
2846 * likes => int count,
2847 * dislikes => int count
2848 * @throws BadRequestException
2849 * @throws ImagickException
2850 * @throws InternalServerErrorException
2851 * @throws UnauthorizedException
2853 function api_format_items_activities($item, $type = "json")
2862 'attendmaybe' => [],
2865 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2866 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2868 while ($parent_item = Item::fetch($ret)) {
2869 // not used as result should be structured like other user data
2870 //builtin_activity_puller($i, $activities);
2872 // get user data and add it to the array of the activity
2873 $user = api_get_user($a, $parent_item['author-id']);
2874 switch ($parent_item['verb']) {
2876 $activities['like'][] = $user;
2878 case ACTIVITY_DISLIKE:
2879 $activities['dislike'][] = $user;
2881 case ACTIVITY_ATTEND:
2882 $activities['attendyes'][] = $user;
2884 case ACTIVITY_ATTENDNO:
2885 $activities['attendno'][] = $user;
2887 case ACTIVITY_ATTENDMAYBE:
2888 $activities['attendmaybe'][] = $user;
2897 if ($type == "xml") {
2898 $xml_activities = [];
2899 foreach ($activities as $k => $v) {
2900 // change xml element from "like" to "friendica:like"
2901 $xml_activities["friendica:".$k] = $v;
2902 // add user data into xml output
2904 foreach ($v as $user) {
2905 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2908 $activities = $xml_activities;
2916 * @brief return data from profiles
2918 * @param array $profile_row array containing data from db table 'profile'
2920 * @throws InternalServerErrorException
2922 function api_format_items_profiles($profile_row)
2925 'profile_id' => $profile_row['id'],
2926 'profile_name' => $profile_row['profile-name'],
2927 'is_default' => $profile_row['is-default'] ? true : false,
2928 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2929 'profile_photo' => $profile_row['photo'],
2930 'profile_thumb' => $profile_row['thumb'],
2931 'publish' => $profile_row['publish'] ? true : false,
2932 'net_publish' => $profile_row['net-publish'] ? true : false,
2933 'description' => $profile_row['pdesc'],
2934 'date_of_birth' => $profile_row['dob'],
2935 'address' => $profile_row['address'],
2936 'city' => $profile_row['locality'],
2937 'region' => $profile_row['region'],
2938 'postal_code' => $profile_row['postal-code'],
2939 'country' => $profile_row['country-name'],
2940 'hometown' => $profile_row['hometown'],
2941 'gender' => $profile_row['gender'],
2942 'marital' => $profile_row['marital'],
2943 'marital_with' => $profile_row['with'],
2944 'marital_since' => $profile_row['howlong'],
2945 'sexual' => $profile_row['sexual'],
2946 'politic' => $profile_row['politic'],
2947 'religion' => $profile_row['religion'],
2948 'public_keywords' => $profile_row['pub_keywords'],
2949 'private_keywords' => $profile_row['prv_keywords'],
2950 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2951 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2952 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2953 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2954 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2955 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2956 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2957 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2958 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2959 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2960 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2961 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2962 'homepage' => $profile_row['homepage'],
2969 * @brief format items to be returned by api
2971 * @param array $r array of items
2972 * @param array $user_info
2973 * @param bool $filter_user filter items by $user_info
2974 * @param string $type Return type (atom, rss, xml, json)
2976 * @throws BadRequestException
2977 * @throws ImagickException
2978 * @throws InternalServerErrorException
2979 * @throws UnauthorizedException
2981 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2987 foreach ((array)$r as $item) {
2988 localize_item($item);
2989 list($status_user, $owner_user) = api_item_get_user($a, $item);
2991 // Look if the posts are matching if they should be filtered by user id
2992 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2996 $in_reply_to = api_in_reply_to($item);
2998 $converted = api_convert_item($item);
3000 if ($type == "xml") {
3001 $geo = "georss:point";
3007 'text' => $converted["text"],
3008 'truncated' => false,
3009 'created_at'=> api_date($item['created']),
3010 'in_reply_to_status_id' => $in_reply_to['status_id'],
3011 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3012 'source' => (($item['app']) ? $item['app'] : 'web'),
3013 'id' => intval($item['id']),
3014 'id_str' => (string) intval($item['id']),
3015 'in_reply_to_user_id' => $in_reply_to['user_id'],
3016 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3017 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3019 'favorited' => $item['starred'] ? true : false,
3020 'user' => $status_user,
3021 'friendica_owner' => $owner_user,
3022 'friendica_private' => $item['private'] == 1,
3023 //'entities' => NULL,
3024 'statusnet_html' => $converted["html"],
3025 'statusnet_conversation_id' => $item['parent'],
3026 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3027 'friendica_activities' => api_format_items_activities($item, $type),
3030 if (count($converted["attachments"]) > 0) {
3031 $status["attachments"] = $converted["attachments"];
3034 if (count($converted["entities"]) > 0) {
3035 $status["entities"] = $converted["entities"];
3038 if ($status["source"] == 'web') {
3039 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3040 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3041 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3044 if ($item["id"] == $item["parent"]) {
3045 $retweeted_item = api_share_as_retweet($item);
3046 if ($retweeted_item !== false) {
3047 $retweeted_status = $status;
3048 $status['user'] = $status['friendica_owner'];
3050 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3051 } catch (BadRequestException $e) {
3052 // user not found. should be found?
3053 /// @todo check if the user should be always found
3054 $retweeted_status["user"] = [];
3057 $rt_converted = api_convert_item($retweeted_item);
3059 $retweeted_status['text'] = $rt_converted["text"];
3060 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3061 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3062 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3063 $status['retweeted_status'] = $retweeted_status;
3067 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3068 unset($status["user"]["uid"]);
3069 unset($status["user"]["self"]);
3071 if ($item["coord"] != "") {
3072 $coords = explode(' ', $item["coord"]);
3073 if (count($coords) == 2) {
3074 if ($type == "json") {
3075 $status["geo"] = ['type' => 'Point',
3076 'coordinates' => [(float) $coords[0],
3077 (float) $coords[1]]];
3078 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3079 $status["georss:point"] = $item["coord"];
3089 * Returns the remaining number of API requests available to the user before the API limit is reached.
3091 * @param string $type Return type (atom, rss, xml, json)
3093 * @return array|string
3096 function api_account_rate_limit_status($type)
3098 if ($type == "xml") {
3100 'remaining-hits' => '150',
3101 '@attributes' => ["type" => "integer"],
3102 'hourly-limit' => '150',
3103 '@attributes2' => ["type" => "integer"],
3104 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3105 '@attributes3' => ["type" => "datetime"],
3106 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3107 '@attributes4' => ["type" => "integer"],
3111 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3112 'remaining_hits' => '150',
3113 'hourly_limit' => '150',
3114 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3118 return api_format_data('hash', $type, ['hash' => $hash]);
3121 /// @TODO move to top of file or somewhere better
3122 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3125 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3127 * @param string $type Return type (atom, rss, xml, json)
3129 * @return array|string
3131 function api_help_test($type)
3133 if ($type == 'xml') {
3139 return api_format_data('ok', $type, ["ok" => $ok]);
3142 /// @TODO move to top of file or somewhere better
3143 api_register_func('api/help/test', 'api_help_test', false);
3146 * Returns all lists the user subscribes to.
3148 * @param string $type Return type (atom, rss, xml, json)
3150 * @return array|string
3151 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3153 function api_lists_list($type)
3156 /// @TODO $ret is not filled here?
3157 return api_format_data('lists', $type, ["lists_list" => $ret]);
3160 /// @TODO move to top of file or somewhere better
3161 api_register_func('api/lists/list', 'api_lists_list', true);
3162 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3165 * Returns all groups the user owns.
3167 * @param string $type Return type (atom, rss, xml, json)
3169 * @return array|string
3170 * @throws BadRequestException
3171 * @throws ForbiddenException
3172 * @throws ImagickException
3173 * @throws InternalServerErrorException
3174 * @throws UnauthorizedException
3175 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3177 function api_lists_ownerships($type)
3181 if (api_user() === false) {
3182 throw new ForbiddenException();
3186 $user_info = api_get_user($a);
3187 $uid = $user_info['uid'];
3189 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3191 // loop through all groups
3193 foreach ($groups as $group) {
3194 if ($group['visible']) {
3200 'name' => $group['name'],
3201 'id' => intval($group['id']),
3202 'id_str' => (string) $group['id'],
3203 'user' => $user_info,
3207 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3210 /// @TODO move to top of file or somewhere better
3211 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3214 * Returns recent statuses from users in the specified group.
3216 * @param string $type Return type (atom, rss, xml, json)
3218 * @return array|string
3219 * @throws BadRequestException
3220 * @throws ForbiddenException
3221 * @throws ImagickException
3222 * @throws InternalServerErrorException
3223 * @throws UnauthorizedException
3224 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3226 function api_lists_statuses($type)
3230 $user_info = api_get_user($a);
3231 if (api_user() === false || $user_info === false) {
3232 throw new ForbiddenException();
3235 unset($_REQUEST["user_id"]);
3236 unset($_GET["user_id"]);
3238 unset($_REQUEST["screen_name"]);
3239 unset($_GET["screen_name"]);
3241 if (empty($_REQUEST['list_id'])) {
3242 throw new BadRequestException('list_id not specified');
3246 $count = defaults($_REQUEST, 'count', 20);
3247 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3251 $since_id = defaults($_REQUEST, 'since_id', 0);
3252 $max_id = defaults($_REQUEST, 'max_id', 0);
3253 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3254 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3256 $start = $page * $count;
3258 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3259 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3262 $condition[0] .= " AND `item`.`id` <= ?";
3263 $condition[] = $max_id;
3265 if ($exclude_replies > 0) {
3266 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3268 if ($conversation_id > 0) {
3269 $condition[0] .= " AND `item`.`parent` = ?";
3270 $condition[] = $conversation_id;
3273 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3274 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3276 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3278 $data = ['status' => $items];
3283 $data = api_rss_extra($a, $data, $user_info);
3287 return api_format_data("statuses", $type, $data);
3290 /// @TODO move to top of file or somewhere better
3291 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3294 * Considers friends and followers lists to be private and won't return
3295 * anything if any user_id parameter is passed.
3297 * @brief Returns either the friends of the follower list
3299 * @param string $qtype Either "friends" or "followers"
3300 * @return boolean|array
3301 * @throws BadRequestException
3302 * @throws ForbiddenException
3303 * @throws ImagickException
3304 * @throws InternalServerErrorException
3305 * @throws UnauthorizedException
3307 function api_statuses_f($qtype)
3311 if (api_user() === false) {
3312 throw new ForbiddenException();
3316 $count = defaults($_GET, 'count', 20);
3317 $page = defaults($_GET, 'page', 1);
3321 $start = ($page - 1) * $count;
3323 $user_info = api_get_user($a);
3325 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3326 /* this is to stop Hotot to load friends multiple times
3327 * I'm not sure if I'm missing return something or
3328 * is a bug in hotot. Workaround, meantime
3332 return array('$users' => $ret);*/
3337 if ($qtype == 'friends') {
3338 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3339 } elseif ($qtype == 'followers') {
3340 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3343 // friends and followers only for self
3344 if ($user_info['self'] == 0) {
3345 $sql_extra = " AND false ";
3348 if ($qtype == 'blocks') {
3349 $sql_filter = 'AND `blocked` AND NOT `pending`';
3350 } elseif ($qtype == 'incoming') {
3351 $sql_filter = 'AND `pending`';
3353 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3371 foreach ($r as $cid) {
3372 $user = api_get_user($a, $cid['nurl']);
3373 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3374 unset($user["uid"]);
3375 unset($user["self"]);
3382 return ['user' => $ret];
3387 * Returns the user's friends.
3389 * @brief Returns the list of friends of the provided user
3391 * @deprecated By Twitter API in favor of friends/list
3393 * @param string $type Either "json" or "xml"
3394 * @return boolean|string|array
3395 * @throws BadRequestException
3396 * @throws ForbiddenException
3398 function api_statuses_friends($type)
3400 $data = api_statuses_f("friends");
3401 if ($data === false) {
3404 return api_format_data("users", $type, $data);
3408 * Returns the user's followers.
3410 * @brief Returns the list of followers of the provided user
3412 * @deprecated By Twitter API in favor of friends/list
3414 * @param string $type Either "json" or "xml"
3415 * @return boolean|string|array
3416 * @throws BadRequestException
3417 * @throws ForbiddenException
3419 function api_statuses_followers($type)
3421 $data = api_statuses_f("followers");
3422 if ($data === false) {
3425 return api_format_data("users", $type, $data);
3428 /// @TODO move to top of file or somewhere better
3429 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3430 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3433 * Returns the list of blocked users
3435 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3437 * @param string $type Either "json" or "xml"
3439 * @return boolean|string|array
3440 * @throws BadRequestException
3441 * @throws ForbiddenException
3443 function api_blocks_list($type)
3445 $data = api_statuses_f('blocks');
3446 if ($data === false) {
3449 return api_format_data("users", $type, $data);
3452 /// @TODO move to top of file or somewhere better
3453 api_register_func('api/blocks/list', 'api_blocks_list', true);
3456 * Returns the list of pending users IDs
3458 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3460 * @param string $type Either "json" or "xml"
3462 * @return boolean|string|array
3463 * @throws BadRequestException
3464 * @throws ForbiddenException
3466 function api_friendships_incoming($type)
3468 $data = api_statuses_f('incoming');
3469 if ($data === false) {
3474 foreach ($data['user'] as $user) {
3475 $ids[] = $user['id'];
3478 return api_format_data("ids", $type, ['id' => $ids]);
3481 /// @TODO move to top of file or somewhere better
3482 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3485 * Returns the instance's configuration information.
3487 * @param string $type Return type (atom, rss, xml, json)
3489 * @return array|string
3490 * @throws InternalServerErrorException
3492 function api_statusnet_config($type)
3496 $name = Config::get('config', 'sitename');
3497 $server = $a->getHostName();
3498 $logo = System::baseUrl() . '/images/friendica-64.png';
3499 $email = Config::get('config', 'admin_email');
3500 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3501 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3502 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3503 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3504 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3507 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3508 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3509 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3510 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3511 'shorturllength' => '30',
3513 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3514 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3515 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3516 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3521 return api_format_data('config', $type, ['config' => $config]);
3524 /// @TODO move to top of file or somewhere better
3525 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3526 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3530 * @param string $type Return type (atom, rss, xml, json)
3532 * @return array|string
3534 function api_statusnet_version($type)
3537 $fake_statusnet_version = "0.9.7";
3539 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3542 /// @TODO move to top of file or somewhere better
3543 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3544 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3548 * @param string $type Return type (atom, rss, xml, json)
3550 * @return array|string|void
3551 * @throws BadRequestException
3552 * @throws ForbiddenException
3553 * @throws ImagickException
3554 * @throws InternalServerErrorException
3555 * @throws UnauthorizedException
3556 * @todo use api_format_data() to return data
3558 function api_ff_ids($type)
3561 throw new ForbiddenException();
3568 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3571 "SELECT `pcontact`.`id` FROM `contact`
3572 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3573 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3576 if (!DBA::isResult($r)) {
3581 foreach ($r as $rr) {
3582 if ($stringify_ids) {
3585 $ids[] = intval($rr['id']);
3589 return api_format_data("ids", $type, ['id' => $ids]);
3593 * Returns the ID of every user the user is following.
3595 * @param string $type Return type (atom, rss, xml, json)
3597 * @return array|string
3598 * @throws BadRequestException
3599 * @throws ForbiddenException
3600 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3602 function api_friends_ids($type)
3604 return api_ff_ids($type);
3608 * Returns the ID of every user following the user.
3610 * @param string $type Return type (atom, rss, xml, json)
3612 * @return array|string
3613 * @throws BadRequestException
3614 * @throws ForbiddenException
3615 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3617 function api_followers_ids($type)
3619 return api_ff_ids($type);
3622 /// @TODO move to top of file or somewhere better
3623 api_register_func('api/friends/ids', 'api_friends_ids', true);
3624 api_register_func('api/followers/ids', 'api_followers_ids', true);
3627 * Sends a new direct message.
3629 * @param string $type Return type (atom, rss, xml, json)
3631 * @return array|string
3632 * @throws BadRequestException
3633 * @throws ForbiddenException
3634 * @throws ImagickException
3635 * @throws InternalServerErrorException
3636 * @throws NotFoundException
3637 * @throws UnauthorizedException
3638 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3640 function api_direct_messages_new($type)
3644 if (api_user() === false) {
3645 throw new ForbiddenException();
3648 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3652 $sender = api_get_user($a);
3655 if (!empty($_POST['screen_name'])) {
3657 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3659 DBA::escape($_POST['screen_name'])
3662 if (DBA::isResult($r)) {
3663 // Selecting the id by priority, friendica first
3664 api_best_nickname($r);
3666 $recipient = api_get_user($a, $r[0]['nurl']);
3669 $recipient = api_get_user($a, $_POST['user_id']);
3672 if (empty($recipient)) {
3673 throw new NotFoundException('Recipient not found');
3677 if (!empty($_REQUEST['replyto'])) {
3679 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3681 intval($_REQUEST['replyto'])
3683 $replyto = $r[0]['parent-uri'];
3684 $sub = $r[0]['title'];
3686 if (!empty($_REQUEST['title'])) {
3687 $sub = $_REQUEST['title'];
3689 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3693 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3696 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3697 $ret = api_format_messages($r[0], $recipient, $sender);
3699 $ret = ["error"=>$id];
3702 $data = ['direct_message'=>$ret];
3708 $data = api_rss_extra($a, $data, $sender);
3712 return api_format_data("direct-messages", $type, $data);
3715 /// @TODO move to top of file or somewhere better
3716 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3719 * Destroys a direct message.
3721 * @brief delete a direct_message from mail table through api
3723 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3724 * @return string|array
3725 * @throws BadRequestException
3726 * @throws ForbiddenException
3727 * @throws ImagickException
3728 * @throws InternalServerErrorException
3729 * @throws UnauthorizedException
3730 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3732 function api_direct_messages_destroy($type)
3736 if (api_user() === false) {
3737 throw new ForbiddenException();
3741 $user_info = api_get_user($a);
3743 $id = defaults($_REQUEST, 'id', 0);
3745 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3746 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3747 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3749 $uid = $user_info['uid'];
3750 // error if no id or parenturi specified (for clients posting parent-uri as well)
3751 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3752 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3753 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3756 // BadRequestException if no id specified (for clients using Twitter API)
3758 throw new BadRequestException('Message id not specified');
3761 // add parent-uri to sql command if specified by calling app
3762 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3764 // get data of the specified message id
3766 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3771 // error message if specified id is not in database
3772 if (!DBA::isResult($r)) {
3773 if ($verbose == "true") {
3774 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3775 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3777 /// @todo BadRequestException ok for Twitter API clients?
3778 throw new BadRequestException('message id not in database');
3783 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3788 if ($verbose == "true") {
3791 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3792 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3794 $answer = ['result' => 'error', 'message' => 'unknown error'];
3795 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3798 /// @todo return JSON data like Twitter API not yet implemented
3801 /// @TODO move to top of file or somewhere better
3802 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3807 * @brief unfollow contact
3809 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3810 * @return string|array
3811 * @throws BadRequestException
3812 * @throws ForbiddenException
3813 * @throws ImagickException
3814 * @throws InternalServerErrorException
3815 * @throws NotFoundException
3816 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3818 function api_friendships_destroy($type)
3822 if ($uid === false) {
3823 throw new ForbiddenException();
3826 $contact_id = defaults($_REQUEST, 'user_id');
3828 if (empty($contact_id)) {
3829 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3830 throw new BadRequestException("no user_id specified");
3833 // Get Contact by given id
3834 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3836 if(!DBA::isResult($contact)) {
3837 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3838 throw new NotFoundException("no contact found to given ID");
3841 $url = $contact["url"];
3843 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3844 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3845 Strings::normaliseLink($url), $url];
3846 $contact = DBA::selectFirst('contact', [], $condition);
3848 if (!DBA::isResult($contact)) {
3849 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3850 throw new NotFoundException("Not following Contact");
3853 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3854 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3855 throw new ExpectationFailedException("Not supported");
3858 $dissolve = ($contact['rel'] == Contact::SHARING);
3860 $owner = User::getOwnerDataById($uid);
3862 Contact::terminateFriendship($owner, $contact, $dissolve);
3865 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3866 throw new NotFoundException("Error Processing Request");
3869 // Sharing-only contacts get deleted as there no relationship any more
3871 Contact::remove($contact['id']);
3873 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3876 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3877 unset($contact["uid"]);
3878 unset($contact["self"]);
3880 // Set screen_name since Twidere requests it
3881 $contact["screen_name"] = $contact["nick"];
3883 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3885 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3889 * @param string $type Return type (atom, rss, xml, json)
3890 * @param string $box
3891 * @param string $verbose
3893 * @return array|string
3894 * @throws BadRequestException
3895 * @throws ForbiddenException
3896 * @throws ImagickException
3897 * @throws InternalServerErrorException
3898 * @throws UnauthorizedException
3900 function api_direct_messages_box($type, $box, $verbose)
3903 if (api_user() === false) {
3904 throw new ForbiddenException();
3907 $count = defaults($_GET, 'count', 20);
3908 $page = defaults($_REQUEST, 'page', 1) - 1;
3913 $since_id = defaults($_REQUEST, 'since_id', 0);
3914 $max_id = defaults($_REQUEST, 'max_id', 0);
3916 $user_id = defaults($_REQUEST, 'user_id', '');
3917 $screen_name = defaults($_REQUEST, 'screen_name', '');
3920 unset($_REQUEST["user_id"]);
3921 unset($_GET["user_id"]);
3923 unset($_REQUEST["screen_name"]);
3924 unset($_GET["screen_name"]);
3926 $user_info = api_get_user($a);
3927 if ($user_info === false) {
3928 throw new ForbiddenException();
3930 $profile_url = $user_info["url"];
3933 $start = $page * $count;
3938 if ($box=="sentbox") {
3939 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3940 } elseif ($box == "conversation") {
3941 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3942 } elseif ($box == "all") {
3943 $sql_extra = "true";
3944 } elseif ($box == "inbox") {
3945 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3949 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3952 if ($user_id != "") {
3953 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3954 } elseif ($screen_name !="") {
3955 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3959 "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",
3965 if ($verbose == "true" && !DBA::isResult($r)) {
3966 $answer = ['result' => 'error', 'message' => 'no mails available'];
3967 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3971 foreach ($r as $item) {
3972 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3973 $recipient = $user_info;
3974 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3975 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3976 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3977 $sender = $user_info;
3980 if (isset($recipient) && isset($sender)) {
3981 $ret[] = api_format_messages($item, $recipient, $sender);
3986 $data = ['direct_message' => $ret];
3991 $data = api_rss_extra($a, $data, $user_info);
3995 return api_format_data("direct-messages", $type, $data);
3999 * Returns the most recent direct messages sent by the user.
4001 * @param string $type Return type (atom, rss, xml, json)
4003 * @return array|string
4004 * @throws BadRequestException
4005 * @throws ForbiddenException
4006 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4008 function api_direct_messages_sentbox($type)
4010 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4011 return api_direct_messages_box($type, "sentbox", $verbose);
4015 * Returns the most recent direct messages sent to the user.
4017 * @param string $type Return type (atom, rss, xml, json)
4019 * @return array|string
4020 * @throws BadRequestException
4021 * @throws ForbiddenException
4022 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4024 function api_direct_messages_inbox($type)
4026 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4027 return api_direct_messages_box($type, "inbox", $verbose);
4032 * @param string $type Return type (atom, rss, xml, json)
4034 * @return array|string
4035 * @throws BadRequestException
4036 * @throws ForbiddenException
4038 function api_direct_messages_all($type)
4040 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4041 return api_direct_messages_box($type, "all", $verbose);
4046 * @param string $type Return type (atom, rss, xml, json)
4048 * @return array|string
4049 * @throws BadRequestException
4050 * @throws ForbiddenException
4052 function api_direct_messages_conversation($type)
4054 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4055 return api_direct_messages_box($type, "conversation", $verbose);
4058 /// @TODO move to top of file or somewhere better
4059 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4060 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4061 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4062 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4065 * Returns an OAuth Request Token.
4067 * @see https://oauth.net/core/1.0/#auth_step1
4069 function api_oauth_request_token()
4071 $oauth1 = new FKOAuth1();
4073 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4074 } catch (Exception $e) {
4075 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4083 * Returns an OAuth Access Token.
4085 * @return array|string
4086 * @see https://oauth.net/core/1.0/#auth_step3
4088 function api_oauth_access_token()
4090 $oauth1 = new FKOAuth1();
4092 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4093 } catch (Exception $e) {
4094 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4101 /// @TODO move to top of file or somewhere better
4102 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4103 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4107 * @brief delete a complete photoalbum with all containing photos from database through api
4109 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4110 * @return string|array
4111 * @throws BadRequestException
4112 * @throws ForbiddenException
4113 * @throws InternalServerErrorException
4115 function api_fr_photoalbum_delete($type)
4117 if (api_user() === false) {
4118 throw new ForbiddenException();
4121 $album = defaults($_REQUEST, 'album', "");
4123 // we do not allow calls without album string
4125 throw new BadRequestException("no albumname specified");
4127 // check if album is existing
4129 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4133 if (!DBA::isResult($r)) {
4134 throw new BadRequestException("album not available");
4137 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4138 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4139 foreach ($r as $rr) {
4140 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4141 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4143 if (!DBA::isResult($photo_item)) {
4144 throw new InternalServerErrorException("problem with deleting items occured");
4146 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4149 // now let's delete all photos from the album
4150 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4152 // return success of deletion or error message
4154 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4155 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4157 throw new InternalServerErrorException("unknown error - deleting from database failed");
4162 * @brief update the name of the album for all photos of an album
4164 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4165 * @return string|array
4166 * @throws BadRequestException
4167 * @throws ForbiddenException
4168 * @throws InternalServerErrorException
4170 function api_fr_photoalbum_update($type)
4172 if (api_user() === false) {
4173 throw new ForbiddenException();
4176 $album = defaults($_REQUEST, 'album', "");
4177 $album_new = defaults($_REQUEST, 'album_new', "");
4179 // we do not allow calls without album string
4181 throw new BadRequestException("no albumname specified");
4183 if ($album_new == "") {
4184 throw new BadRequestException("no new albumname specified");
4186 // check if album is existing
4187 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4188 throw new BadRequestException("album not available");
4190 // now let's update all photos to the albumname
4191 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4193 // return success of updating or error message
4195 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4196 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4198 throw new InternalServerErrorException("unknown error - updating in database failed");
4204 * @brief list all photos of the authenticated user
4206 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4207 * @return string|array
4208 * @throws ForbiddenException
4209 * @throws InternalServerErrorException
4211 function api_fr_photos_list($type)
4213 if (api_user() === false) {
4214 throw new ForbiddenException();
4217 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4218 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4219 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4220 intval(local_user())
4223 'image/jpeg' => 'jpg',
4224 'image/png' => 'png',
4225 'image/gif' => 'gif'
4227 $data = ['photo'=>[]];
4228 if (DBA::isResult($r)) {
4229 foreach ($r as $rr) {
4231 $photo['id'] = $rr['resource-id'];
4232 $photo['album'] = $rr['album'];
4233 $photo['filename'] = $rr['filename'];
4234 $photo['type'] = $rr['type'];
4235 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4236 $photo['created'] = $rr['created'];
4237 $photo['edited'] = $rr['edited'];
4238 $photo['desc'] = $rr['desc'];
4240 if ($type == "xml") {
4241 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4243 $photo['thumb'] = $thumb;
4244 $data['photo'][] = $photo;
4248 return api_format_data("photos", $type, $data);
4252 * @brief upload a new photo or change an existing photo
4254 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4255 * @return string|array
4256 * @throws BadRequestException
4257 * @throws ForbiddenException
4258 * @throws ImagickException
4259 * @throws InternalServerErrorException
4260 * @throws NotFoundException
4262 function api_fr_photo_create_update($type)
4264 if (api_user() === false) {
4265 throw new ForbiddenException();
4268 $photo_id = defaults($_REQUEST, 'photo_id', null);
4269 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4270 $album = defaults($_REQUEST, 'album', null);
4271 $album_new = defaults($_REQUEST, 'album_new', null);
4272 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4273 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4274 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4275 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4276 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4278 // do several checks on input parameters
4279 // we do not allow calls without album string
4280 if ($album == null) {
4281 throw new BadRequestException("no albumname specified");
4283 // if photo_id == null --> we are uploading a new photo
4284 if ($photo_id == null) {
4287 // error if no media posted in create-mode
4288 if (empty($_FILES['media'])) {
4290 throw new BadRequestException("no media data submitted");
4293 // album_new will be ignored in create-mode
4298 // check if photo is existing in databasei
4299 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4300 throw new BadRequestException("photo not available");
4304 // checks on acl strings provided by clients
4305 $acl_input_error = false;
4306 $acl_input_error |= check_acl_input($allow_cid);
4307 $acl_input_error |= check_acl_input($deny_cid);
4308 $acl_input_error |= check_acl_input($allow_gid);
4309 $acl_input_error |= check_acl_input($deny_gid);
4310 if ($acl_input_error) {
4311 throw new BadRequestException("acl data invalid");
4313 // now let's upload the new media in create-mode
4314 if ($mode == "create") {
4315 $media = $_FILES['media'];
4316 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4318 // return success of updating or error message
4319 if (!is_null($data)) {
4320 return api_format_data("photo_create", $type, $data);
4322 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4326 // now let's do the changes in update-mode
4327 if ($mode == "update") {
4328 $updated_fields = [];
4330 if (!is_null($desc)) {
4331 $updated_fields['desc'] = $desc;
4334 if (!is_null($album_new)) {
4335 $updated_fields['album'] = $album_new;
4338 if (!is_null($allow_cid)) {
4339 $allow_cid = trim($allow_cid);
4340 $updated_fields['allow_cid'] = $allow_cid;
4343 if (!is_null($deny_cid)) {
4344 $deny_cid = trim($deny_cid);
4345 $updated_fields['deny_cid'] = $deny_cid;
4348 if (!is_null($allow_gid)) {
4349 $allow_gid = trim($allow_gid);
4350 $updated_fields['allow_gid'] = $allow_gid;
4353 if (!is_null($deny_gid)) {
4354 $deny_gid = trim($deny_gid);
4355 $updated_fields['deny_gid'] = $deny_gid;
4359 if (count($updated_fields) > 0) {
4360 $nothingtodo = false;
4361 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4363 $nothingtodo = true;
4366 if (!empty($_FILES['media'])) {
4367 $nothingtodo = false;
4368 $media = $_FILES['media'];
4369 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4370 if (!is_null($data)) {
4371 return api_format_data("photo_update", $type, $data);
4375 // return success of updating or error message
4377 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4378 return api_format_data("photo_update", $type, ['$result' => $answer]);
4381 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4382 return api_format_data("photo_update", $type, ['$result' => $answer]);
4384 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4387 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4391 * @brief delete a single photo from the database through api
4393 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4394 * @return string|array
4395 * @throws BadRequestException
4396 * @throws ForbiddenException
4397 * @throws InternalServerErrorException
4399 function api_fr_photo_delete($type)
4401 if (api_user() === false) {
4402 throw new ForbiddenException();
4406 $photo_id = defaults($_REQUEST, 'photo_id', null);
4408 // do several checks on input parameters
4409 // we do not allow calls without photo id
4410 if ($photo_id == null) {
4411 throw new BadRequestException("no photo_id specified");
4414 // check if photo is existing in database
4415 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4416 throw new BadRequestException("photo not available");
4419 // now we can perform on the deletion of the photo
4420 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4422 // return success of deletion or error message
4424 // retrieve the id of the parent element (the photo element)
4425 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4426 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4428 if (!DBA::isResult($photo_item)) {
4429 throw new InternalServerErrorException("problem with deleting items occured");
4431 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4432 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4433 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4435 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4436 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4438 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4444 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4446 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4447 * @return string|array
4448 * @throws BadRequestException
4449 * @throws ForbiddenException
4450 * @throws InternalServerErrorException
4451 * @throws NotFoundException
4453 function api_fr_photo_detail($type)
4455 if (api_user() === false) {
4456 throw new ForbiddenException();
4458 if (empty($_REQUEST['photo_id'])) {
4459 throw new BadRequestException("No photo id.");
4462 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4463 $photo_id = $_REQUEST['photo_id'];
4465 // prepare json/xml output with data from database for the requested photo
4466 $data = prepare_photo_data($type, $scale, $photo_id);
4468 return api_format_data("photo_detail", $type, $data);
4473 * Updates the user’s profile image.
4475 * @brief updates the profile image for the user (either a specified profile or the default profile)
4477 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4479 * @return string|array
4480 * @throws BadRequestException
4481 * @throws ForbiddenException
4482 * @throws ImagickException
4483 * @throws InternalServerErrorException
4484 * @throws NotFoundException
4485 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4487 function api_account_update_profile_image($type)
4489 if (api_user() === false) {
4490 throw new ForbiddenException();
4493 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4495 // error if image data is missing
4496 if (empty($_FILES['image'])) {
4497 throw new BadRequestException("no media data submitted");
4500 // check if specified profile id is valid
4501 if ($profile_id != 0) {
4502 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4503 // error message if specified profile id is not in database
4504 if (!DBA::isResult($profile)) {
4505 throw new BadRequestException("profile_id not available");
4507 $is_default_profile = $profile['is-default'];
4509 $is_default_profile = 1;
4512 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4514 if (!empty($_FILES['image'])) {
4515 $media = $_FILES['image'];
4516 } elseif (!empty($_FILES['media'])) {
4517 $media = $_FILES['media'];
4519 // save new profile image
4520 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4523 if (is_array($media['type'])) {
4524 $filetype = $media['type'][0];
4526 $filetype = $media['type'];
4528 if ($filetype == "image/jpeg") {
4530 } elseif ($filetype == "image/png") {
4533 throw new InternalServerErrorException('Unsupported filetype');
4536 // change specified profile or all profiles to the new resource-id
4537 if ($is_default_profile) {
4538 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4539 Photo::update(['profile' => false], $condition);
4541 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4542 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4543 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4546 Contact::updateSelfFromUserID(api_user(), true);
4548 // Update global directory in background
4549 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4550 if ($url && strlen(Config::get('system', 'directory'))) {
4551 Worker::add(PRIORITY_LOW, "Directory", $url);
4554 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4556 // output for client
4558 return api_account_verify_credentials($type);
4560 // SaveMediaToDatabase failed for some reason
4561 throw new InternalServerErrorException("image upload failed");
4565 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4566 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4567 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4568 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4569 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4570 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4571 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4572 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4573 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4576 * Update user profile
4578 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4580 * @return array|string
4581 * @throws BadRequestException
4582 * @throws ForbiddenException
4583 * @throws ImagickException
4584 * @throws InternalServerErrorException
4585 * @throws UnauthorizedException
4587 function api_account_update_profile($type)
4589 $local_user = api_user();
4590 $api_user = api_get_user(get_app());
4592 if (!empty($_POST['name'])) {
4593 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4594 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4595 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4596 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4599 if (isset($_POST['description'])) {
4600 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4601 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4602 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4605 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4606 // Update global directory in background
4607 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4608 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4611 return api_account_verify_credentials($type);
4614 /// @TODO move to top of file or somewhere better
4615 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4619 * @param string $acl_string
4623 function check_acl_input($acl_string)
4625 if ($acl_string == null || $acl_string == " ") {
4628 $contact_not_found = false;
4630 // split <x><y><z> into array of cid's
4631 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4633 // check for each cid if it is available on server
4634 $cid_array = $array[0];
4635 foreach ($cid_array as $cid) {
4636 $cid = str_replace("<", "", $cid);
4637 $cid = str_replace(">", "", $cid);
4638 $condition = ['id' => $cid, 'uid' => api_user()];
4639 $contact_not_found |= !DBA::exists('contact', $condition);
4641 return $contact_not_found;
4646 * @param string $mediatype
4647 * @param array $media
4648 * @param string $type
4649 * @param string $album
4650 * @param string $allow_cid
4651 * @param string $deny_cid
4652 * @param string $allow_gid
4653 * @param string $deny_gid
4654 * @param string $desc
4655 * @param integer $profile
4656 * @param boolean $visibility
4657 * @param string $photo_id
4659 * @throws BadRequestException
4660 * @throws ForbiddenException
4661 * @throws ImagickException
4662 * @throws InternalServerErrorException
4663 * @throws NotFoundException
4665 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)
4673 if (is_array($media)) {
4674 if (is_array($media['tmp_name'])) {
4675 $src = $media['tmp_name'][0];
4677 $src = $media['tmp_name'];
4679 if (is_array($media['name'])) {
4680 $filename = basename($media['name'][0]);
4682 $filename = basename($media['name']);
4684 if (is_array($media['size'])) {
4685 $filesize = intval($media['size'][0]);
4687 $filesize = intval($media['size']);
4689 if (is_array($media['type'])) {
4690 $filetype = $media['type'][0];
4692 $filetype = $media['type'];
4696 if ($filetype == "") {
4697 $filetype=Image::guessType($filename);
4699 $imagedata = @getimagesize($src);
4701 $filetype = $imagedata['mime'];
4704 "File upload src: " . $src . " - filename: " . $filename .
4705 " - size: " . $filesize . " - type: " . $filetype,
4709 // check if there was a php upload error
4710 if ($filesize == 0 && $media['error'] == 1) {
4711 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4713 // check against max upload size within Friendica instance
4714 $maximagesize = Config::get('system', 'maximagesize');
4715 if ($maximagesize && ($filesize > $maximagesize)) {
4716 $formattedBytes = Strings::formatBytes($maximagesize);
4717 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4720 // create Photo instance with the data of the image
4721 $imagedata = @file_get_contents($src);
4722 $Image = new Image($imagedata, $filetype);
4723 if (!$Image->isValid()) {
4724 throw new InternalServerErrorException("unable to process image data");
4727 // check orientation of image
4728 $Image->orient($src);
4731 // check max length of images on server
4732 $max_length = Config::get('system', 'max_image_length');
4734 $max_length = MAX_IMAGE_LENGTH;
4736 if ($max_length > 0) {
4737 $Image->scaleDown($max_length);
4738 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4740 $width = $Image->getWidth();
4741 $height = $Image->getHeight();
4743 // create a new resource-id if not already provided
4744 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4746 if ($mediatype == "photo") {
4747 // upload normal image (scales 0, 1, 2)
4748 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4750 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4752 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4754 if ($width > 640 || $height > 640) {
4755 $Image->scaleDown(640);
4756 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4758 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4762 if ($width > 320 || $height > 320) {
4763 $Image->scaleDown(320);
4764 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4766 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4769 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4770 } elseif ($mediatype == "profileimage") {
4771 // upload profile image (scales 4, 5, 6)
4772 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4774 if ($width > 300 || $height > 300) {
4775 $Image->scaleDown(300);
4776 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4778 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4782 if ($width > 80 || $height > 80) {
4783 $Image->scaleDown(80);
4784 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4786 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4790 if ($width > 48 || $height > 48) {
4791 $Image->scaleDown(48);
4792 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4794 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4797 $Image->__destruct();
4798 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4801 if (isset($r) && $r) {
4802 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4803 if ($photo_id == null && $mediatype == "photo") {
4804 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4806 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4807 return prepare_photo_data($type, false, $hash);
4809 throw new InternalServerErrorException("image upload failed");
4815 * @param string $hash
4816 * @param string $allow_cid
4817 * @param string $deny_cid
4818 * @param string $allow_gid
4819 * @param string $deny_gid
4820 * @param string $filetype
4821 * @param boolean $visibility
4822 * @throws InternalServerErrorException
4824 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4826 // get data about the api authenticated user
4827 $uri = Item::newURI(intval(api_user()));
4828 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4831 $arr['guid'] = System::createUUID();
4832 $arr['uid'] = intval(api_user());
4834 $arr['parent-uri'] = $uri;
4835 $arr['type'] = 'photo';
4837 $arr['resource-id'] = $hash;
4838 $arr['contact-id'] = $owner_record['id'];
4839 $arr['owner-name'] = $owner_record['name'];
4840 $arr['owner-link'] = $owner_record['url'];
4841 $arr['owner-avatar'] = $owner_record['thumb'];
4842 $arr['author-name'] = $owner_record['name'];
4843 $arr['author-link'] = $owner_record['url'];
4844 $arr['author-avatar'] = $owner_record['thumb'];
4846 $arr['allow_cid'] = $allow_cid;
4847 $arr['allow_gid'] = $allow_gid;
4848 $arr['deny_cid'] = $deny_cid;
4849 $arr['deny_gid'] = $deny_gid;
4850 $arr['visible'] = $visibility;
4854 'image/jpeg' => 'jpg',
4855 'image/png' => 'png',
4856 'image/gif' => 'gif'
4859 // adds link to the thumbnail scale photo
4860 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4861 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4864 // do the magic for storing the item in the database and trigger the federation to other contacts
4870 * @param string $type
4872 * @param string $photo_id
4875 * @throws BadRequestException
4876 * @throws ForbiddenException
4877 * @throws ImagickException
4878 * @throws InternalServerErrorException
4879 * @throws NotFoundException
4880 * @throws UnauthorizedException
4882 function prepare_photo_data($type, $scale, $photo_id)
4885 $user_info = api_get_user($a);
4887 if ($user_info === false) {
4888 throw new ForbiddenException();
4891 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4892 $data_sql = ($scale === false ? "" : "data, ");
4894 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4895 // clients needs to convert this in their way for further processing
4897 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4898 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4899 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4900 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4902 intval(local_user()),
4903 DBA::escape($photo_id),
4908 'image/jpeg' => 'jpg',
4909 'image/png' => 'png',
4910 'image/gif' => 'gif'
4913 // prepare output data for photo
4914 if (DBA::isResult($r)) {
4915 $data = ['photo' => $r[0]];
4916 $data['photo']['id'] = $data['photo']['resource-id'];
4917 if ($scale !== false) {
4918 $data['photo']['data'] = base64_encode($data['photo']['data']);
4920 unset($data['photo']['datasize']); //needed only with scale param
4922 if ($type == "xml") {
4923 $data['photo']['links'] = [];
4924 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4925 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4927 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4930 $data['photo']['link'] = [];
4931 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4933 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4934 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4938 unset($data['photo']['resource-id']);
4939 unset($data['photo']['minscale']);
4940 unset($data['photo']['maxscale']);
4942 throw new NotFoundException();
4945 // retrieve item element for getting activities (like, dislike etc.) related to photo
4946 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4947 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4949 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4951 // retrieve comments on photo
4952 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4953 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4955 $statuses = Item::selectForUser(api_user(), [], $condition);
4957 // prepare output of comments
4958 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4960 if ($type == "xml") {
4962 foreach ($commentData as $comment) {
4963 $comments[$k++ . ":comment"] = $comment;
4966 foreach ($commentData as $comment) {
4967 $comments[] = $comment;
4970 $data['photo']['friendica_comments'] = $comments;
4972 // include info if rights on photo and rights on item are mismatching
4973 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4974 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4975 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4976 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4977 $data['photo']['rights_mismatch'] = $rights_mismatch;
4984 * Similar as /mod/redir.php
4985 * redirect to 'url' after dfrn auth
4987 * Why this when there is mod/redir.php already?
4988 * This use api_user() and api_login()
4991 * c_url: url of remote contact to auth to
4992 * url: string, url to redirect after auth
4994 function api_friendica_remoteauth()
4996 $url = defaults($_GET, 'url', '');
4997 $c_url = defaults($_GET, 'c_url', '');
4999 if ($url === '' || $c_url === '') {
5000 throw new BadRequestException("Wrong parameters.");
5003 $c_url = Strings::normaliseLink($c_url);
5007 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5009 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5010 throw new BadRequestException("Unknown contact");
5013 $cid = $contact['id'];
5015 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
5017 if ($contact['duplex'] && $contact['issued-id']) {
5018 $orig_id = $contact['issued-id'];
5019 $dfrn_id = '1:' . $orig_id;
5021 if ($contact['duplex'] && $contact['dfrn-id']) {
5022 $orig_id = $contact['dfrn-id'];
5023 $dfrn_id = '0:' . $orig_id;
5026 $sec = Strings::getRandomHex();
5028 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5029 'sec' => $sec, 'expire' => time() + 45];
5030 DBA::insert('profile_check', $fields);
5032 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5033 $dest = ($url ? '&destination_url=' . $url : '');
5035 System::externalRedirect(
5036 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5037 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5038 . '&type=profile&sec=' . $sec . $dest
5041 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5044 * @brief Return the item shared, if the item contains only the [share] tag
5046 * @param array $item Sharer item
5047 * @return array|false Shared item or false if not a reshare
5048 * @throws ImagickException
5049 * @throws InternalServerErrorException
5051 function api_share_as_retweet(&$item)
5053 $body = trim($item["body"]);
5055 if (Diaspora::isReshare($body, false) === false) {
5056 if ($item['author-id'] == $item['owner-id']) {
5059 // Reshares from OStatus, ActivityPub and Twitter
5060 $reshared_item = $item;
5061 $reshared_item['owner-id'] = $reshared_item['author-id'];
5062 $reshared_item['owner-link'] = $reshared_item['author-link'];
5063 $reshared_item['owner-name'] = $reshared_item['author-name'];
5064 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5065 return $reshared_item;
5069 /// @TODO "$1" should maybe mean '$1' ?
5070 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5072 * Skip if there is no shared message in there
5073 * we already checked this in diaspora::isReshare()
5074 * but better one more than one less...
5076 if (($body == $attributes) || empty($attributes)) {
5080 // build the fake reshared item
5081 $reshared_item = $item;
5084 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5085 if (!empty($matches[1])) {
5086 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5089 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5090 if (!empty($matches[1])) {
5091 $author = $matches[1];
5095 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5096 if (!empty($matches[1])) {
5097 $profile = $matches[1];
5100 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5101 if (!empty($matches[1])) {
5102 $profile = $matches[1];
5106 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5107 if (!empty($matches[1])) {
5108 $avatar = $matches[1];
5111 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5112 if (!empty($matches[1])) {
5113 $avatar = $matches[1];
5117 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5118 if (!empty($matches[1])) {
5119 $link = $matches[1];
5122 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5123 if (!empty($matches[1])) {
5124 $link = $matches[1];
5128 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5129 if (!empty($matches[1])) {
5130 $posted = $matches[1];
5133 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5134 if (!empty($matches[1])) {
5135 $posted = $matches[1];
5138 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5140 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5144 $reshared_item["body"] = $shared_body;
5145 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5146 $reshared_item["author-name"] = $author;
5147 $reshared_item["author-link"] = $profile;
5148 $reshared_item["author-avatar"] = $avatar;
5149 $reshared_item["plink"] = $link;
5150 $reshared_item["created"] = $posted;
5151 $reshared_item["edited"] = $posted;
5153 return $reshared_item;
5158 * @param string $profile
5160 * @return string|false
5161 * @throws InternalServerErrorException
5162 * @todo remove trailing junk from profile url
5163 * @todo pump.io check has to check the website
5165 function api_get_nick($profile)
5170 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5171 DBA::escape(Strings::normaliseLink($profile))
5174 if (DBA::isResult($r)) {
5175 $nick = $r[0]["nick"];
5180 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5181 DBA::escape(Strings::normaliseLink($profile))
5184 if (DBA::isResult($r)) {
5185 $nick = $r[0]["nick"];
5190 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5191 if ($friendica != $profile) {
5197 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5198 if ($diaspora != $profile) {
5204 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5205 if ($twitter != $profile) {
5212 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5213 if ($StatusnetHost != $profile) {
5214 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5215 if ($StatusnetUser != $profile) {
5216 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5217 $user = json_decode($UserData);
5219 $nick = $user->screen_name;
5225 // To-Do: look at the page if its really a pumpio site
5226 //if (!$nick == "") {
5227 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5228 // if ($pumpio != $profile)
5230 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5243 * @param array $item
5248 function api_in_reply_to($item)
5252 $in_reply_to['status_id'] = null;
5253 $in_reply_to['user_id'] = null;
5254 $in_reply_to['status_id_str'] = null;
5255 $in_reply_to['user_id_str'] = null;
5256 $in_reply_to['screen_name'] = null;
5258 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5259 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5260 if (DBA::isResult($parent)) {
5261 $in_reply_to['status_id'] = intval($parent['id']);
5263 $in_reply_to['status_id'] = intval($item['parent']);
5266 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5268 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5269 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5271 if (DBA::isResult($parent)) {
5272 if ($parent['author-nick'] == "") {
5273 $parent['author-nick'] = api_get_nick($parent['author-link']);
5276 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5277 $in_reply_to['user_id'] = intval($parent['author-id']);
5278 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5281 // There seems to be situation, where both fields are identical:
5282 // https://github.com/friendica/friendica/issues/1010
5283 // This is a bugfix for that.
5284 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5285 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']]);
5286 $in_reply_to['status_id'] = null;
5287 $in_reply_to['user_id'] = null;
5288 $in_reply_to['status_id_str'] = null;
5289 $in_reply_to['user_id_str'] = null;
5290 $in_reply_to['screen_name'] = null;
5294 return $in_reply_to;
5299 * @param string $text
5302 * @throws InternalServerErrorException
5304 function api_clean_plain_items($text)
5306 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5308 $text = BBCode::cleanPictureLinks($text);
5309 $URLSearchString = "^\[\]";
5311 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5313 if ($include_entities == "true") {
5314 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5317 // Simplify "attachment" element
5318 $text = api_clean_attachments($text);
5324 * @brief Removes most sharing information for API text export
5326 * @param string $body The original body
5328 * @return string Cleaned body
5329 * @throws InternalServerErrorException
5331 function api_clean_attachments($body)
5333 $data = BBCode::getAttachmentData($body);
5340 if (isset($data["text"])) {
5341 $body = $data["text"];
5343 if (($body == "") && isset($data["title"])) {
5344 $body = $data["title"];
5346 if (isset($data["url"])) {
5347 $body .= "\n".$data["url"];
5349 $body .= $data["after"];
5356 * @param array $contacts
5360 function api_best_nickname(&$contacts)
5364 if (count($contacts) == 0) {
5368 foreach ($contacts as $contact) {
5369 if ($contact["network"] == "") {
5370 $contact["network"] = "dfrn";
5371 $best_contact = [$contact];
5375 if (sizeof($best_contact) == 0) {
5376 foreach ($contacts as $contact) {
5377 if ($contact["network"] == "dfrn") {
5378 $best_contact = [$contact];
5383 if (sizeof($best_contact) == 0) {
5384 foreach ($contacts as $contact) {
5385 if ($contact["network"] == "dspr") {
5386 $best_contact = [$contact];
5391 if (sizeof($best_contact) == 0) {
5392 foreach ($contacts as $contact) {
5393 if ($contact["network"] == "stat") {
5394 $best_contact = [$contact];
5399 if (sizeof($best_contact) == 0) {
5400 foreach ($contacts as $contact) {
5401 if ($contact["network"] == "pump") {
5402 $best_contact = [$contact];
5407 if (sizeof($best_contact) == 0) {
5408 foreach ($contacts as $contact) {
5409 if ($contact["network"] == "twit") {
5410 $best_contact = [$contact];
5415 if (sizeof($best_contact) == 1) {
5416 $contacts = $best_contact;
5418 $contacts = [$contacts[0]];
5423 * Return all or a specified group of the user with the containing contacts.
5425 * @param string $type Return type (atom, rss, xml, json)
5427 * @return array|string
5428 * @throws BadRequestException
5429 * @throws ForbiddenException
5430 * @throws ImagickException
5431 * @throws InternalServerErrorException
5432 * @throws UnauthorizedException
5434 function api_friendica_group_show($type)
5438 if (api_user() === false) {
5439 throw new ForbiddenException();
5443 $user_info = api_get_user($a);
5444 $gid = defaults($_REQUEST, 'gid', 0);
5445 $uid = $user_info['uid'];
5447 // get data of the specified group id or all groups if not specified
5450 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5454 // error message if specified gid is not in database
5455 if (!DBA::isResult($r)) {
5456 throw new BadRequestException("gid not available");
5460 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5465 // loop through all groups and retrieve all members for adding data in the user array
5467 foreach ($r as $rr) {
5468 $members = Contact::getByGroupId($rr['id']);
5471 if ($type == "xml") {
5472 $user_element = "users";
5474 foreach ($members as $member) {
5475 $user = api_get_user($a, $member['nurl']);
5476 $users[$k++.":user"] = $user;
5479 $user_element = "user";
5480 foreach ($members as $member) {
5481 $user = api_get_user($a, $member['nurl']);
5485 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5487 return api_format_data("groups", $type, ['group' => $grps]);
5489 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5493 * Delete the specified group of the user.
5495 * @param string $type Return type (atom, rss, xml, json)
5497 * @return array|string
5498 * @throws BadRequestException
5499 * @throws ForbiddenException
5500 * @throws ImagickException
5501 * @throws InternalServerErrorException
5502 * @throws UnauthorizedException
5504 function api_friendica_group_delete($type)
5508 if (api_user() === false) {
5509 throw new ForbiddenException();
5513 $user_info = api_get_user($a);
5514 $gid = defaults($_REQUEST, 'gid', 0);
5515 $name = defaults($_REQUEST, 'name', "");
5516 $uid = $user_info['uid'];
5518 // error if no gid specified
5519 if ($gid == 0 || $name == "") {
5520 throw new BadRequestException('gid or name not specified');
5523 // get data of the specified group id
5525 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5529 // error message if specified gid is not in database
5530 if (!DBA::isResult($r)) {
5531 throw new BadRequestException('gid not available');
5534 // get data of the specified group id and group name
5536 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5541 // error message if specified gid is not in database
5542 if (!DBA::isResult($rname)) {
5543 throw new BadRequestException('wrong group name');
5547 $ret = Group::removeByName($uid, $name);
5550 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5551 return api_format_data("group_delete", $type, ['result' => $success]);
5553 throw new BadRequestException('other API error');
5556 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5561 * @param string $type Return type (atom, rss, xml, json)
5563 * @return array|string
5564 * @throws BadRequestException
5565 * @throws ForbiddenException
5566 * @throws ImagickException
5567 * @throws InternalServerErrorException
5568 * @throws UnauthorizedException
5569 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5571 function api_lists_destroy($type)
5575 if (api_user() === false) {
5576 throw new ForbiddenException();
5580 $user_info = api_get_user($a);
5581 $gid = defaults($_REQUEST, 'list_id', 0);
5582 $uid = $user_info['uid'];
5584 // error if no gid specified
5586 throw new BadRequestException('gid not specified');
5589 // get data of the specified group id
5590 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5591 // error message if specified gid is not in database
5593 throw new BadRequestException('gid not available');
5596 if (Group::remove($gid)) {
5598 'name' => $group['name'],
5599 'id' => intval($gid),
5600 'id_str' => (string) $gid,
5601 'user' => $user_info
5604 return api_format_data("lists", $type, ['lists' => $list]);
5607 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5610 * Add a new group to the database.
5612 * @param string $name Group name
5613 * @param int $uid User ID
5614 * @param array $users List of users to add to the group
5617 * @throws BadRequestException
5619 function group_create($name, $uid, $users = [])
5621 // error if no name specified
5623 throw new BadRequestException('group name not specified');
5626 // get data of the specified group name
5628 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5632 // error message if specified group name already exists
5633 if (DBA::isResult($rname)) {
5634 throw new BadRequestException('group name already exists');
5637 // check if specified group name is a deleted group
5639 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5643 // error message if specified group name already exists
5644 if (DBA::isResult($rname)) {
5645 $reactivate_group = true;
5649 $ret = Group::create($uid, $name);
5651 $gid = Group::getIdByName($uid, $name);
5653 throw new BadRequestException('other API error');
5657 $erroraddinguser = false;
5659 foreach ($users as $user) {
5660 $cid = $user['cid'];
5661 // check if user really exists as contact
5663 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5667 if (count($contact)) {
5668 Group::addMember($gid, $cid);
5670 $erroraddinguser = true;
5671 $errorusers[] = $cid;
5675 // return success message incl. missing users in array
5676 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5678 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5682 * Create the specified group with the posted array of contacts.
5684 * @param string $type Return type (atom, rss, xml, json)
5686 * @return array|string
5687 * @throws BadRequestException
5688 * @throws ForbiddenException
5689 * @throws ImagickException
5690 * @throws InternalServerErrorException
5691 * @throws UnauthorizedException
5693 function api_friendica_group_create($type)
5697 if (api_user() === false) {
5698 throw new ForbiddenException();
5702 $user_info = api_get_user($a);
5703 $name = defaults($_REQUEST, 'name', "");
5704 $uid = $user_info['uid'];
5705 $json = json_decode($_POST['json'], true);
5706 $users = $json['user'];
5708 $success = group_create($name, $uid, $users);
5710 return api_format_data("group_create", $type, ['result' => $success]);
5712 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5715 * Create a new group.
5717 * @param string $type Return type (atom, rss, xml, json)
5719 * @return array|string
5720 * @throws BadRequestException
5721 * @throws ForbiddenException
5722 * @throws ImagickException
5723 * @throws InternalServerErrorException
5724 * @throws UnauthorizedException
5725 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5727 function api_lists_create($type)
5731 if (api_user() === false) {
5732 throw new ForbiddenException();
5736 $user_info = api_get_user($a);
5737 $name = defaults($_REQUEST, 'name', "");
5738 $uid = $user_info['uid'];
5740 $success = group_create($name, $uid);
5741 if ($success['success']) {
5743 'name' => $success['name'],
5744 'id' => intval($success['gid']),
5745 'id_str' => (string) $success['gid'],
5746 'user' => $user_info
5749 return api_format_data("lists", $type, ['lists'=>$grp]);
5752 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5755 * Update the specified group with the posted array of contacts.
5757 * @param string $type Return type (atom, rss, xml, json)
5759 * @return array|string
5760 * @throws BadRequestException
5761 * @throws ForbiddenException
5762 * @throws ImagickException
5763 * @throws InternalServerErrorException
5764 * @throws UnauthorizedException
5766 function api_friendica_group_update($type)
5770 if (api_user() === false) {
5771 throw new ForbiddenException();
5775 $user_info = api_get_user($a);
5776 $uid = $user_info['uid'];
5777 $gid = defaults($_REQUEST, 'gid', 0);
5778 $name = defaults($_REQUEST, 'name', "");
5779 $json = json_decode($_POST['json'], true);
5780 $users = $json['user'];
5782 // error if no name specified
5784 throw new BadRequestException('group name not specified');
5787 // error if no gid specified
5789 throw new BadRequestException('gid not specified');
5793 $members = Contact::getByGroupId($gid);
5794 foreach ($members as $member) {
5795 $cid = $member['id'];
5796 foreach ($users as $user) {
5797 $found = ($user['cid'] == $cid ? true : false);
5799 if (!isset($found) || !$found) {
5800 Group::removeMemberByName($uid, $name, $cid);
5805 $erroraddinguser = false;
5807 foreach ($users as $user) {
5808 $cid = $user['cid'];
5809 // check if user really exists as contact
5811 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5816 if (count($contact)) {
5817 Group::addMember($gid, $cid);
5819 $erroraddinguser = true;
5820 $errorusers[] = $cid;
5824 // return success message incl. missing users in array
5825 $status = ($erroraddinguser ? "missing user" : "ok");
5826 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5827 return api_format_data("group_update", $type, ['result' => $success]);
5830 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5833 * Update information about a group.
5835 * @param string $type Return type (atom, rss, xml, json)
5837 * @return array|string
5838 * @throws BadRequestException
5839 * @throws ForbiddenException
5840 * @throws ImagickException
5841 * @throws InternalServerErrorException
5842 * @throws UnauthorizedException
5843 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5845 function api_lists_update($type)
5849 if (api_user() === false) {
5850 throw new ForbiddenException();
5854 $user_info = api_get_user($a);
5855 $gid = defaults($_REQUEST, 'list_id', 0);
5856 $name = defaults($_REQUEST, 'name', "");
5857 $uid = $user_info['uid'];
5859 // error if no gid specified
5861 throw new BadRequestException('gid not specified');
5864 // get data of the specified group id
5865 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5866 // error message if specified gid is not in database
5868 throw new BadRequestException('gid not available');
5871 if (Group::update($gid, $name)) {
5874 'id' => intval($gid),
5875 'id_str' => (string) $gid,
5876 'user' => $user_info
5879 return api_format_data("lists", $type, ['lists' => $list]);
5883 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5887 * @param string $type Return type (atom, rss, xml, json)
5889 * @return array|string
5890 * @throws BadRequestException
5891 * @throws ForbiddenException
5892 * @throws ImagickException
5893 * @throws InternalServerErrorException
5895 function api_friendica_activity($type)
5899 if (api_user() === false) {
5900 throw new ForbiddenException();
5902 $verb = strtolower($a->argv[3]);
5903 $verb = preg_replace("|\..*$|", "", $verb);
5905 $id = defaults($_REQUEST, 'id', 0);
5907 $res = Item::performLike($id, $verb);
5910 if ($type == "xml") {
5915 return api_format_data('ok', $type, ['ok' => $ok]);
5917 throw new BadRequestException('Error adding activity');
5921 /// @TODO move to top of file or somewhere better
5922 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5923 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5924 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5925 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5926 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5927 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5928 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5929 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5930 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5931 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5934 * @brief Returns notifications
5936 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5937 * @return string|array
5938 * @throws BadRequestException
5939 * @throws ForbiddenException
5940 * @throws InternalServerErrorException
5942 function api_friendica_notification($type)
5946 if (api_user() === false) {
5947 throw new ForbiddenException();
5950 throw new BadRequestException("Invalid argument count");
5952 $nm = new NotificationsManager();
5954 $notes = $nm->getAll([], "+seen -date", 50);
5956 if ($type == "xml") {
5958 if (!empty($notes)) {
5959 foreach ($notes as $note) {
5960 $xmlnotes[] = ["@attributes" => $note];
5966 return api_format_data("notes", $type, ['note' => $notes]);
5970 * POST request with 'id' param as notification id
5972 * @brief Set notification as seen and returns associated item (if possible)
5974 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5975 * @return string|array
5976 * @throws BadRequestException
5977 * @throws ForbiddenException
5978 * @throws ImagickException
5979 * @throws InternalServerErrorException
5980 * @throws UnauthorizedException
5982 function api_friendica_notification_seen($type)
5985 $user_info = api_get_user($a);
5987 if (api_user() === false || $user_info === false) {
5988 throw new ForbiddenException();
5991 throw new BadRequestException("Invalid argument count");
5994 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5996 $nm = new NotificationsManager();
5997 $note = $nm->getByID($id);
5998 if (is_null($note)) {
5999 throw new BadRequestException("Invalid argument");
6002 $nm->setSeen($note);
6003 if ($note['otype']=='item') {
6004 // would be really better with an ItemsManager and $im->getByID() :-P
6005 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6006 if (DBA::isResult($item)) {
6007 // we found the item, return it to the user
6008 $ret = api_format_items([$item], $user_info, false, $type);
6009 $data = ['status' => $ret];
6010 return api_format_data("status", $type, $data);
6012 // the item can't be found, but we set the note as seen, so we count this as a success
6014 return api_format_data('result', $type, ['result' => "success"]);
6017 /// @TODO move to top of file or somewhere better
6018 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6019 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6022 * @brief update a direct_message to seen state
6024 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6025 * @return string|array (success result=ok, error result=error with error message)
6026 * @throws BadRequestException
6027 * @throws ForbiddenException
6028 * @throws ImagickException
6029 * @throws InternalServerErrorException
6030 * @throws UnauthorizedException
6032 function api_friendica_direct_messages_setseen($type)
6035 if (api_user() === false) {
6036 throw new ForbiddenException();
6040 $user_info = api_get_user($a);
6041 $uid = $user_info['uid'];
6042 $id = defaults($_REQUEST, 'id', 0);
6044 // return error if id is zero
6046 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6047 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6050 // error message if specified id is not in database
6051 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6052 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6053 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6056 // update seen indicator
6057 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6061 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6062 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6064 $answer = ['result' => 'error', 'message' => 'unknown error'];
6065 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6069 /// @TODO move to top of file or somewhere better
6070 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6073 * @brief search for direct_messages containing a searchstring through api
6075 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6076 * @param string $box
6077 * @return string|array (success: success=true if found and search_result contains found messages,
6078 * success=false if nothing was found, search_result='nothing found',
6079 * error: result=error with error message)
6080 * @throws BadRequestException
6081 * @throws ForbiddenException
6082 * @throws ImagickException
6083 * @throws InternalServerErrorException
6084 * @throws UnauthorizedException
6086 function api_friendica_direct_messages_search($type, $box = "")
6090 if (api_user() === false) {
6091 throw new ForbiddenException();
6095 $user_info = api_get_user($a);
6096 $searchstring = defaults($_REQUEST, 'searchstring', "");
6097 $uid = $user_info['uid'];
6099 // error if no searchstring specified
6100 if ($searchstring == "") {
6101 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6102 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6105 // get data for the specified searchstring
6107 "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",
6109 DBA::escape('%'.$searchstring.'%')
6112 $profile_url = $user_info["url"];
6114 // message if nothing was found
6115 if (!DBA::isResult($r)) {
6116 $success = ['success' => false, 'search_results' => 'problem with query'];
6117 } elseif (count($r) == 0) {
6118 $success = ['success' => false, 'search_results' => 'nothing found'];
6121 foreach ($r as $item) {
6122 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6123 $recipient = $user_info;
6124 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6125 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6126 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6127 $sender = $user_info;
6130 if (isset($recipient) && isset($sender)) {
6131 $ret[] = api_format_messages($item, $recipient, $sender);
6134 $success = ['success' => true, 'search_results' => $ret];
6137 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6140 /// @TODO move to top of file or somewhere better
6141 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6144 * @brief return data of all the profiles a user has to the client
6146 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6147 * @return string|array
6148 * @throws BadRequestException
6149 * @throws ForbiddenException
6150 * @throws ImagickException
6151 * @throws InternalServerErrorException
6152 * @throws UnauthorizedException
6154 function api_friendica_profile_show($type)
6158 if (api_user() === false) {
6159 throw new ForbiddenException();
6163 $profile_id = defaults($_REQUEST, 'profile_id', 0);
6165 // retrieve general information about profiles for user
6166 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6167 $directory = Config::get('system', 'directory');
6169 // get data of the specified profile id or all profiles of the user if not specified
6170 if ($profile_id != 0) {
6172 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
6177 // error message if specified gid is not in database
6178 if (!DBA::isResult($r)) {
6179 throw new BadRequestException("profile_id not available");
6183 "SELECT * FROM `profile` WHERE `uid` = %d",
6187 // loop through all returned profiles and retrieve data and users
6190 foreach ($r as $rr) {
6191 $profile = api_format_items_profiles($rr);
6193 // select all users from contact table, loop and prepare standard return for user data
6196 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
6201 foreach ($nurls as $nurl) {
6202 $user = api_get_user($a, $nurl['nurl']);
6203 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6205 $profile['users'] = $users;
6207 // add prepared profile data to array for final return
6208 if ($type == "xml") {
6209 $profiles[$k++ . ":profile"] = $profile;
6211 $profiles[] = $profile;
6215 // return settings, authenticated user and profiles data
6216 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6218 $result = ['multi_profiles' => $multi_profiles ? true : false,
6219 'global_dir' => $directory,
6220 'friendica_owner' => api_get_user($a, $self['nurl']),
6221 'profiles' => $profiles];
6222 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6224 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6227 * Returns a list of saved searches.
6229 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6231 * @param string $type Return format: json or xml
6233 * @return string|array
6236 function api_saved_searches_list($type)
6238 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6241 while ($term = $terms->fetch()) {
6243 'created_at' => api_date(time()),
6244 'id' => intval($term['id']),
6245 'id_str' => $term['id'],
6246 'name' => $term['term'],
6248 'query' => $term['term']
6254 return api_format_data("terms", $type, ['terms' => $result]);
6257 /// @TODO move to top of file or somewhere better
6258 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6261 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6263 * @brief Number of comments
6265 * @param object $data [Status, Status]
6269 function bindComments(&$data)
6271 if (count($data) == 0) {
6277 foreach ($data as $item) {
6278 $ids[] = $item['id'];
6281 $idStr = DBA::escape(implode(', ', $ids));
6282 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6283 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6284 $itemsData = DBA::toArray($items);
6286 foreach ($itemsData as $item) {
6287 $comments[$item['parent']] = $item['comments'];
6290 foreach ($data as $idx => $item) {
6292 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6297 @TODO Maybe open to implement?
6299 [pagename] => api/1.1/statuses/lookup.json
6300 [id] => 605138389168451584
6301 [include_cards] => true
6302 [cards_platform] => Android-12
6303 [include_entities] => true
6304 [include_my_retweet] => 1
6306 [include_reply_count] => true
6307 [include_descendent_reply_count] => true
6311 Not implemented by now:
6312 statuses/retweets_of_me
6317 account/update_location
6318 account/update_profile_background_image
6321 friendica/profile/update
6322 friendica/profile/create
6323 friendica/profile/delete
6325 Not implemented in status.net:
6326 statuses/retweeted_to_me
6327 statuses/retweeted_by_me
6328 direct_messages/destroy
6330 account/update_delivery_device
6331 notifications/follow