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 InternalServerErrorException
166 * @throws UnauthorizedException
167 * @hook 'authenticate'
169 * 'username' => username from login form
170 * 'password' => password from login form
171 * 'authenticated' => return status,
172 * 'user_record' => return authenticated user record
174 * array $user logged user record
176 function api_login(App $a)
178 $oauth1 = new FKOAuth1();
181 $request = OAuthRequest::from_request();
182 list($consumer, $token) = $oauth1->verify_request($request);
183 if (!is_null($token)) {
184 $oauth1->loginUser($token->uid);
185 Hook::callAll('logged_in', $a->user);
188 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
189 var_dump($consumer, $token);
191 } catch (Exception $e) {
192 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
195 // workaround for HTTP-auth in CGI mode
196 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
197 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
198 if (strlen($userpass)) {
199 list($name, $password) = explode(':', $userpass);
200 $_SERVER['PHP_AUTH_USER'] = $name;
201 $_SERVER['PHP_AUTH_PW'] = $password;
205 if (empty($_SERVER['PHP_AUTH_USER'])) {
206 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
207 header('WWW-Authenticate: Basic realm="Friendica"');
208 throw new UnauthorizedException("This API requires login");
211 $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
212 $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
214 // allow "user@server" login (but ignore 'server' part)
215 $at = strstr($user, "@", true);
220 // next code from mod/auth.php. needs better solution
224 'username' => trim($user),
225 'password' => trim($password),
226 'authenticated' => 0,
227 'user_record' => null,
231 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
232 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
233 * and later addons should not interfere with an earlier one that succeeded.
235 Hook::callAll('authenticate', $addon_auth);
237 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
238 $record = $addon_auth['user_record'];
240 $user_id = User::authenticate(trim($user), trim($password), true);
241 if ($user_id !== false) {
242 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
246 if (!DBA::isResult($record)) {
247 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
248 header('WWW-Authenticate: Basic realm="Friendica"');
249 //header('HTTP/1.0 401 Unauthorized');
250 //die('This api requires login');
251 throw new UnauthorizedException("This API requires login");
254 Session::setAuthenticatedForUser($a, $record);
256 $_SESSION["allow_api"] = true;
258 Hook::callAll('logged_in', $a->user);
262 * API endpoints can define which HTTP method to accept when called.
263 * This function check the current HTTP method agains endpoint
266 * @brief Check HTTP method of called API
268 * @param string $method Required methods, uppercase, separated by comma
271 function api_check_method($method)
273 if ($method == "*") {
276 return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
280 * Authenticate user, call registered API function, set HTTP headers
282 * @brief Main API entry point
285 * @return string|array API call result
288 function api_call(App $a)
290 global $API, $called_api;
293 if (strpos($a->query_string, ".xml") > 0) {
296 if (strpos($a->query_string, ".json") > 0) {
299 if (strpos($a->query_string, ".rss") > 0) {
302 if (strpos($a->query_string, ".atom") > 0) {
307 foreach ($API as $p => $info) {
308 if (strpos($a->query_string, $p) === 0) {
309 if (!api_check_method($info['method'])) {
310 throw new MethodNotAllowedException();
313 $called_api = explode("/", $p);
314 //unset($_SERVER['PHP_AUTH_USER']);
316 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
317 if (!empty($info['auth']) && api_user() === false) {
321 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
322 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
324 $stamp = microtime(true);
325 $return = call_user_func($info['func'], $type);
326 $duration = (float) (microtime(true) - $stamp);
328 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
330 $a->getProfiler()->saveLog($a->getLogger(), API_LOG_PREFIX . 'performance');
332 if (false === $return) {
334 * api function returned false withour throw an
335 * exception. This should not happend, throw a 500
337 throw new InternalServerErrorException();
342 header("Content-Type: text/xml");
345 header("Content-Type: application/json");
346 if (!empty($return)) {
347 $json = json_encode(end($return));
348 if (!empty($_GET['callback'])) {
349 $json = $_GET['callback'] . "(" . $json . ")";
355 header("Content-Type: application/rss+xml");
356 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
359 header("Content-Type: application/atom+xml");
360 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
367 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => $a->query_string]);
368 throw new NotImplementedException();
369 } catch (HTTPException $e) {
370 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
371 return api_error($type, $e);
376 * @brief Format API error string
378 * @param string $type Return type (xml, json, rss, as)
379 * @param object $e HTTPException Error object
380 * @return string|array error message formatted as $type
382 function api_error($type, $e)
386 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
387 /// @TODO: https://dev.twitter.com/overview/api/response-codes
389 $error = ["error" => $error,
390 "code" => $e->getCode() . " " . $e->httpdesc,
391 "request" => $a->query_string];
393 $return = api_format_data('status', $type, ['status' => $error]);
397 header("Content-Type: text/xml");
400 header("Content-Type: application/json");
401 $return = json_encode($return);
404 header("Content-Type: application/rss+xml");
407 header("Content-Type: application/atom+xml");
415 * @brief Set values for RSS template
418 * @param array $arr Array to be passed to template
419 * @param array $user_info User info
421 * @throws BadRequestException
422 * @throws ImagickException
423 * @throws InternalServerErrorException
424 * @throws UnauthorizedException
425 * @todo find proper type-hints
427 function api_rss_extra(App $a, $arr, $user_info)
429 if (is_null($user_info)) {
430 $user_info = api_get_user($a);
433 $arr['$user'] = $user_info;
435 'alternate' => $user_info['url'],
436 'self' => System::baseUrl() . "/" . $a->query_string,
437 'base' => System::baseUrl(),
438 'updated' => api_date(null),
439 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
440 'language' => $user_info['lang'],
441 'logo' => System::baseUrl() . "/images/friendica-32.png",
449 * @brief Unique contact to contact url.
451 * @param int $id Contact id
452 * @return bool|string
453 * Contact url or False if contact id is unknown
456 function api_unique_id_to_nurl($id)
458 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
460 if (DBA::isResult($r)) {
468 * @brief Get user info array.
471 * @param int|string $contact_id Contact ID or URL
473 * @throws BadRequestException
474 * @throws ImagickException
475 * @throws InternalServerErrorException
476 * @throws UnauthorizedException
478 function api_get_user(App $a, $contact_id = null)
486 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
488 // Searching for contact URL
489 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
490 $user = DBA::escape(Strings::normaliseLink($contact_id));
492 $extra_query = "AND `contact`.`nurl` = '%s' ";
493 if (api_user() !== false) {
494 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
498 // Searching for contact id with uid = 0
499 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
500 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
503 throw new BadRequestException("User ID ".$contact_id." not found.");
507 $extra_query = "AND `contact`.`nurl` = '%s' ";
508 if (api_user() !== false) {
509 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
513 if (is_null($user) && !empty($_GET['user_id'])) {
514 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
517 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
521 $extra_query = "AND `contact`.`nurl` = '%s' ";
522 if (api_user() !== false) {
523 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
526 if (is_null($user) && !empty($_GET['screen_name'])) {
527 $user = DBA::escape($_GET['screen_name']);
528 $extra_query = "AND `contact`.`nick` = '%s' ";
529 if (api_user() !== false) {
530 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
534 if (is_null($user) && !empty($_GET['profileurl'])) {
535 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
536 $extra_query = "AND `contact`.`nurl` = '%s' ";
537 if (api_user() !== false) {
538 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
542 // $called_api is the API path exploded on / and is expected to have at least 2 elements
543 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
544 $argid = count($called_api);
545 if (!empty($a->argv[$argid])) {
546 $data = explode(".", $a->argv[$argid]);
547 if (count($data) > 1) {
548 list($user, $null) = $data;
551 if (is_numeric($user)) {
552 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
556 $extra_query = "AND `contact`.`nurl` = '%s' ";
557 if (api_user() !== false) {
558 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
562 $user = DBA::escape($user);
563 $extra_query = "AND `contact`.`nick` = '%s' ";
564 if (api_user() !== false) {
565 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
570 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
573 if (api_user() === false) {
577 $user = $_SESSION['uid'];
578 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
582 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
586 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
592 // Selecting the id by priority, friendica first
593 if (is_array($uinfo)) {
594 api_best_nickname($uinfo);
597 // if the contact wasn't found, fetch it from the contacts with uid = 0
598 if (!DBA::isResult($uinfo)) {
600 throw new BadRequestException("User not found.");
603 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
605 if (DBA::isResult($contact)) {
606 // If no nick where given, extract it from the address
607 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
608 $contact['nick'] = api_get_nick($contact["url"]);
612 'id' => $contact["id"],
613 'id_str' => (string) $contact["id"],
614 'name' => $contact["name"],
615 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
616 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
617 'description' => BBCode::toPlaintext($contact["about"]),
618 'profile_image_url' => $contact["micro"],
619 'profile_image_url_https' => $contact["micro"],
620 'profile_image_url_profile_size' => $contact["thumb"],
621 'profile_image_url_large' => $contact["photo"],
622 'url' => $contact["url"],
623 'protected' => false,
624 'followers_count' => 0,
625 'friends_count' => 0,
627 'created_at' => api_date($contact["created"]),
628 'favourites_count' => 0,
630 'time_zone' => 'UTC',
631 'geo_enabled' => false,
633 'statuses_count' => 0,
635 'contributors_enabled' => false,
636 'is_translator' => false,
637 'is_translation_enabled' => false,
638 'following' => false,
639 'follow_request_sent' => false,
640 'statusnet_blocking' => false,
641 'notifications' => false,
642 'statusnet_profile_url' => $contact["url"],
644 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
645 'pid' => Contact::getIdForURL($contact["url"], 0, true),
647 'network' => $contact["network"],
652 throw new BadRequestException("User ".$url." not found.");
656 if ($uinfo[0]['self']) {
657 if ($uinfo[0]['network'] == "") {
658 $uinfo[0]['network'] = Protocol::DFRN;
661 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
662 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
669 // Add a nick if it isn't present there
670 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
671 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
674 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
676 if (!empty($profile['about'])) {
677 $description = $profile['about'];
679 $description = $uinfo[0]["about"];
682 if (!empty($usr['default-location'])) {
683 $location = $usr['default-location'];
684 } elseif (!empty($uinfo[0]["location"])) {
685 $location = $uinfo[0]["location"];
687 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
691 'id' => intval($pcontact_id),
692 'id_str' => (string) intval($pcontact_id),
693 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
694 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
695 'location' => $location,
696 'description' => BBCode::toPlaintext($description),
697 'profile_image_url' => $uinfo[0]['micro'],
698 'profile_image_url_https' => $uinfo[0]['micro'],
699 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
700 'profile_image_url_large' => $uinfo[0]["photo"],
701 'url' => $uinfo[0]['url'],
702 'protected' => false,
703 'followers_count' => intval($countfollowers),
704 'friends_count' => intval($countfriends),
706 'created_at' => api_date($uinfo[0]['created']),
707 'favourites_count' => intval($starred),
709 'time_zone' => 'UTC',
710 'geo_enabled' => false,
712 'statuses_count' => intval($countitems),
714 'contributors_enabled' => false,
715 'is_translator' => false,
716 'is_translation_enabled' => false,
717 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
718 'follow_request_sent' => false,
719 'statusnet_blocking' => false,
720 'notifications' => false,
722 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
723 'statusnet_profile_url' => $uinfo[0]['url'],
724 'uid' => intval($uinfo[0]['uid']),
725 'cid' => intval($uinfo[0]['cid']),
726 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
727 'self' => $uinfo[0]['self'],
728 'network' => $uinfo[0]['network'],
731 // If this is a local user and it uses Frio, we can get its color preferences.
733 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
734 if ($theme_info['theme'] === 'frio') {
735 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
737 if ($schema && ($schema != '---')) {
738 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
739 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
740 require_once $schemefile;
743 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
744 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
745 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
747 if (empty($nav_bg)) {
750 if (empty($link_color)) {
751 $link_color = "#6fdbe8";
753 if (empty($bgcolor)) {
754 $bgcolor = "#ededed";
757 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
758 $ret['profile_link_color'] = str_replace('#', '', $link_color);
759 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
767 * @brief return api-formatted array for item's author and owner
770 * @param array $item item from db
771 * @return array(array:author, array:owner)
772 * @throws BadRequestException
773 * @throws ImagickException
774 * @throws InternalServerErrorException
775 * @throws UnauthorizedException
777 function api_item_get_user(App $a, $item)
779 $status_user = api_get_user($a, defaults($item, 'author-id', null));
781 $author_user = $status_user;
783 $status_user["protected"] = defaults($item, 'private', 0);
785 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
786 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
788 $owner_user = $author_user;
791 return ([$status_user, $author_user, $owner_user]);
795 * @brief walks recursively through an array with the possibility to change value and key
797 * @param array $array The array to walk through
798 * @param callable $callback The callback function
800 * @return array the transformed array
802 function api_walk_recursive(array &$array, callable $callback)
806 foreach ($array as $k => $v) {
808 if ($callback($v, $k)) {
809 $new_array[$k] = api_walk_recursive($v, $callback);
812 if ($callback($v, $k)) {
823 * @brief Callback function to transform the array in an array that can be transformed in a XML file
825 * @param mixed $item Array item value
826 * @param string $key Array key
828 * @return boolean Should the array item be deleted?
830 function api_reformat_xml(&$item, &$key)
832 if (is_bool($item)) {
833 $item = ($item ? "true" : "false");
836 if (substr($key, 0, 10) == "statusnet_") {
837 $key = "statusnet:".substr($key, 10);
838 } elseif (substr($key, 0, 10) == "friendica_") {
839 $key = "friendica:".substr($key, 10);
841 /// @TODO old-lost code?
843 // $key = "default:".$key;
849 * @brief Creates the XML from a JSON style array
851 * @param array $data JSON style array
852 * @param string $root_element Name of the root element
854 * @return string The XML data
856 function api_create_xml(array $data, $root_element)
858 $childname = key($data);
859 $data2 = array_pop($data);
861 $namespaces = ["" => "http://api.twitter.com",
862 "statusnet" => "http://status.net/schema/api/1/",
863 "friendica" => "http://friendi.ca/schema/api/1/",
864 "georss" => "http://www.georss.org/georss"];
866 /// @todo Auto detection of needed namespaces
867 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
871 if (is_array($data2)) {
873 api_walk_recursive($data2, "api_reformat_xml");
879 foreach ($data2 as $item) {
880 $data4[$i++ . ":" . $childname] = $item;
887 $data3 = [$root_element => $data2];
889 $ret = XML::fromArray($data3, $xml, false, $namespaces);
894 * @brief Formats the data according to the data type
896 * @param string $root_element Name of the root element
897 * @param string $type Return type (atom, rss, xml, json)
898 * @param array $data JSON style array
900 * @return array|string (string|array) XML data or JSON data
902 function api_format_data($root_element, $type, $data)
908 $ret = api_create_xml($data, $root_element);
923 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
924 * returns a 401 status code and an error message if not.
926 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
928 * @param string $type Return type (atom, rss, xml, json)
929 * @return array|string
930 * @throws BadRequestException
931 * @throws ForbiddenException
932 * @throws ImagickException
933 * @throws InternalServerErrorException
934 * @throws UnauthorizedException
936 function api_account_verify_credentials($type)
940 if (api_user() === false) {
941 throw new ForbiddenException();
944 unset($_REQUEST["user_id"]);
945 unset($_GET["user_id"]);
947 unset($_REQUEST["screen_name"]);
948 unset($_GET["screen_name"]);
950 $skip_status = defaults($_REQUEST, 'skip_status', false);
952 $user_info = api_get_user($a);
954 // "verified" isn't used here in the standard
955 unset($user_info["verified"]);
957 // - Adding last status
959 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
961 $user_info['status'] = api_format_item($item, $type);
965 // "uid" and "self" are only needed for some internal stuff, so remove it from here
966 unset($user_info["uid"]);
967 unset($user_info["self"]);
969 return api_format_data("user", $type, ['user' => $user_info]);
972 /// @TODO move to top of file or somewhere better
973 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
976 * Get data from $_POST or $_GET
981 function requestdata($k)
983 if (!empty($_POST[$k])) {
986 if (!empty($_GET[$k])) {
993 * Deprecated function to upload media.
995 * @param string $type Return type (atom, rss, xml, json)
997 * @return array|string
998 * @throws BadRequestException
999 * @throws ForbiddenException
1000 * @throws ImagickException
1001 * @throws InternalServerErrorException
1002 * @throws UnauthorizedException
1004 function api_statuses_mediap($type)
1008 if (api_user() === false) {
1009 Logger::log('api_statuses_update: no user');
1010 throw new ForbiddenException();
1012 $user_info = api_get_user($a);
1014 $_REQUEST['profile_uid'] = api_user();
1015 $_REQUEST['api_source'] = true;
1016 $txt = requestdata('status');
1017 /// @TODO old-lost code?
1018 //$txt = urldecode(requestdata('status'));
1020 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1021 $txt = HTML::toBBCodeVideo($txt);
1022 $config = HTMLPurifier_Config::createDefault();
1023 $config->set('Cache.DefinitionImpl', null);
1024 $purifier = new HTMLPurifier($config);
1025 $txt = $purifier->purify($txt);
1027 $txt = HTML::toBBCode($txt);
1029 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1031 $picture = wall_upload_post($a, false);
1033 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1034 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1035 $item_id = item_post($a);
1037 // output the post that we just posted.
1038 return api_status_show($type, $item_id);
1041 /// @TODO move this to top of file or somewhere better!
1042 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1045 * Updates the user’s current status.
1047 * @param string $type Return type (atom, rss, xml, json)
1049 * @return array|string
1050 * @throws BadRequestException
1051 * @throws ForbiddenException
1052 * @throws ImagickException
1053 * @throws InternalServerErrorException
1054 * @throws TooManyRequestsException
1055 * @throws UnauthorizedException
1056 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1058 function api_statuses_update($type)
1062 if (api_user() === false) {
1063 Logger::log('api_statuses_update: no user');
1064 throw new ForbiddenException();
1069 // convert $_POST array items to the form we use for web posts.
1070 if (requestdata('htmlstatus')) {
1071 $txt = requestdata('htmlstatus');
1072 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1073 $txt = HTML::toBBCodeVideo($txt);
1075 $config = HTMLPurifier_Config::createDefault();
1076 $config->set('Cache.DefinitionImpl', null);
1078 $purifier = new HTMLPurifier($config);
1079 $txt = $purifier->purify($txt);
1081 $_REQUEST['body'] = HTML::toBBCode($txt);
1084 $_REQUEST['body'] = requestdata('status');
1087 $_REQUEST['title'] = requestdata('title');
1089 $parent = requestdata('in_reply_to_status_id');
1091 // Twidere sends "-1" if it is no reply ...
1092 if ($parent == -1) {
1096 if (ctype_digit($parent)) {
1097 $_REQUEST['parent'] = $parent;
1099 $_REQUEST['parent_uri'] = $parent;
1102 if (requestdata('lat') && requestdata('long')) {
1103 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1105 $_REQUEST['profile_uid'] = api_user();
1108 // Check for throttling (maximum posts per day, week and month)
1109 $throttle_day = Config::get('system', 'throttle_limit_day');
1110 if ($throttle_day > 0) {
1111 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1113 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1114 $posts_day = DBA::count('thread', $condition);
1116 if ($posts_day > $throttle_day) {
1117 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1118 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1119 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));
1123 $throttle_week = Config::get('system', 'throttle_limit_week');
1124 if ($throttle_week > 0) {
1125 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1127 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1128 $posts_week = DBA::count('thread', $condition);
1130 if ($posts_week > $throttle_week) {
1131 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1132 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1133 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));
1137 $throttle_month = Config::get('system', 'throttle_limit_month');
1138 if ($throttle_month > 0) {
1139 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1141 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1142 $posts_month = DBA::count('thread', $condition);
1144 if ($posts_month > $throttle_month) {
1145 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1146 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1147 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));
1152 if (!empty($_FILES['media'])) {
1153 // upload the image if we have one
1154 $picture = wall_upload_post($a, false);
1155 if (is_array($picture)) {
1156 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1160 if (requestdata('media_ids')) {
1161 $ids = explode(',', requestdata('media_ids'));
1162 foreach ($ids as $id) {
1164 "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",
1168 if (DBA::isResult($r)) {
1169 $phototypes = Image::supportedTypes();
1170 $ext = $phototypes[$r[0]['type']];
1171 $description = $r[0]['desc'] ?? '';
1172 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1173 $_REQUEST['body'] .= '[img=' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1178 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1180 $_REQUEST['api_source'] = true;
1182 if (empty($_REQUEST['source'])) {
1183 $_REQUEST["source"] = api_source();
1186 // call out normal post function
1187 $item_id = item_post($a);
1189 // output the post that we just posted.
1190 return api_status_show($type, $item_id);
1193 /// @TODO move to top of file or somewhere better
1194 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1195 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1198 * Uploads an image to Friendica.
1201 * @throws BadRequestException
1202 * @throws ForbiddenException
1203 * @throws ImagickException
1204 * @throws InternalServerErrorException
1205 * @throws UnauthorizedException
1206 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1208 function api_media_upload()
1212 if (api_user() === false) {
1213 Logger::log('no user');
1214 throw new ForbiddenException();
1219 if (empty($_FILES['media'])) {
1221 throw new BadRequestException("No media.");
1224 $media = wall_upload_post($a, false);
1227 throw new InternalServerErrorException();
1231 $returndata["media_id"] = $media["id"];
1232 $returndata["media_id_string"] = (string)$media["id"];
1233 $returndata["size"] = $media["size"];
1234 $returndata["image"] = ["w" => $media["width"],
1235 "h" => $media["height"],
1236 "image_type" => $media["type"],
1237 "friendica_preview_url" => $media["preview"]];
1239 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1241 return ["media" => $returndata];
1244 /// @TODO move to top of file or somewhere better
1245 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1248 * Updates media meta data (picture descriptions)
1250 * @param string $type Return type (atom, rss, xml, json)
1252 * @return array|string
1253 * @throws BadRequestException
1254 * @throws ForbiddenException
1255 * @throws ImagickException
1256 * @throws InternalServerErrorException
1257 * @throws TooManyRequestsException
1258 * @throws UnauthorizedException
1259 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1261 * @todo Compare the corresponding Twitter function for correct return values
1263 function api_media_metadata_create($type)
1267 if (api_user() === false) {
1268 Logger::info('no user');
1269 throw new ForbiddenException();
1274 $postdata = Network::postdata();
1276 if (empty($postdata)) {
1277 throw new BadRequestException("No post data");
1280 $data = json_decode($postdata, true);
1282 throw new BadRequestException("Invalid post data");
1285 if (empty($data['media_id']) || empty($data['alt_text'])) {
1286 throw new BadRequestException("Missing post data values");
1289 if (empty($data['alt_text']['text'])) {
1290 throw new BadRequestException("No alt text.");
1293 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1295 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1296 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1297 if (!DBA::isResult($photo)) {
1298 throw new BadRequestException("Metadata not found.");
1301 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1304 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1307 * @param string $type Return format (atom, rss, xml, json)
1308 * @param int $item_id
1312 function api_status_show($type, $item_id)
1314 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1318 $item = api_get_item(['id' => $item_id]);
1320 $status_info = api_format_item($item, $type);
1323 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1325 return api_format_data('statuses', $type, ['status' => $status_info]);
1329 * Retrieves the last public status of the provided user info
1331 * @param int $ownerId Public contact Id
1332 * @param int $uid User Id
1336 function api_get_last_status($ownerId, $uid)
1339 'author-id'=> $ownerId,
1341 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1345 $item = api_get_item($condition);
1351 * Retrieves a single item record based on the provided condition and converts it for API use.
1353 * @param array $condition Item table condition array
1357 function api_get_item(array $condition)
1359 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1365 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1366 * The author's most recent status will be returned inline.
1368 * @param string $type Return type (atom, rss, xml, json)
1369 * @return array|string
1370 * @throws BadRequestException
1371 * @throws ImagickException
1372 * @throws InternalServerErrorException
1373 * @throws UnauthorizedException
1374 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1376 function api_users_show($type)
1378 $a = \Friendica\BaseObject::getApp();
1380 $user_info = api_get_user($a);
1382 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1384 $user_info['status'] = api_format_item($item, $type);
1387 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1388 unset($user_info['uid']);
1389 unset($user_info['self']);
1391 return api_format_data('user', $type, ['user' => $user_info]);
1394 /// @TODO move to top of file or somewhere better
1395 api_register_func('api/users/show', 'api_users_show');
1396 api_register_func('api/externalprofile/show', 'api_users_show');
1399 * Search a public user account.
1401 * @param string $type Return type (atom, rss, xml, json)
1403 * @return array|string
1404 * @throws BadRequestException
1405 * @throws ImagickException
1406 * @throws InternalServerErrorException
1407 * @throws UnauthorizedException
1408 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1410 function api_users_search($type)
1416 if (!empty($_GET['q'])) {
1417 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1419 if (!DBA::isResult($r)) {
1420 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1423 if (DBA::isResult($r)) {
1425 foreach ($r as $user) {
1426 $user_info = api_get_user($a, $user["id"]);
1428 if ($type == "xml") {
1429 $userlist[$k++.":user"] = $user_info;
1431 $userlist[] = $user_info;
1434 $userlist = ["users" => $userlist];
1436 throw new BadRequestException("User ".$_GET["q"]." not found.");
1439 throw new BadRequestException("No user specified.");
1442 return api_format_data("users", $type, $userlist);
1445 /// @TODO move to top of file or somewhere better
1446 api_register_func('api/users/search', 'api_users_search');
1449 * Return user objects
1451 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1453 * @param string $type Return format: json or xml
1455 * @return array|string
1456 * @throws BadRequestException
1457 * @throws ImagickException
1458 * @throws InternalServerErrorException
1459 * @throws NotFoundException if the results are empty.
1460 * @throws UnauthorizedException
1462 function api_users_lookup($type)
1466 if (!empty($_REQUEST['user_id'])) {
1467 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1469 $users[] = api_get_user(get_app(), $id);
1474 if (empty($users)) {
1475 throw new NotFoundException;
1478 return api_format_data("users", $type, ['users' => $users]);
1481 /// @TODO move to top of file or somewhere better
1482 api_register_func('api/users/lookup', 'api_users_lookup', true);
1485 * Returns statuses that match a specified query.
1487 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1489 * @param string $type Return format: json, xml, atom, rss
1491 * @return array|string
1492 * @throws BadRequestException if the "q" parameter is missing.
1493 * @throws ForbiddenException
1494 * @throws ImagickException
1495 * @throws InternalServerErrorException
1496 * @throws UnauthorizedException
1498 function api_search($type)
1501 $user_info = api_get_user($a);
1503 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1505 if (empty($_REQUEST['q'])) {
1506 throw new BadRequestException('q parameter is required.');
1509 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1512 $data['status'] = [];
1514 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1515 if (!empty($_REQUEST['rpp'])) {
1516 $count = $_REQUEST['rpp'];
1517 } elseif (!empty($_REQUEST['count'])) {
1518 $count = $_REQUEST['count'];
1521 $since_id = defaults($_REQUEST, 'since_id', 0);
1522 $max_id = defaults($_REQUEST, 'max_id', 0);
1523 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1524 $start = $page * $count;
1525 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1526 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1527 $searchTerm = $matches[1];
1528 $condition = ["`oid` > ?
1529 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1530 AND `otype` = ? AND `type` = ? AND `term` = ?",
1531 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1533 $condition[0] .= ' AND `oid` <= ?';
1534 $condition[] = $max_id;
1536 $terms = DBA::select('term', ['oid'], $condition, []);
1538 while ($term = DBA::fetch($terms)) {
1539 $itemIds[] = $term['oid'];
1543 if (empty($itemIds)) {
1544 return api_format_data('statuses', $type, $data);
1547 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1548 if ($exclude_replies) {
1549 $preCondition[] = '`id` = `parent`';
1552 $condition = [implode(' AND ', $preCondition)];
1554 $condition = ["`id` > ?
1555 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1556 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1557 AND `body` LIKE CONCAT('%',?,'%')",
1558 $since_id, api_user(), $_REQUEST['q']];
1560 $condition[0] .= ' AND `id` <= ?';
1561 $condition[] = $max_id;
1565 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1567 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1569 bindComments($data['status']);
1571 return api_format_data('statuses', $type, $data);
1574 /// @TODO move to top of file or somewhere better
1575 api_register_func('api/search/tweets', 'api_search', true);
1576 api_register_func('api/search', 'api_search', true);
1579 * Returns the most recent statuses posted by the user and the users they follow.
1581 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1583 * @param string $type Return type (atom, rss, xml, json)
1585 * @return array|string
1586 * @throws BadRequestException
1587 * @throws ForbiddenException
1588 * @throws ImagickException
1589 * @throws InternalServerErrorException
1590 * @throws UnauthorizedException
1591 * @todo Optional parameters
1592 * @todo Add reply info
1594 function api_statuses_home_timeline($type)
1597 $user_info = api_get_user($a);
1599 if (api_user() === false || $user_info === false) {
1600 throw new ForbiddenException();
1603 unset($_REQUEST["user_id"]);
1604 unset($_GET["user_id"]);
1606 unset($_REQUEST["screen_name"]);
1607 unset($_GET["screen_name"]);
1609 // get last network messages
1612 $count = defaults($_REQUEST, 'count', 20);
1613 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1617 $since_id = defaults($_REQUEST, 'since_id', 0);
1618 $max_id = defaults($_REQUEST, 'max_id', 0);
1619 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1620 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1622 $start = $page * $count;
1624 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1625 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1628 $condition[0] .= " AND `item`.`id` <= ?";
1629 $condition[] = $max_id;
1631 if ($exclude_replies) {
1632 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1634 if ($conversation_id > 0) {
1635 $condition[0] .= " AND `item`.`parent` = ?";
1636 $condition[] = $conversation_id;
1639 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1640 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1642 $items = Item::inArray($statuses);
1644 $ret = api_format_items($items, $user_info, false, $type);
1646 // Set all posts from the query above to seen
1648 foreach ($items as $item) {
1649 $idarray[] = intval($item["id"]);
1652 if (!empty($idarray)) {
1653 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1655 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1661 $data = ['status' => $ret];
1666 $data = api_rss_extra($a, $data, $user_info);
1670 return api_format_data("statuses", $type, $data);
1674 /// @TODO move to top of file or somewhere better
1675 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1676 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1679 * Returns the most recent statuses from public users.
1681 * @param string $type Return type (atom, rss, xml, json)
1683 * @return array|string
1684 * @throws BadRequestException
1685 * @throws ForbiddenException
1686 * @throws ImagickException
1687 * @throws InternalServerErrorException
1688 * @throws UnauthorizedException
1690 function api_statuses_public_timeline($type)
1693 $user_info = api_get_user($a);
1695 if (api_user() === false || $user_info === false) {
1696 throw new ForbiddenException();
1699 // get last network messages
1702 $count = defaults($_REQUEST, 'count', 20);
1703 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1707 $since_id = defaults($_REQUEST, 'since_id', 0);
1708 $max_id = defaults($_REQUEST, 'max_id', 0);
1709 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1710 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1712 $start = $page * $count;
1714 if ($exclude_replies && !$conversation_id) {
1715 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1716 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1719 $condition[0] .= " AND `thread`.`iid` <= ?";
1720 $condition[] = $max_id;
1723 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1724 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1726 $r = Item::inArray($statuses);
1728 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1729 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1732 $condition[0] .= " AND `item`.`id` <= ?";
1733 $condition[] = $max_id;
1735 if ($conversation_id > 0) {
1736 $condition[0] .= " AND `item`.`parent` = ?";
1737 $condition[] = $conversation_id;
1740 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1741 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1743 $r = Item::inArray($statuses);
1746 $ret = api_format_items($r, $user_info, false, $type);
1750 $data = ['status' => $ret];
1755 $data = api_rss_extra($a, $data, $user_info);
1759 return api_format_data("statuses", $type, $data);
1762 /// @TODO move to top of file or somewhere better
1763 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1766 * Returns the most recent statuses posted by users this node knows about.
1768 * @brief Returns the list of public federated posts this node knows about
1770 * @param string $type Return format: json, xml, atom, rss
1771 * @return array|string
1772 * @throws BadRequestException
1773 * @throws ForbiddenException
1774 * @throws ImagickException
1775 * @throws InternalServerErrorException
1776 * @throws UnauthorizedException
1778 function api_statuses_networkpublic_timeline($type)
1781 $user_info = api_get_user($a);
1783 if (api_user() === false || $user_info === false) {
1784 throw new ForbiddenException();
1787 $since_id = defaults($_REQUEST, 'since_id', 0);
1788 $max_id = defaults($_REQUEST, 'max_id', 0);
1791 $count = defaults($_REQUEST, 'count', 20);
1792 $page = defaults($_REQUEST, 'page', 1);
1796 $start = ($page - 1) * $count;
1798 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1799 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1802 $condition[0] .= " AND `thread`.`iid` <= ?";
1803 $condition[] = $max_id;
1806 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1807 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1809 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1813 $data = ['status' => $ret];
1818 $data = api_rss_extra($a, $data, $user_info);
1822 return api_format_data("statuses", $type, $data);
1825 /// @TODO move to top of file or somewhere better
1826 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1829 * Returns a single status.
1831 * @param string $type Return type (atom, rss, xml, json)
1833 * @return array|string
1834 * @throws BadRequestException
1835 * @throws ForbiddenException
1836 * @throws ImagickException
1837 * @throws InternalServerErrorException
1838 * @throws UnauthorizedException
1839 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1841 function api_statuses_show($type)
1844 $user_info = api_get_user($a);
1846 if (api_user() === false || $user_info === false) {
1847 throw new ForbiddenException();
1851 $id = intval(defaults($a->argv, 3, 0));
1854 $id = intval(defaults($_REQUEST, 'id', 0));
1859 $id = intval(defaults($a->argv, 4, 0));
1862 Logger::log('API: api_statuses_show: ' . $id);
1864 $conversation = !empty($_REQUEST['conversation']);
1866 // try to fetch the item for the local user - or the public item, if there is no local one
1867 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1868 if (!DBA::isResult($uri_item)) {
1869 throw new BadRequestException("There is no status with this id.");
1872 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1873 if (!DBA::isResult($item)) {
1874 throw new BadRequestException("There is no status with this id.");
1879 if ($conversation) {
1880 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1881 $params = ['order' => ['id' => true]];
1883 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1887 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1889 /// @TODO How about copying this to above methods which don't check $r ?
1890 if (!DBA::isResult($statuses)) {
1891 throw new BadRequestException("There is no status with this id.");
1894 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1896 if ($conversation) {
1897 $data = ['status' => $ret];
1898 return api_format_data("statuses", $type, $data);
1900 $data = ['status' => $ret[0]];
1901 return api_format_data("status", $type, $data);
1905 /// @TODO move to top of file or somewhere better
1906 api_register_func('api/statuses/show', 'api_statuses_show', true);
1910 * @param string $type Return type (atom, rss, xml, json)
1912 * @return array|string
1913 * @throws BadRequestException
1914 * @throws ForbiddenException
1915 * @throws ImagickException
1916 * @throws InternalServerErrorException
1917 * @throws UnauthorizedException
1918 * @todo nothing to say?
1920 function api_conversation_show($type)
1923 $user_info = api_get_user($a);
1925 if (api_user() === false || $user_info === false) {
1926 throw new ForbiddenException();
1930 $id = intval(defaults($a->argv , 3 , 0));
1931 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1932 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1933 $count = intval(defaults($_REQUEST, 'count' , 20));
1934 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1939 $start = $page * $count;
1942 $id = intval(defaults($_REQUEST, 'id', 0));
1947 $id = intval(defaults($a->argv, 4, 0));
1950 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1952 // try to fetch the item for the local user - or the public item, if there is no local one
1953 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1954 if (!DBA::isResult($item)) {
1955 throw new BadRequestException("There is no status with this id.");
1958 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1959 if (!DBA::isResult($parent)) {
1960 throw new BadRequestException("There is no status with this id.");
1963 $id = $parent['id'];
1965 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1966 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1969 $condition[0] .= " AND `item`.`id` <= ?";
1970 $condition[] = $max_id;
1973 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1974 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1976 if (!DBA::isResult($statuses)) {
1977 throw new BadRequestException("There is no status with id $id.");
1980 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1982 $data = ['status' => $ret];
1983 return api_format_data("statuses", $type, $data);
1986 /// @TODO move to top of file or somewhere better
1987 api_register_func('api/conversation/show', 'api_conversation_show', true);
1988 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1993 * @param string $type Return type (atom, rss, xml, json)
1995 * @return array|string
1996 * @throws BadRequestException
1997 * @throws ForbiddenException
1998 * @throws ImagickException
1999 * @throws InternalServerErrorException
2000 * @throws UnauthorizedException
2001 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2003 function api_statuses_repeat($type)
2009 if (api_user() === false) {
2010 throw new ForbiddenException();
2016 $id = intval(defaults($a->argv, 3, 0));
2019 $id = intval(defaults($_REQUEST, 'id', 0));
2024 $id = intval(defaults($a->argv, 4, 0));
2027 Logger::log('API: api_statuses_repeat: '.$id);
2029 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2030 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2032 if (DBA::isResult($item) && $item['body'] != "") {
2033 if (strpos($item['body'], "[/share]") !== false) {
2034 $pos = strpos($item['body'], "[share");
2035 $post = substr($item['body'], $pos);
2037 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2039 $post .= $item['body'];
2040 $post .= "[/share]";
2042 $_REQUEST['body'] = $post;
2043 $_REQUEST['profile_uid'] = api_user();
2044 $_REQUEST['api_source'] = true;
2046 if (empty($_REQUEST['source'])) {
2047 $_REQUEST["source"] = api_source();
2050 $item_id = item_post($a);
2052 throw new ForbiddenException();
2055 // output the post that we just posted.
2057 return api_status_show($type, $item_id);
2060 /// @TODO move to top of file or somewhere better
2061 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2064 * Destroys a specific status.
2066 * @param string $type Return type (atom, rss, xml, json)
2068 * @return array|string
2069 * @throws BadRequestException
2070 * @throws ForbiddenException
2071 * @throws ImagickException
2072 * @throws InternalServerErrorException
2073 * @throws UnauthorizedException
2074 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2076 function api_statuses_destroy($type)
2080 if (api_user() === false) {
2081 throw new ForbiddenException();
2087 $id = intval(defaults($a->argv, 3, 0));
2090 $id = intval(defaults($_REQUEST, 'id', 0));
2095 $id = intval(defaults($a->argv, 4, 0));
2098 Logger::log('API: api_statuses_destroy: '.$id);
2100 $ret = api_statuses_show($type);
2102 Item::deleteForUser(['id' => $id], api_user());
2107 /// @TODO move to top of file or somewhere better
2108 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2111 * Returns the most recent mentions.
2113 * @param string $type Return type (atom, rss, xml, json)
2115 * @return array|string
2116 * @throws BadRequestException
2117 * @throws ForbiddenException
2118 * @throws ImagickException
2119 * @throws InternalServerErrorException
2120 * @throws UnauthorizedException
2121 * @see http://developer.twitter.com/doc/get/statuses/mentions
2123 function api_statuses_mentions($type)
2126 $user_info = api_get_user($a);
2128 if (api_user() === false || $user_info === false) {
2129 throw new ForbiddenException();
2132 unset($_REQUEST["user_id"]);
2133 unset($_GET["user_id"]);
2135 unset($_REQUEST["screen_name"]);
2136 unset($_GET["screen_name"]);
2138 // get last network messages
2141 $since_id = defaults($_REQUEST, 'since_id', 0);
2142 $max_id = defaults($_REQUEST, 'max_id' , 0);
2143 $count = defaults($_REQUEST, 'count' , 20);
2144 $page = defaults($_REQUEST, 'page' , 1);
2149 $start = ($page - 1) * $count;
2151 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2152 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2153 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2156 $condition[0] .= " AND `item`.`id` <= ?";
2157 $condition[] = $max_id;
2160 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2161 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2163 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2165 $data = ['status' => $ret];
2170 $data = api_rss_extra($a, $data, $user_info);
2174 return api_format_data("statuses", $type, $data);
2177 /// @TODO move to top of file or somewhere better
2178 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2179 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2182 * Returns the most recent statuses posted by the user.
2184 * @brief Returns a user's public timeline
2186 * @param string $type Either "json" or "xml"
2187 * @return string|array
2188 * @throws BadRequestException
2189 * @throws ForbiddenException
2190 * @throws ImagickException
2191 * @throws InternalServerErrorException
2192 * @throws UnauthorizedException
2193 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2195 function api_statuses_user_timeline($type)
2198 $user_info = api_get_user($a);
2200 if (api_user() === false || $user_info === false) {
2201 throw new ForbiddenException();
2205 "api_statuses_user_timeline: api_user: ". api_user() .
2206 "\nuser_info: ".print_r($user_info, true) .
2207 "\n_REQUEST: ".print_r($_REQUEST, true),
2211 $since_id = defaults($_REQUEST, 'since_id', 0);
2212 $max_id = defaults($_REQUEST, 'max_id', 0);
2213 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2214 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2217 $count = defaults($_REQUEST, 'count', 20);
2218 $page = defaults($_REQUEST, 'page', 1);
2222 $start = ($page - 1) * $count;
2224 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2225 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2227 if ($user_info['self'] == 1) {
2228 $condition[0] .= ' AND `item`.`wall` ';
2231 if ($exclude_replies) {
2232 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2235 if ($conversation_id > 0) {
2236 $condition[0] .= " AND `item`.`parent` = ?";
2237 $condition[] = $conversation_id;
2241 $condition[0] .= " AND `item`.`id` <= ?";
2242 $condition[] = $max_id;
2245 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2246 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2248 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2252 $data = ['status' => $ret];
2257 $data = api_rss_extra($a, $data, $user_info);
2261 return api_format_data("statuses", $type, $data);
2264 /// @TODO move to top of file or somewhere better
2265 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2268 * Star/unstar an item.
2269 * param: id : id of the item
2271 * @param string $type Return type (atom, rss, xml, json)
2273 * @return array|string
2274 * @throws BadRequestException
2275 * @throws ForbiddenException
2276 * @throws ImagickException
2277 * @throws InternalServerErrorException
2278 * @throws UnauthorizedException
2279 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2281 function api_favorites_create_destroy($type)
2285 if (api_user() === false) {
2286 throw new ForbiddenException();
2289 // for versioned api.
2290 /// @TODO We need a better global soluton
2291 $action_argv_id = 2;
2292 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2293 $action_argv_id = 3;
2296 if ($a->argc <= $action_argv_id) {
2297 throw new BadRequestException("Invalid request.");
2299 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2300 if ($a->argc == $action_argv_id + 2) {
2301 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2303 $itemid = intval(defaults($_REQUEST, 'id', 0));
2306 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2308 if (!DBA::isResult($item)) {
2309 throw new BadRequestException("Invalid item.");
2314 $item['starred'] = 1;
2317 $item['starred'] = 0;
2320 throw new BadRequestException("Invalid action ".$action);
2323 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2326 throw new InternalServerErrorException("DB error");
2330 $user_info = api_get_user($a);
2331 $rets = api_format_items([$item], $user_info, false, $type);
2334 $data = ['status' => $ret];
2339 $data = api_rss_extra($a, $data, $user_info);
2343 return api_format_data("status", $type, $data);
2346 /// @TODO move to top of file or somewhere better
2347 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2348 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2351 * Returns the most recent favorite statuses.
2353 * @param string $type Return type (atom, rss, xml, json)
2355 * @return string|array
2356 * @throws BadRequestException
2357 * @throws ForbiddenException
2358 * @throws ImagickException
2359 * @throws InternalServerErrorException
2360 * @throws UnauthorizedException
2362 function api_favorites($type)
2367 $user_info = api_get_user($a);
2369 if (api_user() === false || $user_info === false) {
2370 throw new ForbiddenException();
2375 // in friendica starred item are private
2376 // return favorites only for self
2377 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2379 if ($user_info['self'] == 0) {
2383 $since_id = defaults($_REQUEST, 'since_id', 0);
2384 $max_id = defaults($_REQUEST, 'max_id', 0);
2385 $count = defaults($_GET, 'count', 20);
2386 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2391 $start = $page*$count;
2393 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2394 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2396 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2399 $condition[0] .= " AND `item`.`id` <= ?";
2400 $condition[] = $max_id;
2403 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2405 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2410 $data = ['status' => $ret];
2415 $data = api_rss_extra($a, $data, $user_info);
2419 return api_format_data("statuses", $type, $data);
2422 /// @TODO move to top of file or somewhere better
2423 api_register_func('api/favorites', 'api_favorites', true);
2427 * @param array $item
2428 * @param array $recipient
2429 * @param array $sender
2432 * @throws InternalServerErrorException
2434 function api_format_messages($item, $recipient, $sender)
2436 // standard meta information
2438 'id' => $item['id'],
2439 'sender_id' => $sender['id'],
2441 'recipient_id' => $recipient['id'],
2442 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2443 'sender_screen_name' => $sender['screen_name'],
2444 'recipient_screen_name' => $recipient['screen_name'],
2445 'sender' => $sender,
2446 'recipient' => $recipient,
2448 'friendica_seen' => defaults($item, 'seen', 0),
2449 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2452 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2453 if (isset($ret['sender']['uid'])) {
2454 unset($ret['sender']['uid']);
2456 if (isset($ret['sender']['self'])) {
2457 unset($ret['sender']['self']);
2459 if (isset($ret['recipient']['uid'])) {
2460 unset($ret['recipient']['uid']);
2462 if (isset($ret['recipient']['self'])) {
2463 unset($ret['recipient']['self']);
2466 //don't send title to regular StatusNET requests to avoid confusing these apps
2467 if (!empty($_GET['getText'])) {
2468 $ret['title'] = $item['title'];
2469 if ($_GET['getText'] == 'html') {
2470 $ret['text'] = BBCode::convert($item['body'], false);
2471 } elseif ($_GET['getText'] == 'plain') {
2472 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2475 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2477 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2478 unset($ret['sender']);
2479 unset($ret['recipient']);
2487 * @param array $item
2490 * @throws InternalServerErrorException
2492 function api_convert_item($item)
2494 $body = $item['body'];
2495 $attachments = api_get_attachments($body);
2497 // Workaround for ostatus messages where the title is identically to the body
2498 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2499 $statusbody = trim(HTML::toPlaintext($html, 0));
2501 // handle data: images
2502 $statusbody = api_format_items_embeded_images($item, $statusbody);
2504 $statustitle = trim($item['title']);
2506 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2507 $statustext = trim($statusbody);
2509 $statustext = trim($statustitle."\n\n".$statusbody);
2512 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2513 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2516 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2518 // Workaround for clients with limited HTML parser functionality
2519 $search = ["<br>", "<blockquote>", "</blockquote>",
2520 "<h1>", "</h1>", "<h2>", "</h2>",
2521 "<h3>", "</h3>", "<h4>", "</h4>",
2522 "<h5>", "</h5>", "<h6>", "</h6>"];
2523 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2524 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2525 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2526 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2527 $statushtml = str_replace($search, $replace, $statushtml);
2529 if ($item['title'] != "") {
2530 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2534 $oldtext = $statushtml;
2535 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2536 } while ($oldtext != $statushtml);
2538 if (substr($statushtml, 0, 4) == '<br>') {
2539 $statushtml = substr($statushtml, 4);
2542 if (substr($statushtml, 0, -4) == '<br>') {
2543 $statushtml = substr($statushtml, -4);
2546 // feeds without body should contain the link
2547 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2548 $statushtml .= BBCode::convert($item['plink']);
2551 $entities = api_get_entitities($statustext, $body);
2554 "text" => $statustext,
2555 "html" => $statushtml,
2556 "attachments" => $attachments,
2557 "entities" => $entities
2563 * @param string $body
2566 * @throws InternalServerErrorException
2568 function api_get_attachments(&$body)
2571 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2573 $URLSearchString = "^\[\]";
2574 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2582 foreach ($images[1] as $image) {
2583 $imagedata = Image::getInfoFromURL($image);
2586 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2590 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2591 foreach ($images[0] as $orig) {
2592 $body = str_replace($orig, "", $body);
2596 return $attachments;
2601 * @param string $text
2602 * @param string $bbcode
2605 * @throws InternalServerErrorException
2606 * @todo Links at the first character of the post
2608 function api_get_entitities(&$text, $bbcode)
2610 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2612 if ($include_entities != "true") {
2613 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2615 foreach ($images[1] as $image) {
2616 $replace = ProxyUtils::proxifyUrl($image);
2617 $text = str_replace($image, $replace, $text);
2622 $bbcode = BBCode::cleanPictureLinks($bbcode);
2624 // Change pure links in text to bbcode uris
2625 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2628 $entities["hashtags"] = [];
2629 $entities["symbols"] = [];
2630 $entities["urls"] = [];
2631 $entities["user_mentions"] = [];
2633 $URLSearchString = "^\[\]";
2635 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2637 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2638 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2639 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2641 $bbcode = preg_replace(
2642 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2643 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2646 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2648 $bbcode = preg_replace(
2649 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2650 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2653 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2655 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2657 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2658 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2661 foreach ($urls[1] as $id => $url) {
2662 //$start = strpos($text, $url, $offset);
2663 $start = iconv_strpos($text, $url, 0, "UTF-8");
2664 if (!($start === false)) {
2665 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2669 ksort($ordered_urls);
2672 //foreach ($urls[1] AS $id=>$url) {
2673 foreach ($ordered_urls as $url) {
2674 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2675 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2677 $display_url = $url["title"];
2679 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2680 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2682 if (strlen($display_url) > 26) {
2683 $display_url = substr($display_url, 0, 25)."…";
2687 //$start = strpos($text, $url, $offset);
2688 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2689 if (!($start === false)) {
2690 $entities["urls"][] = ["url" => $url["url"],
2691 "expanded_url" => $url["url"],
2692 "display_url" => $display_url,
2693 "indices" => [$start, $start+strlen($url["url"])]];
2694 $offset = $start + 1;
2698 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2699 $ordered_images = [];
2700 foreach ($images as $image) {
2701 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2702 if (!($start === false)) {
2703 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2707 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2708 foreach ($images[1] as $image) {
2709 $start = iconv_strpos($text, $image, 0, "UTF-8");
2710 if (!($start === false)) {
2711 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2714 //$entities["media"] = array();
2717 foreach ($ordered_images as $image) {
2718 $url = $image['url'];
2719 $ext_alt_text = $image['alt'];
2721 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2722 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2724 if (strlen($display_url) > 26) {
2725 $display_url = substr($display_url, 0, 25)."…";
2728 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2729 if (!($start === false)) {
2730 $image = Image::getInfoFromURL($url);
2732 // If image cache is activated, then use the following sizes:
2733 // thumb (150), small (340), medium (600) and large (1024)
2734 if (!Config::get("system", "proxy_disabled")) {
2735 $media_url = ProxyUtils::proxifyUrl($url);
2738 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2739 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2741 if (($image[0] > 150) || ($image[1] > 150)) {
2742 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2743 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2746 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2747 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2749 if (($image[0] > 600) || ($image[1] > 600)) {
2750 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2751 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2755 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2758 $entities["media"][] = [
2760 "id_str" => (string) ($start + 1),
2761 "indices" => [$start, $start+strlen($url)],
2762 "media_url" => Strings::normaliseLink($media_url),
2763 "media_url_https" => $media_url,
2765 "display_url" => $display_url,
2766 "expanded_url" => $url,
2767 "ext_alt_text" => $ext_alt_text,
2771 $offset = $start + 1;
2780 * @param array $item
2781 * @param string $text
2785 function api_format_items_embeded_images($item, $text)
2787 $text = preg_replace_callback(
2788 '|data:image/([^;]+)[^=]+=*|m',
2789 function () use ($item) {
2790 return System::baseUrl() . '/display/' . $item['guid'];
2798 * @brief return <a href='url'>name</a> as array
2800 * @param string $txt text
2805 function api_contactlink_to_array($txt)
2808 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2809 if ($r && count($match)==3) {
2811 'name' => $match[2],
2825 * @brief return likes, dislikes and attend status for item
2827 * @param array $item array
2828 * @param string $type Return type (atom, rss, xml, json)
2831 * likes => int count,
2832 * dislikes => int count
2833 * @throws BadRequestException
2834 * @throws ImagickException
2835 * @throws InternalServerErrorException
2836 * @throws UnauthorizedException
2838 function api_format_items_activities($item, $type = "json")
2847 'attendmaybe' => [],
2850 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2851 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2853 while ($parent_item = Item::fetch($ret)) {
2854 // not used as result should be structured like other user data
2855 //builtin_activity_puller($i, $activities);
2857 // get user data and add it to the array of the activity
2858 $user = api_get_user($a, $parent_item['author-id']);
2859 switch ($parent_item['verb']) {
2861 $activities['like'][] = $user;
2863 case ACTIVITY_DISLIKE:
2864 $activities['dislike'][] = $user;
2866 case ACTIVITY_ATTEND:
2867 $activities['attendyes'][] = $user;
2869 case ACTIVITY_ATTENDNO:
2870 $activities['attendno'][] = $user;
2872 case ACTIVITY_ATTENDMAYBE:
2873 $activities['attendmaybe'][] = $user;
2882 if ($type == "xml") {
2883 $xml_activities = [];
2884 foreach ($activities as $k => $v) {
2885 // change xml element from "like" to "friendica:like"
2886 $xml_activities["friendica:".$k] = $v;
2887 // add user data into xml output
2889 foreach ($v as $user) {
2890 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2893 $activities = $xml_activities;
2901 * @brief return data from profiles
2903 * @param array $profile_row array containing data from db table 'profile'
2905 * @throws InternalServerErrorException
2907 function api_format_items_profiles($profile_row)
2910 'profile_id' => $profile_row['id'],
2911 'profile_name' => $profile_row['profile-name'],
2912 'is_default' => $profile_row['is-default'] ? true : false,
2913 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2914 'profile_photo' => $profile_row['photo'],
2915 'profile_thumb' => $profile_row['thumb'],
2916 'publish' => $profile_row['publish'] ? true : false,
2917 'net_publish' => $profile_row['net-publish'] ? true : false,
2918 'description' => $profile_row['pdesc'],
2919 'date_of_birth' => $profile_row['dob'],
2920 'address' => $profile_row['address'],
2921 'city' => $profile_row['locality'],
2922 'region' => $profile_row['region'],
2923 'postal_code' => $profile_row['postal-code'],
2924 'country' => $profile_row['country-name'],
2925 'hometown' => $profile_row['hometown'],
2926 'gender' => $profile_row['gender'],
2927 'marital' => $profile_row['marital'],
2928 'marital_with' => $profile_row['with'],
2929 'marital_since' => $profile_row['howlong'],
2930 'sexual' => $profile_row['sexual'],
2931 'politic' => $profile_row['politic'],
2932 'religion' => $profile_row['religion'],
2933 'public_keywords' => $profile_row['pub_keywords'],
2934 'private_keywords' => $profile_row['prv_keywords'],
2935 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2936 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2937 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2938 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2939 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2940 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2941 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2942 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2943 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2944 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2945 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2946 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2947 'homepage' => $profile_row['homepage'],
2954 * @brief format items to be returned by api
2956 * @param array $items array of items
2957 * @param array $user_info
2958 * @param bool $filter_user filter items by $user_info
2959 * @param string $type Return type (atom, rss, xml, json)
2961 * @throws BadRequestException
2962 * @throws ImagickException
2963 * @throws InternalServerErrorException
2964 * @throws UnauthorizedException
2966 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2968 $a = \Friendica\BaseObject::getApp();
2972 foreach ((array)$items as $item) {
2973 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2975 // Look if the posts are matching if they should be filtered by user id
2976 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2980 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2989 * @param array $item Item record
2990 * @param string $type Return format (atom, rss, xml, json)
2991 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2992 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2993 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2994 * @return array API-formatted status
2995 * @throws BadRequestException
2996 * @throws ImagickException
2997 * @throws InternalServerErrorException
2998 * @throws UnauthorizedException
3000 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3002 $a = \Friendica\BaseObject::getApp();
3004 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3005 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3008 localize_item($item);
3010 $in_reply_to = api_in_reply_to($item);
3012 $converted = api_convert_item($item);
3014 if ($type == "xml") {
3015 $geo = "georss:point";
3021 'text' => $converted["text"],
3022 'truncated' => false,
3023 'created_at'=> api_date($item['created']),
3024 'in_reply_to_status_id' => $in_reply_to['status_id'],
3025 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3026 'source' => (($item['app']) ? $item['app'] : 'web'),
3027 'id' => intval($item['id']),
3028 'id_str' => (string) intval($item['id']),
3029 'in_reply_to_user_id' => $in_reply_to['user_id'],
3030 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3031 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3033 'favorited' => $item['starred'] ? true : false,
3034 'user' => $status_user,
3035 'friendica_author' => $author_user,
3036 'friendica_owner' => $owner_user,
3037 'friendica_private' => $item['private'] == 1,
3038 //'entities' => NULL,
3039 'statusnet_html' => $converted["html"],
3040 'statusnet_conversation_id' => $item['parent'],
3041 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3042 'friendica_activities' => api_format_items_activities($item, $type),
3043 'friendica_title' => $item['title'],
3044 'friendica_html' => BBCode::convert($item['body'], false)
3047 if (count($converted["attachments"]) > 0) {
3048 $status["attachments"] = $converted["attachments"];
3051 if (count($converted["entities"]) > 0) {
3052 $status["entities"] = $converted["entities"];
3055 if ($status["source"] == 'web') {
3056 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3057 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3058 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3061 $retweeted_item = [];
3064 if ($item["id"] == $item["parent"]) {
3065 $body = $item['body'];
3066 $retweeted_item = api_share_as_retweet($item);
3067 if ($body != $item['body']) {
3068 $quoted_item = $retweeted_item;
3069 $retweeted_item = [];
3073 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3074 $announce = api_get_announce($item);
3075 if (!empty($announce)) {
3076 $retweeted_item = $item;
3078 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3082 if (!empty($quoted_item)) {
3083 $conv_quoted = api_convert_item($quoted_item);
3084 $quoted_status = $status;
3085 unset($quoted_status['friendica_author']);
3086 unset($quoted_status['friendica_owner']);
3087 unset($quoted_status['friendica_activities']);
3088 unset($quoted_status['friendica_private']);
3089 unset($quoted_status['statusnet_conversation_id']);
3090 $quoted_status['text'] = $conv_quoted['text'];
3091 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3093 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3094 } catch (BadRequestException $e) {
3095 // user not found. should be found?
3096 /// @todo check if the user should be always found
3097 $quoted_status["user"] = [];
3101 if (!empty($retweeted_item)) {
3102 $retweeted_status = $status;
3103 unset($retweeted_status['friendica_author']);
3104 unset($retweeted_status['friendica_owner']);
3105 unset($retweeted_status['friendica_activities']);
3106 unset($retweeted_status['friendica_private']);
3107 unset($retweeted_status['statusnet_conversation_id']);
3108 $status['user'] = $status['friendica_owner'];
3110 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3111 } catch (BadRequestException $e) {
3112 // user not found. should be found?
3113 /// @todo check if the user should be always found
3114 $retweeted_status["user"] = [];
3117 $rt_converted = api_convert_item($retweeted_item);
3119 $retweeted_status['text'] = $rt_converted["text"];
3120 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3121 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3123 if (!empty($quoted_status)) {
3124 $retweeted_status['quoted_status'] = $quoted_status;
3127 $status['friendica_author'] = $retweeted_status['user'];
3128 $status['retweeted_status'] = $retweeted_status;
3129 } elseif (!empty($quoted_status)) {
3130 $root_status = api_convert_item($item);
3132 $status['text'] = $root_status["text"];
3133 $status['statusnet_html'] = $root_status["html"];
3134 $status['quoted_status'] = $quoted_status;
3137 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3138 unset($status["user"]["uid"]);
3139 unset($status["user"]["self"]);
3141 if ($item["coord"] != "") {
3142 $coords = explode(' ', $item["coord"]);
3143 if (count($coords) == 2) {
3144 if ($type == "json") {
3145 $status["geo"] = ['type' => 'Point',
3146 'coordinates' => [(float) $coords[0],
3147 (float) $coords[1]]];
3148 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3149 $status["georss:point"] = $item["coord"];
3158 * Returns the remaining number of API requests available to the user before the API limit is reached.
3160 * @param string $type Return type (atom, rss, xml, json)
3162 * @return array|string
3165 function api_account_rate_limit_status($type)
3167 if ($type == "xml") {
3169 'remaining-hits' => '150',
3170 '@attributes' => ["type" => "integer"],
3171 'hourly-limit' => '150',
3172 '@attributes2' => ["type" => "integer"],
3173 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3174 '@attributes3' => ["type" => "datetime"],
3175 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3176 '@attributes4' => ["type" => "integer"],
3180 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3181 'remaining_hits' => '150',
3182 'hourly_limit' => '150',
3183 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3187 return api_format_data('hash', $type, ['hash' => $hash]);
3190 /// @TODO move to top of file or somewhere better
3191 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3194 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3196 * @param string $type Return type (atom, rss, xml, json)
3198 * @return array|string
3200 function api_help_test($type)
3202 if ($type == 'xml') {
3208 return api_format_data('ok', $type, ["ok" => $ok]);
3211 /// @TODO move to top of file or somewhere better
3212 api_register_func('api/help/test', 'api_help_test', false);
3215 * Returns all lists the user subscribes to.
3217 * @param string $type Return type (atom, rss, xml, json)
3219 * @return array|string
3220 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3222 function api_lists_list($type)
3225 /// @TODO $ret is not filled here?
3226 return api_format_data('lists', $type, ["lists_list" => $ret]);
3229 /// @TODO move to top of file or somewhere better
3230 api_register_func('api/lists/list', 'api_lists_list', true);
3231 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3234 * Returns all groups the user owns.
3236 * @param string $type Return type (atom, rss, xml, json)
3238 * @return array|string
3239 * @throws BadRequestException
3240 * @throws ForbiddenException
3241 * @throws ImagickException
3242 * @throws InternalServerErrorException
3243 * @throws UnauthorizedException
3244 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3246 function api_lists_ownerships($type)
3250 if (api_user() === false) {
3251 throw new ForbiddenException();
3255 $user_info = api_get_user($a);
3256 $uid = $user_info['uid'];
3258 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3260 // loop through all groups
3262 foreach ($groups as $group) {
3263 if ($group['visible']) {
3269 'name' => $group['name'],
3270 'id' => intval($group['id']),
3271 'id_str' => (string) $group['id'],
3272 'user' => $user_info,
3276 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3279 /// @TODO move to top of file or somewhere better
3280 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3283 * Returns recent statuses from users in the specified group.
3285 * @param string $type Return type (atom, rss, xml, json)
3287 * @return array|string
3288 * @throws BadRequestException
3289 * @throws ForbiddenException
3290 * @throws ImagickException
3291 * @throws InternalServerErrorException
3292 * @throws UnauthorizedException
3293 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3295 function api_lists_statuses($type)
3299 $user_info = api_get_user($a);
3300 if (api_user() === false || $user_info === false) {
3301 throw new ForbiddenException();
3304 unset($_REQUEST["user_id"]);
3305 unset($_GET["user_id"]);
3307 unset($_REQUEST["screen_name"]);
3308 unset($_GET["screen_name"]);
3310 if (empty($_REQUEST['list_id'])) {
3311 throw new BadRequestException('list_id not specified');
3315 $count = defaults($_REQUEST, 'count', 20);
3316 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3320 $since_id = defaults($_REQUEST, 'since_id', 0);
3321 $max_id = defaults($_REQUEST, 'max_id', 0);
3322 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3323 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3325 $start = $page * $count;
3327 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3328 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3331 $condition[0] .= " AND `item`.`id` <= ?";
3332 $condition[] = $max_id;
3334 if ($exclude_replies > 0) {
3335 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3337 if ($conversation_id > 0) {
3338 $condition[0] .= " AND `item`.`parent` = ?";
3339 $condition[] = $conversation_id;
3342 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3343 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3345 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3347 $data = ['status' => $items];
3352 $data = api_rss_extra($a, $data, $user_info);
3356 return api_format_data("statuses", $type, $data);
3359 /// @TODO move to top of file or somewhere better
3360 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3363 * Considers friends and followers lists to be private and won't return
3364 * anything if any user_id parameter is passed.
3366 * @brief Returns either the friends of the follower list
3368 * @param string $qtype Either "friends" or "followers"
3369 * @return boolean|array
3370 * @throws BadRequestException
3371 * @throws ForbiddenException
3372 * @throws ImagickException
3373 * @throws InternalServerErrorException
3374 * @throws UnauthorizedException
3376 function api_statuses_f($qtype)
3380 if (api_user() === false) {
3381 throw new ForbiddenException();
3385 $count = defaults($_GET, 'count', 20);
3386 $page = defaults($_GET, 'page', 1);
3390 $start = ($page - 1) * $count;
3392 $user_info = api_get_user($a);
3394 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3395 /* this is to stop Hotot to load friends multiple times
3396 * I'm not sure if I'm missing return something or
3397 * is a bug in hotot. Workaround, meantime
3401 return array('$users' => $ret);*/
3406 if ($qtype == 'friends') {
3407 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3408 } elseif ($qtype == 'followers') {
3409 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3412 // friends and followers only for self
3413 if ($user_info['self'] == 0) {
3414 $sql_extra = " AND false ";
3417 if ($qtype == 'blocks') {
3418 $sql_filter = 'AND `blocked` AND NOT `pending`';
3419 } elseif ($qtype == 'incoming') {
3420 $sql_filter = 'AND `pending`';
3422 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3440 foreach ($r as $cid) {
3441 $user = api_get_user($a, $cid['nurl']);
3442 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3443 unset($user["uid"]);
3444 unset($user["self"]);
3451 return ['user' => $ret];
3456 * Returns the user's friends.
3458 * @brief Returns the list of friends of the provided user
3460 * @deprecated By Twitter API in favor of friends/list
3462 * @param string $type Either "json" or "xml"
3463 * @return boolean|string|array
3464 * @throws BadRequestException
3465 * @throws ForbiddenException
3467 function api_statuses_friends($type)
3469 $data = api_statuses_f("friends");
3470 if ($data === false) {
3473 return api_format_data("users", $type, $data);
3477 * Returns the user's followers.
3479 * @brief Returns the list of followers of the provided user
3481 * @deprecated By Twitter API in favor of friends/list
3483 * @param string $type Either "json" or "xml"
3484 * @return boolean|string|array
3485 * @throws BadRequestException
3486 * @throws ForbiddenException
3488 function api_statuses_followers($type)
3490 $data = api_statuses_f("followers");
3491 if ($data === false) {
3494 return api_format_data("users", $type, $data);
3497 /// @TODO move to top of file or somewhere better
3498 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3499 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3502 * Returns the list of blocked users
3504 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3506 * @param string $type Either "json" or "xml"
3508 * @return boolean|string|array
3509 * @throws BadRequestException
3510 * @throws ForbiddenException
3512 function api_blocks_list($type)
3514 $data = api_statuses_f('blocks');
3515 if ($data === false) {
3518 return api_format_data("users", $type, $data);
3521 /// @TODO move to top of file or somewhere better
3522 api_register_func('api/blocks/list', 'api_blocks_list', true);
3525 * Returns the list of pending users IDs
3527 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3529 * @param string $type Either "json" or "xml"
3531 * @return boolean|string|array
3532 * @throws BadRequestException
3533 * @throws ForbiddenException
3535 function api_friendships_incoming($type)
3537 $data = api_statuses_f('incoming');
3538 if ($data === false) {
3543 foreach ($data['user'] as $user) {
3544 $ids[] = $user['id'];
3547 return api_format_data("ids", $type, ['id' => $ids]);
3550 /// @TODO move to top of file or somewhere better
3551 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3554 * Returns the instance's configuration information.
3556 * @param string $type Return type (atom, rss, xml, json)
3558 * @return array|string
3559 * @throws InternalServerErrorException
3561 function api_statusnet_config($type)
3565 $name = Config::get('config', 'sitename');
3566 $server = $a->getHostName();
3567 $logo = System::baseUrl() . '/images/friendica-64.png';
3568 $email = Config::get('config', 'admin_email');
3569 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3570 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3571 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3572 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3573 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3576 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3577 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3578 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3579 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3580 'shorturllength' => '30',
3582 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3583 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3584 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3585 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3590 return api_format_data('config', $type, ['config' => $config]);
3593 /// @TODO move to top of file or somewhere better
3594 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3595 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3599 * @param string $type Return type (atom, rss, xml, json)
3601 * @return array|string
3603 function api_statusnet_version($type)
3606 $fake_statusnet_version = "0.9.7";
3608 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3611 /// @TODO move to top of file or somewhere better
3612 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3613 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3617 * @param string $type Return type (atom, rss, xml, json)
3619 * @return array|string|void
3620 * @throws BadRequestException
3621 * @throws ForbiddenException
3622 * @throws ImagickException
3623 * @throws InternalServerErrorException
3624 * @throws UnauthorizedException
3625 * @todo use api_format_data() to return data
3627 function api_ff_ids($type)
3630 throw new ForbiddenException();
3637 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3640 "SELECT `pcontact`.`id` FROM `contact`
3641 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3642 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3645 if (!DBA::isResult($r)) {
3650 foreach ($r as $rr) {
3651 if ($stringify_ids) {
3654 $ids[] = intval($rr['id']);
3658 return api_format_data("ids", $type, ['id' => $ids]);
3662 * Returns the ID of every user the user is following.
3664 * @param string $type Return type (atom, rss, xml, json)
3666 * @return array|string
3667 * @throws BadRequestException
3668 * @throws ForbiddenException
3669 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3671 function api_friends_ids($type)
3673 return api_ff_ids($type);
3677 * Returns the ID of every user following the user.
3679 * @param string $type Return type (atom, rss, xml, json)
3681 * @return array|string
3682 * @throws BadRequestException
3683 * @throws ForbiddenException
3684 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3686 function api_followers_ids($type)
3688 return api_ff_ids($type);
3691 /// @TODO move to top of file or somewhere better
3692 api_register_func('api/friends/ids', 'api_friends_ids', true);
3693 api_register_func('api/followers/ids', 'api_followers_ids', true);
3696 * Sends a new direct message.
3698 * @param string $type Return type (atom, rss, xml, json)
3700 * @return array|string
3701 * @throws BadRequestException
3702 * @throws ForbiddenException
3703 * @throws ImagickException
3704 * @throws InternalServerErrorException
3705 * @throws NotFoundException
3706 * @throws UnauthorizedException
3707 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3709 function api_direct_messages_new($type)
3713 if (api_user() === false) {
3714 throw new ForbiddenException();
3717 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3721 $sender = api_get_user($a);
3724 if (!empty($_POST['screen_name'])) {
3726 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3728 DBA::escape($_POST['screen_name'])
3731 if (DBA::isResult($r)) {
3732 // Selecting the id by priority, friendica first
3733 api_best_nickname($r);
3735 $recipient = api_get_user($a, $r[0]['nurl']);
3738 $recipient = api_get_user($a, $_POST['user_id']);
3741 if (empty($recipient)) {
3742 throw new NotFoundException('Recipient not found');
3746 if (!empty($_REQUEST['replyto'])) {
3748 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3750 intval($_REQUEST['replyto'])
3752 $replyto = $r[0]['parent-uri'];
3753 $sub = $r[0]['title'];
3755 if (!empty($_REQUEST['title'])) {
3756 $sub = $_REQUEST['title'];
3758 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3762 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3765 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3766 $ret = api_format_messages($r[0], $recipient, $sender);
3768 $ret = ["error"=>$id];
3771 $data = ['direct_message'=>$ret];
3777 $data = api_rss_extra($a, $data, $sender);
3781 return api_format_data("direct-messages", $type, $data);
3784 /// @TODO move to top of file or somewhere better
3785 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3788 * Destroys a direct message.
3790 * @brief delete a direct_message from mail table through api
3792 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3793 * @return string|array
3794 * @throws BadRequestException
3795 * @throws ForbiddenException
3796 * @throws ImagickException
3797 * @throws InternalServerErrorException
3798 * @throws UnauthorizedException
3799 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3801 function api_direct_messages_destroy($type)
3805 if (api_user() === false) {
3806 throw new ForbiddenException();
3810 $user_info = api_get_user($a);
3812 $id = defaults($_REQUEST, 'id', 0);
3814 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3815 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3816 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3818 $uid = $user_info['uid'];
3819 // error if no id or parenturi specified (for clients posting parent-uri as well)
3820 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3821 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3822 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3825 // BadRequestException if no id specified (for clients using Twitter API)
3827 throw new BadRequestException('Message id not specified');
3830 // add parent-uri to sql command if specified by calling app
3831 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3833 // get data of the specified message id
3835 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3840 // error message if specified id is not in database
3841 if (!DBA::isResult($r)) {
3842 if ($verbose == "true") {
3843 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3844 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3846 /// @todo BadRequestException ok for Twitter API clients?
3847 throw new BadRequestException('message id not in database');
3852 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3857 if ($verbose == "true") {
3860 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3861 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3863 $answer = ['result' => 'error', 'message' => 'unknown error'];
3864 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3867 /// @todo return JSON data like Twitter API not yet implemented
3870 /// @TODO move to top of file or somewhere better
3871 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3876 * @brief unfollow contact
3878 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3879 * @return string|array
3880 * @throws BadRequestException
3881 * @throws ForbiddenException
3882 * @throws ImagickException
3883 * @throws InternalServerErrorException
3884 * @throws NotFoundException
3885 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3887 function api_friendships_destroy($type)
3891 if ($uid === false) {
3892 throw new ForbiddenException();
3895 $contact_id = defaults($_REQUEST, 'user_id');
3897 if (empty($contact_id)) {
3898 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3899 throw new BadRequestException("no user_id specified");
3902 // Get Contact by given id
3903 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3905 if(!DBA::isResult($contact)) {
3906 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3907 throw new NotFoundException("no contact found to given ID");
3910 $url = $contact["url"];
3912 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3913 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3914 Strings::normaliseLink($url), $url];
3915 $contact = DBA::selectFirst('contact', [], $condition);
3917 if (!DBA::isResult($contact)) {
3918 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3919 throw new NotFoundException("Not following Contact");
3922 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3923 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3924 throw new ExpectationFailedException("Not supported");
3927 $dissolve = ($contact['rel'] == Contact::SHARING);
3929 $owner = User::getOwnerDataById($uid);
3931 Contact::terminateFriendship($owner, $contact, $dissolve);
3934 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3935 throw new NotFoundException("Error Processing Request");
3938 // Sharing-only contacts get deleted as there no relationship any more
3940 Contact::remove($contact['id']);
3942 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3945 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3946 unset($contact["uid"]);
3947 unset($contact["self"]);
3949 // Set screen_name since Twidere requests it
3950 $contact["screen_name"] = $contact["nick"];
3952 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3954 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3958 * @param string $type Return type (atom, rss, xml, json)
3959 * @param string $box
3960 * @param string $verbose
3962 * @return array|string
3963 * @throws BadRequestException
3964 * @throws ForbiddenException
3965 * @throws ImagickException
3966 * @throws InternalServerErrorException
3967 * @throws UnauthorizedException
3969 function api_direct_messages_box($type, $box, $verbose)
3972 if (api_user() === false) {
3973 throw new ForbiddenException();
3976 $count = defaults($_GET, 'count', 20);
3977 $page = defaults($_REQUEST, 'page', 1) - 1;
3982 $since_id = defaults($_REQUEST, 'since_id', 0);
3983 $max_id = defaults($_REQUEST, 'max_id', 0);
3985 $user_id = defaults($_REQUEST, 'user_id', '');
3986 $screen_name = defaults($_REQUEST, 'screen_name', '');
3989 unset($_REQUEST["user_id"]);
3990 unset($_GET["user_id"]);
3992 unset($_REQUEST["screen_name"]);
3993 unset($_GET["screen_name"]);
3995 $user_info = api_get_user($a);
3996 if ($user_info === false) {
3997 throw new ForbiddenException();
3999 $profile_url = $user_info["url"];
4002 $start = $page * $count;
4007 if ($box=="sentbox") {
4008 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
4009 } elseif ($box == "conversation") {
4010 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
4011 } elseif ($box == "all") {
4012 $sql_extra = "true";
4013 } elseif ($box == "inbox") {
4014 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4018 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4021 if ($user_id != "") {
4022 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4023 } elseif ($screen_name !="") {
4024 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4028 "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",
4034 if ($verbose == "true" && !DBA::isResult($r)) {
4035 $answer = ['result' => 'error', 'message' => 'no mails available'];
4036 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4040 foreach ($r as $item) {
4041 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4042 $recipient = $user_info;
4043 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4044 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4045 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4046 $sender = $user_info;
4049 if (isset($recipient) && isset($sender)) {
4050 $ret[] = api_format_messages($item, $recipient, $sender);
4055 $data = ['direct_message' => $ret];
4060 $data = api_rss_extra($a, $data, $user_info);
4064 return api_format_data("direct-messages", $type, $data);
4068 * Returns the most recent direct messages sent by the user.
4070 * @param string $type Return type (atom, rss, xml, json)
4072 * @return array|string
4073 * @throws BadRequestException
4074 * @throws ForbiddenException
4075 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4077 function api_direct_messages_sentbox($type)
4079 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4080 return api_direct_messages_box($type, "sentbox", $verbose);
4084 * Returns the most recent direct messages sent to the user.
4086 * @param string $type Return type (atom, rss, xml, json)
4088 * @return array|string
4089 * @throws BadRequestException
4090 * @throws ForbiddenException
4091 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4093 function api_direct_messages_inbox($type)
4095 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4096 return api_direct_messages_box($type, "inbox", $verbose);
4101 * @param string $type Return type (atom, rss, xml, json)
4103 * @return array|string
4104 * @throws BadRequestException
4105 * @throws ForbiddenException
4107 function api_direct_messages_all($type)
4109 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4110 return api_direct_messages_box($type, "all", $verbose);
4115 * @param string $type Return type (atom, rss, xml, json)
4117 * @return array|string
4118 * @throws BadRequestException
4119 * @throws ForbiddenException
4121 function api_direct_messages_conversation($type)
4123 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4124 return api_direct_messages_box($type, "conversation", $verbose);
4127 /// @TODO move to top of file or somewhere better
4128 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4129 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4130 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4131 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4134 * Returns an OAuth Request Token.
4136 * @see https://oauth.net/core/1.0/#auth_step1
4138 function api_oauth_request_token()
4140 $oauth1 = new FKOAuth1();
4142 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4143 } catch (Exception $e) {
4144 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4152 * Returns an OAuth Access Token.
4154 * @return array|string
4155 * @see https://oauth.net/core/1.0/#auth_step3
4157 function api_oauth_access_token()
4159 $oauth1 = new FKOAuth1();
4161 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4162 } catch (Exception $e) {
4163 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4170 /// @TODO move to top of file or somewhere better
4171 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4172 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4176 * @brief delete a complete photoalbum with all containing photos from database through api
4178 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4179 * @return string|array
4180 * @throws BadRequestException
4181 * @throws ForbiddenException
4182 * @throws InternalServerErrorException
4184 function api_fr_photoalbum_delete($type)
4186 if (api_user() === false) {
4187 throw new ForbiddenException();
4190 $album = defaults($_REQUEST, 'album', "");
4192 // we do not allow calls without album string
4194 throw new BadRequestException("no albumname specified");
4196 // check if album is existing
4198 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4202 if (!DBA::isResult($r)) {
4203 throw new BadRequestException("album not available");
4206 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4207 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4208 foreach ($r as $rr) {
4209 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4210 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4212 if (!DBA::isResult($photo_item)) {
4213 throw new InternalServerErrorException("problem with deleting items occured");
4215 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4218 // now let's delete all photos from the album
4219 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4221 // return success of deletion or error message
4223 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4224 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4226 throw new InternalServerErrorException("unknown error - deleting from database failed");
4231 * @brief update the name of the album for all photos of an album
4233 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4234 * @return string|array
4235 * @throws BadRequestException
4236 * @throws ForbiddenException
4237 * @throws InternalServerErrorException
4239 function api_fr_photoalbum_update($type)
4241 if (api_user() === false) {
4242 throw new ForbiddenException();
4245 $album = defaults($_REQUEST, 'album', "");
4246 $album_new = defaults($_REQUEST, 'album_new', "");
4248 // we do not allow calls without album string
4250 throw new BadRequestException("no albumname specified");
4252 if ($album_new == "") {
4253 throw new BadRequestException("no new albumname specified");
4255 // check if album is existing
4256 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4257 throw new BadRequestException("album not available");
4259 // now let's update all photos to the albumname
4260 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4262 // return success of updating or error message
4264 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4265 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4267 throw new InternalServerErrorException("unknown error - updating in database failed");
4273 * @brief list all photos of the authenticated user
4275 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4276 * @return string|array
4277 * @throws ForbiddenException
4278 * @throws InternalServerErrorException
4280 function api_fr_photos_list($type)
4282 if (api_user() === false) {
4283 throw new ForbiddenException();
4286 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4287 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4288 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4289 intval(local_user())
4292 'image/jpeg' => 'jpg',
4293 'image/png' => 'png',
4294 'image/gif' => 'gif'
4296 $data = ['photo'=>[]];
4297 if (DBA::isResult($r)) {
4298 foreach ($r as $rr) {
4300 $photo['id'] = $rr['resource-id'];
4301 $photo['album'] = $rr['album'];
4302 $photo['filename'] = $rr['filename'];
4303 $photo['type'] = $rr['type'];
4304 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4305 $photo['created'] = $rr['created'];
4306 $photo['edited'] = $rr['edited'];
4307 $photo['desc'] = $rr['desc'];
4309 if ($type == "xml") {
4310 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4312 $photo['thumb'] = $thumb;
4313 $data['photo'][] = $photo;
4317 return api_format_data("photos", $type, $data);
4321 * @brief upload a new photo or change an existing photo
4323 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4324 * @return string|array
4325 * @throws BadRequestException
4326 * @throws ForbiddenException
4327 * @throws ImagickException
4328 * @throws InternalServerErrorException
4329 * @throws NotFoundException
4331 function api_fr_photo_create_update($type)
4333 if (api_user() === false) {
4334 throw new ForbiddenException();
4337 $photo_id = defaults($_REQUEST, 'photo_id', null);
4338 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4339 $album = defaults($_REQUEST, 'album', null);
4340 $album_new = defaults($_REQUEST, 'album_new', null);
4341 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4342 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4343 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4344 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4345 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4347 // do several checks on input parameters
4348 // we do not allow calls without album string
4349 if ($album == null) {
4350 throw new BadRequestException("no albumname specified");
4352 // if photo_id == null --> we are uploading a new photo
4353 if ($photo_id == null) {
4356 // error if no media posted in create-mode
4357 if (empty($_FILES['media'])) {
4359 throw new BadRequestException("no media data submitted");
4362 // album_new will be ignored in create-mode
4367 // check if photo is existing in databasei
4368 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4369 throw new BadRequestException("photo not available");
4373 // checks on acl strings provided by clients
4374 $acl_input_error = false;
4375 $acl_input_error |= check_acl_input($allow_cid);
4376 $acl_input_error |= check_acl_input($deny_cid);
4377 $acl_input_error |= check_acl_input($allow_gid);
4378 $acl_input_error |= check_acl_input($deny_gid);
4379 if ($acl_input_error) {
4380 throw new BadRequestException("acl data invalid");
4382 // now let's upload the new media in create-mode
4383 if ($mode == "create") {
4384 $media = $_FILES['media'];
4385 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4387 // return success of updating or error message
4388 if (!is_null($data)) {
4389 return api_format_data("photo_create", $type, $data);
4391 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4395 // now let's do the changes in update-mode
4396 if ($mode == "update") {
4397 $updated_fields = [];
4399 if (!is_null($desc)) {
4400 $updated_fields['desc'] = $desc;
4403 if (!is_null($album_new)) {
4404 $updated_fields['album'] = $album_new;
4407 if (!is_null($allow_cid)) {
4408 $allow_cid = trim($allow_cid);
4409 $updated_fields['allow_cid'] = $allow_cid;
4412 if (!is_null($deny_cid)) {
4413 $deny_cid = trim($deny_cid);
4414 $updated_fields['deny_cid'] = $deny_cid;
4417 if (!is_null($allow_gid)) {
4418 $allow_gid = trim($allow_gid);
4419 $updated_fields['allow_gid'] = $allow_gid;
4422 if (!is_null($deny_gid)) {
4423 $deny_gid = trim($deny_gid);
4424 $updated_fields['deny_gid'] = $deny_gid;
4428 if (count($updated_fields) > 0) {
4429 $nothingtodo = false;
4430 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4432 $nothingtodo = true;
4435 if (!empty($_FILES['media'])) {
4436 $nothingtodo = false;
4437 $media = $_FILES['media'];
4438 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4439 if (!is_null($data)) {
4440 return api_format_data("photo_update", $type, $data);
4444 // return success of updating or error message
4446 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4447 return api_format_data("photo_update", $type, ['$result' => $answer]);
4450 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4451 return api_format_data("photo_update", $type, ['$result' => $answer]);
4453 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4456 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4460 * @brief delete a single photo from the database through api
4462 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4463 * @return string|array
4464 * @throws BadRequestException
4465 * @throws ForbiddenException
4466 * @throws InternalServerErrorException
4468 function api_fr_photo_delete($type)
4470 if (api_user() === false) {
4471 throw new ForbiddenException();
4475 $photo_id = defaults($_REQUEST, 'photo_id', null);
4477 // do several checks on input parameters
4478 // we do not allow calls without photo id
4479 if ($photo_id == null) {
4480 throw new BadRequestException("no photo_id specified");
4483 // check if photo is existing in database
4484 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4485 throw new BadRequestException("photo not available");
4488 // now we can perform on the deletion of the photo
4489 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4491 // return success of deletion or error message
4493 // retrieve the id of the parent element (the photo element)
4494 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4495 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4497 if (!DBA::isResult($photo_item)) {
4498 throw new InternalServerErrorException("problem with deleting items occured");
4500 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4501 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4502 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4504 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4505 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4507 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4513 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4515 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4516 * @return string|array
4517 * @throws BadRequestException
4518 * @throws ForbiddenException
4519 * @throws InternalServerErrorException
4520 * @throws NotFoundException
4522 function api_fr_photo_detail($type)
4524 if (api_user() === false) {
4525 throw new ForbiddenException();
4527 if (empty($_REQUEST['photo_id'])) {
4528 throw new BadRequestException("No photo id.");
4531 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4532 $photo_id = $_REQUEST['photo_id'];
4534 // prepare json/xml output with data from database for the requested photo
4535 $data = prepare_photo_data($type, $scale, $photo_id);
4537 return api_format_data("photo_detail", $type, $data);
4542 * Updates the user’s profile image.
4544 * @brief updates the profile image for the user (either a specified profile or the default profile)
4546 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4548 * @return string|array
4549 * @throws BadRequestException
4550 * @throws ForbiddenException
4551 * @throws ImagickException
4552 * @throws InternalServerErrorException
4553 * @throws NotFoundException
4554 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4556 function api_account_update_profile_image($type)
4558 if (api_user() === false) {
4559 throw new ForbiddenException();
4562 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4564 // error if image data is missing
4565 if (empty($_FILES['image'])) {
4566 throw new BadRequestException("no media data submitted");
4569 // check if specified profile id is valid
4570 if ($profile_id != 0) {
4571 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4572 // error message if specified profile id is not in database
4573 if (!DBA::isResult($profile)) {
4574 throw new BadRequestException("profile_id not available");
4576 $is_default_profile = $profile['is-default'];
4578 $is_default_profile = 1;
4581 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4583 if (!empty($_FILES['image'])) {
4584 $media = $_FILES['image'];
4585 } elseif (!empty($_FILES['media'])) {
4586 $media = $_FILES['media'];
4588 // save new profile image
4589 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4592 if (is_array($media['type'])) {
4593 $filetype = $media['type'][0];
4595 $filetype = $media['type'];
4597 if ($filetype == "image/jpeg") {
4599 } elseif ($filetype == "image/png") {
4602 throw new InternalServerErrorException('Unsupported filetype');
4605 // change specified profile or all profiles to the new resource-id
4606 if ($is_default_profile) {
4607 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4608 Photo::update(['profile' => false], $condition);
4610 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4611 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4612 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4615 Contact::updateSelfFromUserID(api_user(), true);
4617 // Update global directory in background
4618 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4619 if ($url && strlen(Config::get('system', 'directory'))) {
4620 Worker::add(PRIORITY_LOW, "Directory", $url);
4623 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4625 // output for client
4627 return api_account_verify_credentials($type);
4629 // SaveMediaToDatabase failed for some reason
4630 throw new InternalServerErrorException("image upload failed");
4634 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4635 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4636 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4637 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4638 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4639 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4640 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4641 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4642 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4645 * Update user profile
4647 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4649 * @return array|string
4650 * @throws BadRequestException
4651 * @throws ForbiddenException
4652 * @throws ImagickException
4653 * @throws InternalServerErrorException
4654 * @throws UnauthorizedException
4656 function api_account_update_profile($type)
4658 $local_user = api_user();
4659 $api_user = api_get_user(get_app());
4661 if (!empty($_POST['name'])) {
4662 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4663 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4664 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4665 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4668 if (isset($_POST['description'])) {
4669 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4670 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4671 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4674 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4675 // Update global directory in background
4676 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4677 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4680 return api_account_verify_credentials($type);
4683 /// @TODO move to top of file or somewhere better
4684 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4688 * @param string $acl_string
4692 function check_acl_input($acl_string)
4694 if ($acl_string == null || $acl_string == " ") {
4697 $contact_not_found = false;
4699 // split <x><y><z> into array of cid's
4700 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4702 // check for each cid if it is available on server
4703 $cid_array = $array[0];
4704 foreach ($cid_array as $cid) {
4705 $cid = str_replace("<", "", $cid);
4706 $cid = str_replace(">", "", $cid);
4707 $condition = ['id' => $cid, 'uid' => api_user()];
4708 $contact_not_found |= !DBA::exists('contact', $condition);
4710 return $contact_not_found;
4715 * @param string $mediatype
4716 * @param array $media
4717 * @param string $type
4718 * @param string $album
4719 * @param string $allow_cid
4720 * @param string $deny_cid
4721 * @param string $allow_gid
4722 * @param string $deny_gid
4723 * @param string $desc
4724 * @param integer $profile
4725 * @param boolean $visibility
4726 * @param string $photo_id
4728 * @throws BadRequestException
4729 * @throws ForbiddenException
4730 * @throws ImagickException
4731 * @throws InternalServerErrorException
4732 * @throws NotFoundException
4734 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)
4742 if (is_array($media)) {
4743 if (is_array($media['tmp_name'])) {
4744 $src = $media['tmp_name'][0];
4746 $src = $media['tmp_name'];
4748 if (is_array($media['name'])) {
4749 $filename = basename($media['name'][0]);
4751 $filename = basename($media['name']);
4753 if (is_array($media['size'])) {
4754 $filesize = intval($media['size'][0]);
4756 $filesize = intval($media['size']);
4758 if (is_array($media['type'])) {
4759 $filetype = $media['type'][0];
4761 $filetype = $media['type'];
4765 if ($filetype == "") {
4766 $filetype=Image::guessType($filename);
4768 $imagedata = @getimagesize($src);
4770 $filetype = $imagedata['mime'];
4773 "File upload src: " . $src . " - filename: " . $filename .
4774 " - size: " . $filesize . " - type: " . $filetype,
4778 // check if there was a php upload error
4779 if ($filesize == 0 && $media['error'] == 1) {
4780 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4782 // check against max upload size within Friendica instance
4783 $maximagesize = Config::get('system', 'maximagesize');
4784 if ($maximagesize && ($filesize > $maximagesize)) {
4785 $formattedBytes = Strings::formatBytes($maximagesize);
4786 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4789 // create Photo instance with the data of the image
4790 $imagedata = @file_get_contents($src);
4791 $Image = new Image($imagedata, $filetype);
4792 if (!$Image->isValid()) {
4793 throw new InternalServerErrorException("unable to process image data");
4796 // check orientation of image
4797 $Image->orient($src);
4800 // check max length of images on server
4801 $max_length = Config::get('system', 'max_image_length');
4803 $max_length = MAX_IMAGE_LENGTH;
4805 if ($max_length > 0) {
4806 $Image->scaleDown($max_length);
4807 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4809 $width = $Image->getWidth();
4810 $height = $Image->getHeight();
4812 // create a new resource-id if not already provided
4813 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4815 if ($mediatype == "photo") {
4816 // upload normal image (scales 0, 1, 2)
4817 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4819 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4821 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4823 if ($width > 640 || $height > 640) {
4824 $Image->scaleDown(640);
4825 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4827 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4831 if ($width > 320 || $height > 320) {
4832 $Image->scaleDown(320);
4833 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4835 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4838 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4839 } elseif ($mediatype == "profileimage") {
4840 // upload profile image (scales 4, 5, 6)
4841 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4843 if ($width > 300 || $height > 300) {
4844 $Image->scaleDown(300);
4845 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4847 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4851 if ($width > 80 || $height > 80) {
4852 $Image->scaleDown(80);
4853 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4855 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4859 if ($width > 48 || $height > 48) {
4860 $Image->scaleDown(48);
4861 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4863 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4866 $Image->__destruct();
4867 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4870 if (isset($r) && $r) {
4871 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4872 if ($photo_id == null && $mediatype == "photo") {
4873 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4875 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4876 return prepare_photo_data($type, false, $hash);
4878 throw new InternalServerErrorException("image upload failed");
4884 * @param string $hash
4885 * @param string $allow_cid
4886 * @param string $deny_cid
4887 * @param string $allow_gid
4888 * @param string $deny_gid
4889 * @param string $filetype
4890 * @param boolean $visibility
4891 * @throws InternalServerErrorException
4893 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4895 // get data about the api authenticated user
4896 $uri = Item::newURI(intval(api_user()));
4897 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4900 $arr['guid'] = System::createUUID();
4901 $arr['uid'] = intval(api_user());
4903 $arr['parent-uri'] = $uri;
4904 $arr['type'] = 'photo';
4906 $arr['resource-id'] = $hash;
4907 $arr['contact-id'] = $owner_record['id'];
4908 $arr['owner-name'] = $owner_record['name'];
4909 $arr['owner-link'] = $owner_record['url'];
4910 $arr['owner-avatar'] = $owner_record['thumb'];
4911 $arr['author-name'] = $owner_record['name'];
4912 $arr['author-link'] = $owner_record['url'];
4913 $arr['author-avatar'] = $owner_record['thumb'];
4915 $arr['allow_cid'] = $allow_cid;
4916 $arr['allow_gid'] = $allow_gid;
4917 $arr['deny_cid'] = $deny_cid;
4918 $arr['deny_gid'] = $deny_gid;
4919 $arr['visible'] = $visibility;
4923 'image/jpeg' => 'jpg',
4924 'image/png' => 'png',
4925 'image/gif' => 'gif'
4928 // adds link to the thumbnail scale photo
4929 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4930 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4933 // do the magic for storing the item in the database and trigger the federation to other contacts
4939 * @param string $type
4941 * @param string $photo_id
4944 * @throws BadRequestException
4945 * @throws ForbiddenException
4946 * @throws ImagickException
4947 * @throws InternalServerErrorException
4948 * @throws NotFoundException
4949 * @throws UnauthorizedException
4951 function prepare_photo_data($type, $scale, $photo_id)
4954 $user_info = api_get_user($a);
4956 if ($user_info === false) {
4957 throw new ForbiddenException();
4960 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4961 $data_sql = ($scale === false ? "" : "data, ");
4963 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4964 // clients needs to convert this in their way for further processing
4966 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4967 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4968 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4969 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4970 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4971 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4973 intval(local_user()),
4974 DBA::escape($photo_id),
4979 'image/jpeg' => 'jpg',
4980 'image/png' => 'png',
4981 'image/gif' => 'gif'
4984 // prepare output data for photo
4985 if (DBA::isResult($r)) {
4986 $data = ['photo' => $r[0]];
4987 $data['photo']['id'] = $data['photo']['resource-id'];
4988 if ($scale !== false) {
4989 $data['photo']['data'] = base64_encode($data['photo']['data']);
4991 unset($data['photo']['datasize']); //needed only with scale param
4993 if ($type == "xml") {
4994 $data['photo']['links'] = [];
4995 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4996 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4998 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
5001 $data['photo']['link'] = [];
5002 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
5004 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5005 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
5009 unset($data['photo']['resource-id']);
5010 unset($data['photo']['minscale']);
5011 unset($data['photo']['maxscale']);
5013 throw new NotFoundException();
5016 // retrieve item element for getting activities (like, dislike etc.) related to photo
5017 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5018 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5020 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5022 // retrieve comments on photo
5023 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5024 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5026 $statuses = Item::selectForUser(api_user(), [], $condition);
5028 // prepare output of comments
5029 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5031 if ($type == "xml") {
5033 foreach ($commentData as $comment) {
5034 $comments[$k++ . ":comment"] = $comment;
5037 foreach ($commentData as $comment) {
5038 $comments[] = $comment;
5041 $data['photo']['friendica_comments'] = $comments;
5043 // include info if rights on photo and rights on item are mismatching
5044 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5045 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5046 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5047 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5048 $data['photo']['rights_mismatch'] = $rights_mismatch;
5055 * Similar as /mod/redir.php
5056 * redirect to 'url' after dfrn auth
5058 * Why this when there is mod/redir.php already?
5059 * This use api_user() and api_login()
5062 * c_url: url of remote contact to auth to
5063 * url: string, url to redirect after auth
5065 function api_friendica_remoteauth()
5067 $url = defaults($_GET, 'url', '');
5068 $c_url = defaults($_GET, 'c_url', '');
5070 if ($url === '' || $c_url === '') {
5071 throw new BadRequestException("Wrong parameters.");
5074 $c_url = Strings::normaliseLink($c_url);
5078 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5080 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5081 throw new BadRequestException("Unknown contact");
5084 $cid = $contact['id'];
5086 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
5088 if ($contact['duplex'] && $contact['issued-id']) {
5089 $orig_id = $contact['issued-id'];
5090 $dfrn_id = '1:' . $orig_id;
5092 if ($contact['duplex'] && $contact['dfrn-id']) {
5093 $orig_id = $contact['dfrn-id'];
5094 $dfrn_id = '0:' . $orig_id;
5097 $sec = Strings::getRandomHex();
5099 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5100 'sec' => $sec, 'expire' => time() + 45];
5101 DBA::insert('profile_check', $fields);
5103 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5104 $dest = ($url ? '&destination_url=' . $url : '');
5106 System::externalRedirect(
5107 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5108 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5109 . '&type=profile&sec=' . $sec . $dest
5112 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5115 * Return an item with announcer data if it had been announced
5117 * @param array $item Item array
5118 * @return array Item array with announce data
5120 function api_get_announce($item)
5122 // Quit if the item already has got a different owner and author
5123 if ($item['owner-id'] != $item['author-id']) {
5127 // Don't change original or Diaspora posts
5128 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5132 // Quit if we do now the original author and it had been a post from a native network
5133 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5137 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5138 $activity = Item::activityToIndex(ACTIVITY2_ANNOUNCE);
5139 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5140 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5141 if (!DBA::isResult($announce)) {
5145 return array_merge($item, $announce);
5149 * @brief Return the item shared, if the item contains only the [share] tag
5151 * @param array $item Sharer item
5152 * @return array|false Shared item or false if not a reshare
5153 * @throws ImagickException
5154 * @throws InternalServerErrorException
5156 function api_share_as_retweet(&$item)
5158 $body = trim($item["body"]);
5160 if (Diaspora::isReshare($body, false) === false) {
5161 if ($item['author-id'] == $item['owner-id']) {
5164 // Reshares from OStatus, ActivityPub and Twitter
5165 $reshared_item = $item;
5166 $reshared_item['owner-id'] = $reshared_item['author-id'];
5167 $reshared_item['owner-link'] = $reshared_item['author-link'];
5168 $reshared_item['owner-name'] = $reshared_item['author-name'];
5169 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5170 return $reshared_item;
5174 /// @TODO "$1" should maybe mean '$1' ?
5175 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5177 * Skip if there is no shared message in there
5178 * we already checked this in diaspora::isReshare()
5179 * but better one more than one less...
5181 if (($body == $attributes) || empty($attributes)) {
5185 // build the fake reshared item
5186 $reshared_item = $item;
5189 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5190 if (!empty($matches[1])) {
5191 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5194 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5195 if (!empty($matches[1])) {
5196 $author = $matches[1];
5200 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5201 if (!empty($matches[1])) {
5202 $profile = $matches[1];
5205 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5206 if (!empty($matches[1])) {
5207 $profile = $matches[1];
5211 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5212 if (!empty($matches[1])) {
5213 $avatar = $matches[1];
5216 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5217 if (!empty($matches[1])) {
5218 $avatar = $matches[1];
5222 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5223 if (!empty($matches[1])) {
5224 $link = $matches[1];
5227 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5228 if (!empty($matches[1])) {
5229 $link = $matches[1];
5233 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5234 if (!empty($matches[1])) {
5235 $posted = $matches[1];
5238 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5239 if (!empty($matches[1])) {
5240 $posted = $matches[1];
5243 if (!preg_match("/(.*?)\[share.*?\]\s?(.*?)\s?\[\/share\]\s?(.*?)/ism", $body, $matches)) {
5247 $pre_body = trim($matches[1]);
5248 if ($pre_body != '') {
5249 $item['body'] = $pre_body;
5252 $shared_body = trim($matches[2]);
5254 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5258 $reshared_item["share-pre-body"] = $pre_body;
5259 $reshared_item["body"] = $shared_body;
5260 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5261 $reshared_item["author-name"] = $author;
5262 $reshared_item["author-link"] = $profile;
5263 $reshared_item["author-avatar"] = $avatar;
5264 $reshared_item["plink"] = $link;
5265 $reshared_item["created"] = $posted;
5266 $reshared_item["edited"] = $posted;
5268 return $reshared_item;
5273 * @param string $profile
5275 * @return string|false
5276 * @throws InternalServerErrorException
5277 * @todo remove trailing junk from profile url
5278 * @todo pump.io check has to check the website
5280 function api_get_nick($profile)
5285 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5286 DBA::escape(Strings::normaliseLink($profile))
5289 if (DBA::isResult($r)) {
5290 $nick = $r[0]["nick"];
5295 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5296 DBA::escape(Strings::normaliseLink($profile))
5299 if (DBA::isResult($r)) {
5300 $nick = $r[0]["nick"];
5305 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5306 if ($friendica != $profile) {
5312 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5313 if ($diaspora != $profile) {
5319 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5320 if ($twitter != $profile) {
5327 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5328 if ($StatusnetHost != $profile) {
5329 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5330 if ($StatusnetUser != $profile) {
5331 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5332 $user = json_decode($UserData);
5334 $nick = $user->screen_name;
5340 // To-Do: look at the page if its really a pumpio site
5341 //if (!$nick == "") {
5342 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5343 // if ($pumpio != $profile)
5345 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5358 * @param array $item
5363 function api_in_reply_to($item)
5367 $in_reply_to['status_id'] = null;
5368 $in_reply_to['user_id'] = null;
5369 $in_reply_to['status_id_str'] = null;
5370 $in_reply_to['user_id_str'] = null;
5371 $in_reply_to['screen_name'] = null;
5373 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5374 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5375 if (DBA::isResult($parent)) {
5376 $in_reply_to['status_id'] = intval($parent['id']);
5378 $in_reply_to['status_id'] = intval($item['parent']);
5381 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5383 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5384 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5386 if (DBA::isResult($parent)) {
5387 if ($parent['author-nick'] == "") {
5388 $parent['author-nick'] = api_get_nick($parent['author-link']);
5391 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5392 $in_reply_to['user_id'] = intval($parent['author-id']);
5393 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5396 // There seems to be situation, where both fields are identical:
5397 // https://github.com/friendica/friendica/issues/1010
5398 // This is a bugfix for that.
5399 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5400 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']]);
5401 $in_reply_to['status_id'] = null;
5402 $in_reply_to['user_id'] = null;
5403 $in_reply_to['status_id_str'] = null;
5404 $in_reply_to['user_id_str'] = null;
5405 $in_reply_to['screen_name'] = null;
5409 return $in_reply_to;
5414 * @param string $text
5417 * @throws InternalServerErrorException
5419 function api_clean_plain_items($text)
5421 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5423 $text = BBCode::cleanPictureLinks($text);
5424 $URLSearchString = "^\[\]";
5426 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5428 if ($include_entities == "true") {
5429 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5432 // Simplify "attachment" element
5433 $text = api_clean_attachments($text);
5439 * @brief Removes most sharing information for API text export
5441 * @param string $body The original body
5443 * @return string Cleaned body
5444 * @throws InternalServerErrorException
5446 function api_clean_attachments($body)
5448 $data = BBCode::getAttachmentData($body);
5455 if (isset($data["text"])) {
5456 $body = $data["text"];
5458 if (($body == "") && isset($data["title"])) {
5459 $body = $data["title"];
5461 if (isset($data["url"])) {
5462 $body .= "\n".$data["url"];
5464 $body .= $data["after"];
5471 * @param array $contacts
5475 function api_best_nickname(&$contacts)
5479 if (count($contacts) == 0) {
5483 foreach ($contacts as $contact) {
5484 if ($contact["network"] == "") {
5485 $contact["network"] = "dfrn";
5486 $best_contact = [$contact];
5490 if (sizeof($best_contact) == 0) {
5491 foreach ($contacts as $contact) {
5492 if ($contact["network"] == "dfrn") {
5493 $best_contact = [$contact];
5498 if (sizeof($best_contact) == 0) {
5499 foreach ($contacts as $contact) {
5500 if ($contact["network"] == "dspr") {
5501 $best_contact = [$contact];
5506 if (sizeof($best_contact) == 0) {
5507 foreach ($contacts as $contact) {
5508 if ($contact["network"] == "stat") {
5509 $best_contact = [$contact];
5514 if (sizeof($best_contact) == 0) {
5515 foreach ($contacts as $contact) {
5516 if ($contact["network"] == "pump") {
5517 $best_contact = [$contact];
5522 if (sizeof($best_contact) == 0) {
5523 foreach ($contacts as $contact) {
5524 if ($contact["network"] == "twit") {
5525 $best_contact = [$contact];
5530 if (sizeof($best_contact) == 1) {
5531 $contacts = $best_contact;
5533 $contacts = [$contacts[0]];
5538 * Return all or a specified group of the user with the containing contacts.
5540 * @param string $type Return type (atom, rss, xml, json)
5542 * @return array|string
5543 * @throws BadRequestException
5544 * @throws ForbiddenException
5545 * @throws ImagickException
5546 * @throws InternalServerErrorException
5547 * @throws UnauthorizedException
5549 function api_friendica_group_show($type)
5553 if (api_user() === false) {
5554 throw new ForbiddenException();
5558 $user_info = api_get_user($a);
5559 $gid = defaults($_REQUEST, 'gid', 0);
5560 $uid = $user_info['uid'];
5562 // get data of the specified group id or all groups if not specified
5565 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5569 // error message if specified gid is not in database
5570 if (!DBA::isResult($r)) {
5571 throw new BadRequestException("gid not available");
5575 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5580 // loop through all groups and retrieve all members for adding data in the user array
5582 foreach ($r as $rr) {
5583 $members = Contact::getByGroupId($rr['id']);
5586 if ($type == "xml") {
5587 $user_element = "users";
5589 foreach ($members as $member) {
5590 $user = api_get_user($a, $member['nurl']);
5591 $users[$k++.":user"] = $user;
5594 $user_element = "user";
5595 foreach ($members as $member) {
5596 $user = api_get_user($a, $member['nurl']);
5600 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5602 return api_format_data("groups", $type, ['group' => $grps]);
5604 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5608 * Delete the specified group of the user.
5610 * @param string $type Return type (atom, rss, xml, json)
5612 * @return array|string
5613 * @throws BadRequestException
5614 * @throws ForbiddenException
5615 * @throws ImagickException
5616 * @throws InternalServerErrorException
5617 * @throws UnauthorizedException
5619 function api_friendica_group_delete($type)
5623 if (api_user() === false) {
5624 throw new ForbiddenException();
5628 $user_info = api_get_user($a);
5629 $gid = defaults($_REQUEST, 'gid', 0);
5630 $name = defaults($_REQUEST, 'name', "");
5631 $uid = $user_info['uid'];
5633 // error if no gid specified
5634 if ($gid == 0 || $name == "") {
5635 throw new BadRequestException('gid or name not specified');
5638 // get data of the specified group id
5640 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5644 // error message if specified gid is not in database
5645 if (!DBA::isResult($r)) {
5646 throw new BadRequestException('gid not available');
5649 // get data of the specified group id and group name
5651 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5656 // error message if specified gid is not in database
5657 if (!DBA::isResult($rname)) {
5658 throw new BadRequestException('wrong group name');
5662 $ret = Group::removeByName($uid, $name);
5665 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5666 return api_format_data("group_delete", $type, ['result' => $success]);
5668 throw new BadRequestException('other API error');
5671 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5676 * @param string $type Return type (atom, rss, xml, json)
5678 * @return array|string
5679 * @throws BadRequestException
5680 * @throws ForbiddenException
5681 * @throws ImagickException
5682 * @throws InternalServerErrorException
5683 * @throws UnauthorizedException
5684 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5686 function api_lists_destroy($type)
5690 if (api_user() === false) {
5691 throw new ForbiddenException();
5695 $user_info = api_get_user($a);
5696 $gid = defaults($_REQUEST, 'list_id', 0);
5697 $uid = $user_info['uid'];
5699 // error if no gid specified
5701 throw new BadRequestException('gid not specified');
5704 // get data of the specified group id
5705 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5706 // error message if specified gid is not in database
5708 throw new BadRequestException('gid not available');
5711 if (Group::remove($gid)) {
5713 'name' => $group['name'],
5714 'id' => intval($gid),
5715 'id_str' => (string) $gid,
5716 'user' => $user_info
5719 return api_format_data("lists", $type, ['lists' => $list]);
5722 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5725 * Add a new group to the database.
5727 * @param string $name Group name
5728 * @param int $uid User ID
5729 * @param array $users List of users to add to the group
5732 * @throws BadRequestException
5734 function group_create($name, $uid, $users = [])
5736 // error if no name specified
5738 throw new BadRequestException('group name not specified');
5741 // get data of the specified group name
5743 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5747 // error message if specified group name already exists
5748 if (DBA::isResult($rname)) {
5749 throw new BadRequestException('group name already exists');
5752 // check if specified group name is a deleted group
5754 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5758 // error message if specified group name already exists
5759 if (DBA::isResult($rname)) {
5760 $reactivate_group = true;
5764 $ret = Group::create($uid, $name);
5766 $gid = Group::getIdByName($uid, $name);
5768 throw new BadRequestException('other API error');
5772 $erroraddinguser = false;
5774 foreach ($users as $user) {
5775 $cid = $user['cid'];
5776 // check if user really exists as contact
5778 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5782 if (count($contact)) {
5783 Group::addMember($gid, $cid);
5785 $erroraddinguser = true;
5786 $errorusers[] = $cid;
5790 // return success message incl. missing users in array
5791 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5793 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5797 * Create the specified group with the posted array of contacts.
5799 * @param string $type Return type (atom, rss, xml, json)
5801 * @return array|string
5802 * @throws BadRequestException
5803 * @throws ForbiddenException
5804 * @throws ImagickException
5805 * @throws InternalServerErrorException
5806 * @throws UnauthorizedException
5808 function api_friendica_group_create($type)
5812 if (api_user() === false) {
5813 throw new ForbiddenException();
5817 $user_info = api_get_user($a);
5818 $name = defaults($_REQUEST, 'name', "");
5819 $uid = $user_info['uid'];
5820 $json = json_decode($_POST['json'], true);
5821 $users = $json['user'];
5823 $success = group_create($name, $uid, $users);
5825 return api_format_data("group_create", $type, ['result' => $success]);
5827 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5830 * Create a new group.
5832 * @param string $type Return type (atom, rss, xml, json)
5834 * @return array|string
5835 * @throws BadRequestException
5836 * @throws ForbiddenException
5837 * @throws ImagickException
5838 * @throws InternalServerErrorException
5839 * @throws UnauthorizedException
5840 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5842 function api_lists_create($type)
5846 if (api_user() === false) {
5847 throw new ForbiddenException();
5851 $user_info = api_get_user($a);
5852 $name = defaults($_REQUEST, 'name', "");
5853 $uid = $user_info['uid'];
5855 $success = group_create($name, $uid);
5856 if ($success['success']) {
5858 'name' => $success['name'],
5859 'id' => intval($success['gid']),
5860 'id_str' => (string) $success['gid'],
5861 'user' => $user_info
5864 return api_format_data("lists", $type, ['lists'=>$grp]);
5867 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5870 * Update the specified group with the posted array of contacts.
5872 * @param string $type Return type (atom, rss, xml, json)
5874 * @return array|string
5875 * @throws BadRequestException
5876 * @throws ForbiddenException
5877 * @throws ImagickException
5878 * @throws InternalServerErrorException
5879 * @throws UnauthorizedException
5881 function api_friendica_group_update($type)
5885 if (api_user() === false) {
5886 throw new ForbiddenException();
5890 $user_info = api_get_user($a);
5891 $uid = $user_info['uid'];
5892 $gid = defaults($_REQUEST, 'gid', 0);
5893 $name = defaults($_REQUEST, 'name', "");
5894 $json = json_decode($_POST['json'], true);
5895 $users = $json['user'];
5897 // error if no name specified
5899 throw new BadRequestException('group name not specified');
5902 // error if no gid specified
5904 throw new BadRequestException('gid not specified');
5908 $members = Contact::getByGroupId($gid);
5909 foreach ($members as $member) {
5910 $cid = $member['id'];
5911 foreach ($users as $user) {
5912 $found = ($user['cid'] == $cid ? true : false);
5914 if (!isset($found) || !$found) {
5915 Group::removeMemberByName($uid, $name, $cid);
5920 $erroraddinguser = false;
5922 foreach ($users as $user) {
5923 $cid = $user['cid'];
5924 // check if user really exists as contact
5926 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5931 if (count($contact)) {
5932 Group::addMember($gid, $cid);
5934 $erroraddinguser = true;
5935 $errorusers[] = $cid;
5939 // return success message incl. missing users in array
5940 $status = ($erroraddinguser ? "missing user" : "ok");
5941 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5942 return api_format_data("group_update", $type, ['result' => $success]);
5945 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5948 * Update information about a group.
5950 * @param string $type Return type (atom, rss, xml, json)
5952 * @return array|string
5953 * @throws BadRequestException
5954 * @throws ForbiddenException
5955 * @throws ImagickException
5956 * @throws InternalServerErrorException
5957 * @throws UnauthorizedException
5958 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5960 function api_lists_update($type)
5964 if (api_user() === false) {
5965 throw new ForbiddenException();
5969 $user_info = api_get_user($a);
5970 $gid = defaults($_REQUEST, 'list_id', 0);
5971 $name = defaults($_REQUEST, 'name', "");
5972 $uid = $user_info['uid'];
5974 // error if no gid specified
5976 throw new BadRequestException('gid not specified');
5979 // get data of the specified group id
5980 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5981 // error message if specified gid is not in database
5983 throw new BadRequestException('gid not available');
5986 if (Group::update($gid, $name)) {
5989 'id' => intval($gid),
5990 'id_str' => (string) $gid,
5991 'user' => $user_info
5994 return api_format_data("lists", $type, ['lists' => $list]);
5998 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
6002 * @param string $type Return type (atom, rss, xml, json)
6004 * @return array|string
6005 * @throws BadRequestException
6006 * @throws ForbiddenException
6007 * @throws ImagickException
6008 * @throws InternalServerErrorException
6010 function api_friendica_activity($type)
6014 if (api_user() === false) {
6015 throw new ForbiddenException();
6017 $verb = strtolower($a->argv[3]);
6018 $verb = preg_replace("|\..*$|", "", $verb);
6020 $id = defaults($_REQUEST, 'id', 0);
6022 $res = Item::performLike($id, $verb);
6025 if ($type == "xml") {
6030 return api_format_data('ok', $type, ['ok' => $ok]);
6032 throw new BadRequestException('Error adding activity');
6036 /// @TODO move to top of file or somewhere better
6037 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
6038 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
6039 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
6040 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
6041 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
6042 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
6043 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
6044 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
6045 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
6046 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
6049 * @brief Returns notifications
6051 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6052 * @return string|array
6053 * @throws BadRequestException
6054 * @throws ForbiddenException
6055 * @throws InternalServerErrorException
6057 function api_friendica_notification($type)
6061 if (api_user() === false) {
6062 throw new ForbiddenException();
6065 throw new BadRequestException("Invalid argument count");
6067 $nm = new NotificationsManager();
6069 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
6071 if ($type == "xml") {
6073 if (!empty($notes)) {
6074 foreach ($notes as $note) {
6075 $xmlnotes[] = ["@attributes" => $note];
6081 return api_format_data("notes", $type, ['note' => $notes]);
6085 * POST request with 'id' param as notification id
6087 * @brief Set notification as seen and returns associated item (if possible)
6089 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6090 * @return string|array
6091 * @throws BadRequestException
6092 * @throws ForbiddenException
6093 * @throws ImagickException
6094 * @throws InternalServerErrorException
6095 * @throws UnauthorizedException
6097 function api_friendica_notification_seen($type)
6100 $user_info = api_get_user($a);
6102 if (api_user() === false || $user_info === false) {
6103 throw new ForbiddenException();
6106 throw new BadRequestException("Invalid argument count");
6109 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
6111 $nm = new NotificationsManager();
6112 $note = $nm->getByID($id);
6113 if (is_null($note)) {
6114 throw new BadRequestException("Invalid argument");
6117 $nm->setSeen($note);
6118 if ($note['otype']=='item') {
6119 // would be really better with an ItemsManager and $im->getByID() :-P
6120 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6121 if (DBA::isResult($item)) {
6122 // we found the item, return it to the user
6123 $ret = api_format_items([$item], $user_info, false, $type);
6124 $data = ['status' => $ret];
6125 return api_format_data("status", $type, $data);
6127 // the item can't be found, but we set the note as seen, so we count this as a success
6129 return api_format_data('result', $type, ['result' => "success"]);
6132 /// @TODO move to top of file or somewhere better
6133 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6134 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6137 * @brief update a direct_message to seen state
6139 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6140 * @return string|array (success result=ok, error result=error with error message)
6141 * @throws BadRequestException
6142 * @throws ForbiddenException
6143 * @throws ImagickException
6144 * @throws InternalServerErrorException
6145 * @throws UnauthorizedException
6147 function api_friendica_direct_messages_setseen($type)
6150 if (api_user() === false) {
6151 throw new ForbiddenException();
6155 $user_info = api_get_user($a);
6156 $uid = $user_info['uid'];
6157 $id = defaults($_REQUEST, 'id', 0);
6159 // return error if id is zero
6161 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6162 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6165 // error message if specified id is not in database
6166 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6167 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6168 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6171 // update seen indicator
6172 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6176 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6177 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6179 $answer = ['result' => 'error', 'message' => 'unknown error'];
6180 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6184 /// @TODO move to top of file or somewhere better
6185 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6188 * @brief search for direct_messages containing a searchstring through api
6190 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6191 * @param string $box
6192 * @return string|array (success: success=true if found and search_result contains found messages,
6193 * success=false if nothing was found, search_result='nothing found',
6194 * error: result=error with error message)
6195 * @throws BadRequestException
6196 * @throws ForbiddenException
6197 * @throws ImagickException
6198 * @throws InternalServerErrorException
6199 * @throws UnauthorizedException
6201 function api_friendica_direct_messages_search($type, $box = "")
6205 if (api_user() === false) {
6206 throw new ForbiddenException();
6210 $user_info = api_get_user($a);
6211 $searchstring = defaults($_REQUEST, 'searchstring', "");
6212 $uid = $user_info['uid'];
6214 // error if no searchstring specified
6215 if ($searchstring == "") {
6216 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6217 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6220 // get data for the specified searchstring
6222 "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",
6224 DBA::escape('%'.$searchstring.'%')
6227 $profile_url = $user_info["url"];
6229 // message if nothing was found
6230 if (!DBA::isResult($r)) {
6231 $success = ['success' => false, 'search_results' => 'problem with query'];
6232 } elseif (count($r) == 0) {
6233 $success = ['success' => false, 'search_results' => 'nothing found'];
6236 foreach ($r as $item) {
6237 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6238 $recipient = $user_info;
6239 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6240 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6241 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6242 $sender = $user_info;
6245 if (isset($recipient) && isset($sender)) {
6246 $ret[] = api_format_messages($item, $recipient, $sender);
6249 $success = ['success' => true, 'search_results' => $ret];
6252 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6255 /// @TODO move to top of file or somewhere better
6256 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6259 * @brief return data of all the profiles a user has to the client
6261 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6262 * @return string|array
6263 * @throws BadRequestException
6264 * @throws ForbiddenException
6265 * @throws ImagickException
6266 * @throws InternalServerErrorException
6267 * @throws UnauthorizedException
6269 function api_friendica_profile_show($type)
6273 if (api_user() === false) {
6274 throw new ForbiddenException();
6278 $profile_id = defaults($_REQUEST, 'profile_id', 0);
6280 // retrieve general information about profiles for user
6281 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6282 $directory = Config::get('system', 'directory');
6284 // get data of the specified profile id or all profiles of the user if not specified
6285 if ($profile_id != 0) {
6286 $r = Profile::getById(api_user(), $profile_id);
6287 // error message if specified gid is not in database
6288 if (!DBA::isResult($r)) {
6289 throw new BadRequestException("profile_id not available");
6292 $r = Profile::getListByUser(api_user());
6294 // loop through all returned profiles and retrieve data and users
6297 if (DBA::isResult($r)) {
6298 foreach ($r as $rr) {
6299 $profile = api_format_items_profiles($rr);
6301 // select all users from contact table, loop and prepare standard return for user data
6303 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6304 foreach ($nurls as $nurl) {
6305 $user = api_get_user($a, $nurl['nurl']);
6306 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6308 $profile['users'] = $users;
6310 // add prepared profile data to array for final return
6311 if ($type == "xml") {
6312 $profiles[$k++ . ":profile"] = $profile;
6314 $profiles[] = $profile;
6319 // return settings, authenticated user and profiles data
6320 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6322 $result = ['multi_profiles' => $multi_profiles ? true : false,
6323 'global_dir' => $directory,
6324 'friendica_owner' => api_get_user($a, $self['nurl']),
6325 'profiles' => $profiles];
6326 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6328 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6331 * Returns a list of saved searches.
6333 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6335 * @param string $type Return format: json or xml
6337 * @return string|array
6340 function api_saved_searches_list($type)
6342 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6345 while ($term = DBA::fetch($terms)) {
6347 'created_at' => api_date(time()),
6348 'id' => intval($term['id']),
6349 'id_str' => $term['id'],
6350 'name' => $term['term'],
6352 'query' => $term['term']
6358 return api_format_data("terms", $type, ['terms' => $result]);
6361 /// @TODO move to top of file or somewhere better
6362 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6365 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6367 * @brief Number of comments
6369 * @param object $data [Status, Status]
6373 function bindComments(&$data)
6375 if (count($data) == 0) {
6381 foreach ($data as $item) {
6382 $ids[] = $item['id'];
6385 $idStr = DBA::escape(implode(', ', $ids));
6386 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6387 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6388 $itemsData = DBA::toArray($items);
6390 foreach ($itemsData as $item) {
6391 $comments[$item['parent']] = $item['comments'];
6394 foreach ($data as $idx => $item) {
6396 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6401 @TODO Maybe open to implement?
6403 [pagename] => api/1.1/statuses/lookup.json
6404 [id] => 605138389168451584
6405 [include_cards] => true
6406 [cards_platform] => Android-12
6407 [include_entities] => true
6408 [include_my_retweet] => 1
6410 [include_reply_count] => true
6411 [include_descendent_reply_count] => true
6415 Not implemented by now:
6416 statuses/retweets_of_me
6421 account/update_location
6422 account/update_profile_background_image
6425 friendica/profile/update
6426 friendica/profile/create
6427 friendica/profile/delete
6429 Not implemented in status.net:
6430 statuses/retweeted_to_me
6431 statuses/retweeted_by_me
6432 direct_messages/destroy
6434 account/update_delivery_device
6435 notifications/follow