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 'mod/share.php';
52 require_once 'mod/item.php';
53 require_once '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 $json = json_encode(end($return));
347 if (!empty($_GET['callback'])) {
348 $json = $_GET['callback'] . "(" . $json . ")";
353 header("Content-Type: application/rss+xml");
354 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
357 header("Content-Type: application/atom+xml");
358 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
365 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => $a->query_string]);
366 throw new NotImplementedException();
367 } catch (HTTPException $e) {
368 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
369 return api_error($type, $e);
374 * @brief Format API error string
376 * @param string $type Return type (xml, json, rss, as)
377 * @param object $e HTTPException Error object
378 * @return string|array error message formatted as $type
380 function api_error($type, $e)
384 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
385 /// @TODO: https://dev.twitter.com/overview/api/response-codes
387 $error = ["error" => $error,
388 "code" => $e->getCode() . " " . $e->httpdesc,
389 "request" => $a->query_string];
391 $return = api_format_data('status', $type, ['status' => $error]);
395 header("Content-Type: text/xml");
398 header("Content-Type: application/json");
399 $return = json_encode($return);
402 header("Content-Type: application/rss+xml");
405 header("Content-Type: application/atom+xml");
413 * @brief Set values for RSS template
416 * @param array $arr Array to be passed to template
417 * @param array $user_info User info
419 * @throws BadRequestException
420 * @throws ImagickException
421 * @throws InternalServerErrorException
422 * @throws UnauthorizedException
423 * @todo find proper type-hints
425 function api_rss_extra(App $a, $arr, $user_info)
427 if (is_null($user_info)) {
428 $user_info = api_get_user($a);
431 $arr['$user'] = $user_info;
433 'alternate' => $user_info['url'],
434 'self' => System::baseUrl() . "/" . $a->query_string,
435 'base' => System::baseUrl(),
436 'updated' => api_date(null),
437 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
438 'language' => $user_info['lang'],
439 'logo' => System::baseUrl() . "/images/friendica-32.png",
447 * @brief Unique contact to contact url.
449 * @param int $id Contact id
450 * @return bool|string
451 * Contact url or False if contact id is unknown
454 function api_unique_id_to_nurl($id)
456 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
458 if (DBA::isResult($r)) {
466 * @brief Get user info array.
469 * @param int|string $contact_id Contact ID or URL
471 * @throws BadRequestException
472 * @throws ImagickException
473 * @throws InternalServerErrorException
474 * @throws UnauthorizedException
476 function api_get_user(App $a, $contact_id = null)
484 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
486 // Searching for contact URL
487 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
488 $user = DBA::escape(Strings::normaliseLink($contact_id));
490 $extra_query = "AND `contact`.`nurl` = '%s' ";
491 if (api_user() !== false) {
492 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
496 // Searching for contact id with uid = 0
497 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
498 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
501 throw new BadRequestException("User ID ".$contact_id." not found.");
505 $extra_query = "AND `contact`.`nurl` = '%s' ";
506 if (api_user() !== false) {
507 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
511 if (is_null($user) && !empty($_GET['user_id'])) {
512 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
515 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
519 $extra_query = "AND `contact`.`nurl` = '%s' ";
520 if (api_user() !== false) {
521 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
524 if (is_null($user) && !empty($_GET['screen_name'])) {
525 $user = DBA::escape($_GET['screen_name']);
526 $extra_query = "AND `contact`.`nick` = '%s' ";
527 if (api_user() !== false) {
528 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
532 if (is_null($user) && !empty($_GET['profileurl'])) {
533 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
534 $extra_query = "AND `contact`.`nurl` = '%s' ";
535 if (api_user() !== false) {
536 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
540 // $called_api is the API path exploded on / and is expected to have at least 2 elements
541 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
542 $argid = count($called_api);
543 if (!empty($a->argv[$argid])) {
544 $data = explode(".", $a->argv[$argid]);
545 if (count($data) > 1) {
546 list($user, $null) = $data;
549 if (is_numeric($user)) {
550 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
554 $extra_query = "AND `contact`.`nurl` = '%s' ";
555 if (api_user() !== false) {
556 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
560 $user = DBA::escape($user);
561 $extra_query = "AND `contact`.`nick` = '%s' ";
562 if (api_user() !== false) {
563 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
568 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
571 if (api_user() === false) {
575 $user = $_SESSION['uid'];
576 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
580 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
584 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
590 // Selecting the id by priority, friendica first
591 if (is_array($uinfo)) {
592 api_best_nickname($uinfo);
595 // if the contact wasn't found, fetch it from the contacts with uid = 0
596 if (!DBA::isResult($uinfo)) {
598 throw new BadRequestException("User not found.");
601 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
603 if (DBA::isResult($contact)) {
604 // If no nick where given, extract it from the address
605 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
606 $contact['nick'] = api_get_nick($contact["url"]);
610 'id' => $contact["id"],
611 'id_str' => (string) $contact["id"],
612 'name' => $contact["name"],
613 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
614 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
615 'description' => HTML::toPlaintext(BBCode::toPlaintext($contact["about"])),
616 'profile_image_url' => $contact["micro"],
617 'profile_image_url_https' => $contact["micro"],
618 'profile_image_url_profile_size' => $contact["thumb"],
619 'profile_image_url_large' => $contact["photo"],
620 'url' => $contact["url"],
621 'protected' => false,
622 'followers_count' => 0,
623 'friends_count' => 0,
625 'created_at' => api_date($contact["created"]),
626 'favourites_count' => 0,
628 'time_zone' => 'UTC',
629 'geo_enabled' => false,
631 'statuses_count' => 0,
633 'contributors_enabled' => false,
634 'is_translator' => false,
635 'is_translation_enabled' => false,
636 'following' => false,
637 'follow_request_sent' => false,
638 'statusnet_blocking' => false,
639 'notifications' => false,
640 'statusnet_profile_url' => $contact["url"],
642 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
643 'pid' => Contact::getIdForURL($contact["url"], 0, true),
645 'network' => $contact["network"],
650 throw new BadRequestException("User ".$url." not found.");
654 if ($uinfo[0]['self']) {
655 if ($uinfo[0]['network'] == "") {
656 $uinfo[0]['network'] = Protocol::DFRN;
659 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
660 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
667 // Add a nick if it isn't present there
668 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
669 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
672 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
674 if (!empty($profile['about'])) {
675 $description = $profile['about'];
677 $description = $uinfo[0]["about"];
680 if (!empty($usr['default-location'])) {
681 $location = $usr['default-location'];
682 } elseif (!empty($uinfo[0]["location"])) {
683 $location = $uinfo[0]["location"];
685 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
689 'id' => intval($pcontact_id),
690 'id_str' => (string) intval($pcontact_id),
691 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
692 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
693 'location' => $location,
694 'description' => HTML::toPlaintext(BBCode::toPlaintext($description)),
695 'profile_image_url' => $uinfo[0]['micro'],
696 'profile_image_url_https' => $uinfo[0]['micro'],
697 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
698 'profile_image_url_large' => $uinfo[0]["photo"],
699 'url' => $uinfo[0]['url'],
700 'protected' => false,
701 'followers_count' => intval($countfollowers),
702 'friends_count' => intval($countfriends),
704 'created_at' => api_date($uinfo[0]['created']),
705 'favourites_count' => intval($starred),
707 'time_zone' => 'UTC',
708 'geo_enabled' => false,
710 'statuses_count' => intval($countitems),
712 'contributors_enabled' => false,
713 'is_translator' => false,
714 'is_translation_enabled' => false,
715 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
716 'follow_request_sent' => false,
717 'statusnet_blocking' => false,
718 'notifications' => false,
720 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
721 'statusnet_profile_url' => $uinfo[0]['url'],
722 'uid' => intval($uinfo[0]['uid']),
723 'cid' => intval($uinfo[0]['cid']),
724 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
725 'self' => $uinfo[0]['self'],
726 'network' => $uinfo[0]['network'],
729 // If this is a local user and it uses Frio, we can get its color preferences.
731 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
732 if ($theme_info['theme'] === 'frio') {
733 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
735 if ($schema && ($schema != '---')) {
736 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
737 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
738 require_once $schemefile;
741 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
742 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
743 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
745 if (empty($nav_bg)) {
748 if (empty($link_color)) {
749 $link_color = "#6fdbe8";
751 if (empty($bgcolor)) {
752 $bgcolor = "#ededed";
755 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
756 $ret['profile_link_color'] = str_replace('#', '', $link_color);
757 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
765 * @brief return api-formatted array for item's author and owner
768 * @param array $item item from db
769 * @return array(array:author, array:owner)
770 * @throws BadRequestException
771 * @throws ImagickException
772 * @throws InternalServerErrorException
773 * @throws UnauthorizedException
775 function api_item_get_user(App $a, $item)
777 $status_user = api_get_user($a, defaults($item, 'author-id', null));
779 $author_user = $status_user;
781 $status_user["protected"] = defaults($item, 'private', 0);
783 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
784 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
786 $owner_user = $author_user;
789 return ([$status_user, $author_user, $owner_user]);
793 * @brief walks recursively through an array with the possibility to change value and key
795 * @param array $array The array to walk through
796 * @param callable $callback The callback function
798 * @return array the transformed array
800 function api_walk_recursive(array &$array, callable $callback)
804 foreach ($array as $k => $v) {
806 if ($callback($v, $k)) {
807 $new_array[$k] = api_walk_recursive($v, $callback);
810 if ($callback($v, $k)) {
821 * @brief Callback function to transform the array in an array that can be transformed in a XML file
823 * @param mixed $item Array item value
824 * @param string $key Array key
826 * @return boolean Should the array item be deleted?
828 function api_reformat_xml(&$item, &$key)
830 if (is_bool($item)) {
831 $item = ($item ? "true" : "false");
834 if (substr($key, 0, 10) == "statusnet_") {
835 $key = "statusnet:".substr($key, 10);
836 } elseif (substr($key, 0, 10) == "friendica_") {
837 $key = "friendica:".substr($key, 10);
839 /// @TODO old-lost code?
841 // $key = "default:".$key;
847 * @brief Creates the XML from a JSON style array
849 * @param array $data JSON style array
850 * @param string $root_element Name of the root element
852 * @return string The XML data
854 function api_create_xml(array $data, $root_element)
856 $childname = key($data);
857 $data2 = array_pop($data);
859 $namespaces = ["" => "http://api.twitter.com",
860 "statusnet" => "http://status.net/schema/api/1/",
861 "friendica" => "http://friendi.ca/schema/api/1/",
862 "georss" => "http://www.georss.org/georss"];
864 /// @todo Auto detection of needed namespaces
865 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
869 if (is_array($data2)) {
871 api_walk_recursive($data2, "api_reformat_xml");
877 foreach ($data2 as $item) {
878 $data4[$i++ . ":" . $childname] = $item;
885 $data3 = [$root_element => $data2];
887 $ret = XML::fromArray($data3, $xml, false, $namespaces);
892 * @brief Formats the data according to the data type
894 * @param string $root_element Name of the root element
895 * @param string $type Return type (atom, rss, xml, json)
896 * @param array $data JSON style array
898 * @return array|string (string|array) XML data or JSON data
900 function api_format_data($root_element, $type, $data)
906 $ret = api_create_xml($data, $root_element);
921 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
922 * returns a 401 status code and an error message if not.
924 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
926 * @param string $type Return type (atom, rss, xml, json)
927 * @return array|string
928 * @throws BadRequestException
929 * @throws ForbiddenException
930 * @throws ImagickException
931 * @throws InternalServerErrorException
932 * @throws UnauthorizedException
934 function api_account_verify_credentials($type)
938 if (api_user() === false) {
939 throw new ForbiddenException();
942 unset($_REQUEST["user_id"]);
943 unset($_GET["user_id"]);
945 unset($_REQUEST["screen_name"]);
946 unset($_GET["screen_name"]);
948 $skip_status = defaults($_REQUEST, 'skip_status', false);
950 $user_info = api_get_user($a);
952 // "verified" isn't used here in the standard
953 unset($user_info["verified"]);
955 // - Adding last status
957 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
959 $user_info['status'] = api_format_item($item, $type);
963 // "uid" and "self" are only needed for some internal stuff, so remove it from here
964 unset($user_info["uid"]);
965 unset($user_info["self"]);
967 return api_format_data("user", $type, ['user' => $user_info]);
970 /// @TODO move to top of file or somewhere better
971 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
974 * Get data from $_POST or $_GET
979 function requestdata($k)
981 if (!empty($_POST[$k])) {
984 if (!empty($_GET[$k])) {
991 * Deprecated function to upload media.
993 * @param string $type Return type (atom, rss, xml, json)
995 * @return array|string
996 * @throws BadRequestException
997 * @throws ForbiddenException
998 * @throws ImagickException
999 * @throws InternalServerErrorException
1000 * @throws UnauthorizedException
1002 function api_statuses_mediap($type)
1006 if (api_user() === false) {
1007 Logger::log('api_statuses_update: no user');
1008 throw new ForbiddenException();
1010 $user_info = api_get_user($a);
1012 $_REQUEST['profile_uid'] = api_user();
1013 $_REQUEST['api_source'] = true;
1014 $txt = requestdata('status');
1015 /// @TODO old-lost code?
1016 //$txt = urldecode(requestdata('status'));
1018 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1019 $txt = HTML::toBBCodeVideo($txt);
1020 $config = HTMLPurifier_Config::createDefault();
1021 $config->set('Cache.DefinitionImpl', null);
1022 $purifier = new HTMLPurifier($config);
1023 $txt = $purifier->purify($txt);
1025 $txt = HTML::toBBCode($txt);
1027 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1029 $picture = wall_upload_post($a, false);
1031 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1032 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1033 $item_id = item_post($a);
1035 // output the post that we just posted.
1036 return api_status_show($type, $item_id);
1039 /// @TODO move this to top of file or somewhere better!
1040 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1043 * Updates the user’s current status.
1045 * @param string $type Return type (atom, rss, xml, json)
1047 * @return array|string
1048 * @throws BadRequestException
1049 * @throws ForbiddenException
1050 * @throws ImagickException
1051 * @throws InternalServerErrorException
1052 * @throws TooManyRequestsException
1053 * @throws UnauthorizedException
1054 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1056 function api_statuses_update($type)
1060 if (api_user() === false) {
1061 Logger::log('api_statuses_update: no user');
1062 throw new ForbiddenException();
1067 // convert $_POST array items to the form we use for web posts.
1068 if (requestdata('htmlstatus')) {
1069 $txt = requestdata('htmlstatus');
1070 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1071 $txt = HTML::toBBCodeVideo($txt);
1073 $config = HTMLPurifier_Config::createDefault();
1074 $config->set('Cache.DefinitionImpl', null);
1076 $purifier = new HTMLPurifier($config);
1077 $txt = $purifier->purify($txt);
1079 $_REQUEST['body'] = HTML::toBBCode($txt);
1082 $_REQUEST['body'] = requestdata('status');
1085 $_REQUEST['title'] = requestdata('title');
1087 $parent = requestdata('in_reply_to_status_id');
1089 // Twidere sends "-1" if it is no reply ...
1090 if ($parent == -1) {
1094 if (ctype_digit($parent)) {
1095 $_REQUEST['parent'] = $parent;
1097 $_REQUEST['parent_uri'] = $parent;
1100 if (requestdata('lat') && requestdata('long')) {
1101 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1103 $_REQUEST['profile_uid'] = api_user();
1106 // Check for throttling (maximum posts per day, week and month)
1107 $throttle_day = Config::get('system', 'throttle_limit_day');
1108 if ($throttle_day > 0) {
1109 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1111 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1112 $posts_day = DBA::count('thread', $condition);
1114 if ($posts_day > $throttle_day) {
1115 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1116 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1117 throw new TooManyRequestsException(L10n::tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1121 $throttle_week = Config::get('system', 'throttle_limit_week');
1122 if ($throttle_week > 0) {
1123 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1125 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1126 $posts_week = DBA::count('thread', $condition);
1128 if ($posts_week > $throttle_week) {
1129 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1130 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1131 throw new TooManyRequestsException(L10n::tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
1135 $throttle_month = Config::get('system', 'throttle_limit_month');
1136 if ($throttle_month > 0) {
1137 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1139 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1140 $posts_month = DBA::count('thread', $condition);
1142 if ($posts_month > $throttle_month) {
1143 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1144 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1145 throw new TooManyRequestsException(L10n::t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1150 if (!empty($_FILES['media'])) {
1151 // upload the image if we have one
1152 $picture = wall_upload_post($a, false);
1153 if (is_array($picture)) {
1154 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1158 // To-Do: Multiple IDs
1159 if (requestdata('media_ids')) {
1161 "SELECT `resource-id`, `scale`, `nickname`, `type`, `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",
1162 intval(requestdata('media_ids')),
1165 if (DBA::isResult($r)) {
1166 $phototypes = Image::supportedTypes();
1167 $ext = $phototypes[$r[0]['type']];
1168 $description = $r[0]['desc'] ?? '';
1169 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1170 $_REQUEST['body'] .= '[img=' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1174 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1176 $_REQUEST['api_source'] = true;
1178 if (empty($_REQUEST['source'])) {
1179 $_REQUEST["source"] = api_source();
1182 // call out normal post function
1183 $item_id = item_post($a);
1185 // output the post that we just posted.
1186 return api_status_show($type, $item_id);
1189 /// @TODO move to top of file or somewhere better
1190 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1191 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1194 * Uploads an image to Friendica.
1197 * @throws BadRequestException
1198 * @throws ForbiddenException
1199 * @throws ImagickException
1200 * @throws InternalServerErrorException
1201 * @throws UnauthorizedException
1202 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1204 function api_media_upload()
1208 if (api_user() === false) {
1209 Logger::log('no user');
1210 throw new ForbiddenException();
1215 if (empty($_FILES['media'])) {
1217 throw new BadRequestException("No media.");
1220 $media = wall_upload_post($a, false);
1223 throw new InternalServerErrorException();
1227 $returndata["media_id"] = $media["id"];
1228 $returndata["media_id_string"] = (string)$media["id"];
1229 $returndata["size"] = $media["size"];
1230 $returndata["image"] = ["w" => $media["width"],
1231 "h" => $media["height"],
1232 "image_type" => $media["type"],
1233 "friendica_preview_url" => $media["preview"]];
1235 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1237 return ["media" => $returndata];
1240 /// @TODO move to top of file or somewhere better
1241 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1244 * Updates media meta data (picture descriptions)
1246 * @param string $type Return type (atom, rss, xml, json)
1248 * @return array|string
1249 * @throws BadRequestException
1250 * @throws ForbiddenException
1251 * @throws ImagickException
1252 * @throws InternalServerErrorException
1253 * @throws TooManyRequestsException
1254 * @throws UnauthorizedException
1255 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1257 * @todo Compare the corresponding Twitter function for correct return values
1259 function api_media_metadata_create($type)
1263 if (api_user() === false) {
1264 Logger::info('no user');
1265 throw new ForbiddenException();
1270 $postdata = Network::postdata();
1272 if (empty($postdata)) {
1273 throw new BadRequestException("No post data");
1276 $data = json_decode($postdata, true);
1278 throw new BadRequestException("Invalid post data");
1281 if (empty($data['media_id']) || empty($data['alt_text'])) {
1282 throw new BadRequestException("Missing post data values");
1285 if (empty($data['alt_text']['text'])) {
1286 throw new BadRequestException("No alt text.");
1289 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1291 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1292 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1293 if (!DBA::isResult($photo)) {
1294 throw new BadRequestException("Metadata not found.");
1297 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1300 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1303 * @param string $type Return format (atom, rss, xml, json)
1304 * @param int $item_id
1308 function api_status_show($type, $item_id)
1310 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1314 $item = api_get_item(['id' => $item_id]);
1316 $status_info = api_format_item($item, $type);
1319 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1321 return api_format_data('statuses', $type, ['status' => $status_info]);
1325 * Retrieves the last public status of the provided user info
1327 * @param int $ownerId Public contact Id
1328 * @param int $uid User Id
1332 function api_get_last_status($ownerId, $uid)
1335 'author-id'=> $ownerId,
1337 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1341 $item = api_get_item($condition);
1347 * Retrieves a single item record based on the provided condition and converts it for API use.
1349 * @param array $condition Item table condition array
1353 function api_get_item(array $condition)
1355 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1361 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1362 * The author's most recent status will be returned inline.
1364 * @param string $type Return type (atom, rss, xml, json)
1365 * @return array|string
1366 * @throws BadRequestException
1367 * @throws ImagickException
1368 * @throws InternalServerErrorException
1369 * @throws UnauthorizedException
1370 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1372 function api_users_show($type)
1374 $a = \Friendica\BaseObject::getApp();
1376 $user_info = api_get_user($a);
1378 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1380 $user_info['status'] = api_format_item($item, $type);
1383 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1384 unset($user_info['uid']);
1385 unset($user_info['self']);
1387 return api_format_data('user', $type, ['user' => $user_info]);
1390 /// @TODO move to top of file or somewhere better
1391 api_register_func('api/users/show', 'api_users_show');
1392 api_register_func('api/externalprofile/show', 'api_users_show');
1395 * Search a public user account.
1397 * @param string $type Return type (atom, rss, xml, json)
1399 * @return array|string
1400 * @throws BadRequestException
1401 * @throws ImagickException
1402 * @throws InternalServerErrorException
1403 * @throws UnauthorizedException
1404 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1406 function api_users_search($type)
1412 if (!empty($_GET['q'])) {
1413 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1415 if (!DBA::isResult($r)) {
1416 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1419 if (DBA::isResult($r)) {
1421 foreach ($r as $user) {
1422 $user_info = api_get_user($a, $user["id"]);
1424 if ($type == "xml") {
1425 $userlist[$k++.":user"] = $user_info;
1427 $userlist[] = $user_info;
1430 $userlist = ["users" => $userlist];
1432 throw new BadRequestException("User ".$_GET["q"]." not found.");
1435 throw new BadRequestException("No user specified.");
1438 return api_format_data("users", $type, $userlist);
1441 /// @TODO move to top of file or somewhere better
1442 api_register_func('api/users/search', 'api_users_search');
1445 * Return user objects
1447 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1449 * @param string $type Return format: json or xml
1451 * @return array|string
1452 * @throws BadRequestException
1453 * @throws ImagickException
1454 * @throws InternalServerErrorException
1455 * @throws NotFoundException if the results are empty.
1456 * @throws UnauthorizedException
1458 function api_users_lookup($type)
1462 if (!empty($_REQUEST['user_id'])) {
1463 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1465 $users[] = api_get_user(get_app(), $id);
1470 if (empty($users)) {
1471 throw new NotFoundException;
1474 return api_format_data("users", $type, ['users' => $users]);
1477 /// @TODO move to top of file or somewhere better
1478 api_register_func('api/users/lookup', 'api_users_lookup', true);
1481 * Returns statuses that match a specified query.
1483 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1485 * @param string $type Return format: json, xml, atom, rss
1487 * @return array|string
1488 * @throws BadRequestException if the "q" parameter is missing.
1489 * @throws ForbiddenException
1490 * @throws ImagickException
1491 * @throws InternalServerErrorException
1492 * @throws UnauthorizedException
1494 function api_search($type)
1497 $user_info = api_get_user($a);
1499 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1501 if (empty($_REQUEST['q'])) {
1502 throw new BadRequestException('q parameter is required.');
1505 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1508 $data['status'] = [];
1510 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1511 if (!empty($_REQUEST['rpp'])) {
1512 $count = $_REQUEST['rpp'];
1513 } elseif (!empty($_REQUEST['count'])) {
1514 $count = $_REQUEST['count'];
1517 $since_id = defaults($_REQUEST, 'since_id', 0);
1518 $max_id = defaults($_REQUEST, 'max_id', 0);
1519 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1520 $start = $page * $count;
1521 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1522 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1523 $searchTerm = $matches[1];
1524 $condition = ["`oid` > ?
1525 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1526 AND `otype` = ? AND `type` = ? AND `term` = ?",
1527 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1529 $condition[0] .= ' AND `oid` <= ?';
1530 $condition[] = $max_id;
1532 $terms = DBA::select('term', ['oid'], $condition, []);
1534 while ($term = DBA::fetch($terms)) {
1535 $itemIds[] = $term['oid'];
1539 if (empty($itemIds)) {
1540 return api_format_data('statuses', $type, $data);
1543 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1544 if ($exclude_replies) {
1545 $preCondition[] = '`id` = `parent`';
1548 $condition = [implode(' AND ', $preCondition)];
1550 $condition = ["`id` > ?
1551 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1552 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1553 AND `body` LIKE CONCAT('%',?,'%')",
1554 $since_id, api_user(), $_REQUEST['q']];
1556 $condition[0] .= ' AND `id` <= ?';
1557 $condition[] = $max_id;
1561 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1563 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1565 bindComments($data['status']);
1567 return api_format_data('statuses', $type, $data);
1570 /// @TODO move to top of file or somewhere better
1571 api_register_func('api/search/tweets', 'api_search', true);
1572 api_register_func('api/search', 'api_search', true);
1575 * Returns the most recent statuses posted by the user and the users they follow.
1577 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1579 * @param string $type Return type (atom, rss, xml, json)
1581 * @return array|string
1582 * @throws BadRequestException
1583 * @throws ForbiddenException
1584 * @throws ImagickException
1585 * @throws InternalServerErrorException
1586 * @throws UnauthorizedException
1587 * @todo Optional parameters
1588 * @todo Add reply info
1590 function api_statuses_home_timeline($type)
1593 $user_info = api_get_user($a);
1595 if (api_user() === false || $user_info === false) {
1596 throw new ForbiddenException();
1599 unset($_REQUEST["user_id"]);
1600 unset($_GET["user_id"]);
1602 unset($_REQUEST["screen_name"]);
1603 unset($_GET["screen_name"]);
1605 // get last network messages
1608 $count = defaults($_REQUEST, 'count', 20);
1609 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1613 $since_id = defaults($_REQUEST, 'since_id', 0);
1614 $max_id = defaults($_REQUEST, 'max_id', 0);
1615 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1616 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1618 $start = $page * $count;
1620 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1621 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1624 $condition[0] .= " AND `item`.`id` <= ?";
1625 $condition[] = $max_id;
1627 if ($exclude_replies) {
1628 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1630 if ($conversation_id > 0) {
1631 $condition[0] .= " AND `item`.`parent` = ?";
1632 $condition[] = $conversation_id;
1635 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1636 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1638 $items = Item::inArray($statuses);
1640 $ret = api_format_items($items, $user_info, false, $type);
1642 // Set all posts from the query above to seen
1644 foreach ($items as $item) {
1645 $idarray[] = intval($item["id"]);
1648 if (!empty($idarray)) {
1649 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1651 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1657 $data = ['status' => $ret];
1662 $data = api_rss_extra($a, $data, $user_info);
1666 return api_format_data("statuses", $type, $data);
1670 /// @TODO move to top of file or somewhere better
1671 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1672 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1675 * Returns the most recent statuses from public users.
1677 * @param string $type Return type (atom, rss, xml, json)
1679 * @return array|string
1680 * @throws BadRequestException
1681 * @throws ForbiddenException
1682 * @throws ImagickException
1683 * @throws InternalServerErrorException
1684 * @throws UnauthorizedException
1686 function api_statuses_public_timeline($type)
1689 $user_info = api_get_user($a);
1691 if (api_user() === false || $user_info === false) {
1692 throw new ForbiddenException();
1695 // get last network messages
1698 $count = defaults($_REQUEST, 'count', 20);
1699 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1703 $since_id = defaults($_REQUEST, 'since_id', 0);
1704 $max_id = defaults($_REQUEST, 'max_id', 0);
1705 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1706 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1708 $start = $page * $count;
1710 if ($exclude_replies && !$conversation_id) {
1711 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1712 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1715 $condition[0] .= " AND `thread`.`iid` <= ?";
1716 $condition[] = $max_id;
1719 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1720 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1722 $r = Item::inArray($statuses);
1724 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1725 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1728 $condition[0] .= " AND `item`.`id` <= ?";
1729 $condition[] = $max_id;
1731 if ($conversation_id > 0) {
1732 $condition[0] .= " AND `item`.`parent` = ?";
1733 $condition[] = $conversation_id;
1736 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1737 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1739 $r = Item::inArray($statuses);
1742 $ret = api_format_items($r, $user_info, false, $type);
1746 $data = ['status' => $ret];
1751 $data = api_rss_extra($a, $data, $user_info);
1755 return api_format_data("statuses", $type, $data);
1758 /// @TODO move to top of file or somewhere better
1759 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1762 * Returns the most recent statuses posted by users this node knows about.
1764 * @brief Returns the list of public federated posts this node knows about
1766 * @param string $type Return format: json, xml, atom, rss
1767 * @return array|string
1768 * @throws BadRequestException
1769 * @throws ForbiddenException
1770 * @throws ImagickException
1771 * @throws InternalServerErrorException
1772 * @throws UnauthorizedException
1774 function api_statuses_networkpublic_timeline($type)
1777 $user_info = api_get_user($a);
1779 if (api_user() === false || $user_info === false) {
1780 throw new ForbiddenException();
1783 $since_id = defaults($_REQUEST, 'since_id', 0);
1784 $max_id = defaults($_REQUEST, 'max_id', 0);
1787 $count = defaults($_REQUEST, 'count', 20);
1788 $page = defaults($_REQUEST, 'page', 1);
1792 $start = ($page - 1) * $count;
1794 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1795 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1798 $condition[0] .= " AND `thread`.`iid` <= ?";
1799 $condition[] = $max_id;
1802 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1803 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1805 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1809 $data = ['status' => $ret];
1814 $data = api_rss_extra($a, $data, $user_info);
1818 return api_format_data("statuses", $type, $data);
1821 /// @TODO move to top of file or somewhere better
1822 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1825 * Returns a single status.
1827 * @param string $type Return type (atom, rss, xml, json)
1829 * @return array|string
1830 * @throws BadRequestException
1831 * @throws ForbiddenException
1832 * @throws ImagickException
1833 * @throws InternalServerErrorException
1834 * @throws UnauthorizedException
1835 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1837 function api_statuses_show($type)
1840 $user_info = api_get_user($a);
1842 if (api_user() === false || $user_info === false) {
1843 throw new ForbiddenException();
1847 $id = intval(defaults($a->argv, 3, 0));
1850 $id = intval(defaults($_REQUEST, 'id', 0));
1855 $id = intval(defaults($a->argv, 4, 0));
1858 Logger::log('API: api_statuses_show: ' . $id);
1860 $conversation = !empty($_REQUEST['conversation']);
1862 // try to fetch the item for the local user - or the public item, if there is no local one
1863 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1864 if (!DBA::isResult($uri_item)) {
1865 throw new BadRequestException("There is no status with this id.");
1868 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1869 if (!DBA::isResult($item)) {
1870 throw new BadRequestException("There is no status with this id.");
1875 if ($conversation) {
1876 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1877 $params = ['order' => ['id' => true]];
1879 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1883 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1885 /// @TODO How about copying this to above methods which don't check $r ?
1886 if (!DBA::isResult($statuses)) {
1887 throw new BadRequestException("There is no status with this id.");
1890 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1892 if ($conversation) {
1893 $data = ['status' => $ret];
1894 return api_format_data("statuses", $type, $data);
1896 $data = ['status' => $ret[0]];
1897 return api_format_data("status", $type, $data);
1901 /// @TODO move to top of file or somewhere better
1902 api_register_func('api/statuses/show', 'api_statuses_show', true);
1906 * @param string $type Return type (atom, rss, xml, json)
1908 * @return array|string
1909 * @throws BadRequestException
1910 * @throws ForbiddenException
1911 * @throws ImagickException
1912 * @throws InternalServerErrorException
1913 * @throws UnauthorizedException
1914 * @todo nothing to say?
1916 function api_conversation_show($type)
1919 $user_info = api_get_user($a);
1921 if (api_user() === false || $user_info === false) {
1922 throw new ForbiddenException();
1926 $id = intval(defaults($a->argv , 3 , 0));
1927 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1928 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1929 $count = intval(defaults($_REQUEST, 'count' , 20));
1930 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1935 $start = $page * $count;
1938 $id = intval(defaults($_REQUEST, 'id', 0));
1943 $id = intval(defaults($a->argv, 4, 0));
1946 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1948 // try to fetch the item for the local user - or the public item, if there is no local one
1949 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1950 if (!DBA::isResult($item)) {
1951 throw new BadRequestException("There is no status with this id.");
1954 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1955 if (!DBA::isResult($parent)) {
1956 throw new BadRequestException("There is no status with this id.");
1959 $id = $parent['id'];
1961 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1962 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1965 $condition[0] .= " AND `item`.`id` <= ?";
1966 $condition[] = $max_id;
1969 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1970 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1972 if (!DBA::isResult($statuses)) {
1973 throw new BadRequestException("There is no status with id $id.");
1976 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1978 $data = ['status' => $ret];
1979 return api_format_data("statuses", $type, $data);
1982 /// @TODO move to top of file or somewhere better
1983 api_register_func('api/conversation/show', 'api_conversation_show', true);
1984 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1989 * @param string $type Return type (atom, rss, xml, json)
1991 * @return array|string
1992 * @throws BadRequestException
1993 * @throws ForbiddenException
1994 * @throws ImagickException
1995 * @throws InternalServerErrorException
1996 * @throws UnauthorizedException
1997 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1999 function api_statuses_repeat($type)
2005 if (api_user() === false) {
2006 throw new ForbiddenException();
2012 $id = intval(defaults($a->argv, 3, 0));
2015 $id = intval(defaults($_REQUEST, 'id', 0));
2020 $id = intval(defaults($a->argv, 4, 0));
2023 Logger::log('API: api_statuses_repeat: '.$id);
2025 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2026 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2028 if (DBA::isResult($item) && $item['body'] != "") {
2029 if (strpos($item['body'], "[/share]") !== false) {
2030 $pos = strpos($item['body'], "[share");
2031 $post = substr($item['body'], $pos);
2033 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2035 $post .= $item['body'];
2036 $post .= "[/share]";
2038 $_REQUEST['body'] = $post;
2039 $_REQUEST['profile_uid'] = api_user();
2040 $_REQUEST['api_source'] = true;
2042 if (empty($_REQUEST['source'])) {
2043 $_REQUEST["source"] = api_source();
2046 $item_id = item_post($a);
2048 throw new ForbiddenException();
2051 // output the post that we just posted.
2053 return api_status_show($type, $item_id);
2056 /// @TODO move to top of file or somewhere better
2057 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2060 * Destroys a specific status.
2062 * @param string $type Return type (atom, rss, xml, json)
2064 * @return array|string
2065 * @throws BadRequestException
2066 * @throws ForbiddenException
2067 * @throws ImagickException
2068 * @throws InternalServerErrorException
2069 * @throws UnauthorizedException
2070 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2072 function api_statuses_destroy($type)
2076 if (api_user() === false) {
2077 throw new ForbiddenException();
2083 $id = intval(defaults($a->argv, 3, 0));
2086 $id = intval(defaults($_REQUEST, 'id', 0));
2091 $id = intval(defaults($a->argv, 4, 0));
2094 Logger::log('API: api_statuses_destroy: '.$id);
2096 $ret = api_statuses_show($type);
2098 Item::deleteForUser(['id' => $id], api_user());
2103 /// @TODO move to top of file or somewhere better
2104 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2107 * Returns the most recent mentions.
2109 * @param string $type Return type (atom, rss, xml, json)
2111 * @return array|string
2112 * @throws BadRequestException
2113 * @throws ForbiddenException
2114 * @throws ImagickException
2115 * @throws InternalServerErrorException
2116 * @throws UnauthorizedException
2117 * @see http://developer.twitter.com/doc/get/statuses/mentions
2119 function api_statuses_mentions($type)
2122 $user_info = api_get_user($a);
2124 if (api_user() === false || $user_info === false) {
2125 throw new ForbiddenException();
2128 unset($_REQUEST["user_id"]);
2129 unset($_GET["user_id"]);
2131 unset($_REQUEST["screen_name"]);
2132 unset($_GET["screen_name"]);
2134 // get last network messages
2137 $since_id = defaults($_REQUEST, 'since_id', 0);
2138 $max_id = defaults($_REQUEST, 'max_id' , 0);
2139 $count = defaults($_REQUEST, 'count' , 20);
2140 $page = defaults($_REQUEST, 'page' , 1);
2145 $start = ($page - 1) * $count;
2147 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2148 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2149 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2152 $condition[0] .= " AND `item`.`id` <= ?";
2153 $condition[] = $max_id;
2156 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2157 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2159 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2161 $data = ['status' => $ret];
2166 $data = api_rss_extra($a, $data, $user_info);
2170 return api_format_data("statuses", $type, $data);
2173 /// @TODO move to top of file or somewhere better
2174 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2175 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2178 * Returns the most recent statuses posted by the user.
2180 * @brief Returns a user's public timeline
2182 * @param string $type Either "json" or "xml"
2183 * @return string|array
2184 * @throws BadRequestException
2185 * @throws ForbiddenException
2186 * @throws ImagickException
2187 * @throws InternalServerErrorException
2188 * @throws UnauthorizedException
2189 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2191 function api_statuses_user_timeline($type)
2194 $user_info = api_get_user($a);
2196 if (api_user() === false || $user_info === false) {
2197 throw new ForbiddenException();
2201 "api_statuses_user_timeline: api_user: ". api_user() .
2202 "\nuser_info: ".print_r($user_info, true) .
2203 "\n_REQUEST: ".print_r($_REQUEST, true),
2207 $since_id = defaults($_REQUEST, 'since_id', 0);
2208 $max_id = defaults($_REQUEST, 'max_id', 0);
2209 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2210 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2213 $count = defaults($_REQUEST, 'count', 20);
2214 $page = defaults($_REQUEST, 'page', 1);
2218 $start = ($page - 1) * $count;
2220 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2221 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2223 if ($user_info['self'] == 1) {
2224 $condition[0] .= ' AND `item`.`wall` ';
2227 if ($exclude_replies) {
2228 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2231 if ($conversation_id > 0) {
2232 $condition[0] .= " AND `item`.`parent` = ?";
2233 $condition[] = $conversation_id;
2237 $condition[0] .= " AND `item`.`id` <= ?";
2238 $condition[] = $max_id;
2241 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2242 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2244 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2248 $data = ['status' => $ret];
2253 $data = api_rss_extra($a, $data, $user_info);
2257 return api_format_data("statuses", $type, $data);
2260 /// @TODO move to top of file or somewhere better
2261 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2264 * Star/unstar an item.
2265 * param: id : id of the item
2267 * @param string $type Return type (atom, rss, xml, json)
2269 * @return array|string
2270 * @throws BadRequestException
2271 * @throws ForbiddenException
2272 * @throws ImagickException
2273 * @throws InternalServerErrorException
2274 * @throws UnauthorizedException
2275 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2277 function api_favorites_create_destroy($type)
2281 if (api_user() === false) {
2282 throw new ForbiddenException();
2285 // for versioned api.
2286 /// @TODO We need a better global soluton
2287 $action_argv_id = 2;
2288 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2289 $action_argv_id = 3;
2292 if ($a->argc <= $action_argv_id) {
2293 throw new BadRequestException("Invalid request.");
2295 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2296 if ($a->argc == $action_argv_id + 2) {
2297 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2299 $itemid = intval(defaults($_REQUEST, 'id', 0));
2302 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2304 if (!DBA::isResult($item)) {
2305 throw new BadRequestException("Invalid item.");
2310 $item['starred'] = 1;
2313 $item['starred'] = 0;
2316 throw new BadRequestException("Invalid action ".$action);
2319 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2322 throw new InternalServerErrorException("DB error");
2326 $user_info = api_get_user($a);
2327 $rets = api_format_items([$item], $user_info, false, $type);
2330 $data = ['status' => $ret];
2335 $data = api_rss_extra($a, $data, $user_info);
2339 return api_format_data("status", $type, $data);
2342 /// @TODO move to top of file or somewhere better
2343 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2344 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2347 * Returns the most recent favorite statuses.
2349 * @param string $type Return type (atom, rss, xml, json)
2351 * @return string|array
2352 * @throws BadRequestException
2353 * @throws ForbiddenException
2354 * @throws ImagickException
2355 * @throws InternalServerErrorException
2356 * @throws UnauthorizedException
2358 function api_favorites($type)
2363 $user_info = api_get_user($a);
2365 if (api_user() === false || $user_info === false) {
2366 throw new ForbiddenException();
2371 // in friendica starred item are private
2372 // return favorites only for self
2373 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2375 if ($user_info['self'] == 0) {
2379 $since_id = defaults($_REQUEST, 'since_id', 0);
2380 $max_id = defaults($_REQUEST, 'max_id', 0);
2381 $count = defaults($_GET, 'count', 20);
2382 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2387 $start = $page*$count;
2389 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2390 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2392 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2395 $condition[0] .= " AND `item`.`id` <= ?";
2396 $condition[] = $max_id;
2399 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2401 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2406 $data = ['status' => $ret];
2411 $data = api_rss_extra($a, $data, $user_info);
2415 return api_format_data("statuses", $type, $data);
2418 /// @TODO move to top of file or somewhere better
2419 api_register_func('api/favorites', 'api_favorites', true);
2423 * @param array $item
2424 * @param array $recipient
2425 * @param array $sender
2428 * @throws InternalServerErrorException
2430 function api_format_messages($item, $recipient, $sender)
2432 // standard meta information
2434 'id' => $item['id'],
2435 'sender_id' => $sender['id'],
2437 'recipient_id' => $recipient['id'],
2438 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2439 'sender_screen_name' => $sender['screen_name'],
2440 'recipient_screen_name' => $recipient['screen_name'],
2441 'sender' => $sender,
2442 'recipient' => $recipient,
2444 'friendica_seen' => defaults($item, 'seen', 0),
2445 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2448 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2449 if (isset($ret['sender']['uid'])) {
2450 unset($ret['sender']['uid']);
2452 if (isset($ret['sender']['self'])) {
2453 unset($ret['sender']['self']);
2455 if (isset($ret['recipient']['uid'])) {
2456 unset($ret['recipient']['uid']);
2458 if (isset($ret['recipient']['self'])) {
2459 unset($ret['recipient']['self']);
2462 //don't send title to regular StatusNET requests to avoid confusing these apps
2463 if (!empty($_GET['getText'])) {
2464 $ret['title'] = $item['title'];
2465 if ($_GET['getText'] == 'html') {
2466 $ret['text'] = BBCode::convert($item['body'], false);
2467 } elseif ($_GET['getText'] == 'plain') {
2468 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2471 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2473 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2474 unset($ret['sender']);
2475 unset($ret['recipient']);
2483 * @param array $item
2486 * @throws InternalServerErrorException
2488 function api_convert_item($item)
2490 $body = $item['body'];
2491 $attachments = api_get_attachments($body);
2493 // Workaround for ostatus messages where the title is identically to the body
2494 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2495 $statusbody = trim(HTML::toPlaintext($html, 0));
2497 // handle data: images
2498 $statusbody = api_format_items_embeded_images($item, $statusbody);
2500 $statustitle = trim($item['title']);
2502 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2503 $statustext = trim($statusbody);
2505 $statustext = trim($statustitle."\n\n".$statusbody);
2508 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2509 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2512 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2514 // Workaround for clients with limited HTML parser functionality
2515 $search = ["<br>", "<blockquote>", "</blockquote>",
2516 "<h1>", "</h1>", "<h2>", "</h2>",
2517 "<h3>", "</h3>", "<h4>", "</h4>",
2518 "<h5>", "</h5>", "<h6>", "</h6>"];
2519 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2520 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2521 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2522 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2523 $statushtml = str_replace($search, $replace, $statushtml);
2525 if ($item['title'] != "") {
2526 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2530 $oldtext = $statushtml;
2531 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2532 } while ($oldtext != $statushtml);
2534 if (substr($statushtml, 0, 4) == '<br>') {
2535 $statushtml = substr($statushtml, 4);
2538 if (substr($statushtml, 0, -4) == '<br>') {
2539 $statushtml = substr($statushtml, -4);
2542 // feeds without body should contain the link
2543 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2544 $statushtml .= BBCode::convert($item['plink']);
2547 $entities = api_get_entitities($statustext, $body);
2550 "text" => $statustext,
2551 "html" => $statushtml,
2552 "attachments" => $attachments,
2553 "entities" => $entities
2559 * @param string $body
2562 * @throws InternalServerErrorException
2564 function api_get_attachments(&$body)
2567 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2569 $URLSearchString = "^\[\]";
2570 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2578 foreach ($images[1] as $image) {
2579 $imagedata = Image::getInfoFromURL($image);
2582 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2586 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2587 foreach ($images[0] as $orig) {
2588 $body = str_replace($orig, "", $body);
2592 return $attachments;
2597 * @param string $text
2598 * @param string $bbcode
2601 * @throws InternalServerErrorException
2602 * @todo Links at the first character of the post
2604 function api_get_entitities(&$text, $bbcode)
2606 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2608 if ($include_entities != "true") {
2609 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2611 foreach ($images[1] as $image) {
2612 $replace = ProxyUtils::proxifyUrl($image);
2613 $text = str_replace($image, $replace, $text);
2618 $bbcode = BBCode::cleanPictureLinks($bbcode);
2620 // Change pure links in text to bbcode uris
2621 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2624 $entities["hashtags"] = [];
2625 $entities["symbols"] = [];
2626 $entities["urls"] = [];
2627 $entities["user_mentions"] = [];
2629 $URLSearchString = "^\[\]";
2631 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2633 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2634 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2635 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2637 $bbcode = preg_replace(
2638 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2639 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2642 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2644 $bbcode = preg_replace(
2645 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2646 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2649 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2651 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2653 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2654 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2657 foreach ($urls[1] as $id => $url) {
2658 //$start = strpos($text, $url, $offset);
2659 $start = iconv_strpos($text, $url, 0, "UTF-8");
2660 if (!($start === false)) {
2661 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2665 ksort($ordered_urls);
2668 //foreach ($urls[1] AS $id=>$url) {
2669 foreach ($ordered_urls as $url) {
2670 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2671 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2673 $display_url = $url["title"];
2675 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2676 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2678 if (strlen($display_url) > 26) {
2679 $display_url = substr($display_url, 0, 25)."…";
2683 //$start = strpos($text, $url, $offset);
2684 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2685 if (!($start === false)) {
2686 $entities["urls"][] = ["url" => $url["url"],
2687 "expanded_url" => $url["url"],
2688 "display_url" => $display_url,
2689 "indices" => [$start, $start+strlen($url["url"])]];
2690 $offset = $start + 1;
2694 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2695 $ordered_images = [];
2696 foreach ($images[1] as $image) {
2697 //$start = strpos($text, $url, $offset);
2698 $start = iconv_strpos($text, $image, 0, "UTF-8");
2699 if (!($start === false)) {
2700 $ordered_images[$start] = $image;
2703 //$entities["media"] = array();
2706 foreach ($ordered_images as $url) {
2707 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2708 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2710 if (strlen($display_url) > 26) {
2711 $display_url = substr($display_url, 0, 25)."…";
2714 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2715 if (!($start === false)) {
2716 $image = Image::getInfoFromURL($url);
2718 // If image cache is activated, then use the following sizes:
2719 // thumb (150), small (340), medium (600) and large (1024)
2720 if (!Config::get("system", "proxy_disabled")) {
2721 $media_url = ProxyUtils::proxifyUrl($url);
2724 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2725 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2727 if (($image[0] > 150) || ($image[1] > 150)) {
2728 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2729 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2732 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2733 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2735 if (($image[0] > 600) || ($image[1] > 600)) {
2736 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2737 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2741 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2744 $entities["media"][] = [
2746 "id_str" => (string) ($start + 1),
2747 "indices" => [$start, $start+strlen($url)],
2748 "media_url" => Strings::normaliseLink($media_url),
2749 "media_url_https" => $media_url,
2751 "display_url" => $display_url,
2752 "expanded_url" => $url,
2756 $offset = $start + 1;
2765 * @param array $item
2766 * @param string $text
2770 function api_format_items_embeded_images($item, $text)
2772 $text = preg_replace_callback(
2773 '|data:image/([^;]+)[^=]+=*|m',
2774 function () use ($item) {
2775 return System::baseUrl() . '/display/' . $item['guid'];
2783 * @brief return <a href='url'>name</a> as array
2785 * @param string $txt text
2790 function api_contactlink_to_array($txt)
2793 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2794 if ($r && count($match)==3) {
2796 'name' => $match[2],
2810 * @brief return likes, dislikes and attend status for item
2812 * @param array $item array
2813 * @param string $type Return type (atom, rss, xml, json)
2816 * likes => int count,
2817 * dislikes => int count
2818 * @throws BadRequestException
2819 * @throws ImagickException
2820 * @throws InternalServerErrorException
2821 * @throws UnauthorizedException
2823 function api_format_items_activities($item, $type = "json")
2832 'attendmaybe' => [],
2835 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2836 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2838 while ($parent_item = Item::fetch($ret)) {
2839 // not used as result should be structured like other user data
2840 //builtin_activity_puller($i, $activities);
2842 // get user data and add it to the array of the activity
2843 $user = api_get_user($a, $parent_item['author-id']);
2844 switch ($parent_item['verb']) {
2846 $activities['like'][] = $user;
2848 case ACTIVITY_DISLIKE:
2849 $activities['dislike'][] = $user;
2851 case ACTIVITY_ATTEND:
2852 $activities['attendyes'][] = $user;
2854 case ACTIVITY_ATTENDNO:
2855 $activities['attendno'][] = $user;
2857 case ACTIVITY_ATTENDMAYBE:
2858 $activities['attendmaybe'][] = $user;
2867 if ($type == "xml") {
2868 $xml_activities = [];
2869 foreach ($activities as $k => $v) {
2870 // change xml element from "like" to "friendica:like"
2871 $xml_activities["friendica:".$k] = $v;
2872 // add user data into xml output
2874 foreach ($v as $user) {
2875 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2878 $activities = $xml_activities;
2886 * @brief return data from profiles
2888 * @param array $profile_row array containing data from db table 'profile'
2890 * @throws InternalServerErrorException
2892 function api_format_items_profiles($profile_row)
2895 'profile_id' => $profile_row['id'],
2896 'profile_name' => $profile_row['profile-name'],
2897 'is_default' => $profile_row['is-default'] ? true : false,
2898 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2899 'profile_photo' => $profile_row['photo'],
2900 'profile_thumb' => $profile_row['thumb'],
2901 'publish' => $profile_row['publish'] ? true : false,
2902 'net_publish' => $profile_row['net-publish'] ? true : false,
2903 'description' => $profile_row['pdesc'],
2904 'date_of_birth' => $profile_row['dob'],
2905 'address' => $profile_row['address'],
2906 'city' => $profile_row['locality'],
2907 'region' => $profile_row['region'],
2908 'postal_code' => $profile_row['postal-code'],
2909 'country' => $profile_row['country-name'],
2910 'hometown' => $profile_row['hometown'],
2911 'gender' => $profile_row['gender'],
2912 'marital' => $profile_row['marital'],
2913 'marital_with' => $profile_row['with'],
2914 'marital_since' => $profile_row['howlong'],
2915 'sexual' => $profile_row['sexual'],
2916 'politic' => $profile_row['politic'],
2917 'religion' => $profile_row['religion'],
2918 'public_keywords' => $profile_row['pub_keywords'],
2919 'private_keywords' => $profile_row['prv_keywords'],
2920 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2921 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2922 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2923 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2924 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2925 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2926 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2927 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2928 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2929 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2930 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2931 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2932 'homepage' => $profile_row['homepage'],
2939 * @brief format items to be returned by api
2941 * @param array $items array of items
2942 * @param array $user_info
2943 * @param bool $filter_user filter items by $user_info
2944 * @param string $type Return type (atom, rss, xml, json)
2946 * @throws BadRequestException
2947 * @throws ImagickException
2948 * @throws InternalServerErrorException
2949 * @throws UnauthorizedException
2951 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2953 $a = \Friendica\BaseObject::getApp();
2957 foreach ((array)$items as $item) {
2958 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2960 // Look if the posts are matching if they should be filtered by user id
2961 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2965 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2974 * @param array $item Item record
2975 * @param string $type Return format (atom, rss, xml, json)
2976 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2977 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2978 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2979 * @return array API-formatted status
2980 * @throws BadRequestException
2981 * @throws ImagickException
2982 * @throws InternalServerErrorException
2983 * @throws UnauthorizedException
2985 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2987 $a = \Friendica\BaseObject::getApp();
2989 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2990 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2993 localize_item($item);
2995 $in_reply_to = api_in_reply_to($item);
2997 $converted = api_convert_item($item);
2999 if ($type == "xml") {
3000 $geo = "georss:point";
3006 'text' => $converted["text"],
3007 'truncated' => false,
3008 'created_at'=> api_date($item['created']),
3009 'in_reply_to_status_id' => $in_reply_to['status_id'],
3010 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3011 'source' => (($item['app']) ? $item['app'] : 'web'),
3012 'id' => intval($item['id']),
3013 'id_str' => (string) intval($item['id']),
3014 'in_reply_to_user_id' => $in_reply_to['user_id'],
3015 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3016 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3018 'favorited' => $item['starred'] ? true : false,
3019 'user' => $status_user,
3020 'friendica_author' => $author_user,
3021 'friendica_owner' => $owner_user,
3022 'friendica_private' => $item['private'] == 1,
3023 //'entities' => NULL,
3024 'statusnet_html' => $converted["html"],
3025 'statusnet_conversation_id' => $item['parent'],
3026 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3027 'friendica_activities' => api_format_items_activities($item, $type),
3030 if (count($converted["attachments"]) > 0) {
3031 $status["attachments"] = $converted["attachments"];
3034 if (count($converted["entities"]) > 0) {
3035 $status["entities"] = $converted["entities"];
3038 if ($status["source"] == 'web') {
3039 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3040 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3041 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3044 $retweeted_item = [];
3047 if ($item["id"] == $item["parent"]) {
3048 $body = $item['body'];
3049 $retweeted_item = api_share_as_retweet($item);
3050 if ($body != $item['body']) {
3051 $quoted_item = $retweeted_item;
3052 $retweeted_item = [];
3056 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3057 $announce = api_get_announce($item);
3058 if (!empty($announce)) {
3059 $retweeted_item = $item;
3061 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3065 if (!empty($quoted_item)) {
3066 $conv_quoted = api_convert_item($quoted_item);
3067 $quoted_status = $status;
3068 unset($quoted_status['friendica_author']);
3069 unset($quoted_status['friendica_owner']);
3070 unset($quoted_status['friendica_activities']);
3071 unset($quoted_status['friendica_private']);
3072 unset($quoted_status['statusnet_conversation_id']);
3073 $quoted_status['text'] = $conv_quoted['text'];
3074 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3076 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3077 } catch (BadRequestException $e) {
3078 // user not found. should be found?
3079 /// @todo check if the user should be always found
3080 $quoted_status["user"] = [];
3084 if (!empty($retweeted_item)) {
3085 $retweeted_status = $status;
3086 unset($retweeted_status['friendica_author']);
3087 unset($retweeted_status['friendica_owner']);
3088 unset($retweeted_status['friendica_activities']);
3089 unset($retweeted_status['friendica_private']);
3090 unset($retweeted_status['statusnet_conversation_id']);
3091 $status['user'] = $status['friendica_owner'];
3093 $retweeted_status["user"] = api_get_user($a, $retweeted_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 $retweeted_status["user"] = [];
3100 $rt_converted = api_convert_item($retweeted_item);
3102 $retweeted_status['text'] = $rt_converted["text"];
3103 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3104 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3106 if (!empty($quoted_status)) {
3107 $retweeted_status['quoted_status'] = $quoted_status;
3110 $status['friendica_author'] = $retweeted_status['user'];
3111 $status['retweeted_status'] = $retweeted_status;
3112 } elseif (!empty($quoted_status)) {
3113 $root_status = api_convert_item($item);
3115 $status['text'] = $root_status["text"];
3116 $status['statusnet_html'] = $root_status["html"];
3117 $status['quoted_status'] = $quoted_status;
3120 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3121 unset($status["user"]["uid"]);
3122 unset($status["user"]["self"]);
3124 if ($item["coord"] != "") {
3125 $coords = explode(' ', $item["coord"]);
3126 if (count($coords) == 2) {
3127 if ($type == "json") {
3128 $status["geo"] = ['type' => 'Point',
3129 'coordinates' => [(float) $coords[0],
3130 (float) $coords[1]]];
3131 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3132 $status["georss:point"] = $item["coord"];
3141 * Returns the remaining number of API requests available to the user before the API limit is reached.
3143 * @param string $type Return type (atom, rss, xml, json)
3145 * @return array|string
3148 function api_account_rate_limit_status($type)
3150 if ($type == "xml") {
3152 'remaining-hits' => '150',
3153 '@attributes' => ["type" => "integer"],
3154 'hourly-limit' => '150',
3155 '@attributes2' => ["type" => "integer"],
3156 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3157 '@attributes3' => ["type" => "datetime"],
3158 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3159 '@attributes4' => ["type" => "integer"],
3163 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3164 'remaining_hits' => '150',
3165 'hourly_limit' => '150',
3166 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3170 return api_format_data('hash', $type, ['hash' => $hash]);
3173 /// @TODO move to top of file or somewhere better
3174 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3177 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3179 * @param string $type Return type (atom, rss, xml, json)
3181 * @return array|string
3183 function api_help_test($type)
3185 if ($type == 'xml') {
3191 return api_format_data('ok', $type, ["ok" => $ok]);
3194 /// @TODO move to top of file or somewhere better
3195 api_register_func('api/help/test', 'api_help_test', false);
3198 * Returns all lists the user subscribes to.
3200 * @param string $type Return type (atom, rss, xml, json)
3202 * @return array|string
3203 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3205 function api_lists_list($type)
3208 /// @TODO $ret is not filled here?
3209 return api_format_data('lists', $type, ["lists_list" => $ret]);
3212 /// @TODO move to top of file or somewhere better
3213 api_register_func('api/lists/list', 'api_lists_list', true);
3214 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3217 * Returns all groups the user owns.
3219 * @param string $type Return type (atom, rss, xml, json)
3221 * @return array|string
3222 * @throws BadRequestException
3223 * @throws ForbiddenException
3224 * @throws ImagickException
3225 * @throws InternalServerErrorException
3226 * @throws UnauthorizedException
3227 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3229 function api_lists_ownerships($type)
3233 if (api_user() === false) {
3234 throw new ForbiddenException();
3238 $user_info = api_get_user($a);
3239 $uid = $user_info['uid'];
3241 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3243 // loop through all groups
3245 foreach ($groups as $group) {
3246 if ($group['visible']) {
3252 'name' => $group['name'],
3253 'id' => intval($group['id']),
3254 'id_str' => (string) $group['id'],
3255 'user' => $user_info,
3259 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3262 /// @TODO move to top of file or somewhere better
3263 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3266 * Returns recent statuses from users in the specified group.
3268 * @param string $type Return type (atom, rss, xml, json)
3270 * @return array|string
3271 * @throws BadRequestException
3272 * @throws ForbiddenException
3273 * @throws ImagickException
3274 * @throws InternalServerErrorException
3275 * @throws UnauthorizedException
3276 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3278 function api_lists_statuses($type)
3282 $user_info = api_get_user($a);
3283 if (api_user() === false || $user_info === false) {
3284 throw new ForbiddenException();
3287 unset($_REQUEST["user_id"]);
3288 unset($_GET["user_id"]);
3290 unset($_REQUEST["screen_name"]);
3291 unset($_GET["screen_name"]);
3293 if (empty($_REQUEST['list_id'])) {
3294 throw new BadRequestException('list_id not specified');
3298 $count = defaults($_REQUEST, 'count', 20);
3299 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3303 $since_id = defaults($_REQUEST, 'since_id', 0);
3304 $max_id = defaults($_REQUEST, 'max_id', 0);
3305 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3306 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3308 $start = $page * $count;
3310 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3311 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3314 $condition[0] .= " AND `item`.`id` <= ?";
3315 $condition[] = $max_id;
3317 if ($exclude_replies > 0) {
3318 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3320 if ($conversation_id > 0) {
3321 $condition[0] .= " AND `item`.`parent` = ?";
3322 $condition[] = $conversation_id;
3325 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3326 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3328 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3330 $data = ['status' => $items];
3335 $data = api_rss_extra($a, $data, $user_info);
3339 return api_format_data("statuses", $type, $data);
3342 /// @TODO move to top of file or somewhere better
3343 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3346 * Considers friends and followers lists to be private and won't return
3347 * anything if any user_id parameter is passed.
3349 * @brief Returns either the friends of the follower list
3351 * @param string $qtype Either "friends" or "followers"
3352 * @return boolean|array
3353 * @throws BadRequestException
3354 * @throws ForbiddenException
3355 * @throws ImagickException
3356 * @throws InternalServerErrorException
3357 * @throws UnauthorizedException
3359 function api_statuses_f($qtype)
3363 if (api_user() === false) {
3364 throw new ForbiddenException();
3368 $count = defaults($_GET, 'count', 20);
3369 $page = defaults($_GET, 'page', 1);
3373 $start = ($page - 1) * $count;
3375 $user_info = api_get_user($a);
3377 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3378 /* this is to stop Hotot to load friends multiple times
3379 * I'm not sure if I'm missing return something or
3380 * is a bug in hotot. Workaround, meantime
3384 return array('$users' => $ret);*/
3389 if ($qtype == 'friends') {
3390 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3391 } elseif ($qtype == 'followers') {
3392 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3395 // friends and followers only for self
3396 if ($user_info['self'] == 0) {
3397 $sql_extra = " AND false ";
3400 if ($qtype == 'blocks') {
3401 $sql_filter = 'AND `blocked` AND NOT `pending`';
3402 } elseif ($qtype == 'incoming') {
3403 $sql_filter = 'AND `pending`';
3405 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3423 foreach ($r as $cid) {
3424 $user = api_get_user($a, $cid['nurl']);
3425 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3426 unset($user["uid"]);
3427 unset($user["self"]);
3434 return ['user' => $ret];
3439 * Returns the user's friends.
3441 * @brief Returns the list of friends of the provided user
3443 * @deprecated By Twitter API in favor of friends/list
3445 * @param string $type Either "json" or "xml"
3446 * @return boolean|string|array
3447 * @throws BadRequestException
3448 * @throws ForbiddenException
3450 function api_statuses_friends($type)
3452 $data = api_statuses_f("friends");
3453 if ($data === false) {
3456 return api_format_data("users", $type, $data);
3460 * Returns the user's followers.
3462 * @brief Returns the list of followers of the provided user
3464 * @deprecated By Twitter API in favor of friends/list
3466 * @param string $type Either "json" or "xml"
3467 * @return boolean|string|array
3468 * @throws BadRequestException
3469 * @throws ForbiddenException
3471 function api_statuses_followers($type)
3473 $data = api_statuses_f("followers");
3474 if ($data === false) {
3477 return api_format_data("users", $type, $data);
3480 /// @TODO move to top of file or somewhere better
3481 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3482 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3485 * Returns the list of blocked users
3487 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3489 * @param string $type Either "json" or "xml"
3491 * @return boolean|string|array
3492 * @throws BadRequestException
3493 * @throws ForbiddenException
3495 function api_blocks_list($type)
3497 $data = api_statuses_f('blocks');
3498 if ($data === false) {
3501 return api_format_data("users", $type, $data);
3504 /// @TODO move to top of file or somewhere better
3505 api_register_func('api/blocks/list', 'api_blocks_list', true);
3508 * Returns the list of pending users IDs
3510 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3512 * @param string $type Either "json" or "xml"
3514 * @return boolean|string|array
3515 * @throws BadRequestException
3516 * @throws ForbiddenException
3518 function api_friendships_incoming($type)
3520 $data = api_statuses_f('incoming');
3521 if ($data === false) {
3526 foreach ($data['user'] as $user) {
3527 $ids[] = $user['id'];
3530 return api_format_data("ids", $type, ['id' => $ids]);
3533 /// @TODO move to top of file or somewhere better
3534 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3537 * Returns the instance's configuration information.
3539 * @param string $type Return type (atom, rss, xml, json)
3541 * @return array|string
3542 * @throws InternalServerErrorException
3544 function api_statusnet_config($type)
3548 $name = Config::get('config', 'sitename');
3549 $server = $a->getHostName();
3550 $logo = System::baseUrl() . '/images/friendica-64.png';
3551 $email = Config::get('config', 'admin_email');
3552 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3553 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3554 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3555 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3556 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3559 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3560 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3561 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3562 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3563 'shorturllength' => '30',
3565 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3566 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3567 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3568 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3573 return api_format_data('config', $type, ['config' => $config]);
3576 /// @TODO move to top of file or somewhere better
3577 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3578 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3582 * @param string $type Return type (atom, rss, xml, json)
3584 * @return array|string
3586 function api_statusnet_version($type)
3589 $fake_statusnet_version = "0.9.7";
3591 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3594 /// @TODO move to top of file or somewhere better
3595 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3596 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3600 * @param string $type Return type (atom, rss, xml, json)
3602 * @return array|string|void
3603 * @throws BadRequestException
3604 * @throws ForbiddenException
3605 * @throws ImagickException
3606 * @throws InternalServerErrorException
3607 * @throws UnauthorizedException
3608 * @todo use api_format_data() to return data
3610 function api_ff_ids($type)
3613 throw new ForbiddenException();
3620 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3623 "SELECT `pcontact`.`id` FROM `contact`
3624 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3625 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3628 if (!DBA::isResult($r)) {
3633 foreach ($r as $rr) {
3634 if ($stringify_ids) {
3637 $ids[] = intval($rr['id']);
3641 return api_format_data("ids", $type, ['id' => $ids]);
3645 * Returns the ID of every user the user is following.
3647 * @param string $type Return type (atom, rss, xml, json)
3649 * @return array|string
3650 * @throws BadRequestException
3651 * @throws ForbiddenException
3652 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3654 function api_friends_ids($type)
3656 return api_ff_ids($type);
3660 * Returns the ID of every user following the user.
3662 * @param string $type Return type (atom, rss, xml, json)
3664 * @return array|string
3665 * @throws BadRequestException
3666 * @throws ForbiddenException
3667 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3669 function api_followers_ids($type)
3671 return api_ff_ids($type);
3674 /// @TODO move to top of file or somewhere better
3675 api_register_func('api/friends/ids', 'api_friends_ids', true);
3676 api_register_func('api/followers/ids', 'api_followers_ids', true);
3679 * Sends a new direct message.
3681 * @param string $type Return type (atom, rss, xml, json)
3683 * @return array|string
3684 * @throws BadRequestException
3685 * @throws ForbiddenException
3686 * @throws ImagickException
3687 * @throws InternalServerErrorException
3688 * @throws NotFoundException
3689 * @throws UnauthorizedException
3690 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3692 function api_direct_messages_new($type)
3696 if (api_user() === false) {
3697 throw new ForbiddenException();
3700 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3704 $sender = api_get_user($a);
3707 if (!empty($_POST['screen_name'])) {
3709 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3711 DBA::escape($_POST['screen_name'])
3714 if (DBA::isResult($r)) {
3715 // Selecting the id by priority, friendica first
3716 api_best_nickname($r);
3718 $recipient = api_get_user($a, $r[0]['nurl']);
3721 $recipient = api_get_user($a, $_POST['user_id']);
3724 if (empty($recipient)) {
3725 throw new NotFoundException('Recipient not found');
3729 if (!empty($_REQUEST['replyto'])) {
3731 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3733 intval($_REQUEST['replyto'])
3735 $replyto = $r[0]['parent-uri'];
3736 $sub = $r[0]['title'];
3738 if (!empty($_REQUEST['title'])) {
3739 $sub = $_REQUEST['title'];
3741 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3745 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3748 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3749 $ret = api_format_messages($r[0], $recipient, $sender);
3751 $ret = ["error"=>$id];
3754 $data = ['direct_message'=>$ret];
3760 $data = api_rss_extra($a, $data, $sender);
3764 return api_format_data("direct-messages", $type, $data);
3767 /// @TODO move to top of file or somewhere better
3768 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3771 * Destroys a direct message.
3773 * @brief delete a direct_message from mail table through api
3775 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3776 * @return string|array
3777 * @throws BadRequestException
3778 * @throws ForbiddenException
3779 * @throws ImagickException
3780 * @throws InternalServerErrorException
3781 * @throws UnauthorizedException
3782 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3784 function api_direct_messages_destroy($type)
3788 if (api_user() === false) {
3789 throw new ForbiddenException();
3793 $user_info = api_get_user($a);
3795 $id = defaults($_REQUEST, 'id', 0);
3797 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3798 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3799 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3801 $uid = $user_info['uid'];
3802 // error if no id or parenturi specified (for clients posting parent-uri as well)
3803 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3804 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3805 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3808 // BadRequestException if no id specified (for clients using Twitter API)
3810 throw new BadRequestException('Message id not specified');
3813 // add parent-uri to sql command if specified by calling app
3814 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3816 // get data of the specified message id
3818 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3823 // error message if specified id is not in database
3824 if (!DBA::isResult($r)) {
3825 if ($verbose == "true") {
3826 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3827 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3829 /// @todo BadRequestException ok for Twitter API clients?
3830 throw new BadRequestException('message id not in database');
3835 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3840 if ($verbose == "true") {
3843 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3844 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3846 $answer = ['result' => 'error', 'message' => 'unknown error'];
3847 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3850 /// @todo return JSON data like Twitter API not yet implemented
3853 /// @TODO move to top of file or somewhere better
3854 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3859 * @brief unfollow contact
3861 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3862 * @return string|array
3863 * @throws BadRequestException
3864 * @throws ForbiddenException
3865 * @throws ImagickException
3866 * @throws InternalServerErrorException
3867 * @throws NotFoundException
3868 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3870 function api_friendships_destroy($type)
3874 if ($uid === false) {
3875 throw new ForbiddenException();
3878 $contact_id = defaults($_REQUEST, 'user_id');
3880 if (empty($contact_id)) {
3881 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3882 throw new BadRequestException("no user_id specified");
3885 // Get Contact by given id
3886 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3888 if(!DBA::isResult($contact)) {
3889 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3890 throw new NotFoundException("no contact found to given ID");
3893 $url = $contact["url"];
3895 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3896 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3897 Strings::normaliseLink($url), $url];
3898 $contact = DBA::selectFirst('contact', [], $condition);
3900 if (!DBA::isResult($contact)) {
3901 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3902 throw new NotFoundException("Not following Contact");
3905 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3906 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3907 throw new ExpectationFailedException("Not supported");
3910 $dissolve = ($contact['rel'] == Contact::SHARING);
3912 $owner = User::getOwnerDataById($uid);
3914 Contact::terminateFriendship($owner, $contact, $dissolve);
3917 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3918 throw new NotFoundException("Error Processing Request");
3921 // Sharing-only contacts get deleted as there no relationship any more
3923 Contact::remove($contact['id']);
3925 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3928 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3929 unset($contact["uid"]);
3930 unset($contact["self"]);
3932 // Set screen_name since Twidere requests it
3933 $contact["screen_name"] = $contact["nick"];
3935 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3937 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3941 * @param string $type Return type (atom, rss, xml, json)
3942 * @param string $box
3943 * @param string $verbose
3945 * @return array|string
3946 * @throws BadRequestException
3947 * @throws ForbiddenException
3948 * @throws ImagickException
3949 * @throws InternalServerErrorException
3950 * @throws UnauthorizedException
3952 function api_direct_messages_box($type, $box, $verbose)
3955 if (api_user() === false) {
3956 throw new ForbiddenException();
3959 $count = defaults($_GET, 'count', 20);
3960 $page = defaults($_REQUEST, 'page', 1) - 1;
3965 $since_id = defaults($_REQUEST, 'since_id', 0);
3966 $max_id = defaults($_REQUEST, 'max_id', 0);
3968 $user_id = defaults($_REQUEST, 'user_id', '');
3969 $screen_name = defaults($_REQUEST, 'screen_name', '');
3972 unset($_REQUEST["user_id"]);
3973 unset($_GET["user_id"]);
3975 unset($_REQUEST["screen_name"]);
3976 unset($_GET["screen_name"]);
3978 $user_info = api_get_user($a);
3979 if ($user_info === false) {
3980 throw new ForbiddenException();
3982 $profile_url = $user_info["url"];
3985 $start = $page * $count;
3990 if ($box=="sentbox") {
3991 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3992 } elseif ($box == "conversation") {
3993 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3994 } elseif ($box == "all") {
3995 $sql_extra = "true";
3996 } elseif ($box == "inbox") {
3997 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4001 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4004 if ($user_id != "") {
4005 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4006 } elseif ($screen_name !="") {
4007 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4011 "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",
4017 if ($verbose == "true" && !DBA::isResult($r)) {
4018 $answer = ['result' => 'error', 'message' => 'no mails available'];
4019 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4023 foreach ($r as $item) {
4024 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4025 $recipient = $user_info;
4026 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4027 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4028 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4029 $sender = $user_info;
4032 if (isset($recipient) && isset($sender)) {
4033 $ret[] = api_format_messages($item, $recipient, $sender);
4038 $data = ['direct_message' => $ret];
4043 $data = api_rss_extra($a, $data, $user_info);
4047 return api_format_data("direct-messages", $type, $data);
4051 * Returns the most recent direct messages sent by the user.
4053 * @param string $type Return type (atom, rss, xml, json)
4055 * @return array|string
4056 * @throws BadRequestException
4057 * @throws ForbiddenException
4058 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4060 function api_direct_messages_sentbox($type)
4062 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4063 return api_direct_messages_box($type, "sentbox", $verbose);
4067 * Returns the most recent direct messages sent to the user.
4069 * @param string $type Return type (atom, rss, xml, json)
4071 * @return array|string
4072 * @throws BadRequestException
4073 * @throws ForbiddenException
4074 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4076 function api_direct_messages_inbox($type)
4078 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4079 return api_direct_messages_box($type, "inbox", $verbose);
4084 * @param string $type Return type (atom, rss, xml, json)
4086 * @return array|string
4087 * @throws BadRequestException
4088 * @throws ForbiddenException
4090 function api_direct_messages_all($type)
4092 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4093 return api_direct_messages_box($type, "all", $verbose);
4098 * @param string $type Return type (atom, rss, xml, json)
4100 * @return array|string
4101 * @throws BadRequestException
4102 * @throws ForbiddenException
4104 function api_direct_messages_conversation($type)
4106 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4107 return api_direct_messages_box($type, "conversation", $verbose);
4110 /// @TODO move to top of file or somewhere better
4111 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4112 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4113 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4114 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4117 * Returns an OAuth Request Token.
4119 * @see https://oauth.net/core/1.0/#auth_step1
4121 function api_oauth_request_token()
4123 $oauth1 = new FKOAuth1();
4125 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4126 } catch (Exception $e) {
4127 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4135 * Returns an OAuth Access Token.
4137 * @return array|string
4138 * @see https://oauth.net/core/1.0/#auth_step3
4140 function api_oauth_access_token()
4142 $oauth1 = new FKOAuth1();
4144 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4145 } catch (Exception $e) {
4146 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4153 /// @TODO move to top of file or somewhere better
4154 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4155 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4159 * @brief delete a complete photoalbum with all containing photos from database through api
4161 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4162 * @return string|array
4163 * @throws BadRequestException
4164 * @throws ForbiddenException
4165 * @throws InternalServerErrorException
4167 function api_fr_photoalbum_delete($type)
4169 if (api_user() === false) {
4170 throw new ForbiddenException();
4173 $album = defaults($_REQUEST, 'album', "");
4175 // we do not allow calls without album string
4177 throw new BadRequestException("no albumname specified");
4179 // check if album is existing
4181 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4185 if (!DBA::isResult($r)) {
4186 throw new BadRequestException("album not available");
4189 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4190 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4191 foreach ($r as $rr) {
4192 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4193 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4195 if (!DBA::isResult($photo_item)) {
4196 throw new InternalServerErrorException("problem with deleting items occured");
4198 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4201 // now let's delete all photos from the album
4202 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4204 // return success of deletion or error message
4206 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4207 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4209 throw new InternalServerErrorException("unknown error - deleting from database failed");
4214 * @brief update the name of the album for all photos of an album
4216 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4217 * @return string|array
4218 * @throws BadRequestException
4219 * @throws ForbiddenException
4220 * @throws InternalServerErrorException
4222 function api_fr_photoalbum_update($type)
4224 if (api_user() === false) {
4225 throw new ForbiddenException();
4228 $album = defaults($_REQUEST, 'album', "");
4229 $album_new = defaults($_REQUEST, 'album_new', "");
4231 // we do not allow calls without album string
4233 throw new BadRequestException("no albumname specified");
4235 if ($album_new == "") {
4236 throw new BadRequestException("no new albumname specified");
4238 // check if album is existing
4239 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4240 throw new BadRequestException("album not available");
4242 // now let's update all photos to the albumname
4243 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4245 // return success of updating or error message
4247 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4248 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4250 throw new InternalServerErrorException("unknown error - updating in database failed");
4256 * @brief list all photos of the authenticated user
4258 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4259 * @return string|array
4260 * @throws ForbiddenException
4261 * @throws InternalServerErrorException
4263 function api_fr_photos_list($type)
4265 if (api_user() === false) {
4266 throw new ForbiddenException();
4269 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4270 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4271 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4272 intval(local_user())
4275 'image/jpeg' => 'jpg',
4276 'image/png' => 'png',
4277 'image/gif' => 'gif'
4279 $data = ['photo'=>[]];
4280 if (DBA::isResult($r)) {
4281 foreach ($r as $rr) {
4283 $photo['id'] = $rr['resource-id'];
4284 $photo['album'] = $rr['album'];
4285 $photo['filename'] = $rr['filename'];
4286 $photo['type'] = $rr['type'];
4287 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4288 $photo['created'] = $rr['created'];
4289 $photo['edited'] = $rr['edited'];
4290 $photo['desc'] = $rr['desc'];
4292 if ($type == "xml") {
4293 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4295 $photo['thumb'] = $thumb;
4296 $data['photo'][] = $photo;
4300 return api_format_data("photos", $type, $data);
4304 * @brief upload a new photo or change an existing photo
4306 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4307 * @return string|array
4308 * @throws BadRequestException
4309 * @throws ForbiddenException
4310 * @throws ImagickException
4311 * @throws InternalServerErrorException
4312 * @throws NotFoundException
4314 function api_fr_photo_create_update($type)
4316 if (api_user() === false) {
4317 throw new ForbiddenException();
4320 $photo_id = defaults($_REQUEST, 'photo_id', null);
4321 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4322 $album = defaults($_REQUEST, 'album', null);
4323 $album_new = defaults($_REQUEST, 'album_new', null);
4324 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4325 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4326 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4327 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4328 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4330 // do several checks on input parameters
4331 // we do not allow calls without album string
4332 if ($album == null) {
4333 throw new BadRequestException("no albumname specified");
4335 // if photo_id == null --> we are uploading a new photo
4336 if ($photo_id == null) {
4339 // error if no media posted in create-mode
4340 if (empty($_FILES['media'])) {
4342 throw new BadRequestException("no media data submitted");
4345 // album_new will be ignored in create-mode
4350 // check if photo is existing in databasei
4351 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4352 throw new BadRequestException("photo not available");
4356 // checks on acl strings provided by clients
4357 $acl_input_error = false;
4358 $acl_input_error |= check_acl_input($allow_cid);
4359 $acl_input_error |= check_acl_input($deny_cid);
4360 $acl_input_error |= check_acl_input($allow_gid);
4361 $acl_input_error |= check_acl_input($deny_gid);
4362 if ($acl_input_error) {
4363 throw new BadRequestException("acl data invalid");
4365 // now let's upload the new media in create-mode
4366 if ($mode == "create") {
4367 $media = $_FILES['media'];
4368 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4370 // return success of updating or error message
4371 if (!is_null($data)) {
4372 return api_format_data("photo_create", $type, $data);
4374 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4378 // now let's do the changes in update-mode
4379 if ($mode == "update") {
4380 $updated_fields = [];
4382 if (!is_null($desc)) {
4383 $updated_fields['desc'] = $desc;
4386 if (!is_null($album_new)) {
4387 $updated_fields['album'] = $album_new;
4390 if (!is_null($allow_cid)) {
4391 $allow_cid = trim($allow_cid);
4392 $updated_fields['allow_cid'] = $allow_cid;
4395 if (!is_null($deny_cid)) {
4396 $deny_cid = trim($deny_cid);
4397 $updated_fields['deny_cid'] = $deny_cid;
4400 if (!is_null($allow_gid)) {
4401 $allow_gid = trim($allow_gid);
4402 $updated_fields['allow_gid'] = $allow_gid;
4405 if (!is_null($deny_gid)) {
4406 $deny_gid = trim($deny_gid);
4407 $updated_fields['deny_gid'] = $deny_gid;
4411 if (count($updated_fields) > 0) {
4412 $nothingtodo = false;
4413 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4415 $nothingtodo = true;
4418 if (!empty($_FILES['media'])) {
4419 $nothingtodo = false;
4420 $media = $_FILES['media'];
4421 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4422 if (!is_null($data)) {
4423 return api_format_data("photo_update", $type, $data);
4427 // return success of updating or error message
4429 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4430 return api_format_data("photo_update", $type, ['$result' => $answer]);
4433 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4434 return api_format_data("photo_update", $type, ['$result' => $answer]);
4436 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4439 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4443 * @brief delete a single photo from the database through api
4445 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4446 * @return string|array
4447 * @throws BadRequestException
4448 * @throws ForbiddenException
4449 * @throws InternalServerErrorException
4451 function api_fr_photo_delete($type)
4453 if (api_user() === false) {
4454 throw new ForbiddenException();
4458 $photo_id = defaults($_REQUEST, 'photo_id', null);
4460 // do several checks on input parameters
4461 // we do not allow calls without photo id
4462 if ($photo_id == null) {
4463 throw new BadRequestException("no photo_id specified");
4466 // check if photo is existing in database
4467 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4468 throw new BadRequestException("photo not available");
4471 // now we can perform on the deletion of the photo
4472 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4474 // return success of deletion or error message
4476 // retrieve the id of the parent element (the photo element)
4477 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4478 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4480 if (!DBA::isResult($photo_item)) {
4481 throw new InternalServerErrorException("problem with deleting items occured");
4483 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4484 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4485 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4487 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4488 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4490 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4496 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4498 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4499 * @return string|array
4500 * @throws BadRequestException
4501 * @throws ForbiddenException
4502 * @throws InternalServerErrorException
4503 * @throws NotFoundException
4505 function api_fr_photo_detail($type)
4507 if (api_user() === false) {
4508 throw new ForbiddenException();
4510 if (empty($_REQUEST['photo_id'])) {
4511 throw new BadRequestException("No photo id.");
4514 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4515 $photo_id = $_REQUEST['photo_id'];
4517 // prepare json/xml output with data from database for the requested photo
4518 $data = prepare_photo_data($type, $scale, $photo_id);
4520 return api_format_data("photo_detail", $type, $data);
4525 * Updates the user’s profile image.
4527 * @brief updates the profile image for the user (either a specified profile or the default profile)
4529 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4531 * @return string|array
4532 * @throws BadRequestException
4533 * @throws ForbiddenException
4534 * @throws ImagickException
4535 * @throws InternalServerErrorException
4536 * @throws NotFoundException
4537 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4539 function api_account_update_profile_image($type)
4541 if (api_user() === false) {
4542 throw new ForbiddenException();
4545 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4547 // error if image data is missing
4548 if (empty($_FILES['image'])) {
4549 throw new BadRequestException("no media data submitted");
4552 // check if specified profile id is valid
4553 if ($profile_id != 0) {
4554 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4555 // error message if specified profile id is not in database
4556 if (!DBA::isResult($profile)) {
4557 throw new BadRequestException("profile_id not available");
4559 $is_default_profile = $profile['is-default'];
4561 $is_default_profile = 1;
4564 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4566 if (!empty($_FILES['image'])) {
4567 $media = $_FILES['image'];
4568 } elseif (!empty($_FILES['media'])) {
4569 $media = $_FILES['media'];
4571 // save new profile image
4572 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4575 if (is_array($media['type'])) {
4576 $filetype = $media['type'][0];
4578 $filetype = $media['type'];
4580 if ($filetype == "image/jpeg") {
4582 } elseif ($filetype == "image/png") {
4585 throw new InternalServerErrorException('Unsupported filetype');
4588 // change specified profile or all profiles to the new resource-id
4589 if ($is_default_profile) {
4590 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4591 Photo::update(['profile' => false], $condition);
4593 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4594 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4595 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4598 Contact::updateSelfFromUserID(api_user(), true);
4600 // Update global directory in background
4601 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4602 if ($url && strlen(Config::get('system', 'directory'))) {
4603 Worker::add(PRIORITY_LOW, "Directory", $url);
4606 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4608 // output for client
4610 return api_account_verify_credentials($type);
4612 // SaveMediaToDatabase failed for some reason
4613 throw new InternalServerErrorException("image upload failed");
4617 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4618 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4619 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4620 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4621 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4622 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4623 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4624 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4625 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4628 * Update user profile
4630 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4632 * @return array|string
4633 * @throws BadRequestException
4634 * @throws ForbiddenException
4635 * @throws ImagickException
4636 * @throws InternalServerErrorException
4637 * @throws UnauthorizedException
4639 function api_account_update_profile($type)
4641 $local_user = api_user();
4642 $api_user = api_get_user(get_app());
4644 if (!empty($_POST['name'])) {
4645 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4646 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4647 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4648 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4651 if (isset($_POST['description'])) {
4652 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4653 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4654 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4657 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4658 // Update global directory in background
4659 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4660 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4663 return api_account_verify_credentials($type);
4666 /// @TODO move to top of file or somewhere better
4667 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4671 * @param string $acl_string
4675 function check_acl_input($acl_string)
4677 if ($acl_string == null || $acl_string == " ") {
4680 $contact_not_found = false;
4682 // split <x><y><z> into array of cid's
4683 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4685 // check for each cid if it is available on server
4686 $cid_array = $array[0];
4687 foreach ($cid_array as $cid) {
4688 $cid = str_replace("<", "", $cid);
4689 $cid = str_replace(">", "", $cid);
4690 $condition = ['id' => $cid, 'uid' => api_user()];
4691 $contact_not_found |= !DBA::exists('contact', $condition);
4693 return $contact_not_found;
4698 * @param string $mediatype
4699 * @param array $media
4700 * @param string $type
4701 * @param string $album
4702 * @param string $allow_cid
4703 * @param string $deny_cid
4704 * @param string $allow_gid
4705 * @param string $deny_gid
4706 * @param string $desc
4707 * @param integer $profile
4708 * @param boolean $visibility
4709 * @param string $photo_id
4711 * @throws BadRequestException
4712 * @throws ForbiddenException
4713 * @throws ImagickException
4714 * @throws InternalServerErrorException
4715 * @throws NotFoundException
4717 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)
4725 if (is_array($media)) {
4726 if (is_array($media['tmp_name'])) {
4727 $src = $media['tmp_name'][0];
4729 $src = $media['tmp_name'];
4731 if (is_array($media['name'])) {
4732 $filename = basename($media['name'][0]);
4734 $filename = basename($media['name']);
4736 if (is_array($media['size'])) {
4737 $filesize = intval($media['size'][0]);
4739 $filesize = intval($media['size']);
4741 if (is_array($media['type'])) {
4742 $filetype = $media['type'][0];
4744 $filetype = $media['type'];
4748 if ($filetype == "") {
4749 $filetype=Image::guessType($filename);
4751 $imagedata = @getimagesize($src);
4753 $filetype = $imagedata['mime'];
4756 "File upload src: " . $src . " - filename: " . $filename .
4757 " - size: " . $filesize . " - type: " . $filetype,
4761 // check if there was a php upload error
4762 if ($filesize == 0 && $media['error'] == 1) {
4763 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4765 // check against max upload size within Friendica instance
4766 $maximagesize = Config::get('system', 'maximagesize');
4767 if ($maximagesize && ($filesize > $maximagesize)) {
4768 $formattedBytes = Strings::formatBytes($maximagesize);
4769 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4772 // create Photo instance with the data of the image
4773 $imagedata = @file_get_contents($src);
4774 $Image = new Image($imagedata, $filetype);
4775 if (!$Image->isValid()) {
4776 throw new InternalServerErrorException("unable to process image data");
4779 // check orientation of image
4780 $Image->orient($src);
4783 // check max length of images on server
4784 $max_length = Config::get('system', 'max_image_length');
4786 $max_length = MAX_IMAGE_LENGTH;
4788 if ($max_length > 0) {
4789 $Image->scaleDown($max_length);
4790 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4792 $width = $Image->getWidth();
4793 $height = $Image->getHeight();
4795 // create a new resource-id if not already provided
4796 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4798 if ($mediatype == "photo") {
4799 // upload normal image (scales 0, 1, 2)
4800 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4802 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4804 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4806 if ($width > 640 || $height > 640) {
4807 $Image->scaleDown(640);
4808 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4810 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4814 if ($width > 320 || $height > 320) {
4815 $Image->scaleDown(320);
4816 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4818 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4821 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4822 } elseif ($mediatype == "profileimage") {
4823 // upload profile image (scales 4, 5, 6)
4824 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4826 if ($width > 300 || $height > 300) {
4827 $Image->scaleDown(300);
4828 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4830 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4834 if ($width > 80 || $height > 80) {
4835 $Image->scaleDown(80);
4836 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4838 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4842 if ($width > 48 || $height > 48) {
4843 $Image->scaleDown(48);
4844 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4846 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4849 $Image->__destruct();
4850 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4853 if (isset($r) && $r) {
4854 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4855 if ($photo_id == null && $mediatype == "photo") {
4856 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4858 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4859 return prepare_photo_data($type, false, $hash);
4861 throw new InternalServerErrorException("image upload failed");
4867 * @param string $hash
4868 * @param string $allow_cid
4869 * @param string $deny_cid
4870 * @param string $allow_gid
4871 * @param string $deny_gid
4872 * @param string $filetype
4873 * @param boolean $visibility
4874 * @throws InternalServerErrorException
4876 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4878 // get data about the api authenticated user
4879 $uri = Item::newURI(intval(api_user()));
4880 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4883 $arr['guid'] = System::createUUID();
4884 $arr['uid'] = intval(api_user());
4886 $arr['parent-uri'] = $uri;
4887 $arr['type'] = 'photo';
4889 $arr['resource-id'] = $hash;
4890 $arr['contact-id'] = $owner_record['id'];
4891 $arr['owner-name'] = $owner_record['name'];
4892 $arr['owner-link'] = $owner_record['url'];
4893 $arr['owner-avatar'] = $owner_record['thumb'];
4894 $arr['author-name'] = $owner_record['name'];
4895 $arr['author-link'] = $owner_record['url'];
4896 $arr['author-avatar'] = $owner_record['thumb'];
4898 $arr['allow_cid'] = $allow_cid;
4899 $arr['allow_gid'] = $allow_gid;
4900 $arr['deny_cid'] = $deny_cid;
4901 $arr['deny_gid'] = $deny_gid;
4902 $arr['visible'] = $visibility;
4906 'image/jpeg' => 'jpg',
4907 'image/png' => 'png',
4908 'image/gif' => 'gif'
4911 // adds link to the thumbnail scale photo
4912 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4913 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4916 // do the magic for storing the item in the database and trigger the federation to other contacts
4922 * @param string $type
4924 * @param string $photo_id
4927 * @throws BadRequestException
4928 * @throws ForbiddenException
4929 * @throws ImagickException
4930 * @throws InternalServerErrorException
4931 * @throws NotFoundException
4932 * @throws UnauthorizedException
4934 function prepare_photo_data($type, $scale, $photo_id)
4937 $user_info = api_get_user($a);
4939 if ($user_info === false) {
4940 throw new ForbiddenException();
4943 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4944 $data_sql = ($scale === false ? "" : "data, ");
4946 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4947 // clients needs to convert this in their way for further processing
4949 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4950 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4951 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4952 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4953 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4954 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4956 intval(local_user()),
4957 DBA::escape($photo_id),
4962 'image/jpeg' => 'jpg',
4963 'image/png' => 'png',
4964 'image/gif' => 'gif'
4967 // prepare output data for photo
4968 if (DBA::isResult($r)) {
4969 $data = ['photo' => $r[0]];
4970 $data['photo']['id'] = $data['photo']['resource-id'];
4971 if ($scale !== false) {
4972 $data['photo']['data'] = base64_encode($data['photo']['data']);
4974 unset($data['photo']['datasize']); //needed only with scale param
4976 if ($type == "xml") {
4977 $data['photo']['links'] = [];
4978 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4979 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4981 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4984 $data['photo']['link'] = [];
4985 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4987 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4988 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4992 unset($data['photo']['resource-id']);
4993 unset($data['photo']['minscale']);
4994 unset($data['photo']['maxscale']);
4996 throw new NotFoundException();
4999 // retrieve item element for getting activities (like, dislike etc.) related to photo
5000 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5001 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5003 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5005 // retrieve comments on photo
5006 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5007 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5009 $statuses = Item::selectForUser(api_user(), [], $condition);
5011 // prepare output of comments
5012 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5014 if ($type == "xml") {
5016 foreach ($commentData as $comment) {
5017 $comments[$k++ . ":comment"] = $comment;
5020 foreach ($commentData as $comment) {
5021 $comments[] = $comment;
5024 $data['photo']['friendica_comments'] = $comments;
5026 // include info if rights on photo and rights on item are mismatching
5027 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5028 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5029 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5030 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5031 $data['photo']['rights_mismatch'] = $rights_mismatch;
5038 * Similar as /mod/redir.php
5039 * redirect to 'url' after dfrn auth
5041 * Why this when there is mod/redir.php already?
5042 * This use api_user() and api_login()
5045 * c_url: url of remote contact to auth to
5046 * url: string, url to redirect after auth
5048 function api_friendica_remoteauth()
5050 $url = defaults($_GET, 'url', '');
5051 $c_url = defaults($_GET, 'c_url', '');
5053 if ($url === '' || $c_url === '') {
5054 throw new BadRequestException("Wrong parameters.");
5057 $c_url = Strings::normaliseLink($c_url);
5061 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5063 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5064 throw new BadRequestException("Unknown contact");
5067 $cid = $contact['id'];
5069 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
5071 if ($contact['duplex'] && $contact['issued-id']) {
5072 $orig_id = $contact['issued-id'];
5073 $dfrn_id = '1:' . $orig_id;
5075 if ($contact['duplex'] && $contact['dfrn-id']) {
5076 $orig_id = $contact['dfrn-id'];
5077 $dfrn_id = '0:' . $orig_id;
5080 $sec = Strings::getRandomHex();
5082 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5083 'sec' => $sec, 'expire' => time() + 45];
5084 DBA::insert('profile_check', $fields);
5086 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5087 $dest = ($url ? '&destination_url=' . $url : '');
5089 System::externalRedirect(
5090 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5091 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5092 . '&type=profile&sec=' . $sec . $dest
5095 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5098 * Return an item with announcer data if it had been announced
5100 * @param array $item Item array
5101 * @return array Item array with announce data
5103 function api_get_announce($item)
5105 // Quit if the item already has got a different owner and author
5106 if ($item['owner-id'] != $item['author-id']) {
5110 // Don't change original or Diaspora posts
5111 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5115 // Quit if we do now the original author and it had been a post from a native network
5116 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5120 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5121 $activity = Item::activityToIndex(ACTIVITY2_ANNOUNCE);
5122 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5123 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5124 if (!DBA::isResult($announce)) {
5128 return array_merge($item, $announce);
5132 * @brief Return the item shared, if the item contains only the [share] tag
5134 * @param array $item Sharer item
5135 * @return array|false Shared item or false if not a reshare
5136 * @throws ImagickException
5137 * @throws InternalServerErrorException
5139 function api_share_as_retweet(&$item)
5141 $body = trim($item["body"]);
5143 if (Diaspora::isReshare($body, false) === false) {
5144 if ($item['author-id'] == $item['owner-id']) {
5147 // Reshares from OStatus, ActivityPub and Twitter
5148 $reshared_item = $item;
5149 $reshared_item['owner-id'] = $reshared_item['author-id'];
5150 $reshared_item['owner-link'] = $reshared_item['author-link'];
5151 $reshared_item['owner-name'] = $reshared_item['author-name'];
5152 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5153 return $reshared_item;
5157 /// @TODO "$1" should maybe mean '$1' ?
5158 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5160 * Skip if there is no shared message in there
5161 * we already checked this in diaspora::isReshare()
5162 * but better one more than one less...
5164 if (($body == $attributes) || empty($attributes)) {
5168 // build the fake reshared item
5169 $reshared_item = $item;
5172 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5173 if (!empty($matches[1])) {
5174 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5177 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5178 if (!empty($matches[1])) {
5179 $author = $matches[1];
5183 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5184 if (!empty($matches[1])) {
5185 $profile = $matches[1];
5188 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5189 if (!empty($matches[1])) {
5190 $profile = $matches[1];
5194 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5195 if (!empty($matches[1])) {
5196 $avatar = $matches[1];
5199 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5200 if (!empty($matches[1])) {
5201 $avatar = $matches[1];
5205 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5206 if (!empty($matches[1])) {
5207 $link = $matches[1];
5210 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5211 if (!empty($matches[1])) {
5212 $link = $matches[1];
5216 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5217 if (!empty($matches[1])) {
5218 $posted = $matches[1];
5221 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5222 if (!empty($matches[1])) {
5223 $posted = $matches[1];
5226 if (!preg_match("/(.*?)\[share.*?\]\s?(.*?)\s?\[\/share\]\s?(.*?)/ism", $body, $matches)) {
5230 $pre_body = trim($matches[1]);
5231 if ($pre_body != '') {
5232 $item['body'] = $pre_body;
5235 $shared_body = trim($matches[2]);
5237 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5241 $reshared_item["share-pre-body"] = $pre_body;
5242 $reshared_item["body"] = $shared_body;
5243 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5244 $reshared_item["author-name"] = $author;
5245 $reshared_item["author-link"] = $profile;
5246 $reshared_item["author-avatar"] = $avatar;
5247 $reshared_item["plink"] = $link;
5248 $reshared_item["created"] = $posted;
5249 $reshared_item["edited"] = $posted;
5251 return $reshared_item;
5256 * @param string $profile
5258 * @return string|false
5259 * @throws InternalServerErrorException
5260 * @todo remove trailing junk from profile url
5261 * @todo pump.io check has to check the website
5263 function api_get_nick($profile)
5268 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5269 DBA::escape(Strings::normaliseLink($profile))
5272 if (DBA::isResult($r)) {
5273 $nick = $r[0]["nick"];
5278 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5279 DBA::escape(Strings::normaliseLink($profile))
5282 if (DBA::isResult($r)) {
5283 $nick = $r[0]["nick"];
5288 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5289 if ($friendica != $profile) {
5295 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5296 if ($diaspora != $profile) {
5302 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5303 if ($twitter != $profile) {
5310 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5311 if ($StatusnetHost != $profile) {
5312 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5313 if ($StatusnetUser != $profile) {
5314 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5315 $user = json_decode($UserData);
5317 $nick = $user->screen_name;
5323 // To-Do: look at the page if its really a pumpio site
5324 //if (!$nick == "") {
5325 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5326 // if ($pumpio != $profile)
5328 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5341 * @param array $item
5346 function api_in_reply_to($item)
5350 $in_reply_to['status_id'] = null;
5351 $in_reply_to['user_id'] = null;
5352 $in_reply_to['status_id_str'] = null;
5353 $in_reply_to['user_id_str'] = null;
5354 $in_reply_to['screen_name'] = null;
5356 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5357 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5358 if (DBA::isResult($parent)) {
5359 $in_reply_to['status_id'] = intval($parent['id']);
5361 $in_reply_to['status_id'] = intval($item['parent']);
5364 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5366 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5367 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5369 if (DBA::isResult($parent)) {
5370 if ($parent['author-nick'] == "") {
5371 $parent['author-nick'] = api_get_nick($parent['author-link']);
5374 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5375 $in_reply_to['user_id'] = intval($parent['author-id']);
5376 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5379 // There seems to be situation, where both fields are identical:
5380 // https://github.com/friendica/friendica/issues/1010
5381 // This is a bugfix for that.
5382 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5383 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']]);
5384 $in_reply_to['status_id'] = null;
5385 $in_reply_to['user_id'] = null;
5386 $in_reply_to['status_id_str'] = null;
5387 $in_reply_to['user_id_str'] = null;
5388 $in_reply_to['screen_name'] = null;
5392 return $in_reply_to;
5397 * @param string $text
5400 * @throws InternalServerErrorException
5402 function api_clean_plain_items($text)
5404 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5406 $text = BBCode::cleanPictureLinks($text);
5407 $URLSearchString = "^\[\]";
5409 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5411 if ($include_entities == "true") {
5412 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5415 // Simplify "attachment" element
5416 $text = api_clean_attachments($text);
5422 * @brief Removes most sharing information for API text export
5424 * @param string $body The original body
5426 * @return string Cleaned body
5427 * @throws InternalServerErrorException
5429 function api_clean_attachments($body)
5431 $data = BBCode::getAttachmentData($body);
5438 if (isset($data["text"])) {
5439 $body = $data["text"];
5441 if (($body == "") && isset($data["title"])) {
5442 $body = $data["title"];
5444 if (isset($data["url"])) {
5445 $body .= "\n".$data["url"];
5447 $body .= $data["after"];
5454 * @param array $contacts
5458 function api_best_nickname(&$contacts)
5462 if (count($contacts) == 0) {
5466 foreach ($contacts as $contact) {
5467 if ($contact["network"] == "") {
5468 $contact["network"] = "dfrn";
5469 $best_contact = [$contact];
5473 if (sizeof($best_contact) == 0) {
5474 foreach ($contacts as $contact) {
5475 if ($contact["network"] == "dfrn") {
5476 $best_contact = [$contact];
5481 if (sizeof($best_contact) == 0) {
5482 foreach ($contacts as $contact) {
5483 if ($contact["network"] == "dspr") {
5484 $best_contact = [$contact];
5489 if (sizeof($best_contact) == 0) {
5490 foreach ($contacts as $contact) {
5491 if ($contact["network"] == "stat") {
5492 $best_contact = [$contact];
5497 if (sizeof($best_contact) == 0) {
5498 foreach ($contacts as $contact) {
5499 if ($contact["network"] == "pump") {
5500 $best_contact = [$contact];
5505 if (sizeof($best_contact) == 0) {
5506 foreach ($contacts as $contact) {
5507 if ($contact["network"] == "twit") {
5508 $best_contact = [$contact];
5513 if (sizeof($best_contact) == 1) {
5514 $contacts = $best_contact;
5516 $contacts = [$contacts[0]];
5521 * Return all or a specified group of the user with the containing contacts.
5523 * @param string $type Return type (atom, rss, xml, json)
5525 * @return array|string
5526 * @throws BadRequestException
5527 * @throws ForbiddenException
5528 * @throws ImagickException
5529 * @throws InternalServerErrorException
5530 * @throws UnauthorizedException
5532 function api_friendica_group_show($type)
5536 if (api_user() === false) {
5537 throw new ForbiddenException();
5541 $user_info = api_get_user($a);
5542 $gid = defaults($_REQUEST, 'gid', 0);
5543 $uid = $user_info['uid'];
5545 // get data of the specified group id or all groups if not specified
5548 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5552 // error message if specified gid is not in database
5553 if (!DBA::isResult($r)) {
5554 throw new BadRequestException("gid not available");
5558 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5563 // loop through all groups and retrieve all members for adding data in the user array
5565 foreach ($r as $rr) {
5566 $members = Contact::getByGroupId($rr['id']);
5569 if ($type == "xml") {
5570 $user_element = "users";
5572 foreach ($members as $member) {
5573 $user = api_get_user($a, $member['nurl']);
5574 $users[$k++.":user"] = $user;
5577 $user_element = "user";
5578 foreach ($members as $member) {
5579 $user = api_get_user($a, $member['nurl']);
5583 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5585 return api_format_data("groups", $type, ['group' => $grps]);
5587 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5591 * Delete the specified group of the user.
5593 * @param string $type Return type (atom, rss, xml, json)
5595 * @return array|string
5596 * @throws BadRequestException
5597 * @throws ForbiddenException
5598 * @throws ImagickException
5599 * @throws InternalServerErrorException
5600 * @throws UnauthorizedException
5602 function api_friendica_group_delete($type)
5606 if (api_user() === false) {
5607 throw new ForbiddenException();
5611 $user_info = api_get_user($a);
5612 $gid = defaults($_REQUEST, 'gid', 0);
5613 $name = defaults($_REQUEST, 'name', "");
5614 $uid = $user_info['uid'];
5616 // error if no gid specified
5617 if ($gid == 0 || $name == "") {
5618 throw new BadRequestException('gid or name not specified');
5621 // get data of the specified group id
5623 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5627 // error message if specified gid is not in database
5628 if (!DBA::isResult($r)) {
5629 throw new BadRequestException('gid not available');
5632 // get data of the specified group id and group name
5634 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5639 // error message if specified gid is not in database
5640 if (!DBA::isResult($rname)) {
5641 throw new BadRequestException('wrong group name');
5645 $ret = Group::removeByName($uid, $name);
5648 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5649 return api_format_data("group_delete", $type, ['result' => $success]);
5651 throw new BadRequestException('other API error');
5654 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5659 * @param string $type Return type (atom, rss, xml, json)
5661 * @return array|string
5662 * @throws BadRequestException
5663 * @throws ForbiddenException
5664 * @throws ImagickException
5665 * @throws InternalServerErrorException
5666 * @throws UnauthorizedException
5667 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5669 function api_lists_destroy($type)
5673 if (api_user() === false) {
5674 throw new ForbiddenException();
5678 $user_info = api_get_user($a);
5679 $gid = defaults($_REQUEST, 'list_id', 0);
5680 $uid = $user_info['uid'];
5682 // error if no gid specified
5684 throw new BadRequestException('gid not specified');
5687 // get data of the specified group id
5688 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5689 // error message if specified gid is not in database
5691 throw new BadRequestException('gid not available');
5694 if (Group::remove($gid)) {
5696 'name' => $group['name'],
5697 'id' => intval($gid),
5698 'id_str' => (string) $gid,
5699 'user' => $user_info
5702 return api_format_data("lists", $type, ['lists' => $list]);
5705 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5708 * Add a new group to the database.
5710 * @param string $name Group name
5711 * @param int $uid User ID
5712 * @param array $users List of users to add to the group
5715 * @throws BadRequestException
5717 function group_create($name, $uid, $users = [])
5719 // error if no name specified
5721 throw new BadRequestException('group name not specified');
5724 // get data of the specified group name
5726 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5730 // error message if specified group name already exists
5731 if (DBA::isResult($rname)) {
5732 throw new BadRequestException('group name already exists');
5735 // check if specified group name is a deleted group
5737 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5741 // error message if specified group name already exists
5742 if (DBA::isResult($rname)) {
5743 $reactivate_group = true;
5747 $ret = Group::create($uid, $name);
5749 $gid = Group::getIdByName($uid, $name);
5751 throw new BadRequestException('other API error');
5755 $erroraddinguser = false;
5757 foreach ($users as $user) {
5758 $cid = $user['cid'];
5759 // check if user really exists as contact
5761 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5765 if (count($contact)) {
5766 Group::addMember($gid, $cid);
5768 $erroraddinguser = true;
5769 $errorusers[] = $cid;
5773 // return success message incl. missing users in array
5774 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5776 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5780 * Create the specified group with the posted array of contacts.
5782 * @param string $type Return type (atom, rss, xml, json)
5784 * @return array|string
5785 * @throws BadRequestException
5786 * @throws ForbiddenException
5787 * @throws ImagickException
5788 * @throws InternalServerErrorException
5789 * @throws UnauthorizedException
5791 function api_friendica_group_create($type)
5795 if (api_user() === false) {
5796 throw new ForbiddenException();
5800 $user_info = api_get_user($a);
5801 $name = defaults($_REQUEST, 'name', "");
5802 $uid = $user_info['uid'];
5803 $json = json_decode($_POST['json'], true);
5804 $users = $json['user'];
5806 $success = group_create($name, $uid, $users);
5808 return api_format_data("group_create", $type, ['result' => $success]);
5810 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5813 * Create a new group.
5815 * @param string $type Return type (atom, rss, xml, json)
5817 * @return array|string
5818 * @throws BadRequestException
5819 * @throws ForbiddenException
5820 * @throws ImagickException
5821 * @throws InternalServerErrorException
5822 * @throws UnauthorizedException
5823 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5825 function api_lists_create($type)
5829 if (api_user() === false) {
5830 throw new ForbiddenException();
5834 $user_info = api_get_user($a);
5835 $name = defaults($_REQUEST, 'name', "");
5836 $uid = $user_info['uid'];
5838 $success = group_create($name, $uid);
5839 if ($success['success']) {
5841 'name' => $success['name'],
5842 'id' => intval($success['gid']),
5843 'id_str' => (string) $success['gid'],
5844 'user' => $user_info
5847 return api_format_data("lists", $type, ['lists'=>$grp]);
5850 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5853 * Update the specified group with the posted array of contacts.
5855 * @param string $type Return type (atom, rss, xml, json)
5857 * @return array|string
5858 * @throws BadRequestException
5859 * @throws ForbiddenException
5860 * @throws ImagickException
5861 * @throws InternalServerErrorException
5862 * @throws UnauthorizedException
5864 function api_friendica_group_update($type)
5868 if (api_user() === false) {
5869 throw new ForbiddenException();
5873 $user_info = api_get_user($a);
5874 $uid = $user_info['uid'];
5875 $gid = defaults($_REQUEST, 'gid', 0);
5876 $name = defaults($_REQUEST, 'name', "");
5877 $json = json_decode($_POST['json'], true);
5878 $users = $json['user'];
5880 // error if no name specified
5882 throw new BadRequestException('group name not specified');
5885 // error if no gid specified
5887 throw new BadRequestException('gid not specified');
5891 $members = Contact::getByGroupId($gid);
5892 foreach ($members as $member) {
5893 $cid = $member['id'];
5894 foreach ($users as $user) {
5895 $found = ($user['cid'] == $cid ? true : false);
5897 if (!isset($found) || !$found) {
5898 Group::removeMemberByName($uid, $name, $cid);
5903 $erroraddinguser = false;
5905 foreach ($users as $user) {
5906 $cid = $user['cid'];
5907 // check if user really exists as contact
5909 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5914 if (count($contact)) {
5915 Group::addMember($gid, $cid);
5917 $erroraddinguser = true;
5918 $errorusers[] = $cid;
5922 // return success message incl. missing users in array
5923 $status = ($erroraddinguser ? "missing user" : "ok");
5924 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5925 return api_format_data("group_update", $type, ['result' => $success]);
5928 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5931 * Update information about a group.
5933 * @param string $type Return type (atom, rss, xml, json)
5935 * @return array|string
5936 * @throws BadRequestException
5937 * @throws ForbiddenException
5938 * @throws ImagickException
5939 * @throws InternalServerErrorException
5940 * @throws UnauthorizedException
5941 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5943 function api_lists_update($type)
5947 if (api_user() === false) {
5948 throw new ForbiddenException();
5952 $user_info = api_get_user($a);
5953 $gid = defaults($_REQUEST, 'list_id', 0);
5954 $name = defaults($_REQUEST, 'name', "");
5955 $uid = $user_info['uid'];
5957 // error if no gid specified
5959 throw new BadRequestException('gid not specified');
5962 // get data of the specified group id
5963 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5964 // error message if specified gid is not in database
5966 throw new BadRequestException('gid not available');
5969 if (Group::update($gid, $name)) {
5972 'id' => intval($gid),
5973 'id_str' => (string) $gid,
5974 'user' => $user_info
5977 return api_format_data("lists", $type, ['lists' => $list]);
5981 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5985 * @param string $type Return type (atom, rss, xml, json)
5987 * @return array|string
5988 * @throws BadRequestException
5989 * @throws ForbiddenException
5990 * @throws ImagickException
5991 * @throws InternalServerErrorException
5993 function api_friendica_activity($type)
5997 if (api_user() === false) {
5998 throw new ForbiddenException();
6000 $verb = strtolower($a->argv[3]);
6001 $verb = preg_replace("|\..*$|", "", $verb);
6003 $id = defaults($_REQUEST, 'id', 0);
6005 $res = Item::performLike($id, $verb);
6008 if ($type == "xml") {
6013 return api_format_data('ok', $type, ['ok' => $ok]);
6015 throw new BadRequestException('Error adding activity');
6019 /// @TODO move to top of file or somewhere better
6020 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
6021 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
6022 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
6023 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
6024 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
6025 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
6026 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
6027 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
6028 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
6029 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
6032 * @brief Returns notifications
6034 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6035 * @return string|array
6036 * @throws BadRequestException
6037 * @throws ForbiddenException
6038 * @throws InternalServerErrorException
6040 function api_friendica_notification($type)
6044 if (api_user() === false) {
6045 throw new ForbiddenException();
6048 throw new BadRequestException("Invalid argument count");
6050 $nm = new NotificationsManager();
6052 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
6054 if ($type == "xml") {
6056 if (!empty($notes)) {
6057 foreach ($notes as $note) {
6058 $xmlnotes[] = ["@attributes" => $note];
6064 return api_format_data("notes", $type, ['note' => $notes]);
6068 * POST request with 'id' param as notification id
6070 * @brief Set notification as seen and returns associated item (if possible)
6072 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6073 * @return string|array
6074 * @throws BadRequestException
6075 * @throws ForbiddenException
6076 * @throws ImagickException
6077 * @throws InternalServerErrorException
6078 * @throws UnauthorizedException
6080 function api_friendica_notification_seen($type)
6083 $user_info = api_get_user($a);
6085 if (api_user() === false || $user_info === false) {
6086 throw new ForbiddenException();
6089 throw new BadRequestException("Invalid argument count");
6092 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
6094 $nm = new NotificationsManager();
6095 $note = $nm->getByID($id);
6096 if (is_null($note)) {
6097 throw new BadRequestException("Invalid argument");
6100 $nm->setSeen($note);
6101 if ($note['otype']=='item') {
6102 // would be really better with an ItemsManager and $im->getByID() :-P
6103 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6104 if (DBA::isResult($item)) {
6105 // we found the item, return it to the user
6106 $ret = api_format_items([$item], $user_info, false, $type);
6107 $data = ['status' => $ret];
6108 return api_format_data("status", $type, $data);
6110 // the item can't be found, but we set the note as seen, so we count this as a success
6112 return api_format_data('result', $type, ['result' => "success"]);
6115 /// @TODO move to top of file or somewhere better
6116 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6117 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6120 * @brief update a direct_message to seen state
6122 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6123 * @return string|array (success result=ok, error result=error with error message)
6124 * @throws BadRequestException
6125 * @throws ForbiddenException
6126 * @throws ImagickException
6127 * @throws InternalServerErrorException
6128 * @throws UnauthorizedException
6130 function api_friendica_direct_messages_setseen($type)
6133 if (api_user() === false) {
6134 throw new ForbiddenException();
6138 $user_info = api_get_user($a);
6139 $uid = $user_info['uid'];
6140 $id = defaults($_REQUEST, 'id', 0);
6142 // return error if id is zero
6144 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6145 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6148 // error message if specified id is not in database
6149 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6150 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6151 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6154 // update seen indicator
6155 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6159 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6160 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6162 $answer = ['result' => 'error', 'message' => 'unknown error'];
6163 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6167 /// @TODO move to top of file or somewhere better
6168 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6171 * @brief search for direct_messages containing a searchstring through api
6173 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6174 * @param string $box
6175 * @return string|array (success: success=true if found and search_result contains found messages,
6176 * success=false if nothing was found, search_result='nothing found',
6177 * error: result=error with error message)
6178 * @throws BadRequestException
6179 * @throws ForbiddenException
6180 * @throws ImagickException
6181 * @throws InternalServerErrorException
6182 * @throws UnauthorizedException
6184 function api_friendica_direct_messages_search($type, $box = "")
6188 if (api_user() === false) {
6189 throw new ForbiddenException();
6193 $user_info = api_get_user($a);
6194 $searchstring = defaults($_REQUEST, 'searchstring', "");
6195 $uid = $user_info['uid'];
6197 // error if no searchstring specified
6198 if ($searchstring == "") {
6199 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6200 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6203 // get data for the specified searchstring
6205 "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",
6207 DBA::escape('%'.$searchstring.'%')
6210 $profile_url = $user_info["url"];
6212 // message if nothing was found
6213 if (!DBA::isResult($r)) {
6214 $success = ['success' => false, 'search_results' => 'problem with query'];
6215 } elseif (count($r) == 0) {
6216 $success = ['success' => false, 'search_results' => 'nothing found'];
6219 foreach ($r as $item) {
6220 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6221 $recipient = $user_info;
6222 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6223 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6224 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6225 $sender = $user_info;
6228 if (isset($recipient) && isset($sender)) {
6229 $ret[] = api_format_messages($item, $recipient, $sender);
6232 $success = ['success' => true, 'search_results' => $ret];
6235 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6238 /// @TODO move to top of file or somewhere better
6239 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6242 * @brief return data of all the profiles a user has to the client
6244 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6245 * @return string|array
6246 * @throws BadRequestException
6247 * @throws ForbiddenException
6248 * @throws ImagickException
6249 * @throws InternalServerErrorException
6250 * @throws UnauthorizedException
6252 function api_friendica_profile_show($type)
6256 if (api_user() === false) {
6257 throw new ForbiddenException();
6261 $profile_id = defaults($_REQUEST, 'profile_id', 0);
6263 // retrieve general information about profiles for user
6264 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6265 $directory = Config::get('system', 'directory');
6267 // get data of the specified profile id or all profiles of the user if not specified
6268 if ($profile_id != 0) {
6269 $r = Profile::getById(api_user(), $profile_id);
6270 // error message if specified gid is not in database
6271 if (!DBA::isResult($r)) {
6272 throw new BadRequestException("profile_id not available");
6275 $r = Profile::getListByUser(api_user());
6277 // loop through all returned profiles and retrieve data and users
6280 if (DBA::isResult($r)) {
6281 foreach ($r as $rr) {
6282 $profile = api_format_items_profiles($rr);
6284 // select all users from contact table, loop and prepare standard return for user data
6286 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6287 foreach ($nurls as $nurl) {
6288 $user = api_get_user($a, $nurl['nurl']);
6289 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6291 $profile['users'] = $users;
6293 // add prepared profile data to array for final return
6294 if ($type == "xml") {
6295 $profiles[$k++ . ":profile"] = $profile;
6297 $profiles[] = $profile;
6302 // return settings, authenticated user and profiles data
6303 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6305 $result = ['multi_profiles' => $multi_profiles ? true : false,
6306 'global_dir' => $directory,
6307 'friendica_owner' => api_get_user($a, $self['nurl']),
6308 'profiles' => $profiles];
6309 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6311 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6314 * Returns a list of saved searches.
6316 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6318 * @param string $type Return format: json or xml
6320 * @return string|array
6323 function api_saved_searches_list($type)
6325 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6328 while ($term = DBA::fetch($terms)) {
6330 'created_at' => api_date(time()),
6331 'id' => intval($term['id']),
6332 'id_str' => $term['id'],
6333 'name' => $term['term'],
6335 'query' => $term['term']
6341 return api_format_data("terms", $type, ['terms' => $result]);
6344 /// @TODO move to top of file or somewhere better
6345 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6348 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6350 * @brief Number of comments
6352 * @param object $data [Status, Status]
6356 function bindComments(&$data)
6358 if (count($data) == 0) {
6364 foreach ($data as $item) {
6365 $ids[] = $item['id'];
6368 $idStr = DBA::escape(implode(', ', $ids));
6369 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6370 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6371 $itemsData = DBA::toArray($items);
6373 foreach ($itemsData as $item) {
6374 $comments[$item['parent']] = $item['comments'];
6377 foreach ($data as $idx => $item) {
6379 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6384 @TODO Maybe open to implement?
6386 [pagename] => api/1.1/statuses/lookup.json
6387 [id] => 605138389168451584
6388 [include_cards] => true
6389 [cards_platform] => Android-12
6390 [include_entities] => true
6391 [include_my_retweet] => 1
6393 [include_reply_count] => true
6394 [include_descendent_reply_count] => true
6398 Not implemented by now:
6399 statuses/retweets_of_me
6404 account/update_location
6405 account/update_profile_background_image
6408 friendica/profile/update
6409 friendica/profile/create
6410 friendica/profile/delete
6412 Not implemented in status.net:
6413 statuses/retweeted_to_me
6414 statuses/retweeted_by_me
6415 direct_messages/destroy
6417 account/update_delivery_device
6418 notifications/follow