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\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\L10n;
17 use Friendica\Core\Logger;
18 use Friendica\Core\NotificationsManager;
19 use Friendica\Core\PConfig;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\Session;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Mail;
29 use Friendica\Model\Photo;
30 use Friendica\Model\Profile;
31 use Friendica\Model\User;
32 use Friendica\Network\FKOAuth1;
33 use Friendica\Network\HTTPException;
34 use Friendica\Network\HTTPException\BadRequestException;
35 use Friendica\Network\HTTPException\ExpectationFailedException;
36 use Friendica\Network\HTTPException\ForbiddenException;
37 use Friendica\Network\HTTPException\InternalServerErrorException;
38 use Friendica\Network\HTTPException\MethodNotAllowedException;
39 use Friendica\Network\HTTPException\NotFoundException;
40 use Friendica\Network\HTTPException\NotImplementedException;
41 use Friendica\Network\HTTPException\TooManyRequestsException;
42 use Friendica\Network\HTTPException\UnauthorizedException;
43 use Friendica\Object\Image;
44 use Friendica\Protocol\Diaspora;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Network;
47 use Friendica\Util\Proxy as ProxyUtils;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
51 require_once __DIR__ . '/../mod/share.php';
52 require_once __DIR__ . '/../mod/item.php';
53 require_once __DIR__ . '/../mod/wall_upload.php';
55 define('API_METHOD_ANY', '*');
56 define('API_METHOD_GET', 'GET');
57 define('API_METHOD_POST', 'POST,PUT');
58 define('API_METHOD_DELETE', 'POST,DELETE');
60 define('API_LOG_PREFIX', 'API {action} - ');
66 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
67 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
68 * into a page, and visitors will post something without noticing it).
70 * @brief Auth API user
74 if (!empty($_SESSION['allow_api'])) {
82 * Clients can send 'source' parameter to be show in post metadata
83 * as "sent via <source>".
84 * Some clients doesn't send a source param, we support ones we know
87 * @brief Get source name from API client
90 * Client source name, default to "api" if unset/unknown
95 if (requestdata('source')) {
96 return requestdata('source');
99 // Support for known clients that doesn't send a source name
100 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
101 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
105 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
107 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
114 * @brief Format date for API
116 * @param string $str Source date, as UTC
117 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
120 function api_date($str)
122 // Wed May 23 06:01:13 +0000 2007
123 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
127 * Register a function to be the endpoint for defined API path.
129 * @brief Register API endpoint
131 * @param string $path API URL path, relative to System::baseUrl()
132 * @param string $func Function name to call on path request
133 * @param bool $auth API need logged user
134 * @param string $method HTTP method reqiured to call this endpoint.
135 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
136 * Default to API_METHOD_ANY
138 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
148 // Workaround for hotot
149 $path = str_replace("api/", "api/1.1/", $path);
159 * Log in user via OAuth1 or Simple HTTP Auth.
160 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
162 * @brief Login API user
165 * @throws ForbiddenException
166 * @throws InternalServerErrorException
167 * @throws UnauthorizedException
168 * @hook 'authenticate'
170 * 'username' => username from login form
171 * 'password' => password from login form
172 * 'authenticated' => return status,
173 * 'user_record' => return authenticated 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 Session::set('allow_api', true);
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), true);
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 Session::setAuthenticatedForUser($a, $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 if (!empty($return)) {
346 $json = json_encode(end($return));
347 if (!empty($_GET['callback'])) {
348 $json = $_GET['callback'] . "(" . $json . ")";
354 header("Content-Type: application/rss+xml");
355 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
358 header("Content-Type: application/atom+xml");
359 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
366 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => $a->query_string]);
367 throw new NotImplementedException();
368 } catch (HTTPException $e) {
369 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
370 return api_error($type, $e);
375 * @brief Format API error string
377 * @param string $type Return type (xml, json, rss, as)
378 * @param object $e HTTPException Error object
379 * @return string|array error message formatted as $type
381 function api_error($type, $e)
385 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
386 /// @TODO: https://dev.twitter.com/overview/api/response-codes
388 $error = ["error" => $error,
389 "code" => $e->getCode() . " " . $e->httpdesc,
390 "request" => $a->query_string];
392 $return = api_format_data('status', $type, ['status' => $error]);
396 header("Content-Type: text/xml");
399 header("Content-Type: application/json");
400 $return = json_encode($return);
403 header("Content-Type: application/rss+xml");
406 header("Content-Type: application/atom+xml");
414 * @brief Set values for RSS template
417 * @param array $arr Array to be passed to template
418 * @param array $user_info User info
420 * @throws BadRequestException
421 * @throws ImagickException
422 * @throws InternalServerErrorException
423 * @throws UnauthorizedException
424 * @todo find proper type-hints
426 function api_rss_extra(App $a, $arr, $user_info)
428 if (is_null($user_info)) {
429 $user_info = api_get_user($a);
432 $arr['$user'] = $user_info;
434 'alternate' => $user_info['url'],
435 'self' => System::baseUrl() . "/" . $a->query_string,
436 'base' => System::baseUrl(),
437 'updated' => api_date(null),
438 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
439 'language' => $user_info['lang'],
440 'logo' => System::baseUrl() . "/images/friendica-32.png",
448 * @brief Unique contact to contact url.
450 * @param int $id Contact id
451 * @return bool|string
452 * Contact url or False if contact id is unknown
455 function api_unique_id_to_nurl($id)
457 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
459 if (DBA::isResult($r)) {
467 * @brief Get user info array.
470 * @param int|string $contact_id Contact ID or URL
472 * @throws BadRequestException
473 * @throws ImagickException
474 * @throws InternalServerErrorException
475 * @throws UnauthorizedException
477 function api_get_user(App $a, $contact_id = null)
485 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
487 // Searching for contact URL
488 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
489 $user = DBA::escape(Strings::normaliseLink($contact_id));
491 $extra_query = "AND `contact`.`nurl` = '%s' ";
492 if (api_user() !== false) {
493 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
497 // Searching for contact id with uid = 0
498 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
499 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
502 throw new BadRequestException("User ID ".$contact_id." not found.");
506 $extra_query = "AND `contact`.`nurl` = '%s' ";
507 if (api_user() !== false) {
508 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
512 if (is_null($user) && !empty($_GET['user_id'])) {
513 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
516 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
520 $extra_query = "AND `contact`.`nurl` = '%s' ";
521 if (api_user() !== false) {
522 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
525 if (is_null($user) && !empty($_GET['screen_name'])) {
526 $user = DBA::escape($_GET['screen_name']);
527 $extra_query = "AND `contact`.`nick` = '%s' ";
528 if (api_user() !== false) {
529 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
533 if (is_null($user) && !empty($_GET['profileurl'])) {
534 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
535 $extra_query = "AND `contact`.`nurl` = '%s' ";
536 if (api_user() !== false) {
537 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
541 // $called_api is the API path exploded on / and is expected to have at least 2 elements
542 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
543 $argid = count($called_api);
544 if (!empty($a->argv[$argid])) {
545 $data = explode(".", $a->argv[$argid]);
546 if (count($data) > 1) {
547 list($user, $null) = $data;
550 if (is_numeric($user)) {
551 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
555 $extra_query = "AND `contact`.`nurl` = '%s' ";
556 if (api_user() !== false) {
557 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
561 $user = DBA::escape($user);
562 $extra_query = "AND `contact`.`nick` = '%s' ";
563 if (api_user() !== false) {
564 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
569 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
572 if (api_user() === false) {
576 $user = $_SESSION['uid'];
577 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
581 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
585 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
591 // Selecting the id by priority, friendica first
592 if (is_array($uinfo)) {
593 api_best_nickname($uinfo);
596 // if the contact wasn't found, fetch it from the contacts with uid = 0
597 if (!DBA::isResult($uinfo)) {
599 throw new BadRequestException("User not found.");
602 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
604 if (DBA::isResult($contact)) {
605 // If no nick where given, extract it from the address
606 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
607 $contact['nick'] = api_get_nick($contact["url"]);
611 'id' => $contact["id"],
612 'id_str' => (string) $contact["id"],
613 'name' => $contact["name"],
614 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
615 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
616 'description' => BBCode::toPlaintext($contact["about"]),
617 'profile_image_url' => $contact["micro"],
618 'profile_image_url_https' => $contact["micro"],
619 'profile_image_url_profile_size' => $contact["thumb"],
620 'profile_image_url_large' => $contact["photo"],
621 'url' => $contact["url"],
622 'protected' => false,
623 'followers_count' => 0,
624 'friends_count' => 0,
626 'created_at' => api_date($contact["created"]),
627 'favourites_count' => 0,
629 'time_zone' => 'UTC',
630 'geo_enabled' => false,
632 'statuses_count' => 0,
634 'contributors_enabled' => false,
635 'is_translator' => false,
636 'is_translation_enabled' => false,
637 'following' => false,
638 'follow_request_sent' => false,
639 'statusnet_blocking' => false,
640 'notifications' => false,
641 'statusnet_profile_url' => $contact["url"],
643 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
644 'pid' => Contact::getIdForURL($contact["url"], 0, true),
646 'network' => $contact["network"],
651 throw new BadRequestException("User ".$url." not found.");
655 if ($uinfo[0]['self']) {
656 if ($uinfo[0]['network'] == "") {
657 $uinfo[0]['network'] = Protocol::DFRN;
660 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
661 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
668 // Add a nick if it isn't present there
669 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
670 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
673 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
675 if (!empty($profile['about'])) {
676 $description = $profile['about'];
678 $description = $uinfo[0]["about"];
681 if (!empty($usr['default-location'])) {
682 $location = $usr['default-location'];
683 } elseif (!empty($uinfo[0]["location"])) {
684 $location = $uinfo[0]["location"];
686 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
690 'id' => intval($pcontact_id),
691 'id_str' => (string) intval($pcontact_id),
692 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
693 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
694 'location' => $location,
695 'description' => BBCode::toPlaintext($description),
696 'profile_image_url' => $uinfo[0]['micro'],
697 'profile_image_url_https' => $uinfo[0]['micro'],
698 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
699 'profile_image_url_large' => $uinfo[0]["photo"],
700 'url' => $uinfo[0]['url'],
701 'protected' => false,
702 'followers_count' => intval($countfollowers),
703 'friends_count' => intval($countfriends),
705 'created_at' => api_date($uinfo[0]['created']),
706 'favourites_count' => intval($starred),
708 'time_zone' => 'UTC',
709 'geo_enabled' => false,
711 'statuses_count' => intval($countitems),
713 'contributors_enabled' => false,
714 'is_translator' => false,
715 'is_translation_enabled' => false,
716 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
717 'follow_request_sent' => false,
718 'statusnet_blocking' => false,
719 'notifications' => false,
721 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
722 'statusnet_profile_url' => $uinfo[0]['url'],
723 'uid' => intval($uinfo[0]['uid']),
724 'cid' => intval($uinfo[0]['cid']),
725 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
726 'self' => $uinfo[0]['self'],
727 'network' => $uinfo[0]['network'],
730 // If this is a local user and it uses Frio, we can get its color preferences.
732 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
733 if ($theme_info['theme'] === 'frio') {
734 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
736 if ($schema && ($schema != '---')) {
737 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
738 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
739 require_once $schemefile;
742 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
743 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
744 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
746 if (empty($nav_bg)) {
749 if (empty($link_color)) {
750 $link_color = "#6fdbe8";
752 if (empty($bgcolor)) {
753 $bgcolor = "#ededed";
756 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
757 $ret['profile_link_color'] = str_replace('#', '', $link_color);
758 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
766 * @brief return api-formatted array for item's author and owner
769 * @param array $item item from db
770 * @return array(array:author, array:owner)
771 * @throws BadRequestException
772 * @throws ImagickException
773 * @throws InternalServerErrorException
774 * @throws UnauthorizedException
776 function api_item_get_user(App $a, $item)
778 $status_user = api_get_user($a, defaults($item, 'author-id', null));
780 $author_user = $status_user;
782 $status_user["protected"] = defaults($item, 'private', 0);
784 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
785 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
787 $owner_user = $author_user;
790 return ([$status_user, $author_user, $owner_user]);
794 * @brief walks recursively through an array with the possibility to change value and key
796 * @param array $array The array to walk through
797 * @param callable $callback The callback function
799 * @return array the transformed array
801 function api_walk_recursive(array &$array, callable $callback)
805 foreach ($array as $k => $v) {
807 if ($callback($v, $k)) {
808 $new_array[$k] = api_walk_recursive($v, $callback);
811 if ($callback($v, $k)) {
822 * @brief Callback function to transform the array in an array that can be transformed in a XML file
824 * @param mixed $item Array item value
825 * @param string $key Array key
827 * @return boolean Should the array item be deleted?
829 function api_reformat_xml(&$item, &$key)
831 if (is_bool($item)) {
832 $item = ($item ? "true" : "false");
835 if (substr($key, 0, 10) == "statusnet_") {
836 $key = "statusnet:".substr($key, 10);
837 } elseif (substr($key, 0, 10) == "friendica_") {
838 $key = "friendica:".substr($key, 10);
840 /// @TODO old-lost code?
842 // $key = "default:".$key;
848 * @brief Creates the XML from a JSON style array
850 * @param array $data JSON style array
851 * @param string $root_element Name of the root element
853 * @return string The XML data
855 function api_create_xml(array $data, $root_element)
857 $childname = key($data);
858 $data2 = array_pop($data);
860 $namespaces = ["" => "http://api.twitter.com",
861 "statusnet" => "http://status.net/schema/api/1/",
862 "friendica" => "http://friendi.ca/schema/api/1/",
863 "georss" => "http://www.georss.org/georss"];
865 /// @todo Auto detection of needed namespaces
866 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
870 if (is_array($data2)) {
872 api_walk_recursive($data2, "api_reformat_xml");
878 foreach ($data2 as $item) {
879 $data4[$i++ . ":" . $childname] = $item;
886 $data3 = [$root_element => $data2];
888 $ret = XML::fromArray($data3, $xml, false, $namespaces);
893 * @brief Formats the data according to the data type
895 * @param string $root_element Name of the root element
896 * @param string $type Return type (atom, rss, xml, json)
897 * @param array $data JSON style array
899 * @return array|string (string|array) XML data or JSON data
901 function api_format_data($root_element, $type, $data)
907 $ret = api_create_xml($data, $root_element);
922 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
923 * returns a 401 status code and an error message if not.
925 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
927 * @param string $type Return type (atom, rss, xml, json)
928 * @return array|string
929 * @throws BadRequestException
930 * @throws ForbiddenException
931 * @throws ImagickException
932 * @throws InternalServerErrorException
933 * @throws UnauthorizedException
935 function api_account_verify_credentials($type)
939 if (api_user() === false) {
940 throw new ForbiddenException();
943 unset($_REQUEST["user_id"]);
944 unset($_GET["user_id"]);
946 unset($_REQUEST["screen_name"]);
947 unset($_GET["screen_name"]);
949 $skip_status = defaults($_REQUEST, 'skip_status', false);
951 $user_info = api_get_user($a);
953 // "verified" isn't used here in the standard
954 unset($user_info["verified"]);
956 // - Adding last status
958 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
960 $user_info['status'] = api_format_item($item, $type);
964 // "uid" and "self" are only needed for some internal stuff, so remove it from here
965 unset($user_info["uid"]);
966 unset($user_info["self"]);
968 return api_format_data("user", $type, ['user' => $user_info]);
971 /// @TODO move to top of file or somewhere better
972 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
975 * Get data from $_POST or $_GET
980 function requestdata($k)
982 if (!empty($_POST[$k])) {
985 if (!empty($_GET[$k])) {
992 * Deprecated function to upload media.
994 * @param string $type Return type (atom, rss, xml, json)
996 * @return array|string
997 * @throws BadRequestException
998 * @throws ForbiddenException
999 * @throws ImagickException
1000 * @throws InternalServerErrorException
1001 * @throws UnauthorizedException
1003 function api_statuses_mediap($type)
1007 if (api_user() === false) {
1008 Logger::log('api_statuses_update: no user');
1009 throw new ForbiddenException();
1011 $user_info = api_get_user($a);
1013 $_REQUEST['profile_uid'] = api_user();
1014 $_REQUEST['api_source'] = true;
1015 $txt = requestdata('status');
1016 /// @TODO old-lost code?
1017 //$txt = urldecode(requestdata('status'));
1019 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1020 $txt = HTML::toBBCodeVideo($txt);
1021 $config = HTMLPurifier_Config::createDefault();
1022 $config->set('Cache.DefinitionImpl', null);
1023 $purifier = new HTMLPurifier($config);
1024 $txt = $purifier->purify($txt);
1026 $txt = HTML::toBBCode($txt);
1028 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1030 $picture = wall_upload_post($a, false);
1032 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1033 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1034 $item_id = item_post($a);
1036 // output the post that we just posted.
1037 return api_status_show($type, $item_id);
1040 /// @TODO move this to top of file or somewhere better!
1041 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1044 * Updates the user’s current status.
1046 * @param string $type Return type (atom, rss, xml, json)
1048 * @return array|string
1049 * @throws BadRequestException
1050 * @throws ForbiddenException
1051 * @throws ImagickException
1052 * @throws InternalServerErrorException
1053 * @throws TooManyRequestsException
1054 * @throws UnauthorizedException
1055 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1057 function api_statuses_update($type)
1061 if (api_user() === false) {
1062 Logger::log('api_statuses_update: no user');
1063 throw new ForbiddenException();
1068 // convert $_POST array items to the form we use for web posts.
1069 if (requestdata('htmlstatus')) {
1070 $txt = requestdata('htmlstatus');
1071 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1072 $txt = HTML::toBBCodeVideo($txt);
1074 $config = HTMLPurifier_Config::createDefault();
1075 $config->set('Cache.DefinitionImpl', null);
1077 $purifier = new HTMLPurifier($config);
1078 $txt = $purifier->purify($txt);
1080 $_REQUEST['body'] = HTML::toBBCode($txt);
1083 $_REQUEST['body'] = requestdata('status');
1086 $_REQUEST['title'] = requestdata('title');
1088 $parent = requestdata('in_reply_to_status_id');
1090 // Twidere sends "-1" if it is no reply ...
1091 if ($parent == -1) {
1095 if (ctype_digit($parent)) {
1096 $_REQUEST['parent'] = $parent;
1098 $_REQUEST['parent_uri'] = $parent;
1101 if (requestdata('lat') && requestdata('long')) {
1102 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1104 $_REQUEST['profile_uid'] = api_user();
1107 // Check for throttling (maximum posts per day, week and month)
1108 $throttle_day = Config::get('system', 'throttle_limit_day');
1109 if ($throttle_day > 0) {
1110 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1112 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1113 $posts_day = DBA::count('thread', $condition);
1115 if ($posts_day > $throttle_day) {
1116 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1117 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1118 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));
1122 $throttle_week = Config::get('system', 'throttle_limit_week');
1123 if ($throttle_week > 0) {
1124 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1126 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1127 $posts_week = DBA::count('thread', $condition);
1129 if ($posts_week > $throttle_week) {
1130 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1131 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1132 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));
1136 $throttle_month = Config::get('system', 'throttle_limit_month');
1137 if ($throttle_month > 0) {
1138 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1140 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1141 $posts_month = DBA::count('thread', $condition);
1143 if ($posts_month > $throttle_month) {
1144 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1145 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1146 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));
1151 if (!empty($_FILES['media'])) {
1152 // upload the image if we have one
1153 $picture = wall_upload_post($a, false);
1154 if (is_array($picture)) {
1155 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1159 if (requestdata('media_ids')) {
1160 $ids = explode(',', requestdata('media_ids'));
1161 foreach ($ids as $id) {
1163 "SELECT `resource-id`, `scale`, `nickname`, `type`, `desc` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1167 if (DBA::isResult($r)) {
1168 $phototypes = Image::supportedTypes();
1169 $ext = $phototypes[$r[0]['type']];
1170 $description = $r[0]['desc'] ?? '';
1171 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1172 $_REQUEST['body'] .= '[img=' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1177 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1179 $_REQUEST['api_source'] = true;
1181 if (empty($_REQUEST['source'])) {
1182 $_REQUEST["source"] = api_source();
1185 // call out normal post function
1186 $item_id = item_post($a);
1188 // output the post that we just posted.
1189 return api_status_show($type, $item_id);
1192 /// @TODO move to top of file or somewhere better
1193 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1194 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1197 * Uploads an image to Friendica.
1200 * @throws BadRequestException
1201 * @throws ForbiddenException
1202 * @throws ImagickException
1203 * @throws InternalServerErrorException
1204 * @throws UnauthorizedException
1205 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1207 function api_media_upload()
1211 if (api_user() === false) {
1212 Logger::log('no user');
1213 throw new ForbiddenException();
1218 if (empty($_FILES['media'])) {
1220 throw new BadRequestException("No media.");
1223 $media = wall_upload_post($a, false);
1226 throw new InternalServerErrorException();
1230 $returndata["media_id"] = $media["id"];
1231 $returndata["media_id_string"] = (string)$media["id"];
1232 $returndata["size"] = $media["size"];
1233 $returndata["image"] = ["w" => $media["width"],
1234 "h" => $media["height"],
1235 "image_type" => $media["type"],
1236 "friendica_preview_url" => $media["preview"]];
1238 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1240 return ["media" => $returndata];
1243 /// @TODO move to top of file or somewhere better
1244 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1247 * Updates media meta data (picture descriptions)
1249 * @param string $type Return type (atom, rss, xml, json)
1251 * @return array|string
1252 * @throws BadRequestException
1253 * @throws ForbiddenException
1254 * @throws ImagickException
1255 * @throws InternalServerErrorException
1256 * @throws TooManyRequestsException
1257 * @throws UnauthorizedException
1258 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1260 * @todo Compare the corresponding Twitter function for correct return values
1262 function api_media_metadata_create($type)
1266 if (api_user() === false) {
1267 Logger::info('no user');
1268 throw new ForbiddenException();
1273 $postdata = Network::postdata();
1275 if (empty($postdata)) {
1276 throw new BadRequestException("No post data");
1279 $data = json_decode($postdata, true);
1281 throw new BadRequestException("Invalid post data");
1284 if (empty($data['media_id']) || empty($data['alt_text'])) {
1285 throw new BadRequestException("Missing post data values");
1288 if (empty($data['alt_text']['text'])) {
1289 throw new BadRequestException("No alt text.");
1292 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1294 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1295 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1296 if (!DBA::isResult($photo)) {
1297 throw new BadRequestException("Metadata not found.");
1300 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1303 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1306 * @param string $type Return format (atom, rss, xml, json)
1307 * @param int $item_id
1311 function api_status_show($type, $item_id)
1313 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1317 $item = api_get_item(['id' => $item_id]);
1319 $status_info = api_format_item($item, $type);
1322 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1324 return api_format_data('statuses', $type, ['status' => $status_info]);
1328 * Retrieves the last public status of the provided user info
1330 * @param int $ownerId Public contact Id
1331 * @param int $uid User Id
1335 function api_get_last_status($ownerId, $uid)
1338 'author-id'=> $ownerId,
1340 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1344 $item = api_get_item($condition);
1350 * Retrieves a single item record based on the provided condition and converts it for API use.
1352 * @param array $condition Item table condition array
1356 function api_get_item(array $condition)
1358 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1364 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1365 * The author's most recent status will be returned inline.
1367 * @param string $type Return type (atom, rss, xml, json)
1368 * @return array|string
1369 * @throws BadRequestException
1370 * @throws ImagickException
1371 * @throws InternalServerErrorException
1372 * @throws UnauthorizedException
1373 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1375 function api_users_show($type)
1377 $a = \Friendica\BaseObject::getApp();
1379 $user_info = api_get_user($a);
1381 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1383 $user_info['status'] = api_format_item($item, $type);
1386 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1387 unset($user_info['uid']);
1388 unset($user_info['self']);
1390 return api_format_data('user', $type, ['user' => $user_info]);
1393 /// @TODO move to top of file or somewhere better
1394 api_register_func('api/users/show', 'api_users_show');
1395 api_register_func('api/externalprofile/show', 'api_users_show');
1398 * Search a public user account.
1400 * @param string $type Return type (atom, rss, xml, json)
1402 * @return array|string
1403 * @throws BadRequestException
1404 * @throws ImagickException
1405 * @throws InternalServerErrorException
1406 * @throws UnauthorizedException
1407 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1409 function api_users_search($type)
1415 if (!empty($_GET['q'])) {
1416 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1418 if (!DBA::isResult($r)) {
1419 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1422 if (DBA::isResult($r)) {
1424 foreach ($r as $user) {
1425 $user_info = api_get_user($a, $user["id"]);
1427 if ($type == "xml") {
1428 $userlist[$k++.":user"] = $user_info;
1430 $userlist[] = $user_info;
1433 $userlist = ["users" => $userlist];
1435 throw new BadRequestException("User ".$_GET["q"]." not found.");
1438 throw new BadRequestException("No user specified.");
1441 return api_format_data("users", $type, $userlist);
1444 /// @TODO move to top of file or somewhere better
1445 api_register_func('api/users/search', 'api_users_search');
1448 * Return user objects
1450 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1452 * @param string $type Return format: json or xml
1454 * @return array|string
1455 * @throws BadRequestException
1456 * @throws ImagickException
1457 * @throws InternalServerErrorException
1458 * @throws NotFoundException if the results are empty.
1459 * @throws UnauthorizedException
1461 function api_users_lookup($type)
1465 if (!empty($_REQUEST['user_id'])) {
1466 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1468 $users[] = api_get_user(get_app(), $id);
1473 if (empty($users)) {
1474 throw new NotFoundException;
1477 return api_format_data("users", $type, ['users' => $users]);
1480 /// @TODO move to top of file or somewhere better
1481 api_register_func('api/users/lookup', 'api_users_lookup', true);
1484 * Returns statuses that match a specified query.
1486 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1488 * @param string $type Return format: json, xml, atom, rss
1490 * @return array|string
1491 * @throws BadRequestException if the "q" parameter is missing.
1492 * @throws ForbiddenException
1493 * @throws ImagickException
1494 * @throws InternalServerErrorException
1495 * @throws UnauthorizedException
1497 function api_search($type)
1500 $user_info = api_get_user($a);
1502 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1504 if (empty($_REQUEST['q'])) {
1505 throw new BadRequestException('q parameter is required.');
1508 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1511 $data['status'] = [];
1513 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1514 if (!empty($_REQUEST['rpp'])) {
1515 $count = $_REQUEST['rpp'];
1516 } elseif (!empty($_REQUEST['count'])) {
1517 $count = $_REQUEST['count'];
1520 $since_id = defaults($_REQUEST, 'since_id', 0);
1521 $max_id = defaults($_REQUEST, 'max_id', 0);
1522 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1523 $start = $page * $count;
1524 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1525 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1526 $searchTerm = $matches[1];
1527 $condition = ["`oid` > ?
1528 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1529 AND `otype` = ? AND `type` = ? AND `term` = ?",
1530 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1532 $condition[0] .= ' AND `oid` <= ?';
1533 $condition[] = $max_id;
1535 $terms = DBA::select('term', ['oid'], $condition, []);
1537 while ($term = DBA::fetch($terms)) {
1538 $itemIds[] = $term['oid'];
1542 if (empty($itemIds)) {
1543 return api_format_data('statuses', $type, $data);
1546 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1547 if ($exclude_replies) {
1548 $preCondition[] = '`id` = `parent`';
1551 $condition = [implode(' AND ', $preCondition)];
1553 $condition = ["`id` > ?
1554 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1555 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1556 AND `body` LIKE CONCAT('%',?,'%')",
1557 $since_id, api_user(), $_REQUEST['q']];
1559 $condition[0] .= ' AND `id` <= ?';
1560 $condition[] = $max_id;
1564 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1566 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1568 bindComments($data['status']);
1570 return api_format_data('statuses', $type, $data);
1573 /// @TODO move to top of file or somewhere better
1574 api_register_func('api/search/tweets', 'api_search', true);
1575 api_register_func('api/search', 'api_search', true);
1578 * Returns the most recent statuses posted by the user and the users they follow.
1580 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1582 * @param string $type Return type (atom, rss, xml, json)
1584 * @return array|string
1585 * @throws BadRequestException
1586 * @throws ForbiddenException
1587 * @throws ImagickException
1588 * @throws InternalServerErrorException
1589 * @throws UnauthorizedException
1590 * @todo Optional parameters
1591 * @todo Add reply info
1593 function api_statuses_home_timeline($type)
1596 $user_info = api_get_user($a);
1598 if (api_user() === false || $user_info === false) {
1599 throw new ForbiddenException();
1602 unset($_REQUEST["user_id"]);
1603 unset($_GET["user_id"]);
1605 unset($_REQUEST["screen_name"]);
1606 unset($_GET["screen_name"]);
1608 // get last network messages
1611 $count = defaults($_REQUEST, 'count', 20);
1612 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1616 $since_id = defaults($_REQUEST, 'since_id', 0);
1617 $max_id = defaults($_REQUEST, 'max_id', 0);
1618 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1619 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1621 $start = $page * $count;
1623 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1624 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1627 $condition[0] .= " AND `item`.`id` <= ?";
1628 $condition[] = $max_id;
1630 if ($exclude_replies) {
1631 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1633 if ($conversation_id > 0) {
1634 $condition[0] .= " AND `item`.`parent` = ?";
1635 $condition[] = $conversation_id;
1638 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1639 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1641 $items = Item::inArray($statuses);
1643 $ret = api_format_items($items, $user_info, false, $type);
1645 // Set all posts from the query above to seen
1647 foreach ($items as $item) {
1648 $idarray[] = intval($item["id"]);
1651 if (!empty($idarray)) {
1652 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1654 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1660 $data = ['status' => $ret];
1665 $data = api_rss_extra($a, $data, $user_info);
1669 return api_format_data("statuses", $type, $data);
1673 /// @TODO move to top of file or somewhere better
1674 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1675 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1678 * Returns the most recent statuses from public users.
1680 * @param string $type Return type (atom, rss, xml, json)
1682 * @return array|string
1683 * @throws BadRequestException
1684 * @throws ForbiddenException
1685 * @throws ImagickException
1686 * @throws InternalServerErrorException
1687 * @throws UnauthorizedException
1689 function api_statuses_public_timeline($type)
1692 $user_info = api_get_user($a);
1694 if (api_user() === false || $user_info === false) {
1695 throw new ForbiddenException();
1698 // get last network messages
1701 $count = defaults($_REQUEST, 'count', 20);
1702 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1706 $since_id = defaults($_REQUEST, 'since_id', 0);
1707 $max_id = defaults($_REQUEST, 'max_id', 0);
1708 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1709 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1711 $start = $page * $count;
1713 if ($exclude_replies && !$conversation_id) {
1714 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1715 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1718 $condition[0] .= " AND `thread`.`iid` <= ?";
1719 $condition[] = $max_id;
1722 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1723 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1725 $r = Item::inArray($statuses);
1727 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1728 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1731 $condition[0] .= " AND `item`.`id` <= ?";
1732 $condition[] = $max_id;
1734 if ($conversation_id > 0) {
1735 $condition[0] .= " AND `item`.`parent` = ?";
1736 $condition[] = $conversation_id;
1739 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1740 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1742 $r = Item::inArray($statuses);
1745 $ret = api_format_items($r, $user_info, false, $type);
1749 $data = ['status' => $ret];
1754 $data = api_rss_extra($a, $data, $user_info);
1758 return api_format_data("statuses", $type, $data);
1761 /// @TODO move to top of file or somewhere better
1762 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1765 * Returns the most recent statuses posted by users this node knows about.
1767 * @brief Returns the list of public federated posts this node knows about
1769 * @param string $type Return format: json, xml, atom, rss
1770 * @return array|string
1771 * @throws BadRequestException
1772 * @throws ForbiddenException
1773 * @throws ImagickException
1774 * @throws InternalServerErrorException
1775 * @throws UnauthorizedException
1777 function api_statuses_networkpublic_timeline($type)
1780 $user_info = api_get_user($a);
1782 if (api_user() === false || $user_info === false) {
1783 throw new ForbiddenException();
1786 $since_id = defaults($_REQUEST, 'since_id', 0);
1787 $max_id = defaults($_REQUEST, 'max_id', 0);
1790 $count = defaults($_REQUEST, 'count', 20);
1791 $page = defaults($_REQUEST, 'page', 1);
1795 $start = ($page - 1) * $count;
1797 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1798 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1801 $condition[0] .= " AND `thread`.`iid` <= ?";
1802 $condition[] = $max_id;
1805 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1806 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1808 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1812 $data = ['status' => $ret];
1817 $data = api_rss_extra($a, $data, $user_info);
1821 return api_format_data("statuses", $type, $data);
1824 /// @TODO move to top of file or somewhere better
1825 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1828 * Returns a single status.
1830 * @param string $type Return type (atom, rss, xml, json)
1832 * @return array|string
1833 * @throws BadRequestException
1834 * @throws ForbiddenException
1835 * @throws ImagickException
1836 * @throws InternalServerErrorException
1837 * @throws UnauthorizedException
1838 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1840 function api_statuses_show($type)
1843 $user_info = api_get_user($a);
1845 if (api_user() === false || $user_info === false) {
1846 throw new ForbiddenException();
1850 $id = intval(defaults($a->argv, 3, 0));
1853 $id = intval(defaults($_REQUEST, 'id', 0));
1858 $id = intval(defaults($a->argv, 4, 0));
1861 Logger::log('API: api_statuses_show: ' . $id);
1863 $conversation = !empty($_REQUEST['conversation']);
1865 // try to fetch the item for the local user - or the public item, if there is no local one
1866 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1867 if (!DBA::isResult($uri_item)) {
1868 throw new BadRequestException("There is no status with this id.");
1871 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1872 if (!DBA::isResult($item)) {
1873 throw new BadRequestException("There is no status with this id.");
1878 if ($conversation) {
1879 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1880 $params = ['order' => ['id' => true]];
1882 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1886 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1888 /// @TODO How about copying this to above methods which don't check $r ?
1889 if (!DBA::isResult($statuses)) {
1890 throw new BadRequestException("There is no status with this id.");
1893 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1895 if ($conversation) {
1896 $data = ['status' => $ret];
1897 return api_format_data("statuses", $type, $data);
1899 $data = ['status' => $ret[0]];
1900 return api_format_data("status", $type, $data);
1904 /// @TODO move to top of file or somewhere better
1905 api_register_func('api/statuses/show', 'api_statuses_show', true);
1909 * @param string $type Return type (atom, rss, xml, json)
1911 * @return array|string
1912 * @throws BadRequestException
1913 * @throws ForbiddenException
1914 * @throws ImagickException
1915 * @throws InternalServerErrorException
1916 * @throws UnauthorizedException
1917 * @todo nothing to say?
1919 function api_conversation_show($type)
1922 $user_info = api_get_user($a);
1924 if (api_user() === false || $user_info === false) {
1925 throw new ForbiddenException();
1929 $id = intval(defaults($a->argv , 3 , 0));
1930 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1931 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1932 $count = intval(defaults($_REQUEST, 'count' , 20));
1933 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1938 $start = $page * $count;
1941 $id = intval(defaults($_REQUEST, 'id', 0));
1946 $id = intval(defaults($a->argv, 4, 0));
1949 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1951 // try to fetch the item for the local user - or the public item, if there is no local one
1952 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1953 if (!DBA::isResult($item)) {
1954 throw new BadRequestException("There is no status with this id.");
1957 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1958 if (!DBA::isResult($parent)) {
1959 throw new BadRequestException("There is no status with this id.");
1962 $id = $parent['id'];
1964 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1965 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1968 $condition[0] .= " AND `item`.`id` <= ?";
1969 $condition[] = $max_id;
1972 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1973 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1975 if (!DBA::isResult($statuses)) {
1976 throw new BadRequestException("There is no status with id $id.");
1979 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1981 $data = ['status' => $ret];
1982 return api_format_data("statuses", $type, $data);
1985 /// @TODO move to top of file or somewhere better
1986 api_register_func('api/conversation/show', 'api_conversation_show', true);
1987 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1992 * @param string $type Return type (atom, rss, xml, json)
1994 * @return array|string
1995 * @throws BadRequestException
1996 * @throws ForbiddenException
1997 * @throws ImagickException
1998 * @throws InternalServerErrorException
1999 * @throws UnauthorizedException
2000 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2002 function api_statuses_repeat($type)
2008 if (api_user() === false) {
2009 throw new ForbiddenException();
2015 $id = intval(defaults($a->argv, 3, 0));
2018 $id = intval(defaults($_REQUEST, 'id', 0));
2023 $id = intval(defaults($a->argv, 4, 0));
2026 Logger::log('API: api_statuses_repeat: '.$id);
2028 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2029 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2031 if (DBA::isResult($item) && $item['body'] != "") {
2032 if (strpos($item['body'], "[/share]") !== false) {
2033 $pos = strpos($item['body'], "[share");
2034 $post = substr($item['body'], $pos);
2036 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2038 $post .= $item['body'];
2039 $post .= "[/share]";
2041 $_REQUEST['body'] = $post;
2042 $_REQUEST['profile_uid'] = api_user();
2043 $_REQUEST['api_source'] = true;
2045 if (empty($_REQUEST['source'])) {
2046 $_REQUEST["source"] = api_source();
2049 $item_id = item_post($a);
2051 throw new ForbiddenException();
2054 // output the post that we just posted.
2056 return api_status_show($type, $item_id);
2059 /// @TODO move to top of file or somewhere better
2060 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2063 * Destroys a specific status.
2065 * @param string $type Return type (atom, rss, xml, json)
2067 * @return array|string
2068 * @throws BadRequestException
2069 * @throws ForbiddenException
2070 * @throws ImagickException
2071 * @throws InternalServerErrorException
2072 * @throws UnauthorizedException
2073 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2075 function api_statuses_destroy($type)
2079 if (api_user() === false) {
2080 throw new ForbiddenException();
2086 $id = intval(defaults($a->argv, 3, 0));
2089 $id = intval(defaults($_REQUEST, 'id', 0));
2094 $id = intval(defaults($a->argv, 4, 0));
2097 Logger::log('API: api_statuses_destroy: '.$id);
2099 $ret = api_statuses_show($type);
2101 Item::deleteForUser(['id' => $id], api_user());
2106 /// @TODO move to top of file or somewhere better
2107 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2110 * Returns the most recent mentions.
2112 * @param string $type Return type (atom, rss, xml, json)
2114 * @return array|string
2115 * @throws BadRequestException
2116 * @throws ForbiddenException
2117 * @throws ImagickException
2118 * @throws InternalServerErrorException
2119 * @throws UnauthorizedException
2120 * @see http://developer.twitter.com/doc/get/statuses/mentions
2122 function api_statuses_mentions($type)
2125 $user_info = api_get_user($a);
2127 if (api_user() === false || $user_info === false) {
2128 throw new ForbiddenException();
2131 unset($_REQUEST["user_id"]);
2132 unset($_GET["user_id"]);
2134 unset($_REQUEST["screen_name"]);
2135 unset($_GET["screen_name"]);
2137 // get last network messages
2140 $since_id = defaults($_REQUEST, 'since_id', 0);
2141 $max_id = defaults($_REQUEST, 'max_id' , 0);
2142 $count = defaults($_REQUEST, 'count' , 20);
2143 $page = defaults($_REQUEST, 'page' , 1);
2148 $start = ($page - 1) * $count;
2150 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2151 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2152 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2155 $condition[0] .= " AND `item`.`id` <= ?";
2156 $condition[] = $max_id;
2159 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2160 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2162 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2164 $data = ['status' => $ret];
2169 $data = api_rss_extra($a, $data, $user_info);
2173 return api_format_data("statuses", $type, $data);
2176 /// @TODO move to top of file or somewhere better
2177 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2178 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2181 * Returns the most recent statuses posted by the user.
2183 * @brief Returns a user's public timeline
2185 * @param string $type Either "json" or "xml"
2186 * @return string|array
2187 * @throws BadRequestException
2188 * @throws ForbiddenException
2189 * @throws ImagickException
2190 * @throws InternalServerErrorException
2191 * @throws UnauthorizedException
2192 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2194 function api_statuses_user_timeline($type)
2197 $user_info = api_get_user($a);
2199 if (api_user() === false || $user_info === false) {
2200 throw new ForbiddenException();
2204 "api_statuses_user_timeline: api_user: ". api_user() .
2205 "\nuser_info: ".print_r($user_info, true) .
2206 "\n_REQUEST: ".print_r($_REQUEST, true),
2210 $since_id = defaults($_REQUEST, 'since_id', 0);
2211 $max_id = defaults($_REQUEST, 'max_id', 0);
2212 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2213 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2216 $count = defaults($_REQUEST, 'count', 20);
2217 $page = defaults($_REQUEST, 'page', 1);
2221 $start = ($page - 1) * $count;
2223 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2224 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2226 if ($user_info['self'] == 1) {
2227 $condition[0] .= ' AND `item`.`wall` ';
2230 if ($exclude_replies) {
2231 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2234 if ($conversation_id > 0) {
2235 $condition[0] .= " AND `item`.`parent` = ?";
2236 $condition[] = $conversation_id;
2240 $condition[0] .= " AND `item`.`id` <= ?";
2241 $condition[] = $max_id;
2244 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2245 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2247 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2251 $data = ['status' => $ret];
2256 $data = api_rss_extra($a, $data, $user_info);
2260 return api_format_data("statuses", $type, $data);
2263 /// @TODO move to top of file or somewhere better
2264 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2267 * Star/unstar an item.
2268 * param: id : id of the item
2270 * @param string $type Return type (atom, rss, xml, json)
2272 * @return array|string
2273 * @throws BadRequestException
2274 * @throws ForbiddenException
2275 * @throws ImagickException
2276 * @throws InternalServerErrorException
2277 * @throws UnauthorizedException
2278 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2280 function api_favorites_create_destroy($type)
2284 if (api_user() === false) {
2285 throw new ForbiddenException();
2288 // for versioned api.
2289 /// @TODO We need a better global soluton
2290 $action_argv_id = 2;
2291 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2292 $action_argv_id = 3;
2295 if ($a->argc <= $action_argv_id) {
2296 throw new BadRequestException("Invalid request.");
2298 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2299 if ($a->argc == $action_argv_id + 2) {
2300 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2302 $itemid = intval(defaults($_REQUEST, 'id', 0));
2305 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2307 if (!DBA::isResult($item)) {
2308 throw new BadRequestException("Invalid item.");
2313 $item['starred'] = 1;
2316 $item['starred'] = 0;
2319 throw new BadRequestException("Invalid action ".$action);
2322 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2325 throw new InternalServerErrorException("DB error");
2329 $user_info = api_get_user($a);
2330 $rets = api_format_items([$item], $user_info, false, $type);
2333 $data = ['status' => $ret];
2338 $data = api_rss_extra($a, $data, $user_info);
2342 return api_format_data("status", $type, $data);
2345 /// @TODO move to top of file or somewhere better
2346 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2347 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2350 * Returns the most recent favorite statuses.
2352 * @param string $type Return type (atom, rss, xml, json)
2354 * @return string|array
2355 * @throws BadRequestException
2356 * @throws ForbiddenException
2357 * @throws ImagickException
2358 * @throws InternalServerErrorException
2359 * @throws UnauthorizedException
2361 function api_favorites($type)
2366 $user_info = api_get_user($a);
2368 if (api_user() === false || $user_info === false) {
2369 throw new ForbiddenException();
2374 // in friendica starred item are private
2375 // return favorites only for self
2376 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2378 if ($user_info['self'] == 0) {
2382 $since_id = defaults($_REQUEST, 'since_id', 0);
2383 $max_id = defaults($_REQUEST, 'max_id', 0);
2384 $count = defaults($_GET, 'count', 20);
2385 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2390 $start = $page*$count;
2392 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2393 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2395 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2398 $condition[0] .= " AND `item`.`id` <= ?";
2399 $condition[] = $max_id;
2402 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2404 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2409 $data = ['status' => $ret];
2414 $data = api_rss_extra($a, $data, $user_info);
2418 return api_format_data("statuses", $type, $data);
2421 /// @TODO move to top of file or somewhere better
2422 api_register_func('api/favorites', 'api_favorites', true);
2426 * @param array $item
2427 * @param array $recipient
2428 * @param array $sender
2431 * @throws InternalServerErrorException
2433 function api_format_messages($item, $recipient, $sender)
2435 // standard meta information
2437 'id' => $item['id'],
2438 'sender_id' => $sender['id'],
2440 'recipient_id' => $recipient['id'],
2441 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2442 'sender_screen_name' => $sender['screen_name'],
2443 'recipient_screen_name' => $recipient['screen_name'],
2444 'sender' => $sender,
2445 'recipient' => $recipient,
2447 'friendica_seen' => defaults($item, 'seen', 0),
2448 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2451 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2452 if (isset($ret['sender']['uid'])) {
2453 unset($ret['sender']['uid']);
2455 if (isset($ret['sender']['self'])) {
2456 unset($ret['sender']['self']);
2458 if (isset($ret['recipient']['uid'])) {
2459 unset($ret['recipient']['uid']);
2461 if (isset($ret['recipient']['self'])) {
2462 unset($ret['recipient']['self']);
2465 //don't send title to regular StatusNET requests to avoid confusing these apps
2466 if (!empty($_GET['getText'])) {
2467 $ret['title'] = $item['title'];
2468 if ($_GET['getText'] == 'html') {
2469 $ret['text'] = BBCode::convert($item['body'], false);
2470 } elseif ($_GET['getText'] == 'plain') {
2471 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2474 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2476 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2477 unset($ret['sender']);
2478 unset($ret['recipient']);
2486 * @param array $item
2489 * @throws InternalServerErrorException
2491 function api_convert_item($item)
2493 $body = $item['body'];
2494 $attachments = api_get_attachments($body);
2496 // Workaround for ostatus messages where the title is identically to the body
2497 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2498 $statusbody = trim(HTML::toPlaintext($html, 0));
2500 // handle data: images
2501 $statusbody = api_format_items_embeded_images($item, $statusbody);
2503 $statustitle = trim($item['title']);
2505 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2506 $statustext = trim($statusbody);
2508 $statustext = trim($statustitle."\n\n".$statusbody);
2511 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2512 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2515 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2517 // Workaround for clients with limited HTML parser functionality
2518 $search = ["<br>", "<blockquote>", "</blockquote>",
2519 "<h1>", "</h1>", "<h2>", "</h2>",
2520 "<h3>", "</h3>", "<h4>", "</h4>",
2521 "<h5>", "</h5>", "<h6>", "</h6>"];
2522 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2523 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2524 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2525 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2526 $statushtml = str_replace($search, $replace, $statushtml);
2528 if ($item['title'] != "") {
2529 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2533 $oldtext = $statushtml;
2534 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2535 } while ($oldtext != $statushtml);
2537 if (substr($statushtml, 0, 4) == '<br>') {
2538 $statushtml = substr($statushtml, 4);
2541 if (substr($statushtml, 0, -4) == '<br>') {
2542 $statushtml = substr($statushtml, -4);
2545 // feeds without body should contain the link
2546 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2547 $statushtml .= BBCode::convert($item['plink']);
2550 $entities = api_get_entitities($statustext, $body);
2553 "text" => $statustext,
2554 "html" => $statushtml,
2555 "attachments" => $attachments,
2556 "entities" => $entities
2562 * @param string $body
2565 * @throws InternalServerErrorException
2567 function api_get_attachments(&$body)
2570 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2572 $URLSearchString = "^\[\]";
2573 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2581 foreach ($images[1] as $image) {
2582 $imagedata = Image::getInfoFromURL($image);
2585 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2589 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2590 foreach ($images[0] as $orig) {
2591 $body = str_replace($orig, "", $body);
2595 return $attachments;
2600 * @param string $text
2601 * @param string $bbcode
2604 * @throws InternalServerErrorException
2605 * @todo Links at the first character of the post
2607 function api_get_entitities(&$text, $bbcode)
2609 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2611 if ($include_entities != "true") {
2612 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2614 foreach ($images[1] as $image) {
2615 $replace = ProxyUtils::proxifyUrl($image);
2616 $text = str_replace($image, $replace, $text);
2621 $bbcode = BBCode::cleanPictureLinks($bbcode);
2623 // Change pure links in text to bbcode uris
2624 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2627 $entities["hashtags"] = [];
2628 $entities["symbols"] = [];
2629 $entities["urls"] = [];
2630 $entities["user_mentions"] = [];
2632 $URLSearchString = "^\[\]";
2634 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2636 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2637 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2638 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2640 $bbcode = preg_replace(
2641 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2642 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2645 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2647 $bbcode = preg_replace(
2648 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2649 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2652 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2654 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2656 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2657 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2660 foreach ($urls[1] as $id => $url) {
2661 //$start = strpos($text, $url, $offset);
2662 $start = iconv_strpos($text, $url, 0, "UTF-8");
2663 if (!($start === false)) {
2664 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2668 ksort($ordered_urls);
2671 //foreach ($urls[1] AS $id=>$url) {
2672 foreach ($ordered_urls as $url) {
2673 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2674 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2676 $display_url = $url["title"];
2678 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2679 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2681 if (strlen($display_url) > 26) {
2682 $display_url = substr($display_url, 0, 25)."…";
2686 //$start = strpos($text, $url, $offset);
2687 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2688 if (!($start === false)) {
2689 $entities["urls"][] = ["url" => $url["url"],
2690 "expanded_url" => $url["url"],
2691 "display_url" => $display_url,
2692 "indices" => [$start, $start+strlen($url["url"])]];
2693 $offset = $start + 1;
2697 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2698 $ordered_images = [];
2699 foreach ($images as $image) {
2700 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2701 if (!($start === false)) {
2702 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2706 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2707 foreach ($images[1] as $image) {
2708 $start = iconv_strpos($text, $image, 0, "UTF-8");
2709 if (!($start === false)) {
2710 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2713 //$entities["media"] = array();
2716 foreach ($ordered_images as $image) {
2717 $url = $image['url'];
2718 $ext_alt_text = $image['alt'];
2720 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2721 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2723 if (strlen($display_url) > 26) {
2724 $display_url = substr($display_url, 0, 25)."…";
2727 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2728 if (!($start === false)) {
2729 $image = Image::getInfoFromURL($url);
2731 // If image cache is activated, then use the following sizes:
2732 // thumb (150), small (340), medium (600) and large (1024)
2733 if (!Config::get("system", "proxy_disabled")) {
2734 $media_url = ProxyUtils::proxifyUrl($url);
2737 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2738 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2740 if (($image[0] > 150) || ($image[1] > 150)) {
2741 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2742 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2745 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2746 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2748 if (($image[0] > 600) || ($image[1] > 600)) {
2749 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2750 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2754 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2757 $entities["media"][] = [
2759 "id_str" => (string) ($start + 1),
2760 "indices" => [$start, $start+strlen($url)],
2761 "media_url" => Strings::normaliseLink($media_url),
2762 "media_url_https" => $media_url,
2764 "display_url" => $display_url,
2765 "expanded_url" => $url,
2766 "ext_alt_text" => $ext_alt_text,
2770 $offset = $start + 1;
2779 * @param array $item
2780 * @param string $text
2784 function api_format_items_embeded_images($item, $text)
2786 $text = preg_replace_callback(
2787 '|data:image/([^;]+)[^=]+=*|m',
2788 function () use ($item) {
2789 return System::baseUrl() . '/display/' . $item['guid'];
2797 * @brief return <a href='url'>name</a> as array
2799 * @param string $txt text
2804 function api_contactlink_to_array($txt)
2807 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2808 if ($r && count($match)==3) {
2810 'name' => $match[2],
2824 * @brief return likes, dislikes and attend status for item
2826 * @param array $item array
2827 * @param string $type Return type (atom, rss, xml, json)
2830 * likes => int count,
2831 * dislikes => int count
2832 * @throws BadRequestException
2833 * @throws ImagickException
2834 * @throws InternalServerErrorException
2835 * @throws UnauthorizedException
2837 function api_format_items_activities($item, $type = "json")
2846 'attendmaybe' => [],
2849 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2850 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2852 while ($parent_item = Item::fetch($ret)) {
2853 // not used as result should be structured like other user data
2854 //builtin_activity_puller($i, $activities);
2856 // get user data and add it to the array of the activity
2857 $user = api_get_user($a, $parent_item['author-id']);
2858 switch ($parent_item['verb']) {
2860 $activities['like'][] = $user;
2862 case ACTIVITY_DISLIKE:
2863 $activities['dislike'][] = $user;
2865 case ACTIVITY_ATTEND:
2866 $activities['attendyes'][] = $user;
2868 case ACTIVITY_ATTENDNO:
2869 $activities['attendno'][] = $user;
2871 case ACTIVITY_ATTENDMAYBE:
2872 $activities['attendmaybe'][] = $user;
2881 if ($type == "xml") {
2882 $xml_activities = [];
2883 foreach ($activities as $k => $v) {
2884 // change xml element from "like" to "friendica:like"
2885 $xml_activities["friendica:".$k] = $v;
2886 // add user data into xml output
2888 foreach ($v as $user) {
2889 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2892 $activities = $xml_activities;
2900 * @brief return data from profiles
2902 * @param array $profile_row array containing data from db table 'profile'
2904 * @throws InternalServerErrorException
2906 function api_format_items_profiles($profile_row)
2909 'profile_id' => $profile_row['id'],
2910 'profile_name' => $profile_row['profile-name'],
2911 'is_default' => $profile_row['is-default'] ? true : false,
2912 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2913 'profile_photo' => $profile_row['photo'],
2914 'profile_thumb' => $profile_row['thumb'],
2915 'publish' => $profile_row['publish'] ? true : false,
2916 'net_publish' => $profile_row['net-publish'] ? true : false,
2917 'description' => $profile_row['pdesc'],
2918 'date_of_birth' => $profile_row['dob'],
2919 'address' => $profile_row['address'],
2920 'city' => $profile_row['locality'],
2921 'region' => $profile_row['region'],
2922 'postal_code' => $profile_row['postal-code'],
2923 'country' => $profile_row['country-name'],
2924 'hometown' => $profile_row['hometown'],
2925 'gender' => $profile_row['gender'],
2926 'marital' => $profile_row['marital'],
2927 'marital_with' => $profile_row['with'],
2928 'marital_since' => $profile_row['howlong'],
2929 'sexual' => $profile_row['sexual'],
2930 'politic' => $profile_row['politic'],
2931 'religion' => $profile_row['religion'],
2932 'public_keywords' => $profile_row['pub_keywords'],
2933 'private_keywords' => $profile_row['prv_keywords'],
2934 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2935 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2936 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2937 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2938 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2939 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2940 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2941 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2942 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2943 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2944 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2945 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2946 'homepage' => $profile_row['homepage'],
2953 * @brief format items to be returned by api
2955 * @param array $items array of items
2956 * @param array $user_info
2957 * @param bool $filter_user filter items by $user_info
2958 * @param string $type Return type (atom, rss, xml, json)
2960 * @throws BadRequestException
2961 * @throws ImagickException
2962 * @throws InternalServerErrorException
2963 * @throws UnauthorizedException
2965 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2967 $a = \Friendica\BaseObject::getApp();
2971 foreach ((array)$items as $item) {
2972 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2974 // Look if the posts are matching if they should be filtered by user id
2975 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2979 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2988 * @param array $item Item record
2989 * @param string $type Return format (atom, rss, xml, json)
2990 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2991 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2992 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2993 * @return array API-formatted status
2994 * @throws BadRequestException
2995 * @throws ImagickException
2996 * @throws InternalServerErrorException
2997 * @throws UnauthorizedException
2999 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3001 $a = \Friendica\BaseObject::getApp();
3003 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3004 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3007 localize_item($item);
3009 $in_reply_to = api_in_reply_to($item);
3011 $converted = api_convert_item($item);
3013 if ($type == "xml") {
3014 $geo = "georss:point";
3020 'text' => $converted["text"],
3021 'truncated' => false,
3022 'created_at'=> api_date($item['created']),
3023 'in_reply_to_status_id' => $in_reply_to['status_id'],
3024 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3025 'source' => (($item['app']) ? $item['app'] : 'web'),
3026 'id' => intval($item['id']),
3027 'id_str' => (string) intval($item['id']),
3028 'in_reply_to_user_id' => $in_reply_to['user_id'],
3029 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3030 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3032 'favorited' => $item['starred'] ? true : false,
3033 'user' => $status_user,
3034 'friendica_author' => $author_user,
3035 'friendica_owner' => $owner_user,
3036 'friendica_private' => $item['private'] == 1,
3037 //'entities' => NULL,
3038 'statusnet_html' => $converted["html"],
3039 'statusnet_conversation_id' => $item['parent'],
3040 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3041 'friendica_activities' => api_format_items_activities($item, $type),
3042 'friendica_title' => $item['title'],
3043 'friendica_html' => BBCode::convert($item['body'], false)
3046 if (count($converted["attachments"]) > 0) {
3047 $status["attachments"] = $converted["attachments"];
3050 if (count($converted["entities"]) > 0) {
3051 $status["entities"] = $converted["entities"];
3054 if ($status["source"] == 'web') {
3055 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3056 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3057 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3060 $retweeted_item = [];
3063 if ($item["id"] == $item["parent"]) {
3064 $body = $item['body'];
3065 $retweeted_item = api_share_as_retweet($item);
3066 if ($body != $item['body']) {
3067 $quoted_item = $retweeted_item;
3068 $retweeted_item = [];
3072 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3073 $announce = api_get_announce($item);
3074 if (!empty($announce)) {
3075 $retweeted_item = $item;
3077 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3081 if (!empty($quoted_item)) {
3082 $conv_quoted = api_convert_item($quoted_item);
3083 $quoted_status = $status;
3084 unset($quoted_status['friendica_author']);
3085 unset($quoted_status['friendica_owner']);
3086 unset($quoted_status['friendica_activities']);
3087 unset($quoted_status['friendica_private']);
3088 unset($quoted_status['statusnet_conversation_id']);
3089 $quoted_status['text'] = $conv_quoted['text'];
3090 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3092 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3093 } catch (BadRequestException $e) {
3094 // user not found. should be found?
3095 /// @todo check if the user should be always found
3096 $quoted_status["user"] = [];
3100 if (!empty($retweeted_item)) {
3101 $retweeted_status = $status;
3102 unset($retweeted_status['friendica_author']);
3103 unset($retweeted_status['friendica_owner']);
3104 unset($retweeted_status['friendica_activities']);
3105 unset($retweeted_status['friendica_private']);
3106 unset($retweeted_status['statusnet_conversation_id']);
3107 $status['user'] = $status['friendica_owner'];
3109 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3110 } catch (BadRequestException $e) {
3111 // user not found. should be found?
3112 /// @todo check if the user should be always found
3113 $retweeted_status["user"] = [];
3116 $rt_converted = api_convert_item($retweeted_item);
3118 $retweeted_status['text'] = $rt_converted["text"];
3119 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3120 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3122 if (!empty($quoted_status)) {
3123 $retweeted_status['quoted_status'] = $quoted_status;
3126 $status['friendica_author'] = $retweeted_status['user'];
3127 $status['retweeted_status'] = $retweeted_status;
3128 } elseif (!empty($quoted_status)) {
3129 $root_status = api_convert_item($item);
3131 $status['text'] = $root_status["text"];
3132 $status['statusnet_html'] = $root_status["html"];
3133 $status['quoted_status'] = $quoted_status;
3136 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3137 unset($status["user"]["uid"]);
3138 unset($status["user"]["self"]);
3140 if ($item["coord"] != "") {
3141 $coords = explode(' ', $item["coord"]);
3142 if (count($coords) == 2) {
3143 if ($type == "json") {
3144 $status["geo"] = ['type' => 'Point',
3145 'coordinates' => [(float) $coords[0],
3146 (float) $coords[1]]];
3147 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3148 $status["georss:point"] = $item["coord"];
3157 * Returns the remaining number of API requests available to the user before the API limit is reached.
3159 * @param string $type Return type (atom, rss, xml, json)
3161 * @return array|string
3164 function api_account_rate_limit_status($type)
3166 if ($type == "xml") {
3168 'remaining-hits' => '150',
3169 '@attributes' => ["type" => "integer"],
3170 'hourly-limit' => '150',
3171 '@attributes2' => ["type" => "integer"],
3172 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3173 '@attributes3' => ["type" => "datetime"],
3174 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3175 '@attributes4' => ["type" => "integer"],
3179 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3180 'remaining_hits' => '150',
3181 'hourly_limit' => '150',
3182 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3186 return api_format_data('hash', $type, ['hash' => $hash]);
3189 /// @TODO move to top of file or somewhere better
3190 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3193 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3195 * @param string $type Return type (atom, rss, xml, json)
3197 * @return array|string
3199 function api_help_test($type)
3201 if ($type == 'xml') {
3207 return api_format_data('ok', $type, ["ok" => $ok]);
3210 /// @TODO move to top of file or somewhere better
3211 api_register_func('api/help/test', 'api_help_test', false);
3214 * Returns all lists the user subscribes to.
3216 * @param string $type Return type (atom, rss, xml, json)
3218 * @return array|string
3219 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3221 function api_lists_list($type)
3224 /// @TODO $ret is not filled here?
3225 return api_format_data('lists', $type, ["lists_list" => $ret]);
3228 /// @TODO move to top of file or somewhere better
3229 api_register_func('api/lists/list', 'api_lists_list', true);
3230 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3233 * Returns all groups the user owns.
3235 * @param string $type Return type (atom, rss, xml, json)
3237 * @return array|string
3238 * @throws BadRequestException
3239 * @throws ForbiddenException
3240 * @throws ImagickException
3241 * @throws InternalServerErrorException
3242 * @throws UnauthorizedException
3243 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3245 function api_lists_ownerships($type)
3249 if (api_user() === false) {
3250 throw new ForbiddenException();
3254 $user_info = api_get_user($a);
3255 $uid = $user_info['uid'];
3257 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3259 // loop through all groups
3261 foreach ($groups as $group) {
3262 if ($group['visible']) {
3268 'name' => $group['name'],
3269 'id' => intval($group['id']),
3270 'id_str' => (string) $group['id'],
3271 'user' => $user_info,
3275 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3278 /// @TODO move to top of file or somewhere better
3279 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3282 * Returns recent statuses from users in the specified group.
3284 * @param string $type Return type (atom, rss, xml, json)
3286 * @return array|string
3287 * @throws BadRequestException
3288 * @throws ForbiddenException
3289 * @throws ImagickException
3290 * @throws InternalServerErrorException
3291 * @throws UnauthorizedException
3292 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3294 function api_lists_statuses($type)
3298 $user_info = api_get_user($a);
3299 if (api_user() === false || $user_info === false) {
3300 throw new ForbiddenException();
3303 unset($_REQUEST["user_id"]);
3304 unset($_GET["user_id"]);
3306 unset($_REQUEST["screen_name"]);
3307 unset($_GET["screen_name"]);
3309 if (empty($_REQUEST['list_id'])) {
3310 throw new BadRequestException('list_id not specified');
3314 $count = defaults($_REQUEST, 'count', 20);
3315 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3319 $since_id = defaults($_REQUEST, 'since_id', 0);
3320 $max_id = defaults($_REQUEST, 'max_id', 0);
3321 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3322 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3324 $start = $page * $count;
3326 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3327 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3330 $condition[0] .= " AND `item`.`id` <= ?";
3331 $condition[] = $max_id;
3333 if ($exclude_replies > 0) {
3334 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3336 if ($conversation_id > 0) {
3337 $condition[0] .= " AND `item`.`parent` = ?";
3338 $condition[] = $conversation_id;
3341 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3342 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3344 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3346 $data = ['status' => $items];
3351 $data = api_rss_extra($a, $data, $user_info);
3355 return api_format_data("statuses", $type, $data);
3358 /// @TODO move to top of file or somewhere better
3359 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3362 * Considers friends and followers lists to be private and won't return
3363 * anything if any user_id parameter is passed.
3365 * @brief Returns either the friends of the follower list
3367 * @param string $qtype Either "friends" or "followers"
3368 * @return boolean|array
3369 * @throws BadRequestException
3370 * @throws ForbiddenException
3371 * @throws ImagickException
3372 * @throws InternalServerErrorException
3373 * @throws UnauthorizedException
3375 function api_statuses_f($qtype)
3379 if (api_user() === false) {
3380 throw new ForbiddenException();
3384 $count = defaults($_GET, 'count', 20);
3385 $page = defaults($_GET, 'page', 1);
3389 $start = ($page - 1) * $count;
3391 $user_info = api_get_user($a);
3393 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3394 /* this is to stop Hotot to load friends multiple times
3395 * I'm not sure if I'm missing return something or
3396 * is a bug in hotot. Workaround, meantime
3400 return array('$users' => $ret);*/
3405 if ($qtype == 'friends') {
3406 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3407 } elseif ($qtype == 'followers') {
3408 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3411 // friends and followers only for self
3412 if ($user_info['self'] == 0) {
3413 $sql_extra = " AND false ";
3416 if ($qtype == 'blocks') {
3417 $sql_filter = 'AND `blocked` AND NOT `pending`';
3418 } elseif ($qtype == 'incoming') {
3419 $sql_filter = 'AND `pending`';
3421 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3439 foreach ($r as $cid) {
3440 $user = api_get_user($a, $cid['nurl']);
3441 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3442 unset($user["uid"]);
3443 unset($user["self"]);
3450 return ['user' => $ret];
3455 * Returns the user's friends.
3457 * @brief Returns the list of friends of the provided user
3459 * @deprecated By Twitter API in favor of friends/list
3461 * @param string $type Either "json" or "xml"
3462 * @return boolean|string|array
3463 * @throws BadRequestException
3464 * @throws ForbiddenException
3466 function api_statuses_friends($type)
3468 $data = api_statuses_f("friends");
3469 if ($data === false) {
3472 return api_format_data("users", $type, $data);
3476 * Returns the user's followers.
3478 * @brief Returns the list of followers of the provided user
3480 * @deprecated By Twitter API in favor of friends/list
3482 * @param string $type Either "json" or "xml"
3483 * @return boolean|string|array
3484 * @throws BadRequestException
3485 * @throws ForbiddenException
3487 function api_statuses_followers($type)
3489 $data = api_statuses_f("followers");
3490 if ($data === false) {
3493 return api_format_data("users", $type, $data);
3496 /// @TODO move to top of file or somewhere better
3497 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3498 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3501 * Returns the list of blocked users
3503 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3505 * @param string $type Either "json" or "xml"
3507 * @return boolean|string|array
3508 * @throws BadRequestException
3509 * @throws ForbiddenException
3511 function api_blocks_list($type)
3513 $data = api_statuses_f('blocks');
3514 if ($data === false) {
3517 return api_format_data("users", $type, $data);
3520 /// @TODO move to top of file or somewhere better
3521 api_register_func('api/blocks/list', 'api_blocks_list', true);
3524 * Returns the list of pending users IDs
3526 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3528 * @param string $type Either "json" or "xml"
3530 * @return boolean|string|array
3531 * @throws BadRequestException
3532 * @throws ForbiddenException
3534 function api_friendships_incoming($type)
3536 $data = api_statuses_f('incoming');
3537 if ($data === false) {
3542 foreach ($data['user'] as $user) {
3543 $ids[] = $user['id'];
3546 return api_format_data("ids", $type, ['id' => $ids]);
3549 /// @TODO move to top of file or somewhere better
3550 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3553 * Returns the instance's configuration information.
3555 * @param string $type Return type (atom, rss, xml, json)
3557 * @return array|string
3558 * @throws InternalServerErrorException
3560 function api_statusnet_config($type)
3564 $name = Config::get('config', 'sitename');
3565 $server = $a->getHostName();
3566 $logo = System::baseUrl() . '/images/friendica-64.png';
3567 $email = Config::get('config', 'admin_email');
3568 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3569 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3570 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3571 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3572 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3575 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3576 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3577 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3578 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3579 'shorturllength' => '30',
3581 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3582 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3583 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3584 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3589 return api_format_data('config', $type, ['config' => $config]);
3592 /// @TODO move to top of file or somewhere better
3593 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3594 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3598 * @param string $type Return type (atom, rss, xml, json)
3600 * @return array|string
3602 function api_statusnet_version($type)
3605 $fake_statusnet_version = "0.9.7";
3607 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3610 /// @TODO move to top of file or somewhere better
3611 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3612 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3616 * @param string $type Return type (atom, rss, xml, json)
3618 * @return array|string|void
3619 * @throws BadRequestException
3620 * @throws ForbiddenException
3621 * @throws ImagickException
3622 * @throws InternalServerErrorException
3623 * @throws UnauthorizedException
3624 * @todo use api_format_data() to return data
3626 function api_ff_ids($type)
3629 throw new ForbiddenException();
3636 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3639 "SELECT `pcontact`.`id` FROM `contact`
3640 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3641 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3644 if (!DBA::isResult($r)) {
3649 foreach ($r as $rr) {
3650 if ($stringify_ids) {
3653 $ids[] = intval($rr['id']);
3657 return api_format_data("ids", $type, ['id' => $ids]);
3661 * Returns the ID of every user the user is following.
3663 * @param string $type Return type (atom, rss, xml, json)
3665 * @return array|string
3666 * @throws BadRequestException
3667 * @throws ForbiddenException
3668 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3670 function api_friends_ids($type)
3672 return api_ff_ids($type);
3676 * Returns the ID of every user following the user.
3678 * @param string $type Return type (atom, rss, xml, json)
3680 * @return array|string
3681 * @throws BadRequestException
3682 * @throws ForbiddenException
3683 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3685 function api_followers_ids($type)
3687 return api_ff_ids($type);
3690 /// @TODO move to top of file or somewhere better
3691 api_register_func('api/friends/ids', 'api_friends_ids', true);
3692 api_register_func('api/followers/ids', 'api_followers_ids', true);
3695 * Sends a new direct message.
3697 * @param string $type Return type (atom, rss, xml, json)
3699 * @return array|string
3700 * @throws BadRequestException
3701 * @throws ForbiddenException
3702 * @throws ImagickException
3703 * @throws InternalServerErrorException
3704 * @throws NotFoundException
3705 * @throws UnauthorizedException
3706 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3708 function api_direct_messages_new($type)
3712 if (api_user() === false) {
3713 throw new ForbiddenException();
3716 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3720 $sender = api_get_user($a);
3723 if (!empty($_POST['screen_name'])) {
3725 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3727 DBA::escape($_POST['screen_name'])
3730 if (DBA::isResult($r)) {
3731 // Selecting the id by priority, friendica first
3732 api_best_nickname($r);
3734 $recipient = api_get_user($a, $r[0]['nurl']);
3737 $recipient = api_get_user($a, $_POST['user_id']);
3740 if (empty($recipient)) {
3741 throw new NotFoundException('Recipient not found');
3745 if (!empty($_REQUEST['replyto'])) {
3747 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3749 intval($_REQUEST['replyto'])
3751 $replyto = $r[0]['parent-uri'];
3752 $sub = $r[0]['title'];
3754 if (!empty($_REQUEST['title'])) {
3755 $sub = $_REQUEST['title'];
3757 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3761 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3764 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3765 $ret = api_format_messages($r[0], $recipient, $sender);
3767 $ret = ["error"=>$id];
3770 $data = ['direct_message'=>$ret];
3776 $data = api_rss_extra($a, $data, $sender);
3780 return api_format_data("direct-messages", $type, $data);
3783 /// @TODO move to top of file or somewhere better
3784 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3787 * Destroys a direct message.
3789 * @brief delete a direct_message from mail table through api
3791 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3792 * @return string|array
3793 * @throws BadRequestException
3794 * @throws ForbiddenException
3795 * @throws ImagickException
3796 * @throws InternalServerErrorException
3797 * @throws UnauthorizedException
3798 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3800 function api_direct_messages_destroy($type)
3804 if (api_user() === false) {
3805 throw new ForbiddenException();
3809 $user_info = api_get_user($a);
3811 $id = defaults($_REQUEST, 'id', 0);
3813 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3814 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3815 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3817 $uid = $user_info['uid'];
3818 // error if no id or parenturi specified (for clients posting parent-uri as well)
3819 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3820 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3821 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3824 // BadRequestException if no id specified (for clients using Twitter API)
3826 throw new BadRequestException('Message id not specified');
3829 // add parent-uri to sql command if specified by calling app
3830 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3832 // get data of the specified message id
3834 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3839 // error message if specified id is not in database
3840 if (!DBA::isResult($r)) {
3841 if ($verbose == "true") {
3842 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3843 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3845 /// @todo BadRequestException ok for Twitter API clients?
3846 throw new BadRequestException('message id not in database');
3851 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3856 if ($verbose == "true") {
3859 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3860 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3862 $answer = ['result' => 'error', 'message' => 'unknown error'];
3863 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3866 /// @todo return JSON data like Twitter API not yet implemented
3869 /// @TODO move to top of file or somewhere better
3870 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3875 * @brief unfollow contact
3877 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3878 * @return string|array
3879 * @throws BadRequestException
3880 * @throws ForbiddenException
3881 * @throws ImagickException
3882 * @throws InternalServerErrorException
3883 * @throws NotFoundException
3884 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3886 function api_friendships_destroy($type)
3890 if ($uid === false) {
3891 throw new ForbiddenException();
3894 $contact_id = defaults($_REQUEST, 'user_id');
3896 if (empty($contact_id)) {
3897 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3898 throw new BadRequestException("no user_id specified");
3901 // Get Contact by given id
3902 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3904 if(!DBA::isResult($contact)) {
3905 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3906 throw new NotFoundException("no contact found to given ID");
3909 $url = $contact["url"];
3911 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3912 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3913 Strings::normaliseLink($url), $url];
3914 $contact = DBA::selectFirst('contact', [], $condition);
3916 if (!DBA::isResult($contact)) {
3917 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3918 throw new NotFoundException("Not following Contact");
3921 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3922 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3923 throw new ExpectationFailedException("Not supported");
3926 $dissolve = ($contact['rel'] == Contact::SHARING);
3928 $owner = User::getOwnerDataById($uid);
3930 Contact::terminateFriendship($owner, $contact, $dissolve);
3933 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3934 throw new NotFoundException("Error Processing Request");
3937 // Sharing-only contacts get deleted as there no relationship any more
3939 Contact::remove($contact['id']);
3941 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3944 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3945 unset($contact["uid"]);
3946 unset($contact["self"]);
3948 // Set screen_name since Twidere requests it
3949 $contact["screen_name"] = $contact["nick"];
3951 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3953 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3957 * @param string $type Return type (atom, rss, xml, json)
3958 * @param string $box
3959 * @param string $verbose
3961 * @return array|string
3962 * @throws BadRequestException
3963 * @throws ForbiddenException
3964 * @throws ImagickException
3965 * @throws InternalServerErrorException
3966 * @throws UnauthorizedException
3968 function api_direct_messages_box($type, $box, $verbose)
3971 if (api_user() === false) {
3972 throw new ForbiddenException();
3975 $count = defaults($_GET, 'count', 20);
3976 $page = defaults($_REQUEST, 'page', 1) - 1;
3981 $since_id = defaults($_REQUEST, 'since_id', 0);
3982 $max_id = defaults($_REQUEST, 'max_id', 0);
3984 $user_id = defaults($_REQUEST, 'user_id', '');
3985 $screen_name = defaults($_REQUEST, 'screen_name', '');
3988 unset($_REQUEST["user_id"]);
3989 unset($_GET["user_id"]);
3991 unset($_REQUEST["screen_name"]);
3992 unset($_GET["screen_name"]);
3994 $user_info = api_get_user($a);
3995 if ($user_info === false) {
3996 throw new ForbiddenException();
3998 $profile_url = $user_info["url"];
4001 $start = $page * $count;
4006 if ($box=="sentbox") {
4007 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
4008 } elseif ($box == "conversation") {
4009 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
4010 } elseif ($box == "all") {
4011 $sql_extra = "true";
4012 } elseif ($box == "inbox") {
4013 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4017 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4020 if ($user_id != "") {
4021 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4022 } elseif ($screen_name !="") {
4023 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4027 "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",
4033 if ($verbose == "true" && !DBA::isResult($r)) {
4034 $answer = ['result' => 'error', 'message' => 'no mails available'];
4035 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4039 foreach ($r as $item) {
4040 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4041 $recipient = $user_info;
4042 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4043 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4044 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4045 $sender = $user_info;
4048 if (isset($recipient) && isset($sender)) {
4049 $ret[] = api_format_messages($item, $recipient, $sender);
4054 $data = ['direct_message' => $ret];
4059 $data = api_rss_extra($a, $data, $user_info);
4063 return api_format_data("direct-messages", $type, $data);
4067 * Returns the most recent direct messages sent by the user.
4069 * @param string $type Return type (atom, rss, xml, json)
4071 * @return array|string
4072 * @throws BadRequestException
4073 * @throws ForbiddenException
4074 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4076 function api_direct_messages_sentbox($type)
4078 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4079 return api_direct_messages_box($type, "sentbox", $verbose);
4083 * Returns the most recent direct messages sent to the user.
4085 * @param string $type Return type (atom, rss, xml, json)
4087 * @return array|string
4088 * @throws BadRequestException
4089 * @throws ForbiddenException
4090 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4092 function api_direct_messages_inbox($type)
4094 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4095 return api_direct_messages_box($type, "inbox", $verbose);
4100 * @param string $type Return type (atom, rss, xml, json)
4102 * @return array|string
4103 * @throws BadRequestException
4104 * @throws ForbiddenException
4106 function api_direct_messages_all($type)
4108 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4109 return api_direct_messages_box($type, "all", $verbose);
4114 * @param string $type Return type (atom, rss, xml, json)
4116 * @return array|string
4117 * @throws BadRequestException
4118 * @throws ForbiddenException
4120 function api_direct_messages_conversation($type)
4122 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4123 return api_direct_messages_box($type, "conversation", $verbose);
4126 /// @TODO move to top of file or somewhere better
4127 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4128 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4129 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4130 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4133 * Returns an OAuth Request Token.
4135 * @see https://oauth.net/core/1.0/#auth_step1
4137 function api_oauth_request_token()
4139 $oauth1 = new FKOAuth1();
4141 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4142 } catch (Exception $e) {
4143 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4151 * Returns an OAuth Access Token.
4153 * @return array|string
4154 * @see https://oauth.net/core/1.0/#auth_step3
4156 function api_oauth_access_token()
4158 $oauth1 = new FKOAuth1();
4160 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4161 } catch (Exception $e) {
4162 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4169 /// @TODO move to top of file or somewhere better
4170 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4171 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4175 * @brief delete a complete photoalbum with all containing photos from database through api
4177 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4178 * @return string|array
4179 * @throws BadRequestException
4180 * @throws ForbiddenException
4181 * @throws InternalServerErrorException
4183 function api_fr_photoalbum_delete($type)
4185 if (api_user() === false) {
4186 throw new ForbiddenException();
4189 $album = defaults($_REQUEST, 'album', "");
4191 // we do not allow calls without album string
4193 throw new BadRequestException("no albumname specified");
4195 // check if album is existing
4197 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4201 if (!DBA::isResult($r)) {
4202 throw new BadRequestException("album not available");
4205 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4206 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4207 foreach ($r as $rr) {
4208 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4209 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4211 if (!DBA::isResult($photo_item)) {
4212 throw new InternalServerErrorException("problem with deleting items occured");
4214 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4217 // now let's delete all photos from the album
4218 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4220 // return success of deletion or error message
4222 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4223 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4225 throw new InternalServerErrorException("unknown error - deleting from database failed");
4230 * @brief update the name of the album for all photos of an album
4232 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4233 * @return string|array
4234 * @throws BadRequestException
4235 * @throws ForbiddenException
4236 * @throws InternalServerErrorException
4238 function api_fr_photoalbum_update($type)
4240 if (api_user() === false) {
4241 throw new ForbiddenException();
4244 $album = defaults($_REQUEST, 'album', "");
4245 $album_new = defaults($_REQUEST, 'album_new', "");
4247 // we do not allow calls without album string
4249 throw new BadRequestException("no albumname specified");
4251 if ($album_new == "") {
4252 throw new BadRequestException("no new albumname specified");
4254 // check if album is existing
4255 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4256 throw new BadRequestException("album not available");
4258 // now let's update all photos to the albumname
4259 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4261 // return success of updating or error message
4263 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4264 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4266 throw new InternalServerErrorException("unknown error - updating in database failed");
4272 * @brief list all photos of the authenticated user
4274 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4275 * @return string|array
4276 * @throws ForbiddenException
4277 * @throws InternalServerErrorException
4279 function api_fr_photos_list($type)
4281 if (api_user() === false) {
4282 throw new ForbiddenException();
4285 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4286 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4287 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4288 intval(local_user())
4291 'image/jpeg' => 'jpg',
4292 'image/png' => 'png',
4293 'image/gif' => 'gif'
4295 $data = ['photo'=>[]];
4296 if (DBA::isResult($r)) {
4297 foreach ($r as $rr) {
4299 $photo['id'] = $rr['resource-id'];
4300 $photo['album'] = $rr['album'];
4301 $photo['filename'] = $rr['filename'];
4302 $photo['type'] = $rr['type'];
4303 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4304 $photo['created'] = $rr['created'];
4305 $photo['edited'] = $rr['edited'];
4306 $photo['desc'] = $rr['desc'];
4308 if ($type == "xml") {
4309 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4311 $photo['thumb'] = $thumb;
4312 $data['photo'][] = $photo;
4316 return api_format_data("photos", $type, $data);
4320 * @brief upload a new photo or change an existing photo
4322 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4323 * @return string|array
4324 * @throws BadRequestException
4325 * @throws ForbiddenException
4326 * @throws ImagickException
4327 * @throws InternalServerErrorException
4328 * @throws NotFoundException
4330 function api_fr_photo_create_update($type)
4332 if (api_user() === false) {
4333 throw new ForbiddenException();
4336 $photo_id = defaults($_REQUEST, 'photo_id', null);
4337 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4338 $album = defaults($_REQUEST, 'album', null);
4339 $album_new = defaults($_REQUEST, 'album_new', null);
4340 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4341 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4342 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4343 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4344 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4346 // do several checks on input parameters
4347 // we do not allow calls without album string
4348 if ($album == null) {
4349 throw new BadRequestException("no albumname specified");
4351 // if photo_id == null --> we are uploading a new photo
4352 if ($photo_id == null) {
4355 // error if no media posted in create-mode
4356 if (empty($_FILES['media'])) {
4358 throw new BadRequestException("no media data submitted");
4361 // album_new will be ignored in create-mode
4366 // check if photo is existing in databasei
4367 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4368 throw new BadRequestException("photo not available");
4372 // checks on acl strings provided by clients
4373 $acl_input_error = false;
4374 $acl_input_error |= check_acl_input($allow_cid);
4375 $acl_input_error |= check_acl_input($deny_cid);
4376 $acl_input_error |= check_acl_input($allow_gid);
4377 $acl_input_error |= check_acl_input($deny_gid);
4378 if ($acl_input_error) {
4379 throw new BadRequestException("acl data invalid");
4381 // now let's upload the new media in create-mode
4382 if ($mode == "create") {
4383 $media = $_FILES['media'];
4384 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4386 // return success of updating or error message
4387 if (!is_null($data)) {
4388 return api_format_data("photo_create", $type, $data);
4390 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4394 // now let's do the changes in update-mode
4395 if ($mode == "update") {
4396 $updated_fields = [];
4398 if (!is_null($desc)) {
4399 $updated_fields['desc'] = $desc;
4402 if (!is_null($album_new)) {
4403 $updated_fields['album'] = $album_new;
4406 if (!is_null($allow_cid)) {
4407 $allow_cid = trim($allow_cid);
4408 $updated_fields['allow_cid'] = $allow_cid;
4411 if (!is_null($deny_cid)) {
4412 $deny_cid = trim($deny_cid);
4413 $updated_fields['deny_cid'] = $deny_cid;
4416 if (!is_null($allow_gid)) {
4417 $allow_gid = trim($allow_gid);
4418 $updated_fields['allow_gid'] = $allow_gid;
4421 if (!is_null($deny_gid)) {
4422 $deny_gid = trim($deny_gid);
4423 $updated_fields['deny_gid'] = $deny_gid;
4427 if (count($updated_fields) > 0) {
4428 $nothingtodo = false;
4429 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4431 $nothingtodo = true;
4434 if (!empty($_FILES['media'])) {
4435 $nothingtodo = false;
4436 $media = $_FILES['media'];
4437 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4438 if (!is_null($data)) {
4439 return api_format_data("photo_update", $type, $data);
4443 // return success of updating or error message
4445 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4446 return api_format_data("photo_update", $type, ['$result' => $answer]);
4449 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4450 return api_format_data("photo_update", $type, ['$result' => $answer]);
4452 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4455 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4459 * @brief delete a single photo from the database through api
4461 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4462 * @return string|array
4463 * @throws BadRequestException
4464 * @throws ForbiddenException
4465 * @throws InternalServerErrorException
4467 function api_fr_photo_delete($type)
4469 if (api_user() === false) {
4470 throw new ForbiddenException();
4474 $photo_id = defaults($_REQUEST, 'photo_id', null);
4476 // do several checks on input parameters
4477 // we do not allow calls without photo id
4478 if ($photo_id == null) {
4479 throw new BadRequestException("no photo_id specified");
4482 // check if photo is existing in database
4483 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4484 throw new BadRequestException("photo not available");
4487 // now we can perform on the deletion of the photo
4488 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4490 // return success of deletion or error message
4492 // retrieve the id of the parent element (the photo element)
4493 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4494 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4496 if (!DBA::isResult($photo_item)) {
4497 throw new InternalServerErrorException("problem with deleting items occured");
4499 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4500 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4501 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4503 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4504 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4506 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4512 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4514 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4515 * @return string|array
4516 * @throws BadRequestException
4517 * @throws ForbiddenException
4518 * @throws InternalServerErrorException
4519 * @throws NotFoundException
4521 function api_fr_photo_detail($type)
4523 if (api_user() === false) {
4524 throw new ForbiddenException();
4526 if (empty($_REQUEST['photo_id'])) {
4527 throw new BadRequestException("No photo id.");
4530 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4531 $photo_id = $_REQUEST['photo_id'];
4533 // prepare json/xml output with data from database for the requested photo
4534 $data = prepare_photo_data($type, $scale, $photo_id);
4536 return api_format_data("photo_detail", $type, $data);
4541 * Updates the user’s profile image.
4543 * @brief updates the profile image for the user (either a specified profile or the default profile)
4545 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4547 * @return string|array
4548 * @throws BadRequestException
4549 * @throws ForbiddenException
4550 * @throws ImagickException
4551 * @throws InternalServerErrorException
4552 * @throws NotFoundException
4553 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4555 function api_account_update_profile_image($type)
4557 if (api_user() === false) {
4558 throw new ForbiddenException();
4561 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4563 // error if image data is missing
4564 if (empty($_FILES['image'])) {
4565 throw new BadRequestException("no media data submitted");
4568 // check if specified profile id is valid
4569 if ($profile_id != 0) {
4570 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4571 // error message if specified profile id is not in database
4572 if (!DBA::isResult($profile)) {
4573 throw new BadRequestException("profile_id not available");
4575 $is_default_profile = $profile['is-default'];
4577 $is_default_profile = 1;
4580 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4582 if (!empty($_FILES['image'])) {
4583 $media = $_FILES['image'];
4584 } elseif (!empty($_FILES['media'])) {
4585 $media = $_FILES['media'];
4587 // save new profile image
4588 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4591 if (is_array($media['type'])) {
4592 $filetype = $media['type'][0];
4594 $filetype = $media['type'];
4596 if ($filetype == "image/jpeg") {
4598 } elseif ($filetype == "image/png") {
4601 throw new InternalServerErrorException('Unsupported filetype');
4604 // change specified profile or all profiles to the new resource-id
4605 if ($is_default_profile) {
4606 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4607 Photo::update(['profile' => false], $condition);
4609 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4610 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4611 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4614 Contact::updateSelfFromUserID(api_user(), true);
4616 // Update global directory in background
4617 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4618 if ($url && strlen(Config::get('system', 'directory'))) {
4619 Worker::add(PRIORITY_LOW, "Directory", $url);
4622 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4624 // output for client
4626 return api_account_verify_credentials($type);
4628 // SaveMediaToDatabase failed for some reason
4629 throw new InternalServerErrorException("image upload failed");
4633 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4634 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4635 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4636 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4637 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4638 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4639 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4640 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4641 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4644 * Update user profile
4646 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4648 * @return array|string
4649 * @throws BadRequestException
4650 * @throws ForbiddenException
4651 * @throws ImagickException
4652 * @throws InternalServerErrorException
4653 * @throws UnauthorizedException
4655 function api_account_update_profile($type)
4657 $local_user = api_user();
4658 $api_user = api_get_user(get_app());
4660 if (!empty($_POST['name'])) {
4661 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4662 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4663 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4664 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4667 if (isset($_POST['description'])) {
4668 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4669 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4670 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4673 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4674 // Update global directory in background
4675 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4676 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4679 return api_account_verify_credentials($type);
4682 /// @TODO move to top of file or somewhere better
4683 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4687 * @param string $acl_string
4691 function check_acl_input($acl_string)
4693 if ($acl_string == null || $acl_string == " ") {
4696 $contact_not_found = false;
4698 // split <x><y><z> into array of cid's
4699 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4701 // check for each cid if it is available on server
4702 $cid_array = $array[0];
4703 foreach ($cid_array as $cid) {
4704 $cid = str_replace("<", "", $cid);
4705 $cid = str_replace(">", "", $cid);
4706 $condition = ['id' => $cid, 'uid' => api_user()];
4707 $contact_not_found |= !DBA::exists('contact', $condition);
4709 return $contact_not_found;
4714 * @param string $mediatype
4715 * @param array $media
4716 * @param string $type
4717 * @param string $album
4718 * @param string $allow_cid
4719 * @param string $deny_cid
4720 * @param string $allow_gid
4721 * @param string $deny_gid
4722 * @param string $desc
4723 * @param integer $profile
4724 * @param boolean $visibility
4725 * @param string $photo_id
4727 * @throws BadRequestException
4728 * @throws ForbiddenException
4729 * @throws ImagickException
4730 * @throws InternalServerErrorException
4731 * @throws NotFoundException
4733 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)
4741 if (is_array($media)) {
4742 if (is_array($media['tmp_name'])) {
4743 $src = $media['tmp_name'][0];
4745 $src = $media['tmp_name'];
4747 if (is_array($media['name'])) {
4748 $filename = basename($media['name'][0]);
4750 $filename = basename($media['name']);
4752 if (is_array($media['size'])) {
4753 $filesize = intval($media['size'][0]);
4755 $filesize = intval($media['size']);
4757 if (is_array($media['type'])) {
4758 $filetype = $media['type'][0];
4760 $filetype = $media['type'];
4764 if ($filetype == "") {
4765 $filetype=Image::guessType($filename);
4767 $imagedata = @getimagesize($src);
4769 $filetype = $imagedata['mime'];
4772 "File upload src: " . $src . " - filename: " . $filename .
4773 " - size: " . $filesize . " - type: " . $filetype,
4777 // check if there was a php upload error
4778 if ($filesize == 0 && $media['error'] == 1) {
4779 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4781 // check against max upload size within Friendica instance
4782 $maximagesize = Config::get('system', 'maximagesize');
4783 if ($maximagesize && ($filesize > $maximagesize)) {
4784 $formattedBytes = Strings::formatBytes($maximagesize);
4785 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4788 // create Photo instance with the data of the image
4789 $imagedata = @file_get_contents($src);
4790 $Image = new Image($imagedata, $filetype);
4791 if (!$Image->isValid()) {
4792 throw new InternalServerErrorException("unable to process image data");
4795 // check orientation of image
4796 $Image->orient($src);
4799 // check max length of images on server
4800 $max_length = Config::get('system', 'max_image_length');
4802 $max_length = MAX_IMAGE_LENGTH;
4804 if ($max_length > 0) {
4805 $Image->scaleDown($max_length);
4806 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4808 $width = $Image->getWidth();
4809 $height = $Image->getHeight();
4811 // create a new resource-id if not already provided
4812 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4814 if ($mediatype == "photo") {
4815 // upload normal image (scales 0, 1, 2)
4816 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4818 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4820 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4822 if ($width > 640 || $height > 640) {
4823 $Image->scaleDown(640);
4824 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4826 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4830 if ($width > 320 || $height > 320) {
4831 $Image->scaleDown(320);
4832 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4834 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4837 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4838 } elseif ($mediatype == "profileimage") {
4839 // upload profile image (scales 4, 5, 6)
4840 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4842 if ($width > 300 || $height > 300) {
4843 $Image->scaleDown(300);
4844 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4846 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4850 if ($width > 80 || $height > 80) {
4851 $Image->scaleDown(80);
4852 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4854 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4858 if ($width > 48 || $height > 48) {
4859 $Image->scaleDown(48);
4860 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4862 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4865 $Image->__destruct();
4866 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4869 if (isset($r) && $r) {
4870 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4871 if ($photo_id == null && $mediatype == "photo") {
4872 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4874 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4875 return prepare_photo_data($type, false, $hash);
4877 throw new InternalServerErrorException("image upload failed");
4883 * @param string $hash
4884 * @param string $allow_cid
4885 * @param string $deny_cid
4886 * @param string $allow_gid
4887 * @param string $deny_gid
4888 * @param string $filetype
4889 * @param boolean $visibility
4890 * @throws InternalServerErrorException
4892 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4894 // get data about the api authenticated user
4895 $uri = Item::newURI(intval(api_user()));
4896 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4899 $arr['guid'] = System::createUUID();
4900 $arr['uid'] = intval(api_user());
4902 $arr['parent-uri'] = $uri;
4903 $arr['type'] = 'photo';
4905 $arr['resource-id'] = $hash;
4906 $arr['contact-id'] = $owner_record['id'];
4907 $arr['owner-name'] = $owner_record['name'];
4908 $arr['owner-link'] = $owner_record['url'];
4909 $arr['owner-avatar'] = $owner_record['thumb'];
4910 $arr['author-name'] = $owner_record['name'];
4911 $arr['author-link'] = $owner_record['url'];
4912 $arr['author-avatar'] = $owner_record['thumb'];
4914 $arr['allow_cid'] = $allow_cid;
4915 $arr['allow_gid'] = $allow_gid;
4916 $arr['deny_cid'] = $deny_cid;
4917 $arr['deny_gid'] = $deny_gid;
4918 $arr['visible'] = $visibility;
4922 'image/jpeg' => 'jpg',
4923 'image/png' => 'png',
4924 'image/gif' => 'gif'
4927 // adds link to the thumbnail scale photo
4928 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4929 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4932 // do the magic for storing the item in the database and trigger the federation to other contacts
4938 * @param string $type
4940 * @param string $photo_id
4943 * @throws BadRequestException
4944 * @throws ForbiddenException
4945 * @throws ImagickException
4946 * @throws InternalServerErrorException
4947 * @throws NotFoundException
4948 * @throws UnauthorizedException
4950 function prepare_photo_data($type, $scale, $photo_id)
4953 $user_info = api_get_user($a);
4955 if ($user_info === false) {
4956 throw new ForbiddenException();
4959 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4960 $data_sql = ($scale === false ? "" : "data, ");
4962 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4963 // clients needs to convert this in their way for further processing
4965 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4966 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4967 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4968 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4969 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4970 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4972 intval(local_user()),
4973 DBA::escape($photo_id),
4978 'image/jpeg' => 'jpg',
4979 'image/png' => 'png',
4980 'image/gif' => 'gif'
4983 // prepare output data for photo
4984 if (DBA::isResult($r)) {
4985 $data = ['photo' => $r[0]];
4986 $data['photo']['id'] = $data['photo']['resource-id'];
4987 if ($scale !== false) {
4988 $data['photo']['data'] = base64_encode($data['photo']['data']);
4990 unset($data['photo']['datasize']); //needed only with scale param
4992 if ($type == "xml") {
4993 $data['photo']['links'] = [];
4994 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4995 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4997 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
5000 $data['photo']['link'] = [];
5001 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
5003 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5004 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
5008 unset($data['photo']['resource-id']);
5009 unset($data['photo']['minscale']);
5010 unset($data['photo']['maxscale']);
5012 throw new NotFoundException();
5015 // retrieve item element for getting activities (like, dislike etc.) related to photo
5016 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5017 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5019 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5021 // retrieve comments on photo
5022 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5023 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5025 $statuses = Item::selectForUser(api_user(), [], $condition);
5027 // prepare output of comments
5028 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5030 if ($type == "xml") {
5032 foreach ($commentData as $comment) {
5033 $comments[$k++ . ":comment"] = $comment;
5036 foreach ($commentData as $comment) {
5037 $comments[] = $comment;
5040 $data['photo']['friendica_comments'] = $comments;
5042 // include info if rights on photo and rights on item are mismatching
5043 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5044 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5045 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5046 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5047 $data['photo']['rights_mismatch'] = $rights_mismatch;
5054 * Similar as /mod/redir.php
5055 * redirect to 'url' after dfrn auth
5057 * Why this when there is mod/redir.php already?
5058 * This use api_user() and api_login()
5061 * c_url: url of remote contact to auth to
5062 * url: string, url to redirect after auth
5064 function api_friendica_remoteauth()
5066 $url = defaults($_GET, 'url', '');
5067 $c_url = defaults($_GET, 'c_url', '');
5069 if ($url === '' || $c_url === '') {
5070 throw new BadRequestException("Wrong parameters.");
5073 $c_url = Strings::normaliseLink($c_url);
5077 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5079 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5080 throw new BadRequestException("Unknown contact");
5083 $cid = $contact['id'];
5085 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
5087 if ($contact['duplex'] && $contact['issued-id']) {
5088 $orig_id = $contact['issued-id'];
5089 $dfrn_id = '1:' . $orig_id;
5091 if ($contact['duplex'] && $contact['dfrn-id']) {
5092 $orig_id = $contact['dfrn-id'];
5093 $dfrn_id = '0:' . $orig_id;
5096 $sec = Strings::getRandomHex();
5098 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5099 'sec' => $sec, 'expire' => time() + 45];
5100 DBA::insert('profile_check', $fields);
5102 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5103 $dest = ($url ? '&destination_url=' . $url : '');
5105 System::externalRedirect(
5106 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5107 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5108 . '&type=profile&sec=' . $sec . $dest
5111 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5114 * Return an item with announcer data if it had been announced
5116 * @param array $item Item array
5117 * @return array Item array with announce data
5119 function api_get_announce($item)
5121 // Quit if the item already has got a different owner and author
5122 if ($item['owner-id'] != $item['author-id']) {
5126 // Don't change original or Diaspora posts
5127 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5131 // Quit if we do now the original author and it had been a post from a native network
5132 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5136 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5137 $activity = Item::activityToIndex(ACTIVITY2_ANNOUNCE);
5138 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5139 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5140 if (!DBA::isResult($announce)) {
5144 return array_merge($item, $announce);
5148 * @brief Return the item shared, if the item contains only the [share] tag
5150 * @param array $item Sharer item
5151 * @return array|false Shared item or false if not a reshare
5152 * @throws ImagickException
5153 * @throws InternalServerErrorException
5155 function api_share_as_retweet(&$item)
5157 $body = trim($item["body"]);
5159 if (Diaspora::isReshare($body, false) === false) {
5160 if ($item['author-id'] == $item['owner-id']) {
5163 // Reshares from OStatus, ActivityPub and Twitter
5164 $reshared_item = $item;
5165 $reshared_item['owner-id'] = $reshared_item['author-id'];
5166 $reshared_item['owner-link'] = $reshared_item['author-link'];
5167 $reshared_item['owner-name'] = $reshared_item['author-name'];
5168 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5169 return $reshared_item;
5173 /// @TODO "$1" should maybe mean '$1' ?
5174 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5176 * Skip if there is no shared message in there
5177 * we already checked this in diaspora::isReshare()
5178 * but better one more than one less...
5180 if (($body == $attributes) || empty($attributes)) {
5184 // build the fake reshared item
5185 $reshared_item = $item;
5188 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5189 if (!empty($matches[1])) {
5190 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5193 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5194 if (!empty($matches[1])) {
5195 $author = $matches[1];
5199 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5200 if (!empty($matches[1])) {
5201 $profile = $matches[1];
5204 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5205 if (!empty($matches[1])) {
5206 $profile = $matches[1];
5210 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5211 if (!empty($matches[1])) {
5212 $avatar = $matches[1];
5215 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5216 if (!empty($matches[1])) {
5217 $avatar = $matches[1];
5221 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5222 if (!empty($matches[1])) {
5223 $link = $matches[1];
5226 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5227 if (!empty($matches[1])) {
5228 $link = $matches[1];
5232 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5233 if (!empty($matches[1])) {
5234 $posted = $matches[1];
5237 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5238 if (!empty($matches[1])) {
5239 $posted = $matches[1];
5242 if (!preg_match("/(.*?)\[share.*?\]\s?(.*?)\s?\[\/share\]\s?(.*?)/ism", $body, $matches)) {
5246 $pre_body = trim($matches[1]);
5247 if ($pre_body != '') {
5248 $item['body'] = $pre_body;
5251 $shared_body = trim($matches[2]);
5253 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5257 $reshared_item["share-pre-body"] = $pre_body;
5258 $reshared_item["body"] = $shared_body;
5259 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5260 $reshared_item["author-name"] = $author;
5261 $reshared_item["author-link"] = $profile;
5262 $reshared_item["author-avatar"] = $avatar;
5263 $reshared_item["plink"] = $link;
5264 $reshared_item["created"] = $posted;
5265 $reshared_item["edited"] = $posted;
5267 return $reshared_item;
5272 * @param string $profile
5274 * @return string|false
5275 * @throws InternalServerErrorException
5276 * @todo remove trailing junk from profile url
5277 * @todo pump.io check has to check the website
5279 function api_get_nick($profile)
5284 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5285 DBA::escape(Strings::normaliseLink($profile))
5288 if (DBA::isResult($r)) {
5289 $nick = $r[0]["nick"];
5294 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5295 DBA::escape(Strings::normaliseLink($profile))
5298 if (DBA::isResult($r)) {
5299 $nick = $r[0]["nick"];
5304 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5305 if ($friendica != $profile) {
5311 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5312 if ($diaspora != $profile) {
5318 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5319 if ($twitter != $profile) {
5326 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5327 if ($StatusnetHost != $profile) {
5328 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5329 if ($StatusnetUser != $profile) {
5330 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5331 $user = json_decode($UserData);
5333 $nick = $user->screen_name;
5339 // To-Do: look at the page if its really a pumpio site
5340 //if (!$nick == "") {
5341 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5342 // if ($pumpio != $profile)
5344 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5357 * @param array $item
5362 function api_in_reply_to($item)
5366 $in_reply_to['status_id'] = null;
5367 $in_reply_to['user_id'] = null;
5368 $in_reply_to['status_id_str'] = null;
5369 $in_reply_to['user_id_str'] = null;
5370 $in_reply_to['screen_name'] = null;
5372 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5373 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5374 if (DBA::isResult($parent)) {
5375 $in_reply_to['status_id'] = intval($parent['id']);
5377 $in_reply_to['status_id'] = intval($item['parent']);
5380 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5382 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5383 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5385 if (DBA::isResult($parent)) {
5386 if ($parent['author-nick'] == "") {
5387 $parent['author-nick'] = api_get_nick($parent['author-link']);
5390 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5391 $in_reply_to['user_id'] = intval($parent['author-id']);
5392 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5395 // There seems to be situation, where both fields are identical:
5396 // https://github.com/friendica/friendica/issues/1010
5397 // This is a bugfix for that.
5398 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5399 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']]);
5400 $in_reply_to['status_id'] = null;
5401 $in_reply_to['user_id'] = null;
5402 $in_reply_to['status_id_str'] = null;
5403 $in_reply_to['user_id_str'] = null;
5404 $in_reply_to['screen_name'] = null;
5408 return $in_reply_to;
5413 * @param string $text
5416 * @throws InternalServerErrorException
5418 function api_clean_plain_items($text)
5420 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5422 $text = BBCode::cleanPictureLinks($text);
5423 $URLSearchString = "^\[\]";
5425 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5427 if ($include_entities == "true") {
5428 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5431 // Simplify "attachment" element
5432 $text = api_clean_attachments($text);
5438 * @brief Removes most sharing information for API text export
5440 * @param string $body The original body
5442 * @return string Cleaned body
5443 * @throws InternalServerErrorException
5445 function api_clean_attachments($body)
5447 $data = BBCode::getAttachmentData($body);
5454 if (isset($data["text"])) {
5455 $body = $data["text"];
5457 if (($body == "") && isset($data["title"])) {
5458 $body = $data["title"];
5460 if (isset($data["url"])) {
5461 $body .= "\n".$data["url"];
5463 $body .= $data["after"];
5470 * @param array $contacts
5474 function api_best_nickname(&$contacts)
5478 if (count($contacts) == 0) {
5482 foreach ($contacts as $contact) {
5483 if ($contact["network"] == "") {
5484 $contact["network"] = "dfrn";
5485 $best_contact = [$contact];
5489 if (sizeof($best_contact) == 0) {
5490 foreach ($contacts as $contact) {
5491 if ($contact["network"] == "dfrn") {
5492 $best_contact = [$contact];
5497 if (sizeof($best_contact) == 0) {
5498 foreach ($contacts as $contact) {
5499 if ($contact["network"] == "dspr") {
5500 $best_contact = [$contact];
5505 if (sizeof($best_contact) == 0) {
5506 foreach ($contacts as $contact) {
5507 if ($contact["network"] == "stat") {
5508 $best_contact = [$contact];
5513 if (sizeof($best_contact) == 0) {
5514 foreach ($contacts as $contact) {
5515 if ($contact["network"] == "pump") {
5516 $best_contact = [$contact];
5521 if (sizeof($best_contact) == 0) {
5522 foreach ($contacts as $contact) {
5523 if ($contact["network"] == "twit") {
5524 $best_contact = [$contact];
5529 if (sizeof($best_contact) == 1) {
5530 $contacts = $best_contact;
5532 $contacts = [$contacts[0]];
5537 * Return all or a specified group of the user with the containing contacts.
5539 * @param string $type Return type (atom, rss, xml, json)
5541 * @return array|string
5542 * @throws BadRequestException
5543 * @throws ForbiddenException
5544 * @throws ImagickException
5545 * @throws InternalServerErrorException
5546 * @throws UnauthorizedException
5548 function api_friendica_group_show($type)
5552 if (api_user() === false) {
5553 throw new ForbiddenException();
5557 $user_info = api_get_user($a);
5558 $gid = defaults($_REQUEST, 'gid', 0);
5559 $uid = $user_info['uid'];
5561 // get data of the specified group id or all groups if not specified
5564 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5568 // error message if specified gid is not in database
5569 if (!DBA::isResult($r)) {
5570 throw new BadRequestException("gid not available");
5574 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5579 // loop through all groups and retrieve all members for adding data in the user array
5581 foreach ($r as $rr) {
5582 $members = Contact::getByGroupId($rr['id']);
5585 if ($type == "xml") {
5586 $user_element = "users";
5588 foreach ($members as $member) {
5589 $user = api_get_user($a, $member['nurl']);
5590 $users[$k++.":user"] = $user;
5593 $user_element = "user";
5594 foreach ($members as $member) {
5595 $user = api_get_user($a, $member['nurl']);
5599 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5601 return api_format_data("groups", $type, ['group' => $grps]);
5603 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5607 * Delete the specified group of the user.
5609 * @param string $type Return type (atom, rss, xml, json)
5611 * @return array|string
5612 * @throws BadRequestException
5613 * @throws ForbiddenException
5614 * @throws ImagickException
5615 * @throws InternalServerErrorException
5616 * @throws UnauthorizedException
5618 function api_friendica_group_delete($type)
5622 if (api_user() === false) {
5623 throw new ForbiddenException();
5627 $user_info = api_get_user($a);
5628 $gid = defaults($_REQUEST, 'gid', 0);
5629 $name = defaults($_REQUEST, 'name', "");
5630 $uid = $user_info['uid'];
5632 // error if no gid specified
5633 if ($gid == 0 || $name == "") {
5634 throw new BadRequestException('gid or name not specified');
5637 // get data of the specified group id
5639 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5643 // error message if specified gid is not in database
5644 if (!DBA::isResult($r)) {
5645 throw new BadRequestException('gid not available');
5648 // get data of the specified group id and group name
5650 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5655 // error message if specified gid is not in database
5656 if (!DBA::isResult($rname)) {
5657 throw new BadRequestException('wrong group name');
5661 $ret = Group::removeByName($uid, $name);
5664 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5665 return api_format_data("group_delete", $type, ['result' => $success]);
5667 throw new BadRequestException('other API error');
5670 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5675 * @param string $type Return type (atom, rss, xml, json)
5677 * @return array|string
5678 * @throws BadRequestException
5679 * @throws ForbiddenException
5680 * @throws ImagickException
5681 * @throws InternalServerErrorException
5682 * @throws UnauthorizedException
5683 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5685 function api_lists_destroy($type)
5689 if (api_user() === false) {
5690 throw new ForbiddenException();
5694 $user_info = api_get_user($a);
5695 $gid = defaults($_REQUEST, 'list_id', 0);
5696 $uid = $user_info['uid'];
5698 // error if no gid specified
5700 throw new BadRequestException('gid not specified');
5703 // get data of the specified group id
5704 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5705 // error message if specified gid is not in database
5707 throw new BadRequestException('gid not available');
5710 if (Group::remove($gid)) {
5712 'name' => $group['name'],
5713 'id' => intval($gid),
5714 'id_str' => (string) $gid,
5715 'user' => $user_info
5718 return api_format_data("lists", $type, ['lists' => $list]);
5721 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5724 * Add a new group to the database.
5726 * @param string $name Group name
5727 * @param int $uid User ID
5728 * @param array $users List of users to add to the group
5731 * @throws BadRequestException
5733 function group_create($name, $uid, $users = [])
5735 // error if no name specified
5737 throw new BadRequestException('group name not specified');
5740 // get data of the specified group name
5742 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5746 // error message if specified group name already exists
5747 if (DBA::isResult($rname)) {
5748 throw new BadRequestException('group name already exists');
5751 // check if specified group name is a deleted group
5753 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5757 // error message if specified group name already exists
5758 if (DBA::isResult($rname)) {
5759 $reactivate_group = true;
5763 $ret = Group::create($uid, $name);
5765 $gid = Group::getIdByName($uid, $name);
5767 throw new BadRequestException('other API error');
5771 $erroraddinguser = false;
5773 foreach ($users as $user) {
5774 $cid = $user['cid'];
5775 // check if user really exists as contact
5777 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5781 if (count($contact)) {
5782 Group::addMember($gid, $cid);
5784 $erroraddinguser = true;
5785 $errorusers[] = $cid;
5789 // return success message incl. missing users in array
5790 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5792 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5796 * Create the specified group with the posted array of contacts.
5798 * @param string $type Return type (atom, rss, xml, json)
5800 * @return array|string
5801 * @throws BadRequestException
5802 * @throws ForbiddenException
5803 * @throws ImagickException
5804 * @throws InternalServerErrorException
5805 * @throws UnauthorizedException
5807 function api_friendica_group_create($type)
5811 if (api_user() === false) {
5812 throw new ForbiddenException();
5816 $user_info = api_get_user($a);
5817 $name = defaults($_REQUEST, 'name', "");
5818 $uid = $user_info['uid'];
5819 $json = json_decode($_POST['json'], true);
5820 $users = $json['user'];
5822 $success = group_create($name, $uid, $users);
5824 return api_format_data("group_create", $type, ['result' => $success]);
5826 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5829 * Create a new group.
5831 * @param string $type Return type (atom, rss, xml, json)
5833 * @return array|string
5834 * @throws BadRequestException
5835 * @throws ForbiddenException
5836 * @throws ImagickException
5837 * @throws InternalServerErrorException
5838 * @throws UnauthorizedException
5839 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5841 function api_lists_create($type)
5845 if (api_user() === false) {
5846 throw new ForbiddenException();
5850 $user_info = api_get_user($a);
5851 $name = defaults($_REQUEST, 'name', "");
5852 $uid = $user_info['uid'];
5854 $success = group_create($name, $uid);
5855 if ($success['success']) {
5857 'name' => $success['name'],
5858 'id' => intval($success['gid']),
5859 'id_str' => (string) $success['gid'],
5860 'user' => $user_info
5863 return api_format_data("lists", $type, ['lists'=>$grp]);
5866 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5869 * Update the specified group with the posted array of contacts.
5871 * @param string $type Return type (atom, rss, xml, json)
5873 * @return array|string
5874 * @throws BadRequestException
5875 * @throws ForbiddenException
5876 * @throws ImagickException
5877 * @throws InternalServerErrorException
5878 * @throws UnauthorizedException
5880 function api_friendica_group_update($type)
5884 if (api_user() === false) {
5885 throw new ForbiddenException();
5889 $user_info = api_get_user($a);
5890 $uid = $user_info['uid'];
5891 $gid = defaults($_REQUEST, 'gid', 0);
5892 $name = defaults($_REQUEST, 'name', "");
5893 $json = json_decode($_POST['json'], true);
5894 $users = $json['user'];
5896 // error if no name specified
5898 throw new BadRequestException('group name not specified');
5901 // error if no gid specified
5903 throw new BadRequestException('gid not specified');
5907 $members = Contact::getByGroupId($gid);
5908 foreach ($members as $member) {
5909 $cid = $member['id'];
5910 foreach ($users as $user) {
5911 $found = ($user['cid'] == $cid ? true : false);
5913 if (!isset($found) || !$found) {
5914 Group::removeMemberByName($uid, $name, $cid);
5919 $erroraddinguser = false;
5921 foreach ($users as $user) {
5922 $cid = $user['cid'];
5923 // check if user really exists as contact
5925 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5930 if (count($contact)) {
5931 Group::addMember($gid, $cid);
5933 $erroraddinguser = true;
5934 $errorusers[] = $cid;
5938 // return success message incl. missing users in array
5939 $status = ($erroraddinguser ? "missing user" : "ok");
5940 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5941 return api_format_data("group_update", $type, ['result' => $success]);
5944 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5947 * Update information about a group.
5949 * @param string $type Return type (atom, rss, xml, json)
5951 * @return array|string
5952 * @throws BadRequestException
5953 * @throws ForbiddenException
5954 * @throws ImagickException
5955 * @throws InternalServerErrorException
5956 * @throws UnauthorizedException
5957 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5959 function api_lists_update($type)
5963 if (api_user() === false) {
5964 throw new ForbiddenException();
5968 $user_info = api_get_user($a);
5969 $gid = defaults($_REQUEST, 'list_id', 0);
5970 $name = defaults($_REQUEST, 'name', "");
5971 $uid = $user_info['uid'];
5973 // error if no gid specified
5975 throw new BadRequestException('gid not specified');
5978 // get data of the specified group id
5979 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5980 // error message if specified gid is not in database
5982 throw new BadRequestException('gid not available');
5985 if (Group::update($gid, $name)) {
5988 'id' => intval($gid),
5989 'id_str' => (string) $gid,
5990 'user' => $user_info
5993 return api_format_data("lists", $type, ['lists' => $list]);
5997 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
6001 * @param string $type Return type (atom, rss, xml, json)
6003 * @return array|string
6004 * @throws BadRequestException
6005 * @throws ForbiddenException
6006 * @throws ImagickException
6007 * @throws InternalServerErrorException
6009 function api_friendica_activity($type)
6013 if (api_user() === false) {
6014 throw new ForbiddenException();
6016 $verb = strtolower($a->argv[3]);
6017 $verb = preg_replace("|\..*$|", "", $verb);
6019 $id = defaults($_REQUEST, 'id', 0);
6021 $res = Item::performLike($id, $verb);
6024 if ($type == "xml") {
6029 return api_format_data('ok', $type, ['ok' => $ok]);
6031 throw new BadRequestException('Error adding activity');
6035 /// @TODO move to top of file or somewhere better
6036 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
6037 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
6038 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
6039 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
6040 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
6041 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
6042 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
6043 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
6044 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
6045 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
6048 * @brief Returns notifications
6050 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6051 * @return string|array
6052 * @throws BadRequestException
6053 * @throws ForbiddenException
6054 * @throws InternalServerErrorException
6056 function api_friendica_notification($type)
6060 if (api_user() === false) {
6061 throw new ForbiddenException();
6064 throw new BadRequestException("Invalid argument count");
6066 $nm = new NotificationsManager();
6068 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
6070 if ($type == "xml") {
6072 if (!empty($notes)) {
6073 foreach ($notes as $note) {
6074 $xmlnotes[] = ["@attributes" => $note];
6080 return api_format_data("notes", $type, ['note' => $notes]);
6084 * POST request with 'id' param as notification id
6086 * @brief Set notification as seen and returns associated item (if possible)
6088 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6089 * @return string|array
6090 * @throws BadRequestException
6091 * @throws ForbiddenException
6092 * @throws ImagickException
6093 * @throws InternalServerErrorException
6094 * @throws UnauthorizedException
6096 function api_friendica_notification_seen($type)
6099 $user_info = api_get_user($a);
6101 if (api_user() === false || $user_info === false) {
6102 throw new ForbiddenException();
6105 throw new BadRequestException("Invalid argument count");
6108 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
6110 $nm = new NotificationsManager();
6111 $note = $nm->getByID($id);
6112 if (is_null($note)) {
6113 throw new BadRequestException("Invalid argument");
6116 $nm->setSeen($note);
6117 if ($note['otype']=='item') {
6118 // would be really better with an ItemsManager and $im->getByID() :-P
6119 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6120 if (DBA::isResult($item)) {
6121 // we found the item, return it to the user
6122 $ret = api_format_items([$item], $user_info, false, $type);
6123 $data = ['status' => $ret];
6124 return api_format_data("status", $type, $data);
6126 // the item can't be found, but we set the note as seen, so we count this as a success
6128 return api_format_data('result', $type, ['result' => "success"]);
6131 /// @TODO move to top of file or somewhere better
6132 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6133 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6136 * @brief update a direct_message to seen state
6138 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6139 * @return string|array (success result=ok, error result=error with error message)
6140 * @throws BadRequestException
6141 * @throws ForbiddenException
6142 * @throws ImagickException
6143 * @throws InternalServerErrorException
6144 * @throws UnauthorizedException
6146 function api_friendica_direct_messages_setseen($type)
6149 if (api_user() === false) {
6150 throw new ForbiddenException();
6154 $user_info = api_get_user($a);
6155 $uid = $user_info['uid'];
6156 $id = defaults($_REQUEST, 'id', 0);
6158 // return error if id is zero
6160 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6161 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6164 // error message if specified id is not in database
6165 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6166 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6167 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6170 // update seen indicator
6171 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6175 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6176 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6178 $answer = ['result' => 'error', 'message' => 'unknown error'];
6179 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6183 /// @TODO move to top of file or somewhere better
6184 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6187 * @brief search for direct_messages containing a searchstring through api
6189 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6190 * @param string $box
6191 * @return string|array (success: success=true if found and search_result contains found messages,
6192 * success=false if nothing was found, search_result='nothing found',
6193 * error: result=error with error message)
6194 * @throws BadRequestException
6195 * @throws ForbiddenException
6196 * @throws ImagickException
6197 * @throws InternalServerErrorException
6198 * @throws UnauthorizedException
6200 function api_friendica_direct_messages_search($type, $box = "")
6204 if (api_user() === false) {
6205 throw new ForbiddenException();
6209 $user_info = api_get_user($a);
6210 $searchstring = defaults($_REQUEST, 'searchstring', "");
6211 $uid = $user_info['uid'];
6213 // error if no searchstring specified
6214 if ($searchstring == "") {
6215 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6216 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6219 // get data for the specified searchstring
6221 "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",
6223 DBA::escape('%'.$searchstring.'%')
6226 $profile_url = $user_info["url"];
6228 // message if nothing was found
6229 if (!DBA::isResult($r)) {
6230 $success = ['success' => false, 'search_results' => 'problem with query'];
6231 } elseif (count($r) == 0) {
6232 $success = ['success' => false, 'search_results' => 'nothing found'];
6235 foreach ($r as $item) {
6236 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6237 $recipient = $user_info;
6238 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6239 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6240 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6241 $sender = $user_info;
6244 if (isset($recipient) && isset($sender)) {
6245 $ret[] = api_format_messages($item, $recipient, $sender);
6248 $success = ['success' => true, 'search_results' => $ret];
6251 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6254 /// @TODO move to top of file or somewhere better
6255 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6258 * @brief return data of all the profiles a user has to the client
6260 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6261 * @return string|array
6262 * @throws BadRequestException
6263 * @throws ForbiddenException
6264 * @throws ImagickException
6265 * @throws InternalServerErrorException
6266 * @throws UnauthorizedException
6268 function api_friendica_profile_show($type)
6272 if (api_user() === false) {
6273 throw new ForbiddenException();
6277 $profile_id = defaults($_REQUEST, 'profile_id', 0);
6279 // retrieve general information about profiles for user
6280 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6281 $directory = Config::get('system', 'directory');
6283 // get data of the specified profile id or all profiles of the user if not specified
6284 if ($profile_id != 0) {
6285 $r = Profile::getById(api_user(), $profile_id);
6286 // error message if specified gid is not in database
6287 if (!DBA::isResult($r)) {
6288 throw new BadRequestException("profile_id not available");
6291 $r = Profile::getListByUser(api_user());
6293 // loop through all returned profiles and retrieve data and users
6296 if (DBA::isResult($r)) {
6297 foreach ($r as $rr) {
6298 $profile = api_format_items_profiles($rr);
6300 // select all users from contact table, loop and prepare standard return for user data
6302 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6303 foreach ($nurls as $nurl) {
6304 $user = api_get_user($a, $nurl['nurl']);
6305 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6307 $profile['users'] = $users;
6309 // add prepared profile data to array for final return
6310 if ($type == "xml") {
6311 $profiles[$k++ . ":profile"] = $profile;
6313 $profiles[] = $profile;
6318 // return settings, authenticated user and profiles data
6319 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6321 $result = ['multi_profiles' => $multi_profiles ? true : false,
6322 'global_dir' => $directory,
6323 'friendica_owner' => api_get_user($a, $self['nurl']),
6324 'profiles' => $profiles];
6325 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6327 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6330 * Returns a list of saved searches.
6332 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6334 * @param string $type Return format: json or xml
6336 * @return string|array
6339 function api_saved_searches_list($type)
6341 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6344 while ($term = DBA::fetch($terms)) {
6346 'created_at' => api_date(time()),
6347 'id' => intval($term['id']),
6348 'id_str' => $term['id'],
6349 'name' => $term['term'],
6351 'query' => $term['term']
6357 return api_format_data("terms", $type, ['terms' => $result]);
6360 /// @TODO move to top of file or somewhere better
6361 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6364 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6366 * @brief Number of comments
6368 * @param object $data [Status, Status]
6372 function bindComments(&$data)
6374 if (count($data) == 0) {
6380 foreach ($data as $item) {
6381 $ids[] = $item['id'];
6384 $idStr = DBA::escape(implode(', ', $ids));
6385 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6386 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6387 $itemsData = DBA::toArray($items);
6389 foreach ($itemsData as $item) {
6390 $comments[$item['parent']] = $item['comments'];
6393 foreach ($data as $idx => $item) {
6395 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6400 @TODO Maybe open to implement?
6402 [pagename] => api/1.1/statuses/lookup.json
6403 [id] => 605138389168451584
6404 [include_cards] => true
6405 [cards_platform] => Android-12
6406 [include_entities] => true
6407 [include_my_retweet] => 1
6409 [include_reply_count] => true
6410 [include_descendent_reply_count] => true
6414 Not implemented by now:
6415 statuses/retweets_of_me
6420 account/update_location
6421 account/update_profile_background_image
6424 friendica/profile/update
6425 friendica/profile/create
6426 friendica/profile/delete
6428 Not implemented in status.net:
6429 statuses/retweeted_to_me
6430 statuses/retweeted_by_me
6431 direct_messages/destroy
6433 account/update_delivery_device
6434 notifications/follow