3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Authentication;
15 use Friendica\Core\Config;
16 use Friendica\Core\Hook;
17 use Friendica\Core\L10n;
18 use Friendica\Core\Logger;
19 use Friendica\Core\NotificationsManager;
20 use Friendica\Core\PConfig;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Mail;
29 use Friendica\Model\Photo;
30 use Friendica\Model\User;
31 use Friendica\Network\FKOAuth1;
32 use Friendica\Network\HTTPException;
33 use Friendica\Network\HTTPException\BadRequestException;
34 use Friendica\Network\HTTPException\ExpectationFailedException;
35 use Friendica\Network\HTTPException\ForbiddenException;
36 use Friendica\Network\HTTPException\InternalServerErrorException;
37 use Friendica\Network\HTTPException\MethodNotAllowedException;
38 use Friendica\Network\HTTPException\NotFoundException;
39 use Friendica\Network\HTTPException\NotImplementedException;
40 use Friendica\Network\HTTPException\TooManyRequestsException;
41 use Friendica\Network\HTTPException\UnauthorizedException;
42 use Friendica\Object\Image;
43 use Friendica\Protocol\Diaspora;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Network;
46 use Friendica\Util\Proxy as ProxyUtils;
47 use Friendica\Util\Strings;
48 use Friendica\Util\XML;
50 require_once 'mod/share.php';
51 require_once 'mod/item.php';
52 require_once 'mod/wall_upload.php';
54 define('API_METHOD_ANY', '*');
55 define('API_METHOD_GET', 'GET');
56 define('API_METHOD_POST', 'POST,PUT');
57 define('API_METHOD_DELETE', 'POST,DELETE');
59 define('API_LOG_PREFIX', 'API {action} - ');
65 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
66 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
67 * into a page, and visitors will post something without noticing it).
69 * @brief Auth API user
73 if (!empty($_SESSION['allow_api'])) {
81 * Clients can send 'source' parameter to be show in post metadata
82 * as "sent via <source>".
83 * Some clients doesn't send a source param, we support ones we know
86 * @brief Get source name from API client
89 * Client source name, default to "api" if unset/unknown
94 if (requestdata('source')) {
95 return requestdata('source');
98 // Support for known clients that doesn't send a source name
99 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
100 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
104 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
106 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
113 * @brief Format date for API
115 * @param string $str Source date, as UTC
116 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
119 function api_date($str)
121 // Wed May 23 06:01:13 +0000 2007
122 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
126 * Register a function to be the endpoint for defined API path.
128 * @brief Register API endpoint
130 * @param string $path API URL path, relative to System::baseUrl()
131 * @param string $func Function name to call on path request
132 * @param bool $auth API need logged user
133 * @param string $method HTTP method reqiured to call this endpoint.
134 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
135 * Default to API_METHOD_ANY
137 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
147 // Workaround for hotot
148 $path = str_replace("api/", "api/1.1/", $path);
158 * Log in user via OAuth1 or Simple HTTP Auth.
159 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
161 * @brief Login API user
164 * @throws InternalServerErrorException
165 * @throws UnauthorizedException
166 * @hook 'authenticate'
168 * 'username' => username from login form
169 * 'password' => password from login form
170 * 'authenticated' => return status,
171 * 'user_record' => return authenticated user record
173 * array $user logged user record
175 function api_login(App $a)
177 $oauth1 = new FKOAuth1();
180 $request = OAuthRequest::from_request();
181 list($consumer, $token) = $oauth1->verify_request($request);
182 if (!is_null($token)) {
183 $oauth1->loginUser($token->uid);
184 Hook::callAll('logged_in', $a->user);
187 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
188 var_dump($consumer, $token);
190 } catch (Exception $e) {
191 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
194 // workaround for HTTP-auth in CGI mode
195 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
196 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
197 if (strlen($userpass)) {
198 list($name, $password) = explode(':', $userpass);
199 $_SERVER['PHP_AUTH_USER'] = $name;
200 $_SERVER['PHP_AUTH_PW'] = $password;
204 if (empty($_SERVER['PHP_AUTH_USER'])) {
205 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
206 header('WWW-Authenticate: Basic realm="Friendica"');
207 throw new UnauthorizedException("This API requires login");
210 $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
211 $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
213 // allow "user@server" login (but ignore 'server' part)
214 $at = strstr($user, "@", true);
219 // next code from mod/auth.php. needs better solution
223 'username' => trim($user),
224 'password' => trim($password),
225 'authenticated' => 0,
226 'user_record' => null,
230 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
231 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
232 * and later addons should not interfere with an earlier one that succeeded.
234 Hook::callAll('authenticate', $addon_auth);
236 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
237 $record = $addon_auth['user_record'];
239 $user_id = User::authenticate(trim($user), trim($password));
240 if ($user_id !== false) {
241 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
245 if (!DBA::isResult($record)) {
246 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
247 header('WWW-Authenticate: Basic realm="Friendica"');
248 //header('HTTP/1.0 401 Unauthorized');
249 //die('This api requires login');
250 throw new UnauthorizedException("This API requires login");
253 Authentication::setAuthenticatedSessionForUser($record);
255 $_SESSION["allow_api"] = true;
257 Hook::callAll('logged_in', $a->user);
261 * API endpoints can define which HTTP method to accept when called.
262 * This function check the current HTTP method agains endpoint
265 * @brief Check HTTP method of called API
267 * @param string $method Required methods, uppercase, separated by comma
270 function api_check_method($method)
272 if ($method == "*") {
275 return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
279 * Authenticate user, call registered API function, set HTTP headers
281 * @brief Main API entry point
284 * @return string|array API call result
287 function api_call(App $a)
289 global $API, $called_api;
292 if (strpos($a->query_string, ".xml") > 0) {
295 if (strpos($a->query_string, ".json") > 0) {
298 if (strpos($a->query_string, ".rss") > 0) {
301 if (strpos($a->query_string, ".atom") > 0) {
306 foreach ($API as $p => $info) {
307 if (strpos($a->query_string, $p) === 0) {
308 if (!api_check_method($info['method'])) {
309 throw new MethodNotAllowedException();
312 $called_api = explode("/", $p);
313 //unset($_SERVER['PHP_AUTH_USER']);
315 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
316 if (!empty($info['auth']) && api_user() === false) {
320 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
321 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
323 $stamp = microtime(true);
324 $return = call_user_func($info['func'], $type);
325 $duration = (float) (microtime(true) - $stamp);
327 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
329 $a->getProfiler()->saveLog($a->getLogger(), API_LOG_PREFIX . 'performance');
331 if (false === $return) {
333 * api function returned false withour throw an
334 * exception. This should not happend, throw a 500
336 throw new InternalServerErrorException();
341 header("Content-Type: text/xml");
344 header("Content-Type: application/json");
345 $json = json_encode(end($return));
346 if (!empty($_GET['callback'])) {
347 $json = $_GET['callback'] . "(" . $json . ")";
352 header("Content-Type: application/rss+xml");
353 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
356 header("Content-Type: application/atom+xml");
357 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
364 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call']);
365 throw new NotImplementedException();
366 } catch (HTTPException $e) {
367 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
368 return api_error($type, $e);
373 * @brief Format API error string
375 * @param string $type Return type (xml, json, rss, as)
376 * @param object $e HTTPException Error object
377 * @return string|array error message formatted as $type
379 function api_error($type, $e)
383 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
384 /// @TODO: https://dev.twitter.com/overview/api/response-codes
386 $error = ["error" => $error,
387 "code" => $e->httpcode . " " . $e->httpdesc,
388 "request" => $a->query_string];
390 $return = api_format_data('status', $type, ['status' => $error]);
394 header("Content-Type: text/xml");
397 header("Content-Type: application/json");
398 $return = json_encode($return);
401 header("Content-Type: application/rss+xml");
404 header("Content-Type: application/atom+xml");
412 * @brief Set values for RSS template
415 * @param array $arr Array to be passed to template
416 * @param array $user_info User info
418 * @throws BadRequestException
419 * @throws ImagickException
420 * @throws InternalServerErrorException
421 * @throws UnauthorizedException
422 * @todo find proper type-hints
424 function api_rss_extra(App $a, $arr, $user_info)
426 if (is_null($user_info)) {
427 $user_info = api_get_user($a);
430 $arr['$user'] = $user_info;
432 'alternate' => $user_info['url'],
433 'self' => System::baseUrl() . "/" . $a->query_string,
434 'base' => System::baseUrl(),
435 'updated' => api_date(null),
436 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
437 'language' => $user_info['lang'],
438 'logo' => System::baseUrl() . "/images/friendica-32.png",
446 * @brief Unique contact to contact url.
448 * @param int $id Contact id
449 * @return bool|string
450 * Contact url or False if contact id is unknown
453 function api_unique_id_to_nurl($id)
455 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
457 if (DBA::isResult($r)) {
465 * @brief Get user info array.
468 * @param int|string $contact_id Contact ID or URL
470 * @throws BadRequestException
471 * @throws ImagickException
472 * @throws InternalServerErrorException
473 * @throws UnauthorizedException
475 function api_get_user(App $a, $contact_id = null)
483 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
485 // Searching for contact URL
486 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
487 $user = DBA::escape(Strings::normaliseLink($contact_id));
489 $extra_query = "AND `contact`.`nurl` = '%s' ";
490 if (api_user() !== false) {
491 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
495 // Searching for contact id with uid = 0
496 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
497 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
500 throw new BadRequestException("User ID ".$contact_id." not found.");
504 $extra_query = "AND `contact`.`nurl` = '%s' ";
505 if (api_user() !== false) {
506 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
510 if (is_null($user) && !empty($_GET['user_id'])) {
511 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
514 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
518 $extra_query = "AND `contact`.`nurl` = '%s' ";
519 if (api_user() !== false) {
520 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
523 if (is_null($user) && !empty($_GET['screen_name'])) {
524 $user = DBA::escape($_GET['screen_name']);
525 $extra_query = "AND `contact`.`nick` = '%s' ";
526 if (api_user() !== false) {
527 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
531 if (is_null($user) && !empty($_GET['profileurl'])) {
532 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
533 $extra_query = "AND `contact`.`nurl` = '%s' ";
534 if (api_user() !== false) {
535 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
539 // $called_api is the API path exploded on / and is expected to have at least 2 elements
540 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
541 $argid = count($called_api);
542 if (!empty($a->argv[$argid])) {
543 $data = explode(".", $a->argv[$argid]);
544 if (count($data) > 1) {
545 list($user, $null) = $data;
548 if (is_numeric($user)) {
549 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
553 $extra_query = "AND `contact`.`nurl` = '%s' ";
554 if (api_user() !== false) {
555 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
559 $user = DBA::escape($user);
560 $extra_query = "AND `contact`.`nick` = '%s' ";
561 if (api_user() !== false) {
562 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
567 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
570 if (api_user() === false) {
574 $user = $_SESSION['uid'];
575 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
579 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
583 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
589 // Selecting the id by priority, friendica first
590 if (is_array($uinfo)) {
591 api_best_nickname($uinfo);
594 // if the contact wasn't found, fetch it from the contacts with uid = 0
595 if (!DBA::isResult($uinfo)) {
597 throw new BadRequestException("User not found.");
600 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
602 if (DBA::isResult($contact)) {
603 // If no nick where given, extract it from the address
604 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
605 $contact['nick'] = api_get_nick($contact["url"]);
609 'id' => $contact["id"],
610 'id_str' => (string) $contact["id"],
611 'name' => $contact["name"],
612 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
613 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
614 'description' => $contact["about"],
615 'profile_image_url' => $contact["micro"],
616 'profile_image_url_https' => $contact["micro"],
617 'profile_image_url_profile_size' => $contact["thumb"],
618 'profile_image_url_large' => $contact["photo"],
619 'url' => $contact["url"],
620 'protected' => false,
621 'followers_count' => 0,
622 'friends_count' => 0,
624 'created_at' => api_date($contact["created"]),
625 'favourites_count' => 0,
627 'time_zone' => 'UTC',
628 'geo_enabled' => false,
630 'statuses_count' => 0,
632 'contributors_enabled' => false,
633 'is_translator' => false,
634 'is_translation_enabled' => false,
635 'following' => false,
636 'follow_request_sent' => false,
637 'statusnet_blocking' => false,
638 'notifications' => false,
639 'statusnet_profile_url' => $contact["url"],
641 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
642 'pid' => Contact::getIdForURL($contact["url"], 0, true),
644 'network' => $contact["network"],
649 throw new BadRequestException("User ".$url." not found.");
653 if ($uinfo[0]['self']) {
654 if ($uinfo[0]['network'] == "") {
655 $uinfo[0]['network'] = Protocol::DFRN;
658 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
659 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
666 // Add a nick if it isn't present there
667 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
668 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
671 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
673 if (!empty($profile['about'])) {
674 $description = $profile['about'];
676 $description = $uinfo[0]["about"];
679 if (!empty($usr['default-location'])) {
680 $location = $usr['default-location'];
681 } elseif (!empty($uinfo[0]["location"])) {
682 $location = $uinfo[0]["location"];
684 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
688 'id' => intval($pcontact_id),
689 'id_str' => (string) intval($pcontact_id),
690 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
691 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
692 'location' => $location,
693 'description' => $description,
694 'profile_image_url' => $uinfo[0]['micro'],
695 'profile_image_url_https' => $uinfo[0]['micro'],
696 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
697 'profile_image_url_large' => $uinfo[0]["photo"],
698 'url' => $uinfo[0]['url'],
699 'protected' => false,
700 'followers_count' => intval($countfollowers),
701 'friends_count' => intval($countfriends),
703 'created_at' => api_date($uinfo[0]['created']),
704 'favourites_count' => intval($starred),
706 'time_zone' => 'UTC',
707 'geo_enabled' => false,
709 'statuses_count' => intval($countitems),
711 'contributors_enabled' => false,
712 'is_translator' => false,
713 'is_translation_enabled' => false,
714 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
715 'follow_request_sent' => false,
716 'statusnet_blocking' => false,
717 'notifications' => false,
719 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
720 'statusnet_profile_url' => $uinfo[0]['url'],
721 'uid' => intval($uinfo[0]['uid']),
722 'cid' => intval($uinfo[0]['cid']),
723 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
724 'self' => $uinfo[0]['self'],
725 'network' => $uinfo[0]['network'],
728 // If this is a local user and it uses Frio, we can get its color preferences.
730 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
731 if ($theme_info['theme'] === 'frio') {
732 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
734 if ($schema && ($schema != '---')) {
735 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
736 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
737 require_once $schemefile;
740 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
741 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
742 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
744 if (empty($nav_bg)) {
747 if (empty($link_color)) {
748 $link_color = "#6fdbe8";
750 if (empty($bgcolor)) {
751 $bgcolor = "#ededed";
754 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
755 $ret['profile_link_color'] = str_replace('#', '', $link_color);
756 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
764 * @brief return api-formatted array for item's author and owner
767 * @param array $item item from db
768 * @return array(array:author, array:owner)
769 * @throws BadRequestException
770 * @throws ImagickException
771 * @throws InternalServerErrorException
772 * @throws UnauthorizedException
774 function api_item_get_user(App $a, $item)
776 $status_user = api_get_user($a, defaults($item, 'author-id', null));
778 $author_user = $status_user;
780 $status_user["protected"] = defaults($item, 'private', 0);
782 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
783 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
785 $owner_user = $author_user;
788 return ([$status_user, $author_user, $owner_user]);
792 * @brief walks recursively through an array with the possibility to change value and key
794 * @param array $array The array to walk through
795 * @param callable $callback The callback function
797 * @return array the transformed array
799 function api_walk_recursive(array &$array, callable $callback)
803 foreach ($array as $k => $v) {
805 if ($callback($v, $k)) {
806 $new_array[$k] = api_walk_recursive($v, $callback);
809 if ($callback($v, $k)) {
820 * @brief Callback function to transform the array in an array that can be transformed in a XML file
822 * @param mixed $item Array item value
823 * @param string $key Array key
825 * @return boolean Should the array item be deleted?
827 function api_reformat_xml(&$item, &$key)
829 if (is_bool($item)) {
830 $item = ($item ? "true" : "false");
833 if (substr($key, 0, 10) == "statusnet_") {
834 $key = "statusnet:".substr($key, 10);
835 } elseif (substr($key, 0, 10) == "friendica_") {
836 $key = "friendica:".substr($key, 10);
838 /// @TODO old-lost code?
840 // $key = "default:".$key;
846 * @brief Creates the XML from a JSON style array
848 * @param array $data JSON style array
849 * @param string $root_element Name of the root element
851 * @return string The XML data
853 function api_create_xml(array $data, $root_element)
855 $childname = key($data);
856 $data2 = array_pop($data);
858 $namespaces = ["" => "http://api.twitter.com",
859 "statusnet" => "http://status.net/schema/api/1/",
860 "friendica" => "http://friendi.ca/schema/api/1/",
861 "georss" => "http://www.georss.org/georss"];
863 /// @todo Auto detection of needed namespaces
864 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
868 if (is_array($data2)) {
870 api_walk_recursive($data2, "api_reformat_xml");
876 foreach ($data2 as $item) {
877 $data4[$i++ . ":" . $childname] = $item;
884 $data3 = [$root_element => $data2];
886 $ret = XML::fromArray($data3, $xml, false, $namespaces);
891 * @brief Formats the data according to the data type
893 * @param string $root_element Name of the root element
894 * @param string $type Return type (atom, rss, xml, json)
895 * @param array $data JSON style array
897 * @return array|string (string|array) XML data or JSON data
899 function api_format_data($root_element, $type, $data)
905 $ret = api_create_xml($data, $root_element);
920 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
921 * returns a 401 status code and an error message if not.
923 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
925 * @param string $type Return type (atom, rss, xml, json)
926 * @return array|string
927 * @throws BadRequestException
928 * @throws ForbiddenException
929 * @throws ImagickException
930 * @throws InternalServerErrorException
931 * @throws UnauthorizedException
933 function api_account_verify_credentials($type)
937 if (api_user() === false) {
938 throw new ForbiddenException();
941 unset($_REQUEST["user_id"]);
942 unset($_GET["user_id"]);
944 unset($_REQUEST["screen_name"]);
945 unset($_GET["screen_name"]);
947 $skip_status = defaults($_REQUEST, 'skip_status', false);
949 $user_info = api_get_user($a);
951 // "verified" isn't used here in the standard
952 unset($user_info["verified"]);
954 // - Adding last status
956 $last_status = api_get_last_status($user_info['pid'], api_user());
958 $user_info['status'] = $last_status;
962 // "uid" and "self" are only needed for some internal stuff, so remove it from here
963 unset($user_info["uid"]);
964 unset($user_info["self"]);
966 return api_format_data("user", $type, ['user' => $user_info]);
969 /// @TODO move to top of file or somewhere better
970 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
973 * Get data from $_POST or $_GET
978 function requestdata($k)
980 if (!empty($_POST[$k])) {
983 if (!empty($_GET[$k])) {
990 * Deprecated function to upload media.
992 * @param string $type Return type (atom, rss, xml, json)
994 * @return array|string
995 * @throws BadRequestException
996 * @throws ForbiddenException
997 * @throws ImagickException
998 * @throws InternalServerErrorException
999 * @throws UnauthorizedException
1001 function api_statuses_mediap($type)
1005 if (api_user() === false) {
1006 Logger::log('api_statuses_update: no user');
1007 throw new ForbiddenException();
1009 $user_info = api_get_user($a);
1011 $_REQUEST['profile_uid'] = api_user();
1012 $_REQUEST['api_source'] = true;
1013 $txt = requestdata('status');
1014 /// @TODO old-lost code?
1015 //$txt = urldecode(requestdata('status'));
1017 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1018 $txt = HTML::toBBCodeVideo($txt);
1019 $config = HTMLPurifier_Config::createDefault();
1020 $config->set('Cache.DefinitionImpl', null);
1021 $purifier = new HTMLPurifier($config);
1022 $txt = $purifier->purify($txt);
1024 $txt = HTML::toBBCode($txt);
1026 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1028 $picture = wall_upload_post($a, false);
1030 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1031 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1032 $item_id = item_post($a);
1034 // output the post that we just posted.
1035 return api_status_show($type, $item_id);
1038 /// @TODO move this to top of file or somewhere better!
1039 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1042 * Updates the user’s current status.
1044 * @param string $type Return type (atom, rss, xml, json)
1046 * @return array|string
1047 * @throws BadRequestException
1048 * @throws ForbiddenException
1049 * @throws ImagickException
1050 * @throws InternalServerErrorException
1051 * @throws TooManyRequestsException
1052 * @throws UnauthorizedException
1053 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1055 function api_statuses_update($type)
1059 if (api_user() === false) {
1060 Logger::log('api_statuses_update: no user');
1061 throw new ForbiddenException();
1066 // convert $_POST array items to the form we use for web posts.
1067 if (requestdata('htmlstatus')) {
1068 $txt = requestdata('htmlstatus');
1069 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1070 $txt = HTML::toBBCodeVideo($txt);
1072 $config = HTMLPurifier_Config::createDefault();
1073 $config->set('Cache.DefinitionImpl', null);
1075 $purifier = new HTMLPurifier($config);
1076 $txt = $purifier->purify($txt);
1078 $_REQUEST['body'] = HTML::toBBCode($txt);
1081 $_REQUEST['body'] = requestdata('status');
1084 $_REQUEST['title'] = requestdata('title');
1086 $parent = requestdata('in_reply_to_status_id');
1088 // Twidere sends "-1" if it is no reply ...
1089 if ($parent == -1) {
1093 if (ctype_digit($parent)) {
1094 $_REQUEST['parent'] = $parent;
1096 $_REQUEST['parent_uri'] = $parent;
1099 if (requestdata('lat') && requestdata('long')) {
1100 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1102 $_REQUEST['profile_uid'] = api_user();
1105 // Check for throttling (maximum posts per day, week and month)
1106 $throttle_day = Config::get('system', 'throttle_limit_day');
1107 if ($throttle_day > 0) {
1108 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1110 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1111 $posts_day = DBA::count('thread', $condition);
1113 if ($posts_day > $throttle_day) {
1114 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1115 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1116 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));
1120 $throttle_week = Config::get('system', 'throttle_limit_week');
1121 if ($throttle_week > 0) {
1122 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1124 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1125 $posts_week = DBA::count('thread', $condition);
1127 if ($posts_week > $throttle_week) {
1128 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1129 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1130 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));
1134 $throttle_month = Config::get('system', 'throttle_limit_month');
1135 if ($throttle_month > 0) {
1136 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1138 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1139 $posts_month = DBA::count('thread', $condition);
1141 if ($posts_month > $throttle_month) {
1142 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1143 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1144 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));
1149 if (!empty($_FILES['media'])) {
1150 // upload the image if we have one
1151 $picture = wall_upload_post($a, false);
1152 if (is_array($picture)) {
1153 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1157 // To-Do: Multiple IDs
1158 if (requestdata('media_ids')) {
1160 "SELECT `resource-id`, `scale`, `nickname`, `type` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1161 intval(requestdata('media_ids')),
1164 if (DBA::isResult($r)) {
1165 $phototypes = Image::supportedTypes();
1166 $ext = $phototypes[$r[0]['type']];
1167 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1168 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1172 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1174 $_REQUEST['api_source'] = true;
1176 if (empty($_REQUEST['source'])) {
1177 $_REQUEST["source"] = api_source();
1180 // call out normal post function
1181 $item_id = item_post($a);
1183 // output the post that we just posted.
1184 return api_status_show($type, $item_id);
1187 /// @TODO move to top of file or somewhere better
1188 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1189 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1192 * Uploads an image to Friendica.
1195 * @throws BadRequestException
1196 * @throws ForbiddenException
1197 * @throws ImagickException
1198 * @throws InternalServerErrorException
1199 * @throws UnauthorizedException
1200 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1202 function api_media_upload()
1206 if (api_user() === false) {
1207 Logger::log('no user');
1208 throw new ForbiddenException();
1213 if (empty($_FILES['media'])) {
1215 throw new BadRequestException("No media.");
1218 $media = wall_upload_post($a, false);
1221 throw new InternalServerErrorException();
1225 $returndata["media_id"] = $media["id"];
1226 $returndata["media_id_string"] = (string)$media["id"];
1227 $returndata["size"] = $media["size"];
1228 $returndata["image"] = ["w" => $media["width"],
1229 "h" => $media["height"],
1230 "image_type" => $media["type"],
1231 "friendica_preview_url" => $media["preview"]];
1233 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1235 return ["media" => $returndata];
1238 /// @TODO move to top of file or somewhere better
1239 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1242 * @param string $type Return type (atom, rss, xml, json)
1243 * @param int $item_id
1245 * @throws BadRequestException
1246 * @throws ImagickException
1247 * @throws InternalServerErrorException
1248 * @throws UnauthorizedException
1250 function api_status_show($type, $item_id)
1252 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1254 $a = \Friendica\BaseObject::getApp();
1256 $user_info = api_get_user($a);
1258 $status_info = api_get_status(['id' => $item_id]);
1260 if ($type == 'xml') {
1261 $status_info['georss:point'] = $status_info['geo'];
1262 unset($status_info['geo']);
1266 $status_info['user'] = $user_info;
1268 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1269 unset($status_info['user']['uid']);
1270 unset($status_info['user']['self']);
1274 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1276 return api_format_data('statuses', $type, ['status' => $status_info]);
1280 * Retrieves the last public status of the provided user info
1282 * @param int $ownerId Public contact Id
1283 * @param int $uid User Id
1285 * @throws InternalServerErrorException
1287 function api_get_last_status($ownerId, $uid)
1290 'owner-id' => $ownerId,
1292 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1296 $status_info = api_get_status($condition);
1298 return $status_info;
1302 * Retrieves a single item record based on the provided condition and converts it for API use.
1304 * @param array $condition Item table condition array
1306 * @throws InternalServerErrorException
1308 function api_get_status(array $condition)
1312 $item = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1313 if (DBA::isResult($item)) {
1314 $in_reply_to = api_in_reply_to($item);
1316 $converted = api_convert_item($item);
1319 'created_at' => api_date($item['created']),
1320 'id' => intval($item['id']),
1321 'id_str' => (string) $item['id'],
1322 'text' => $converted['text'],
1323 'source' => $item['app'] ?: 'web',
1324 'truncated' => false,
1325 'in_reply_to_status_id' => $in_reply_to['status_id'],
1326 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1327 'in_reply_to_user_id' => $in_reply_to['user_id'],
1328 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1329 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1331 'coordinates' => '',
1333 'contributors' => '',
1334 'is_quote_status' => false,
1335 'retweet_count' => 0,
1336 'favorite_count' => 0,
1337 'favorited' => $item['starred'] ? true : false,
1338 'retweeted' => false,
1339 'possibly_sensitive' => false,
1341 'statusnet_html' => $converted['html'],
1342 'statusnet_conversation_id' => $item['parent'],
1343 'external_url' => System::baseUrl() . '/display/' . $item['guid'],
1346 if (count($converted['attachments']) > 0) {
1347 $status_info['attachments'] = $converted['attachments'];
1350 if (count($converted['entities']) > 0) {
1351 $status_info['entities'] = $converted['entities'];
1354 if ($status_info['source'] == 'web') {
1355 $status_info['source'] = ContactSelector::networkToName($item['network'], $item['author-link']);
1356 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status_info['source']) {
1357 $status_info['source'] = trim($status_info['source'] . ' (' . ContactSelector::networkToName($item['network'], $item['author-link']) . ')');
1361 return $status_info;
1365 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1366 * The author's most recent status will be returned inline.
1368 * @param string $type Return type (atom, rss, xml, json)
1369 * @return array|string
1370 * @throws BadRequestException
1371 * @throws ImagickException
1372 * @throws InternalServerErrorException
1373 * @throws UnauthorizedException
1374 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1376 function api_users_show($type)
1378 $a = \Friendica\BaseObject::getApp();
1380 $user_info = api_get_user($a);
1382 $lastItem = api_get_last_status($user_info['pid'], $user_info['uid']);
1384 if ($type == 'xml') {
1385 $lastItem['georss:point'] = $lastItem['geo'];
1386 unset($lastItem['geo']);
1389 $user_info['status'] = $lastItem;
1392 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1393 unset($user_info['uid']);
1394 unset($user_info['self']);
1396 return api_format_data('user', $type, ['user' => $user_info]);
1399 /// @TODO move to top of file or somewhere better
1400 api_register_func('api/users/show', 'api_users_show');
1401 api_register_func('api/externalprofile/show', 'api_users_show');
1404 * Search a public user account.
1406 * @param string $type Return type (atom, rss, xml, json)
1408 * @return array|string
1409 * @throws BadRequestException
1410 * @throws ImagickException
1411 * @throws InternalServerErrorException
1412 * @throws UnauthorizedException
1413 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1415 function api_users_search($type)
1421 if (!empty($_GET['q'])) {
1422 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1424 if (!DBA::isResult($r)) {
1425 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1428 if (DBA::isResult($r)) {
1430 foreach ($r as $user) {
1431 $user_info = api_get_user($a, $user["id"]);
1433 if ($type == "xml") {
1434 $userlist[$k++.":user"] = $user_info;
1436 $userlist[] = $user_info;
1439 $userlist = ["users" => $userlist];
1441 throw new BadRequestException("User ".$_GET["q"]." not found.");
1444 throw new BadRequestException("No user specified.");
1447 return api_format_data("users", $type, $userlist);
1450 /// @TODO move to top of file or somewhere better
1451 api_register_func('api/users/search', 'api_users_search');
1454 * Return user objects
1456 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1458 * @param string $type Return format: json or xml
1460 * @return array|string
1461 * @throws BadRequestException
1462 * @throws ImagickException
1463 * @throws InternalServerErrorException
1464 * @throws NotFoundException if the results are empty.
1465 * @throws UnauthorizedException
1467 function api_users_lookup($type)
1471 if (!empty($_REQUEST['user_id'])) {
1472 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1474 $users[] = api_get_user(get_app(), $id);
1479 if (empty($users)) {
1480 throw new NotFoundException;
1483 return api_format_data("users", $type, ['users' => $users]);
1486 /// @TODO move to top of file or somewhere better
1487 api_register_func('api/users/lookup', 'api_users_lookup', true);
1490 * Returns statuses that match a specified query.
1492 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1494 * @param string $type Return format: json, xml, atom, rss
1496 * @return array|string
1497 * @throws BadRequestException if the "q" parameter is missing.
1498 * @throws ForbiddenException
1499 * @throws ImagickException
1500 * @throws InternalServerErrorException
1501 * @throws UnauthorizedException
1503 function api_search($type)
1506 $user_info = api_get_user($a);
1508 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1510 if (empty($_REQUEST['q'])) {
1511 throw new BadRequestException('q parameter is required.');
1514 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1517 $data['status'] = [];
1519 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1520 if (!empty($_REQUEST['rpp'])) {
1521 $count = $_REQUEST['rpp'];
1522 } elseif (!empty($_REQUEST['count'])) {
1523 $count = $_REQUEST['count'];
1526 $since_id = defaults($_REQUEST, 'since_id', 0);
1527 $max_id = defaults($_REQUEST, 'max_id', 0);
1528 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1529 $start = $page * $count;
1530 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1531 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1532 $searchTerm = $matches[1];
1533 $condition = ["`oid` > ?
1534 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1535 AND `otype` = ? AND `type` = ? AND `term` = ?",
1536 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1538 $condition[0] .= ' AND `oid` <= ?';
1539 $condition[] = $max_id;
1541 $terms = DBA::select('term', ['oid'], $condition, []);
1543 while ($term = DBA::fetch($terms)) {
1544 $itemIds[] = $term['oid'];
1548 if (empty($itemIds)) {
1549 return api_format_data('statuses', $type, $data);
1552 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1553 if ($exclude_replies) {
1554 $preCondition[] = '`id` = `parent`';
1557 $condition = [implode(' AND ', $preCondition)];
1559 $condition = ["`id` > ?
1560 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1561 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1562 AND `body` LIKE CONCAT('%',?,'%')",
1563 $since_id, api_user(), $_REQUEST['q']];
1565 $condition[0] .= ' AND `id` <= ?';
1566 $condition[] = $max_id;
1570 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1572 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1574 bindComments($data['status']);
1576 return api_format_data('statuses', $type, $data);
1579 /// @TODO move to top of file or somewhere better
1580 api_register_func('api/search/tweets', 'api_search', true);
1581 api_register_func('api/search', 'api_search', true);
1584 * Returns the most recent statuses posted by the user and the users they follow.
1586 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1588 * @param string $type Return type (atom, rss, xml, json)
1590 * @return array|string
1591 * @throws BadRequestException
1592 * @throws ForbiddenException
1593 * @throws ImagickException
1594 * @throws InternalServerErrorException
1595 * @throws UnauthorizedException
1596 * @todo Optional parameters
1597 * @todo Add reply info
1599 function api_statuses_home_timeline($type)
1602 $user_info = api_get_user($a);
1604 if (api_user() === false || $user_info === false) {
1605 throw new ForbiddenException();
1608 unset($_REQUEST["user_id"]);
1609 unset($_GET["user_id"]);
1611 unset($_REQUEST["screen_name"]);
1612 unset($_GET["screen_name"]);
1614 // get last network messages
1617 $count = defaults($_REQUEST, 'count', 20);
1618 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1622 $since_id = defaults($_REQUEST, 'since_id', 0);
1623 $max_id = defaults($_REQUEST, 'max_id', 0);
1624 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1625 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1627 $start = $page * $count;
1629 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1630 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1633 $condition[0] .= " AND `item`.`id` <= ?";
1634 $condition[] = $max_id;
1636 if ($exclude_replies) {
1637 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1639 if ($conversation_id > 0) {
1640 $condition[0] .= " AND `item`.`parent` = ?";
1641 $condition[] = $conversation_id;
1644 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1645 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1647 $items = Item::inArray($statuses);
1649 $ret = api_format_items($items, $user_info, false, $type);
1651 // Set all posts from the query above to seen
1653 foreach ($items as $item) {
1654 $idarray[] = intval($item["id"]);
1657 if (!empty($idarray)) {
1658 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1660 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1666 $data = ['status' => $ret];
1671 $data = api_rss_extra($a, $data, $user_info);
1675 return api_format_data("statuses", $type, $data);
1679 /// @TODO move to top of file or somewhere better
1680 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1681 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1684 * Returns the most recent statuses from public users.
1686 * @param string $type Return type (atom, rss, xml, json)
1688 * @return array|string
1689 * @throws BadRequestException
1690 * @throws ForbiddenException
1691 * @throws ImagickException
1692 * @throws InternalServerErrorException
1693 * @throws UnauthorizedException
1695 function api_statuses_public_timeline($type)
1698 $user_info = api_get_user($a);
1700 if (api_user() === false || $user_info === false) {
1701 throw new ForbiddenException();
1704 // get last network messages
1707 $count = defaults($_REQUEST, 'count', 20);
1708 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1712 $since_id = defaults($_REQUEST, 'since_id', 0);
1713 $max_id = defaults($_REQUEST, 'max_id', 0);
1714 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1715 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1717 $start = $page * $count;
1719 if ($exclude_replies && !$conversation_id) {
1720 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1721 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1724 $condition[0] .= " AND `thread`.`iid` <= ?";
1725 $condition[] = $max_id;
1728 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1729 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1731 $r = Item::inArray($statuses);
1733 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1734 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1737 $condition[0] .= " AND `item`.`id` <= ?";
1738 $condition[] = $max_id;
1740 if ($conversation_id > 0) {
1741 $condition[0] .= " AND `item`.`parent` = ?";
1742 $condition[] = $conversation_id;
1745 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1746 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1748 $r = Item::inArray($statuses);
1751 $ret = api_format_items($r, $user_info, false, $type);
1755 $data = ['status' => $ret];
1760 $data = api_rss_extra($a, $data, $user_info);
1764 return api_format_data("statuses", $type, $data);
1767 /// @TODO move to top of file or somewhere better
1768 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1771 * Returns the most recent statuses posted by users this node knows about.
1773 * @brief Returns the list of public federated posts this node knows about
1775 * @param string $type Return format: json, xml, atom, rss
1776 * @return array|string
1777 * @throws BadRequestException
1778 * @throws ForbiddenException
1779 * @throws ImagickException
1780 * @throws InternalServerErrorException
1781 * @throws UnauthorizedException
1783 function api_statuses_networkpublic_timeline($type)
1786 $user_info = api_get_user($a);
1788 if (api_user() === false || $user_info === false) {
1789 throw new ForbiddenException();
1792 $since_id = defaults($_REQUEST, 'since_id', 0);
1793 $max_id = defaults($_REQUEST, 'max_id', 0);
1796 $count = defaults($_REQUEST, 'count', 20);
1797 $page = defaults($_REQUEST, 'page', 1);
1801 $start = ($page - 1) * $count;
1803 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1804 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1807 $condition[0] .= " AND `thread`.`iid` <= ?";
1808 $condition[] = $max_id;
1811 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1812 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1814 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1818 $data = ['status' => $ret];
1823 $data = api_rss_extra($a, $data, $user_info);
1827 return api_format_data("statuses", $type, $data);
1830 /// @TODO move to top of file or somewhere better
1831 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1834 * Returns a single status.
1836 * @param string $type Return type (atom, rss, xml, json)
1838 * @return array|string
1839 * @throws BadRequestException
1840 * @throws ForbiddenException
1841 * @throws ImagickException
1842 * @throws InternalServerErrorException
1843 * @throws UnauthorizedException
1844 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1846 function api_statuses_show($type)
1849 $user_info = api_get_user($a);
1851 if (api_user() === false || $user_info === false) {
1852 throw new ForbiddenException();
1856 $id = intval(defaults($a->argv, 3, 0));
1859 $id = intval(defaults($_REQUEST, 'id', 0));
1864 $id = intval(defaults($a->argv, 4, 0));
1867 Logger::log('API: api_statuses_show: ' . $id);
1869 $conversation = !empty($_REQUEST['conversation']);
1871 // try to fetch the item for the local user - or the public item, if there is no local one
1872 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1873 if (!DBA::isResult($uri_item)) {
1874 throw new BadRequestException("There is no status with this id.");
1877 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1878 if (!DBA::isResult($item)) {
1879 throw new BadRequestException("There is no status with this id.");
1884 if ($conversation) {
1885 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1886 $params = ['order' => ['id' => true]];
1888 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1892 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1894 /// @TODO How about copying this to above methods which don't check $r ?
1895 if (!DBA::isResult($statuses)) {
1896 throw new BadRequestException("There is no status with this id.");
1899 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1901 if ($conversation) {
1902 $data = ['status' => $ret];
1903 return api_format_data("statuses", $type, $data);
1905 $data = ['status' => $ret[0]];
1906 return api_format_data("status", $type, $data);
1910 /// @TODO move to top of file or somewhere better
1911 api_register_func('api/statuses/show', 'api_statuses_show', true);
1915 * @param string $type Return type (atom, rss, xml, json)
1917 * @return array|string
1918 * @throws BadRequestException
1919 * @throws ForbiddenException
1920 * @throws ImagickException
1921 * @throws InternalServerErrorException
1922 * @throws UnauthorizedException
1923 * @todo nothing to say?
1925 function api_conversation_show($type)
1928 $user_info = api_get_user($a);
1930 if (api_user() === false || $user_info === false) {
1931 throw new ForbiddenException();
1935 $id = intval(defaults($a->argv , 3 , 0));
1936 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1937 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1938 $count = intval(defaults($_REQUEST, 'count' , 20));
1939 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1944 $start = $page * $count;
1947 $id = intval(defaults($_REQUEST, 'id', 0));
1952 $id = intval(defaults($a->argv, 4, 0));
1955 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1957 // try to fetch the item for the local user - or the public item, if there is no local one
1958 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1959 if (!DBA::isResult($item)) {
1960 throw new BadRequestException("There is no status with this id.");
1963 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1964 if (!DBA::isResult($parent)) {
1965 throw new BadRequestException("There is no status with this id.");
1968 $id = $parent['id'];
1970 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1971 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1974 $condition[0] .= " AND `item`.`id` <= ?";
1975 $condition[] = $max_id;
1978 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1979 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1981 if (!DBA::isResult($statuses)) {
1982 throw new BadRequestException("There is no status with id $id.");
1985 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1987 $data = ['status' => $ret];
1988 return api_format_data("statuses", $type, $data);
1991 /// @TODO move to top of file or somewhere better
1992 api_register_func('api/conversation/show', 'api_conversation_show', true);
1993 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1998 * @param string $type Return type (atom, rss, xml, json)
2000 * @return array|string
2001 * @throws BadRequestException
2002 * @throws ForbiddenException
2003 * @throws ImagickException
2004 * @throws InternalServerErrorException
2005 * @throws UnauthorizedException
2006 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2008 function api_statuses_repeat($type)
2014 if (api_user() === false) {
2015 throw new ForbiddenException();
2021 $id = intval(defaults($a->argv, 3, 0));
2024 $id = intval(defaults($_REQUEST, 'id', 0));
2029 $id = intval(defaults($a->argv, 4, 0));
2032 Logger::log('API: api_statuses_repeat: '.$id);
2034 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2035 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2037 if (DBA::isResult($item) && $item['body'] != "") {
2038 if (strpos($item['body'], "[/share]") !== false) {
2039 $pos = strpos($item['body'], "[share");
2040 $post = substr($item['body'], $pos);
2042 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2044 $post .= $item['body'];
2045 $post .= "[/share]";
2047 $_REQUEST['body'] = $post;
2048 $_REQUEST['profile_uid'] = api_user();
2049 $_REQUEST['api_source'] = true;
2051 if (empty($_REQUEST['source'])) {
2052 $_REQUEST["source"] = api_source();
2055 $item_id = item_post($a);
2057 throw new ForbiddenException();
2060 // output the post that we just posted.
2062 return api_status_show($type, $item_id);
2065 /// @TODO move to top of file or somewhere better
2066 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2069 * Destroys a specific status.
2071 * @param string $type Return type (atom, rss, xml, json)
2073 * @return array|string
2074 * @throws BadRequestException
2075 * @throws ForbiddenException
2076 * @throws ImagickException
2077 * @throws InternalServerErrorException
2078 * @throws UnauthorizedException
2079 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2081 function api_statuses_destroy($type)
2085 if (api_user() === false) {
2086 throw new ForbiddenException();
2092 $id = intval(defaults($a->argv, 3, 0));
2095 $id = intval(defaults($_REQUEST, 'id', 0));
2100 $id = intval(defaults($a->argv, 4, 0));
2103 Logger::log('API: api_statuses_destroy: '.$id);
2105 $ret = api_statuses_show($type);
2107 Item::deleteForUser(['id' => $id], api_user());
2112 /// @TODO move to top of file or somewhere better
2113 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2116 * Returns the most recent mentions.
2118 * @param string $type Return type (atom, rss, xml, json)
2120 * @return array|string
2121 * @throws BadRequestException
2122 * @throws ForbiddenException
2123 * @throws ImagickException
2124 * @throws InternalServerErrorException
2125 * @throws UnauthorizedException
2126 * @see http://developer.twitter.com/doc/get/statuses/mentions
2128 function api_statuses_mentions($type)
2131 $user_info = api_get_user($a);
2133 if (api_user() === false || $user_info === false) {
2134 throw new ForbiddenException();
2137 unset($_REQUEST["user_id"]);
2138 unset($_GET["user_id"]);
2140 unset($_REQUEST["screen_name"]);
2141 unset($_GET["screen_name"]);
2143 // get last network messages
2146 $since_id = defaults($_REQUEST, 'since_id', 0);
2147 $max_id = defaults($_REQUEST, 'max_id' , 0);
2148 $count = defaults($_REQUEST, 'count' , 20);
2149 $page = defaults($_REQUEST, 'page' , 1);
2154 $start = ($page - 1) * $count;
2156 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2157 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2158 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2161 $condition[0] .= " AND `item`.`id` <= ?";
2162 $condition[] = $max_id;
2165 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2166 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2168 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2170 $data = ['status' => $ret];
2175 $data = api_rss_extra($a, $data, $user_info);
2179 return api_format_data("statuses", $type, $data);
2182 /// @TODO move to top of file or somewhere better
2183 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2184 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2187 * Returns the most recent statuses posted by the user.
2189 * @brief Returns a user's public timeline
2191 * @param string $type Either "json" or "xml"
2192 * @return string|array
2193 * @throws BadRequestException
2194 * @throws ForbiddenException
2195 * @throws ImagickException
2196 * @throws InternalServerErrorException
2197 * @throws UnauthorizedException
2198 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2200 function api_statuses_user_timeline($type)
2203 $user_info = api_get_user($a);
2205 if (api_user() === false || $user_info === false) {
2206 throw new ForbiddenException();
2210 "api_statuses_user_timeline: api_user: ". api_user() .
2211 "\nuser_info: ".print_r($user_info, true) .
2212 "\n_REQUEST: ".print_r($_REQUEST, true),
2216 $since_id = defaults($_REQUEST, 'since_id', 0);
2217 $max_id = defaults($_REQUEST, 'max_id', 0);
2218 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2219 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2222 $count = defaults($_REQUEST, 'count', 20);
2223 $page = defaults($_REQUEST, 'page', 1);
2227 $start = ($page - 1) * $count;
2229 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2230 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2232 if ($user_info['self'] == 1) {
2233 $condition[0] .= ' AND `item`.`wall` ';
2236 if ($exclude_replies) {
2237 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2240 if ($conversation_id > 0) {
2241 $condition[0] .= " AND `item`.`parent` = ?";
2242 $condition[] = $conversation_id;
2246 $condition[0] .= " AND `item`.`id` <= ?";
2247 $condition[] = $max_id;
2250 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2251 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2253 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2257 $data = ['status' => $ret];
2262 $data = api_rss_extra($a, $data, $user_info);
2266 return api_format_data("statuses", $type, $data);
2269 /// @TODO move to top of file or somewhere better
2270 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2273 * Star/unstar an item.
2274 * param: id : id of the item
2276 * @param string $type Return type (atom, rss, xml, json)
2278 * @return array|string
2279 * @throws BadRequestException
2280 * @throws ForbiddenException
2281 * @throws ImagickException
2282 * @throws InternalServerErrorException
2283 * @throws UnauthorizedException
2284 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2286 function api_favorites_create_destroy($type)
2290 if (api_user() === false) {
2291 throw new ForbiddenException();
2294 // for versioned api.
2295 /// @TODO We need a better global soluton
2296 $action_argv_id = 2;
2297 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2298 $action_argv_id = 3;
2301 if ($a->argc <= $action_argv_id) {
2302 throw new BadRequestException("Invalid request.");
2304 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2305 if ($a->argc == $action_argv_id + 2) {
2306 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2308 $itemid = intval(defaults($_REQUEST, 'id', 0));
2311 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2313 if (!DBA::isResult($item)) {
2314 throw new BadRequestException("Invalid item.");
2319 $item['starred'] = 1;
2322 $item['starred'] = 0;
2325 throw new BadRequestException("Invalid action ".$action);
2328 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2331 throw new InternalServerErrorException("DB error");
2335 $user_info = api_get_user($a);
2336 $rets = api_format_items([$item], $user_info, false, $type);
2339 $data = ['status' => $ret];
2344 $data = api_rss_extra($a, $data, $user_info);
2348 return api_format_data("status", $type, $data);
2351 /// @TODO move to top of file or somewhere better
2352 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2353 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2356 * Returns the most recent favorite statuses.
2358 * @param string $type Return type (atom, rss, xml, json)
2360 * @return string|array
2361 * @throws BadRequestException
2362 * @throws ForbiddenException
2363 * @throws ImagickException
2364 * @throws InternalServerErrorException
2365 * @throws UnauthorizedException
2367 function api_favorites($type)
2372 $user_info = api_get_user($a);
2374 if (api_user() === false || $user_info === false) {
2375 throw new ForbiddenException();
2380 // in friendica starred item are private
2381 // return favorites only for self
2382 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2384 if ($user_info['self'] == 0) {
2388 $since_id = defaults($_REQUEST, 'since_id', 0);
2389 $max_id = defaults($_REQUEST, 'max_id', 0);
2390 $count = defaults($_GET, 'count', 20);
2391 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2396 $start = $page*$count;
2398 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2399 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2401 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2404 $condition[0] .= " AND `item`.`id` <= ?";
2405 $condition[] = $max_id;
2408 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2410 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2415 $data = ['status' => $ret];
2420 $data = api_rss_extra($a, $data, $user_info);
2424 return api_format_data("statuses", $type, $data);
2427 /// @TODO move to top of file or somewhere better
2428 api_register_func('api/favorites', 'api_favorites', true);
2432 * @param array $item
2433 * @param array $recipient
2434 * @param array $sender
2437 * @throws InternalServerErrorException
2439 function api_format_messages($item, $recipient, $sender)
2441 // standard meta information
2443 'id' => $item['id'],
2444 'sender_id' => $sender['id'],
2446 'recipient_id' => $recipient['id'],
2447 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2448 'sender_screen_name' => $sender['screen_name'],
2449 'recipient_screen_name' => $recipient['screen_name'],
2450 'sender' => $sender,
2451 'recipient' => $recipient,
2453 'friendica_seen' => defaults($item, 'seen', 0),
2454 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2457 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2458 if (isset($ret['sender']['uid'])) {
2459 unset($ret['sender']['uid']);
2461 if (isset($ret['sender']['self'])) {
2462 unset($ret['sender']['self']);
2464 if (isset($ret['recipient']['uid'])) {
2465 unset($ret['recipient']['uid']);
2467 if (isset($ret['recipient']['self'])) {
2468 unset($ret['recipient']['self']);
2471 //don't send title to regular StatusNET requests to avoid confusing these apps
2472 if (!empty($_GET['getText'])) {
2473 $ret['title'] = $item['title'];
2474 if ($_GET['getText'] == 'html') {
2475 $ret['text'] = BBCode::convert($item['body'], false);
2476 } elseif ($_GET['getText'] == 'plain') {
2477 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2480 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2482 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2483 unset($ret['sender']);
2484 unset($ret['recipient']);
2492 * @param array $item
2495 * @throws InternalServerErrorException
2497 function api_convert_item($item)
2499 $body = $item['body'];
2500 $attachments = api_get_attachments($body);
2502 // Workaround for ostatus messages where the title is identically to the body
2503 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2504 $statusbody = trim(HTML::toPlaintext($html, 0));
2506 // handle data: images
2507 $statusbody = api_format_items_embeded_images($item, $statusbody);
2509 $statustitle = trim($item['title']);
2511 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2512 $statustext = trim($statusbody);
2514 $statustext = trim($statustitle."\n\n".$statusbody);
2517 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2518 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2521 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2523 // Workaround for clients with limited HTML parser functionality
2524 $search = ["<br>", "<blockquote>", "</blockquote>",
2525 "<h1>", "</h1>", "<h2>", "</h2>",
2526 "<h3>", "</h3>", "<h4>", "</h4>",
2527 "<h5>", "</h5>", "<h6>", "</h6>"];
2528 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2529 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2530 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2531 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2532 $statushtml = str_replace($search, $replace, $statushtml);
2534 if ($item['title'] != "") {
2535 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2539 $oldtext = $statushtml;
2540 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2541 } while ($oldtext != $statushtml);
2543 if (substr($statushtml, 0, 4) == '<br>') {
2544 $statushtml = substr($statushtml, 4);
2547 if (substr($statushtml, 0, -4) == '<br>') {
2548 $statushtml = substr($statushtml, -4);
2551 // feeds without body should contain the link
2552 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2553 $statushtml .= BBCode::convert($item['plink']);
2556 $entities = api_get_entitities($statustext, $body);
2559 "text" => $statustext,
2560 "html" => $statushtml,
2561 "attachments" => $attachments,
2562 "entities" => $entities
2568 * @param string $body
2571 * @throws InternalServerErrorException
2573 function api_get_attachments(&$body)
2576 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2578 $URLSearchString = "^\[\]";
2579 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2587 foreach ($images[1] as $image) {
2588 $imagedata = Image::getInfoFromURL($image);
2591 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2595 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2596 foreach ($images[0] as $orig) {
2597 $body = str_replace($orig, "", $body);
2601 return $attachments;
2606 * @param string $text
2607 * @param string $bbcode
2610 * @throws InternalServerErrorException
2611 * @todo Links at the first character of the post
2613 function api_get_entitities(&$text, $bbcode)
2615 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2617 if ($include_entities != "true") {
2618 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2620 foreach ($images[1] as $image) {
2621 $replace = ProxyUtils::proxifyUrl($image);
2622 $text = str_replace($image, $replace, $text);
2627 $bbcode = BBCode::cleanPictureLinks($bbcode);
2629 // Change pure links in text to bbcode uris
2630 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2633 $entities["hashtags"] = [];
2634 $entities["symbols"] = [];
2635 $entities["urls"] = [];
2636 $entities["user_mentions"] = [];
2638 $URLSearchString = "^\[\]";
2640 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2642 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2643 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2644 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2646 $bbcode = preg_replace(
2647 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2648 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2651 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2653 $bbcode = preg_replace(
2654 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2655 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2658 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2660 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2662 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2663 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2666 foreach ($urls[1] as $id => $url) {
2667 //$start = strpos($text, $url, $offset);
2668 $start = iconv_strpos($text, $url, 0, "UTF-8");
2669 if (!($start === false)) {
2670 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2674 ksort($ordered_urls);
2677 //foreach ($urls[1] AS $id=>$url) {
2678 foreach ($ordered_urls as $url) {
2679 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2680 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2682 $display_url = $url["title"];
2684 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2685 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2687 if (strlen($display_url) > 26) {
2688 $display_url = substr($display_url, 0, 25)."…";
2692 //$start = strpos($text, $url, $offset);
2693 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2694 if (!($start === false)) {
2695 $entities["urls"][] = ["url" => $url["url"],
2696 "expanded_url" => $url["url"],
2697 "display_url" => $display_url,
2698 "indices" => [$start, $start+strlen($url["url"])]];
2699 $offset = $start + 1;
2703 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2704 $ordered_images = [];
2705 foreach ($images[1] as $image) {
2706 //$start = strpos($text, $url, $offset);
2707 $start = iconv_strpos($text, $image, 0, "UTF-8");
2708 if (!($start === false)) {
2709 $ordered_images[$start] = $image;
2712 //$entities["media"] = array();
2715 foreach ($ordered_images as $url) {
2716 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2717 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2719 if (strlen($display_url) > 26) {
2720 $display_url = substr($display_url, 0, 25)."…";
2723 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2724 if (!($start === false)) {
2725 $image = Image::getInfoFromURL($url);
2727 // If image cache is activated, then use the following sizes:
2728 // thumb (150), small (340), medium (600) and large (1024)
2729 if (!Config::get("system", "proxy_disabled")) {
2730 $media_url = ProxyUtils::proxifyUrl($url);
2733 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2734 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2736 if (($image[0] > 150) || ($image[1] > 150)) {
2737 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2738 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2741 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2742 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2744 if (($image[0] > 600) || ($image[1] > 600)) {
2745 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2746 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2750 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2753 $entities["media"][] = [
2755 "id_str" => (string) ($start + 1),
2756 "indices" => [$start, $start+strlen($url)],
2757 "media_url" => Strings::normaliseLink($media_url),
2758 "media_url_https" => $media_url,
2760 "display_url" => $display_url,
2761 "expanded_url" => $url,
2765 $offset = $start + 1;
2774 * @param array $item
2775 * @param string $text
2779 function api_format_items_embeded_images($item, $text)
2781 $text = preg_replace_callback(
2782 '|data:image/([^;]+)[^=]+=*|m',
2783 function () use ($item) {
2784 return System::baseUrl() . '/display/' . $item['guid'];
2792 * @brief return <a href='url'>name</a> as array
2794 * @param string $txt text
2799 function api_contactlink_to_array($txt)
2802 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2803 if ($r && count($match)==3) {
2805 'name' => $match[2],
2819 * @brief return likes, dislikes and attend status for item
2821 * @param array $item array
2822 * @param string $type Return type (atom, rss, xml, json)
2825 * likes => int count,
2826 * dislikes => int count
2827 * @throws BadRequestException
2828 * @throws ImagickException
2829 * @throws InternalServerErrorException
2830 * @throws UnauthorizedException
2832 function api_format_items_activities($item, $type = "json")
2841 'attendmaybe' => [],
2844 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2845 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2847 while ($parent_item = Item::fetch($ret)) {
2848 // not used as result should be structured like other user data
2849 //builtin_activity_puller($i, $activities);
2851 // get user data and add it to the array of the activity
2852 $user = api_get_user($a, $parent_item['author-id']);
2853 switch ($parent_item['verb']) {
2855 $activities['like'][] = $user;
2857 case ACTIVITY_DISLIKE:
2858 $activities['dislike'][] = $user;
2860 case ACTIVITY_ATTEND:
2861 $activities['attendyes'][] = $user;
2863 case ACTIVITY_ATTENDNO:
2864 $activities['attendno'][] = $user;
2866 case ACTIVITY_ATTENDMAYBE:
2867 $activities['attendmaybe'][] = $user;
2876 if ($type == "xml") {
2877 $xml_activities = [];
2878 foreach ($activities as $k => $v) {
2879 // change xml element from "like" to "friendica:like"
2880 $xml_activities["friendica:".$k] = $v;
2881 // add user data into xml output
2883 foreach ($v as $user) {
2884 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2887 $activities = $xml_activities;
2895 * @brief return data from profiles
2897 * @param array $profile_row array containing data from db table 'profile'
2899 * @throws InternalServerErrorException
2901 function api_format_items_profiles($profile_row)
2904 'profile_id' => $profile_row['id'],
2905 'profile_name' => $profile_row['profile-name'],
2906 'is_default' => $profile_row['is-default'] ? true : false,
2907 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2908 'profile_photo' => $profile_row['photo'],
2909 'profile_thumb' => $profile_row['thumb'],
2910 'publish' => $profile_row['publish'] ? true : false,
2911 'net_publish' => $profile_row['net-publish'] ? true : false,
2912 'description' => $profile_row['pdesc'],
2913 'date_of_birth' => $profile_row['dob'],
2914 'address' => $profile_row['address'],
2915 'city' => $profile_row['locality'],
2916 'region' => $profile_row['region'],
2917 'postal_code' => $profile_row['postal-code'],
2918 'country' => $profile_row['country-name'],
2919 'hometown' => $profile_row['hometown'],
2920 'gender' => $profile_row['gender'],
2921 'marital' => $profile_row['marital'],
2922 'marital_with' => $profile_row['with'],
2923 'marital_since' => $profile_row['howlong'],
2924 'sexual' => $profile_row['sexual'],
2925 'politic' => $profile_row['politic'],
2926 'religion' => $profile_row['religion'],
2927 'public_keywords' => $profile_row['pub_keywords'],
2928 'private_keywords' => $profile_row['prv_keywords'],
2929 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2930 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2931 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2932 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2933 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2934 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2935 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2936 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2937 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2938 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2939 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2940 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2941 'homepage' => $profile_row['homepage'],
2948 * @brief format items to be returned by api
2950 * @param array $r array of items
2951 * @param array $user_info
2952 * @param bool $filter_user filter items by $user_info
2953 * @param string $type Return type (atom, rss, xml, json)
2955 * @throws BadRequestException
2956 * @throws ImagickException
2957 * @throws InternalServerErrorException
2958 * @throws UnauthorizedException
2960 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2966 foreach ((array)$r as $item) {
2967 localize_item($item);
2968 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2970 // Look if the posts are matching if they should be filtered by user id
2971 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2975 $in_reply_to = api_in_reply_to($item);
2977 $converted = api_convert_item($item);
2979 if ($type == "xml") {
2980 $geo = "georss:point";
2986 'text' => $converted["text"],
2987 'truncated' => false,
2988 'created_at'=> api_date($item['created']),
2989 'in_reply_to_status_id' => $in_reply_to['status_id'],
2990 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2991 'source' => (($item['app']) ? $item['app'] : 'web'),
2992 'id' => intval($item['id']),
2993 'id_str' => (string) intval($item['id']),
2994 'in_reply_to_user_id' => $in_reply_to['user_id'],
2995 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2996 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2998 'favorited' => $item['starred'] ? true : false,
2999 'user' => $status_user,
3000 'friendica_author' => $author_user,
3001 'friendica_owner' => $owner_user,
3002 'friendica_private' => $item['private'] == 1,
3003 //'entities' => NULL,
3004 'statusnet_html' => $converted["html"],
3005 'statusnet_conversation_id' => $item['parent'],
3006 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3007 'friendica_activities' => api_format_items_activities($item, $type),
3010 if (count($converted["attachments"]) > 0) {
3011 $status["attachments"] = $converted["attachments"];
3014 if (count($converted["entities"]) > 0) {
3015 $status["entities"] = $converted["entities"];
3018 if ($status["source"] == 'web') {
3019 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3020 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3021 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3024 if ($item["id"] == $item["parent"]) {
3025 $retweeted_item = api_share_as_retweet($item);
3026 if ($retweeted_item !== false) {
3027 $retweeted_status = $status;
3028 $status['user'] = $status['friendica_owner'];
3030 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3031 } catch (BadRequestException $e) {
3032 // user not found. should be found?
3033 /// @todo check if the user should be always found
3034 $retweeted_status["user"] = [];
3037 $rt_converted = api_convert_item($retweeted_item);
3039 $retweeted_status['text'] = $rt_converted["text"];
3040 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3041 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3042 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3043 $status['retweeted_status'] = $retweeted_status;
3044 $status['friendica_author'] = $retweeted_status['friendica_author'];
3048 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3049 unset($status["user"]["uid"]);
3050 unset($status["user"]["self"]);
3052 if ($item["coord"] != "") {
3053 $coords = explode(' ', $item["coord"]);
3054 if (count($coords) == 2) {
3055 if ($type == "json") {
3056 $status["geo"] = ['type' => 'Point',
3057 'coordinates' => [(float) $coords[0],
3058 (float) $coords[1]]];
3059 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3060 $status["georss:point"] = $item["coord"];
3070 * Returns the remaining number of API requests available to the user before the API limit is reached.
3072 * @param string $type Return type (atom, rss, xml, json)
3074 * @return array|string
3077 function api_account_rate_limit_status($type)
3079 if ($type == "xml") {
3081 'remaining-hits' => '150',
3082 '@attributes' => ["type" => "integer"],
3083 'hourly-limit' => '150',
3084 '@attributes2' => ["type" => "integer"],
3085 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3086 '@attributes3' => ["type" => "datetime"],
3087 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3088 '@attributes4' => ["type" => "integer"],
3092 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3093 'remaining_hits' => '150',
3094 'hourly_limit' => '150',
3095 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3099 return api_format_data('hash', $type, ['hash' => $hash]);
3102 /// @TODO move to top of file or somewhere better
3103 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3106 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3108 * @param string $type Return type (atom, rss, xml, json)
3110 * @return array|string
3112 function api_help_test($type)
3114 if ($type == 'xml') {
3120 return api_format_data('ok', $type, ["ok" => $ok]);
3123 /// @TODO move to top of file or somewhere better
3124 api_register_func('api/help/test', 'api_help_test', false);
3127 * Returns all lists the user subscribes to.
3129 * @param string $type Return type (atom, rss, xml, json)
3131 * @return array|string
3132 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3134 function api_lists_list($type)
3137 /// @TODO $ret is not filled here?
3138 return api_format_data('lists', $type, ["lists_list" => $ret]);
3141 /// @TODO move to top of file or somewhere better
3142 api_register_func('api/lists/list', 'api_lists_list', true);
3143 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3146 * Returns all groups the user owns.
3148 * @param string $type Return type (atom, rss, xml, json)
3150 * @return array|string
3151 * @throws BadRequestException
3152 * @throws ForbiddenException
3153 * @throws ImagickException
3154 * @throws InternalServerErrorException
3155 * @throws UnauthorizedException
3156 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3158 function api_lists_ownerships($type)
3162 if (api_user() === false) {
3163 throw new ForbiddenException();
3167 $user_info = api_get_user($a);
3168 $uid = $user_info['uid'];
3170 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3172 // loop through all groups
3174 foreach ($groups as $group) {
3175 if ($group['visible']) {
3181 'name' => $group['name'],
3182 'id' => intval($group['id']),
3183 'id_str' => (string) $group['id'],
3184 'user' => $user_info,
3188 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3191 /// @TODO move to top of file or somewhere better
3192 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3195 * Returns recent statuses from users in the specified group.
3197 * @param string $type Return type (atom, rss, xml, json)
3199 * @return array|string
3200 * @throws BadRequestException
3201 * @throws ForbiddenException
3202 * @throws ImagickException
3203 * @throws InternalServerErrorException
3204 * @throws UnauthorizedException
3205 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3207 function api_lists_statuses($type)
3211 $user_info = api_get_user($a);
3212 if (api_user() === false || $user_info === false) {
3213 throw new ForbiddenException();
3216 unset($_REQUEST["user_id"]);
3217 unset($_GET["user_id"]);
3219 unset($_REQUEST["screen_name"]);
3220 unset($_GET["screen_name"]);
3222 if (empty($_REQUEST['list_id'])) {
3223 throw new BadRequestException('list_id not specified');
3227 $count = defaults($_REQUEST, 'count', 20);
3228 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3232 $since_id = defaults($_REQUEST, 'since_id', 0);
3233 $max_id = defaults($_REQUEST, 'max_id', 0);
3234 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3235 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3237 $start = $page * $count;
3239 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3240 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3243 $condition[0] .= " AND `item`.`id` <= ?";
3244 $condition[] = $max_id;
3246 if ($exclude_replies > 0) {
3247 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3249 if ($conversation_id > 0) {
3250 $condition[0] .= " AND `item`.`parent` = ?";
3251 $condition[] = $conversation_id;
3254 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3255 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3257 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3259 $data = ['status' => $items];
3264 $data = api_rss_extra($a, $data, $user_info);
3268 return api_format_data("statuses", $type, $data);
3271 /// @TODO move to top of file or somewhere better
3272 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3275 * Considers friends and followers lists to be private and won't return
3276 * anything if any user_id parameter is passed.
3278 * @brief Returns either the friends of the follower list
3280 * @param string $qtype Either "friends" or "followers"
3281 * @return boolean|array
3282 * @throws BadRequestException
3283 * @throws ForbiddenException
3284 * @throws ImagickException
3285 * @throws InternalServerErrorException
3286 * @throws UnauthorizedException
3288 function api_statuses_f($qtype)
3292 if (api_user() === false) {
3293 throw new ForbiddenException();
3297 $count = defaults($_GET, 'count', 20);
3298 $page = defaults($_GET, 'page', 1);
3302 $start = ($page - 1) * $count;
3304 $user_info = api_get_user($a);
3306 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3307 /* this is to stop Hotot to load friends multiple times
3308 * I'm not sure if I'm missing return something or
3309 * is a bug in hotot. Workaround, meantime
3313 return array('$users' => $ret);*/
3318 if ($qtype == 'friends') {
3319 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3320 } elseif ($qtype == 'followers') {
3321 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3324 // friends and followers only for self
3325 if ($user_info['self'] == 0) {
3326 $sql_extra = " AND false ";
3329 if ($qtype == 'blocks') {
3330 $sql_filter = 'AND `blocked` AND NOT `pending`';
3331 } elseif ($qtype == 'incoming') {
3332 $sql_filter = 'AND `pending`';
3334 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3352 foreach ($r as $cid) {
3353 $user = api_get_user($a, $cid['nurl']);
3354 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3355 unset($user["uid"]);
3356 unset($user["self"]);
3363 return ['user' => $ret];
3368 * Returns the user's friends.
3370 * @brief Returns the list of friends of the provided user
3372 * @deprecated By Twitter API in favor of friends/list
3374 * @param string $type Either "json" or "xml"
3375 * @return boolean|string|array
3376 * @throws BadRequestException
3377 * @throws ForbiddenException
3379 function api_statuses_friends($type)
3381 $data = api_statuses_f("friends");
3382 if ($data === false) {
3385 return api_format_data("users", $type, $data);
3389 * Returns the user's followers.
3391 * @brief Returns the list of followers of the provided user
3393 * @deprecated By Twitter API in favor of friends/list
3395 * @param string $type Either "json" or "xml"
3396 * @return boolean|string|array
3397 * @throws BadRequestException
3398 * @throws ForbiddenException
3400 function api_statuses_followers($type)
3402 $data = api_statuses_f("followers");
3403 if ($data === false) {
3406 return api_format_data("users", $type, $data);
3409 /// @TODO move to top of file or somewhere better
3410 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3411 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3414 * Returns the list of blocked users
3416 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3418 * @param string $type Either "json" or "xml"
3420 * @return boolean|string|array
3421 * @throws BadRequestException
3422 * @throws ForbiddenException
3424 function api_blocks_list($type)
3426 $data = api_statuses_f('blocks');
3427 if ($data === false) {
3430 return api_format_data("users", $type, $data);
3433 /// @TODO move to top of file or somewhere better
3434 api_register_func('api/blocks/list', 'api_blocks_list', true);
3437 * Returns the list of pending users IDs
3439 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3441 * @param string $type Either "json" or "xml"
3443 * @return boolean|string|array
3444 * @throws BadRequestException
3445 * @throws ForbiddenException
3447 function api_friendships_incoming($type)
3449 $data = api_statuses_f('incoming');
3450 if ($data === false) {
3455 foreach ($data['user'] as $user) {
3456 $ids[] = $user['id'];
3459 return api_format_data("ids", $type, ['id' => $ids]);
3462 /// @TODO move to top of file or somewhere better
3463 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3466 * Returns the instance's configuration information.
3468 * @param string $type Return type (atom, rss, xml, json)
3470 * @return array|string
3471 * @throws InternalServerErrorException
3473 function api_statusnet_config($type)
3477 $name = Config::get('config', 'sitename');
3478 $server = $a->getHostName();
3479 $logo = System::baseUrl() . '/images/friendica-64.png';
3480 $email = Config::get('config', 'admin_email');
3481 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3482 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3483 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3484 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3485 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3488 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3489 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3490 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3491 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3492 'shorturllength' => '30',
3494 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3495 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3496 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3497 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3502 return api_format_data('config', $type, ['config' => $config]);
3505 /// @TODO move to top of file or somewhere better
3506 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3507 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3511 * @param string $type Return type (atom, rss, xml, json)
3513 * @return array|string
3515 function api_statusnet_version($type)
3518 $fake_statusnet_version = "0.9.7";
3520 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3523 /// @TODO move to top of file or somewhere better
3524 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3525 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3529 * @param string $type Return type (atom, rss, xml, json)
3531 * @return array|string|void
3532 * @throws BadRequestException
3533 * @throws ForbiddenException
3534 * @throws ImagickException
3535 * @throws InternalServerErrorException
3536 * @throws UnauthorizedException
3537 * @todo use api_format_data() to return data
3539 function api_ff_ids($type)
3542 throw new ForbiddenException();
3549 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3552 "SELECT `pcontact`.`id` FROM `contact`
3553 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3554 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3557 if (!DBA::isResult($r)) {
3562 foreach ($r as $rr) {
3563 if ($stringify_ids) {
3566 $ids[] = intval($rr['id']);
3570 return api_format_data("ids", $type, ['id' => $ids]);
3574 * Returns the ID of every user the user is following.
3576 * @param string $type Return type (atom, rss, xml, json)
3578 * @return array|string
3579 * @throws BadRequestException
3580 * @throws ForbiddenException
3581 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3583 function api_friends_ids($type)
3585 return api_ff_ids($type);
3589 * Returns the ID of every user following the user.
3591 * @param string $type Return type (atom, rss, xml, json)
3593 * @return array|string
3594 * @throws BadRequestException
3595 * @throws ForbiddenException
3596 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3598 function api_followers_ids($type)
3600 return api_ff_ids($type);
3603 /// @TODO move to top of file or somewhere better
3604 api_register_func('api/friends/ids', 'api_friends_ids', true);
3605 api_register_func('api/followers/ids', 'api_followers_ids', true);
3608 * Sends a new direct message.
3610 * @param string $type Return type (atom, rss, xml, json)
3612 * @return array|string
3613 * @throws BadRequestException
3614 * @throws ForbiddenException
3615 * @throws ImagickException
3616 * @throws InternalServerErrorException
3617 * @throws NotFoundException
3618 * @throws UnauthorizedException
3619 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3621 function api_direct_messages_new($type)
3625 if (api_user() === false) {
3626 throw new ForbiddenException();
3629 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3633 $sender = api_get_user($a);
3636 if (!empty($_POST['screen_name'])) {
3638 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3640 DBA::escape($_POST['screen_name'])
3643 if (DBA::isResult($r)) {
3644 // Selecting the id by priority, friendica first
3645 api_best_nickname($r);
3647 $recipient = api_get_user($a, $r[0]['nurl']);
3650 $recipient = api_get_user($a, $_POST['user_id']);
3653 if (empty($recipient)) {
3654 throw new NotFoundException('Recipient not found');
3658 if (!empty($_REQUEST['replyto'])) {
3660 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3662 intval($_REQUEST['replyto'])
3664 $replyto = $r[0]['parent-uri'];
3665 $sub = $r[0]['title'];
3667 if (!empty($_REQUEST['title'])) {
3668 $sub = $_REQUEST['title'];
3670 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3674 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3677 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3678 $ret = api_format_messages($r[0], $recipient, $sender);
3680 $ret = ["error"=>$id];
3683 $data = ['direct_message'=>$ret];
3689 $data = api_rss_extra($a, $data, $sender);
3693 return api_format_data("direct-messages", $type, $data);
3696 /// @TODO move to top of file or somewhere better
3697 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3700 * Destroys a direct message.
3702 * @brief delete a direct_message from mail table through api
3704 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3705 * @return string|array
3706 * @throws BadRequestException
3707 * @throws ForbiddenException
3708 * @throws ImagickException
3709 * @throws InternalServerErrorException
3710 * @throws UnauthorizedException
3711 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3713 function api_direct_messages_destroy($type)
3717 if (api_user() === false) {
3718 throw new ForbiddenException();
3722 $user_info = api_get_user($a);
3724 $id = defaults($_REQUEST, 'id', 0);
3726 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3727 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3728 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3730 $uid = $user_info['uid'];
3731 // error if no id or parenturi specified (for clients posting parent-uri as well)
3732 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3733 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3734 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3737 // BadRequestException if no id specified (for clients using Twitter API)
3739 throw new BadRequestException('Message id not specified');
3742 // add parent-uri to sql command if specified by calling app
3743 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3745 // get data of the specified message id
3747 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3752 // error message if specified id is not in database
3753 if (!DBA::isResult($r)) {
3754 if ($verbose == "true") {
3755 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3756 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3758 /// @todo BadRequestException ok for Twitter API clients?
3759 throw new BadRequestException('message id not in database');
3764 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3769 if ($verbose == "true") {
3772 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3773 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3775 $answer = ['result' => 'error', 'message' => 'unknown error'];
3776 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3779 /// @todo return JSON data like Twitter API not yet implemented
3782 /// @TODO move to top of file or somewhere better
3783 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3788 * @brief unfollow contact
3790 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3791 * @return string|array
3792 * @throws BadRequestException
3793 * @throws ForbiddenException
3794 * @throws ImagickException
3795 * @throws InternalServerErrorException
3796 * @throws NotFoundException
3797 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3799 function api_friendships_destroy($type)
3803 if ($uid === false) {
3804 throw new ForbiddenException();
3807 $contact_id = defaults($_REQUEST, 'user_id');
3809 if (empty($contact_id)) {
3810 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3811 throw new BadRequestException("no user_id specified");
3814 // Get Contact by given id
3815 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3817 if(!DBA::isResult($contact)) {
3818 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3819 throw new NotFoundException("no contact found to given ID");
3822 $url = $contact["url"];
3824 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3825 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3826 Strings::normaliseLink($url), $url];
3827 $contact = DBA::selectFirst('contact', [], $condition);
3829 if (!DBA::isResult($contact)) {
3830 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3831 throw new NotFoundException("Not following Contact");
3834 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3835 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3836 throw new ExpectationFailedException("Not supported");
3839 $dissolve = ($contact['rel'] == Contact::SHARING);
3841 $owner = User::getOwnerDataById($uid);
3843 Contact::terminateFriendship($owner, $contact, $dissolve);
3846 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3847 throw new NotFoundException("Error Processing Request");
3850 // Sharing-only contacts get deleted as there no relationship any more
3852 Contact::remove($contact['id']);
3854 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3857 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3858 unset($contact["uid"]);
3859 unset($contact["self"]);
3861 // Set screen_name since Twidere requests it
3862 $contact["screen_name"] = $contact["nick"];
3864 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3866 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3870 * @param string $type Return type (atom, rss, xml, json)
3871 * @param string $box
3872 * @param string $verbose
3874 * @return array|string
3875 * @throws BadRequestException
3876 * @throws ForbiddenException
3877 * @throws ImagickException
3878 * @throws InternalServerErrorException
3879 * @throws UnauthorizedException
3881 function api_direct_messages_box($type, $box, $verbose)
3884 if (api_user() === false) {
3885 throw new ForbiddenException();
3888 $count = defaults($_GET, 'count', 20);
3889 $page = defaults($_REQUEST, 'page', 1) - 1;
3894 $since_id = defaults($_REQUEST, 'since_id', 0);
3895 $max_id = defaults($_REQUEST, 'max_id', 0);
3897 $user_id = defaults($_REQUEST, 'user_id', '');
3898 $screen_name = defaults($_REQUEST, 'screen_name', '');
3901 unset($_REQUEST["user_id"]);
3902 unset($_GET["user_id"]);
3904 unset($_REQUEST["screen_name"]);
3905 unset($_GET["screen_name"]);
3907 $user_info = api_get_user($a);
3908 if ($user_info === false) {
3909 throw new ForbiddenException();
3911 $profile_url = $user_info["url"];
3914 $start = $page * $count;
3919 if ($box=="sentbox") {
3920 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3921 } elseif ($box == "conversation") {
3922 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3923 } elseif ($box == "all") {
3924 $sql_extra = "true";
3925 } elseif ($box == "inbox") {
3926 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3930 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3933 if ($user_id != "") {
3934 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3935 } elseif ($screen_name !="") {
3936 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3940 "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",
3946 if ($verbose == "true" && !DBA::isResult($r)) {
3947 $answer = ['result' => 'error', 'message' => 'no mails available'];
3948 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3952 foreach ($r as $item) {
3953 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3954 $recipient = $user_info;
3955 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3956 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3957 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3958 $sender = $user_info;
3961 if (isset($recipient) && isset($sender)) {
3962 $ret[] = api_format_messages($item, $recipient, $sender);
3967 $data = ['direct_message' => $ret];
3972 $data = api_rss_extra($a, $data, $user_info);
3976 return api_format_data("direct-messages", $type, $data);
3980 * Returns the most recent direct messages sent by the user.
3982 * @param string $type Return type (atom, rss, xml, json)
3984 * @return array|string
3985 * @throws BadRequestException
3986 * @throws ForbiddenException
3987 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3989 function api_direct_messages_sentbox($type)
3991 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3992 return api_direct_messages_box($type, "sentbox", $verbose);
3996 * Returns the most recent direct messages sent to the user.
3998 * @param string $type Return type (atom, rss, xml, json)
4000 * @return array|string
4001 * @throws BadRequestException
4002 * @throws ForbiddenException
4003 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4005 function api_direct_messages_inbox($type)
4007 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4008 return api_direct_messages_box($type, "inbox", $verbose);
4013 * @param string $type Return type (atom, rss, xml, json)
4015 * @return array|string
4016 * @throws BadRequestException
4017 * @throws ForbiddenException
4019 function api_direct_messages_all($type)
4021 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4022 return api_direct_messages_box($type, "all", $verbose);
4027 * @param string $type Return type (atom, rss, xml, json)
4029 * @return array|string
4030 * @throws BadRequestException
4031 * @throws ForbiddenException
4033 function api_direct_messages_conversation($type)
4035 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4036 return api_direct_messages_box($type, "conversation", $verbose);
4039 /// @TODO move to top of file or somewhere better
4040 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4041 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4042 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4043 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4046 * Returns an OAuth Request Token.
4048 * @see https://oauth.net/core/1.0/#auth_step1
4050 function api_oauth_request_token()
4052 $oauth1 = new FKOAuth1();
4054 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4055 } catch (Exception $e) {
4056 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4064 * Returns an OAuth Access Token.
4066 * @return array|string
4067 * @see https://oauth.net/core/1.0/#auth_step3
4069 function api_oauth_access_token()
4071 $oauth1 = new FKOAuth1();
4073 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4074 } catch (Exception $e) {
4075 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4082 /// @TODO move to top of file or somewhere better
4083 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4084 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4088 * @brief delete a complete photoalbum with all containing photos from database through api
4090 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4091 * @return string|array
4092 * @throws BadRequestException
4093 * @throws ForbiddenException
4094 * @throws InternalServerErrorException
4096 function api_fr_photoalbum_delete($type)
4098 if (api_user() === false) {
4099 throw new ForbiddenException();
4102 $album = defaults($_REQUEST, 'album', "");
4104 // we do not allow calls without album string
4106 throw new BadRequestException("no albumname specified");
4108 // check if album is existing
4110 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4114 if (!DBA::isResult($r)) {
4115 throw new BadRequestException("album not available");
4118 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4119 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4120 foreach ($r as $rr) {
4121 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4122 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4124 if (!DBA::isResult($photo_item)) {
4125 throw new InternalServerErrorException("problem with deleting items occured");
4127 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4130 // now let's delete all photos from the album
4131 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4133 // return success of deletion or error message
4135 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4136 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4138 throw new InternalServerErrorException("unknown error - deleting from database failed");
4143 * @brief update the name of the album for all photos of an album
4145 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4146 * @return string|array
4147 * @throws BadRequestException
4148 * @throws ForbiddenException
4149 * @throws InternalServerErrorException
4151 function api_fr_photoalbum_update($type)
4153 if (api_user() === false) {
4154 throw new ForbiddenException();
4157 $album = defaults($_REQUEST, 'album', "");
4158 $album_new = defaults($_REQUEST, 'album_new', "");
4160 // we do not allow calls without album string
4162 throw new BadRequestException("no albumname specified");
4164 if ($album_new == "") {
4165 throw new BadRequestException("no new albumname specified");
4167 // check if album is existing
4168 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4169 throw new BadRequestException("album not available");
4171 // now let's update all photos to the albumname
4172 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4174 // return success of updating or error message
4176 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4177 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4179 throw new InternalServerErrorException("unknown error - updating in database failed");
4185 * @brief list all photos of the authenticated user
4187 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4188 * @return string|array
4189 * @throws ForbiddenException
4190 * @throws InternalServerErrorException
4192 function api_fr_photos_list($type)
4194 if (api_user() === false) {
4195 throw new ForbiddenException();
4198 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4199 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4200 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4201 intval(local_user())
4204 'image/jpeg' => 'jpg',
4205 'image/png' => 'png',
4206 'image/gif' => 'gif'
4208 $data = ['photo'=>[]];
4209 if (DBA::isResult($r)) {
4210 foreach ($r as $rr) {
4212 $photo['id'] = $rr['resource-id'];
4213 $photo['album'] = $rr['album'];
4214 $photo['filename'] = $rr['filename'];
4215 $photo['type'] = $rr['type'];
4216 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4217 $photo['created'] = $rr['created'];
4218 $photo['edited'] = $rr['edited'];
4219 $photo['desc'] = $rr['desc'];
4221 if ($type == "xml") {
4222 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4224 $photo['thumb'] = $thumb;
4225 $data['photo'][] = $photo;
4229 return api_format_data("photos", $type, $data);
4233 * @brief upload a new photo or change an existing photo
4235 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4236 * @return string|array
4237 * @throws BadRequestException
4238 * @throws ForbiddenException
4239 * @throws ImagickException
4240 * @throws InternalServerErrorException
4241 * @throws NotFoundException
4243 function api_fr_photo_create_update($type)
4245 if (api_user() === false) {
4246 throw new ForbiddenException();
4249 $photo_id = defaults($_REQUEST, 'photo_id', null);
4250 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4251 $album = defaults($_REQUEST, 'album', null);
4252 $album_new = defaults($_REQUEST, 'album_new', null);
4253 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4254 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4255 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4256 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4257 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4259 // do several checks on input parameters
4260 // we do not allow calls without album string
4261 if ($album == null) {
4262 throw new BadRequestException("no albumname specified");
4264 // if photo_id == null --> we are uploading a new photo
4265 if ($photo_id == null) {
4268 // error if no media posted in create-mode
4269 if (empty($_FILES['media'])) {
4271 throw new BadRequestException("no media data submitted");
4274 // album_new will be ignored in create-mode
4279 // check if photo is existing in databasei
4280 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4281 throw new BadRequestException("photo not available");
4285 // checks on acl strings provided by clients
4286 $acl_input_error = false;
4287 $acl_input_error |= check_acl_input($allow_cid);
4288 $acl_input_error |= check_acl_input($deny_cid);
4289 $acl_input_error |= check_acl_input($allow_gid);
4290 $acl_input_error |= check_acl_input($deny_gid);
4291 if ($acl_input_error) {
4292 throw new BadRequestException("acl data invalid");
4294 // now let's upload the new media in create-mode
4295 if ($mode == "create") {
4296 $media = $_FILES['media'];
4297 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4299 // return success of updating or error message
4300 if (!is_null($data)) {
4301 return api_format_data("photo_create", $type, $data);
4303 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4307 // now let's do the changes in update-mode
4308 if ($mode == "update") {
4309 $updated_fields = [];
4311 if (!is_null($desc)) {
4312 $updated_fields['desc'] = $desc;
4315 if (!is_null($album_new)) {
4316 $updated_fields['album'] = $album_new;
4319 if (!is_null($allow_cid)) {
4320 $allow_cid = trim($allow_cid);
4321 $updated_fields['allow_cid'] = $allow_cid;
4324 if (!is_null($deny_cid)) {
4325 $deny_cid = trim($deny_cid);
4326 $updated_fields['deny_cid'] = $deny_cid;
4329 if (!is_null($allow_gid)) {
4330 $allow_gid = trim($allow_gid);
4331 $updated_fields['allow_gid'] = $allow_gid;
4334 if (!is_null($deny_gid)) {
4335 $deny_gid = trim($deny_gid);
4336 $updated_fields['deny_gid'] = $deny_gid;
4340 if (count($updated_fields) > 0) {
4341 $nothingtodo = false;
4342 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4344 $nothingtodo = true;
4347 if (!empty($_FILES['media'])) {
4348 $nothingtodo = false;
4349 $media = $_FILES['media'];
4350 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4351 if (!is_null($data)) {
4352 return api_format_data("photo_update", $type, $data);
4356 // return success of updating or error message
4358 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4359 return api_format_data("photo_update", $type, ['$result' => $answer]);
4362 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4363 return api_format_data("photo_update", $type, ['$result' => $answer]);
4365 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4368 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4372 * @brief delete a single photo from the database through api
4374 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4375 * @return string|array
4376 * @throws BadRequestException
4377 * @throws ForbiddenException
4378 * @throws InternalServerErrorException
4380 function api_fr_photo_delete($type)
4382 if (api_user() === false) {
4383 throw new ForbiddenException();
4387 $photo_id = defaults($_REQUEST, 'photo_id', null);
4389 // do several checks on input parameters
4390 // we do not allow calls without photo id
4391 if ($photo_id == null) {
4392 throw new BadRequestException("no photo_id specified");
4395 // check if photo is existing in database
4396 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4397 throw new BadRequestException("photo not available");
4400 // now we can perform on the deletion of the photo
4401 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4403 // return success of deletion or error message
4405 // retrieve the id of the parent element (the photo element)
4406 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4407 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4409 if (!DBA::isResult($photo_item)) {
4410 throw new InternalServerErrorException("problem with deleting items occured");
4412 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4413 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4414 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4416 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4417 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4419 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4425 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4427 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4428 * @return string|array
4429 * @throws BadRequestException
4430 * @throws ForbiddenException
4431 * @throws InternalServerErrorException
4432 * @throws NotFoundException
4434 function api_fr_photo_detail($type)
4436 if (api_user() === false) {
4437 throw new ForbiddenException();
4439 if (empty($_REQUEST['photo_id'])) {
4440 throw new BadRequestException("No photo id.");
4443 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4444 $photo_id = $_REQUEST['photo_id'];
4446 // prepare json/xml output with data from database for the requested photo
4447 $data = prepare_photo_data($type, $scale, $photo_id);
4449 return api_format_data("photo_detail", $type, $data);
4454 * Updates the user’s profile image.
4456 * @brief updates the profile image for the user (either a specified profile or the default profile)
4458 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4460 * @return string|array
4461 * @throws BadRequestException
4462 * @throws ForbiddenException
4463 * @throws ImagickException
4464 * @throws InternalServerErrorException
4465 * @throws NotFoundException
4466 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4468 function api_account_update_profile_image($type)
4470 if (api_user() === false) {
4471 throw new ForbiddenException();
4474 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4476 // error if image data is missing
4477 if (empty($_FILES['image'])) {
4478 throw new BadRequestException("no media data submitted");
4481 // check if specified profile id is valid
4482 if ($profile_id != 0) {
4483 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4484 // error message if specified profile id is not in database
4485 if (!DBA::isResult($profile)) {
4486 throw new BadRequestException("profile_id not available");
4488 $is_default_profile = $profile['is-default'];
4490 $is_default_profile = 1;
4493 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4495 if (!empty($_FILES['image'])) {
4496 $media = $_FILES['image'];
4497 } elseif (!empty($_FILES['media'])) {
4498 $media = $_FILES['media'];
4500 // save new profile image
4501 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4504 if (is_array($media['type'])) {
4505 $filetype = $media['type'][0];
4507 $filetype = $media['type'];
4509 if ($filetype == "image/jpeg") {
4511 } elseif ($filetype == "image/png") {
4514 throw new InternalServerErrorException('Unsupported filetype');
4517 // change specified profile or all profiles to the new resource-id
4518 if ($is_default_profile) {
4519 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4520 Photo::update(['profile' => false], $condition);
4522 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4523 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4524 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4527 Contact::updateSelfFromUserID(api_user(), true);
4529 // Update global directory in background
4530 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4531 if ($url && strlen(Config::get('system', 'directory'))) {
4532 Worker::add(PRIORITY_LOW, "Directory", $url);
4535 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4537 // output for client
4539 return api_account_verify_credentials($type);
4541 // SaveMediaToDatabase failed for some reason
4542 throw new InternalServerErrorException("image upload failed");
4546 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4547 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4548 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4549 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4550 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4551 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4552 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4553 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4554 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4557 * Update user profile
4559 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4561 * @return array|string
4562 * @throws BadRequestException
4563 * @throws ForbiddenException
4564 * @throws ImagickException
4565 * @throws InternalServerErrorException
4566 * @throws UnauthorizedException
4568 function api_account_update_profile($type)
4570 $local_user = api_user();
4571 $api_user = api_get_user(get_app());
4573 if (!empty($_POST['name'])) {
4574 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4575 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4576 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4577 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4580 if (isset($_POST['description'])) {
4581 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4582 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4583 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4586 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4587 // Update global directory in background
4588 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4589 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4592 return api_account_verify_credentials($type);
4595 /// @TODO move to top of file or somewhere better
4596 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4600 * @param string $acl_string
4604 function check_acl_input($acl_string)
4606 if ($acl_string == null || $acl_string == " ") {
4609 $contact_not_found = false;
4611 // split <x><y><z> into array of cid's
4612 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4614 // check for each cid if it is available on server
4615 $cid_array = $array[0];
4616 foreach ($cid_array as $cid) {
4617 $cid = str_replace("<", "", $cid);
4618 $cid = str_replace(">", "", $cid);
4619 $condition = ['id' => $cid, 'uid' => api_user()];
4620 $contact_not_found |= !DBA::exists('contact', $condition);
4622 return $contact_not_found;
4627 * @param string $mediatype
4628 * @param array $media
4629 * @param string $type
4630 * @param string $album
4631 * @param string $allow_cid
4632 * @param string $deny_cid
4633 * @param string $allow_gid
4634 * @param string $deny_gid
4635 * @param string $desc
4636 * @param integer $profile
4637 * @param boolean $visibility
4638 * @param string $photo_id
4640 * @throws BadRequestException
4641 * @throws ForbiddenException
4642 * @throws ImagickException
4643 * @throws InternalServerErrorException
4644 * @throws NotFoundException
4646 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)
4654 if (is_array($media)) {
4655 if (is_array($media['tmp_name'])) {
4656 $src = $media['tmp_name'][0];
4658 $src = $media['tmp_name'];
4660 if (is_array($media['name'])) {
4661 $filename = basename($media['name'][0]);
4663 $filename = basename($media['name']);
4665 if (is_array($media['size'])) {
4666 $filesize = intval($media['size'][0]);
4668 $filesize = intval($media['size']);
4670 if (is_array($media['type'])) {
4671 $filetype = $media['type'][0];
4673 $filetype = $media['type'];
4677 if ($filetype == "") {
4678 $filetype=Image::guessType($filename);
4680 $imagedata = @getimagesize($src);
4682 $filetype = $imagedata['mime'];
4685 "File upload src: " . $src . " - filename: " . $filename .
4686 " - size: " . $filesize . " - type: " . $filetype,
4690 // check if there was a php upload error
4691 if ($filesize == 0 && $media['error'] == 1) {
4692 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4694 // check against max upload size within Friendica instance
4695 $maximagesize = Config::get('system', 'maximagesize');
4696 if ($maximagesize && ($filesize > $maximagesize)) {
4697 $formattedBytes = Strings::formatBytes($maximagesize);
4698 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4701 // create Photo instance with the data of the image
4702 $imagedata = @file_get_contents($src);
4703 $Image = new Image($imagedata, $filetype);
4704 if (!$Image->isValid()) {
4705 throw new InternalServerErrorException("unable to process image data");
4708 // check orientation of image
4709 $Image->orient($src);
4712 // check max length of images on server
4713 $max_length = Config::get('system', 'max_image_length');
4715 $max_length = MAX_IMAGE_LENGTH;
4717 if ($max_length > 0) {
4718 $Image->scaleDown($max_length);
4719 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4721 $width = $Image->getWidth();
4722 $height = $Image->getHeight();
4724 // create a new resource-id if not already provided
4725 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4727 if ($mediatype == "photo") {
4728 // upload normal image (scales 0, 1, 2)
4729 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4731 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4733 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4735 if ($width > 640 || $height > 640) {
4736 $Image->scaleDown(640);
4737 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4739 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4743 if ($width > 320 || $height > 320) {
4744 $Image->scaleDown(320);
4745 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4747 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4750 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4751 } elseif ($mediatype == "profileimage") {
4752 // upload profile image (scales 4, 5, 6)
4753 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4755 if ($width > 300 || $height > 300) {
4756 $Image->scaleDown(300);
4757 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4759 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4763 if ($width > 80 || $height > 80) {
4764 $Image->scaleDown(80);
4765 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4767 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4771 if ($width > 48 || $height > 48) {
4772 $Image->scaleDown(48);
4773 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4775 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4778 $Image->__destruct();
4779 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4782 if (isset($r) && $r) {
4783 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4784 if ($photo_id == null && $mediatype == "photo") {
4785 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4787 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4788 return prepare_photo_data($type, false, $hash);
4790 throw new InternalServerErrorException("image upload failed");
4796 * @param string $hash
4797 * @param string $allow_cid
4798 * @param string $deny_cid
4799 * @param string $allow_gid
4800 * @param string $deny_gid
4801 * @param string $filetype
4802 * @param boolean $visibility
4803 * @throws InternalServerErrorException
4805 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4807 // get data about the api authenticated user
4808 $uri = Item::newURI(intval(api_user()));
4809 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4812 $arr['guid'] = System::createUUID();
4813 $arr['uid'] = intval(api_user());
4815 $arr['parent-uri'] = $uri;
4816 $arr['type'] = 'photo';
4818 $arr['resource-id'] = $hash;
4819 $arr['contact-id'] = $owner_record['id'];
4820 $arr['owner-name'] = $owner_record['name'];
4821 $arr['owner-link'] = $owner_record['url'];
4822 $arr['owner-avatar'] = $owner_record['thumb'];
4823 $arr['author-name'] = $owner_record['name'];
4824 $arr['author-link'] = $owner_record['url'];
4825 $arr['author-avatar'] = $owner_record['thumb'];
4827 $arr['allow_cid'] = $allow_cid;
4828 $arr['allow_gid'] = $allow_gid;
4829 $arr['deny_cid'] = $deny_cid;
4830 $arr['deny_gid'] = $deny_gid;
4831 $arr['visible'] = $visibility;
4835 'image/jpeg' => 'jpg',
4836 'image/png' => 'png',
4837 'image/gif' => 'gif'
4840 // adds link to the thumbnail scale photo
4841 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4842 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4845 // do the magic for storing the item in the database and trigger the federation to other contacts
4851 * @param string $type
4853 * @param string $photo_id
4856 * @throws BadRequestException
4857 * @throws ForbiddenException
4858 * @throws ImagickException
4859 * @throws InternalServerErrorException
4860 * @throws NotFoundException
4861 * @throws UnauthorizedException
4863 function prepare_photo_data($type, $scale, $photo_id)
4866 $user_info = api_get_user($a);
4868 if ($user_info === false) {
4869 throw new ForbiddenException();
4872 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4873 $data_sql = ($scale === false ? "" : "data, ");
4875 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4876 // clients needs to convert this in their way for further processing
4878 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4879 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4880 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4881 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4883 intval(local_user()),
4884 DBA::escape($photo_id),
4889 'image/jpeg' => 'jpg',
4890 'image/png' => 'png',
4891 'image/gif' => 'gif'
4894 // prepare output data for photo
4895 if (DBA::isResult($r)) {
4896 $data = ['photo' => $r[0]];
4897 $data['photo']['id'] = $data['photo']['resource-id'];
4898 if ($scale !== false) {
4899 $data['photo']['data'] = base64_encode($data['photo']['data']);
4901 unset($data['photo']['datasize']); //needed only with scale param
4903 if ($type == "xml") {
4904 $data['photo']['links'] = [];
4905 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4906 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4908 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4911 $data['photo']['link'] = [];
4912 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4914 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4915 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4919 unset($data['photo']['resource-id']);
4920 unset($data['photo']['minscale']);
4921 unset($data['photo']['maxscale']);
4923 throw new NotFoundException();
4926 // retrieve item element for getting activities (like, dislike etc.) related to photo
4927 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4928 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4930 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4932 // retrieve comments on photo
4933 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4934 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4936 $statuses = Item::selectForUser(api_user(), [], $condition);
4938 // prepare output of comments
4939 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4941 if ($type == "xml") {
4943 foreach ($commentData as $comment) {
4944 $comments[$k++ . ":comment"] = $comment;
4947 foreach ($commentData as $comment) {
4948 $comments[] = $comment;
4951 $data['photo']['friendica_comments'] = $comments;
4953 // include info if rights on photo and rights on item are mismatching
4954 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4955 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4956 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4957 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4958 $data['photo']['rights_mismatch'] = $rights_mismatch;
4965 * Similar as /mod/redir.php
4966 * redirect to 'url' after dfrn auth
4968 * Why this when there is mod/redir.php already?
4969 * This use api_user() and api_login()
4972 * c_url: url of remote contact to auth to
4973 * url: string, url to redirect after auth
4975 function api_friendica_remoteauth()
4977 $url = defaults($_GET, 'url', '');
4978 $c_url = defaults($_GET, 'c_url', '');
4980 if ($url === '' || $c_url === '') {
4981 throw new BadRequestException("Wrong parameters.");
4984 $c_url = Strings::normaliseLink($c_url);
4988 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4990 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
4991 throw new BadRequestException("Unknown contact");
4994 $cid = $contact['id'];
4996 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4998 if ($contact['duplex'] && $contact['issued-id']) {
4999 $orig_id = $contact['issued-id'];
5000 $dfrn_id = '1:' . $orig_id;
5002 if ($contact['duplex'] && $contact['dfrn-id']) {
5003 $orig_id = $contact['dfrn-id'];
5004 $dfrn_id = '0:' . $orig_id;
5007 $sec = Strings::getRandomHex();
5009 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5010 'sec' => $sec, 'expire' => time() + 45];
5011 DBA::insert('profile_check', $fields);
5013 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5014 $dest = ($url ? '&destination_url=' . $url : '');
5016 System::externalRedirect(
5017 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5018 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5019 . '&type=profile&sec=' . $sec . $dest
5022 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5025 * @brief Return the item shared, if the item contains only the [share] tag
5027 * @param array $item Sharer item
5028 * @return array|false Shared item or false if not a reshare
5029 * @throws ImagickException
5030 * @throws InternalServerErrorException
5032 function api_share_as_retweet(&$item)
5034 $body = trim($item["body"]);
5036 if (Diaspora::isReshare($body, false) === false) {
5037 if ($item['author-id'] == $item['owner-id']) {
5040 // Reshares from OStatus, ActivityPub and Twitter
5041 $reshared_item = $item;
5042 $reshared_item['owner-id'] = $reshared_item['author-id'];
5043 $reshared_item['owner-link'] = $reshared_item['author-link'];
5044 $reshared_item['owner-name'] = $reshared_item['author-name'];
5045 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5046 return $reshared_item;
5050 /// @TODO "$1" should maybe mean '$1' ?
5051 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5053 * Skip if there is no shared message in there
5054 * we already checked this in diaspora::isReshare()
5055 * but better one more than one less...
5057 if (($body == $attributes) || empty($attributes)) {
5061 // build the fake reshared item
5062 $reshared_item = $item;
5065 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5066 if (!empty($matches[1])) {
5067 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5070 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5071 if (!empty($matches[1])) {
5072 $author = $matches[1];
5076 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5077 if (!empty($matches[1])) {
5078 $profile = $matches[1];
5081 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5082 if (!empty($matches[1])) {
5083 $profile = $matches[1];
5087 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5088 if (!empty($matches[1])) {
5089 $avatar = $matches[1];
5092 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5093 if (!empty($matches[1])) {
5094 $avatar = $matches[1];
5098 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5099 if (!empty($matches[1])) {
5100 $link = $matches[1];
5103 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5104 if (!empty($matches[1])) {
5105 $link = $matches[1];
5109 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5110 if (!empty($matches[1])) {
5111 $posted = $matches[1];
5114 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5115 if (!empty($matches[1])) {
5116 $posted = $matches[1];
5119 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5121 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5125 $reshared_item["body"] = $shared_body;
5126 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5127 $reshared_item["author-name"] = $author;
5128 $reshared_item["author-link"] = $profile;
5129 $reshared_item["author-avatar"] = $avatar;
5130 $reshared_item["plink"] = $link;
5131 $reshared_item["created"] = $posted;
5132 $reshared_item["edited"] = $posted;
5134 return $reshared_item;
5139 * @param string $profile
5141 * @return string|false
5142 * @throws InternalServerErrorException
5143 * @todo remove trailing junk from profile url
5144 * @todo pump.io check has to check the website
5146 function api_get_nick($profile)
5151 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5152 DBA::escape(Strings::normaliseLink($profile))
5155 if (DBA::isResult($r)) {
5156 $nick = $r[0]["nick"];
5161 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5162 DBA::escape(Strings::normaliseLink($profile))
5165 if (DBA::isResult($r)) {
5166 $nick = $r[0]["nick"];
5171 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5172 if ($friendica != $profile) {
5178 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5179 if ($diaspora != $profile) {
5185 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5186 if ($twitter != $profile) {
5193 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5194 if ($StatusnetHost != $profile) {
5195 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5196 if ($StatusnetUser != $profile) {
5197 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5198 $user = json_decode($UserData);
5200 $nick = $user->screen_name;
5206 // To-Do: look at the page if its really a pumpio site
5207 //if (!$nick == "") {
5208 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5209 // if ($pumpio != $profile)
5211 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5224 * @param array $item
5229 function api_in_reply_to($item)
5233 $in_reply_to['status_id'] = null;
5234 $in_reply_to['user_id'] = null;
5235 $in_reply_to['status_id_str'] = null;
5236 $in_reply_to['user_id_str'] = null;
5237 $in_reply_to['screen_name'] = null;
5239 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5240 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5241 if (DBA::isResult($parent)) {
5242 $in_reply_to['status_id'] = intval($parent['id']);
5244 $in_reply_to['status_id'] = intval($item['parent']);
5247 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5249 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5250 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5252 if (DBA::isResult($parent)) {
5253 if ($parent['author-nick'] == "") {
5254 $parent['author-nick'] = api_get_nick($parent['author-link']);
5257 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5258 $in_reply_to['user_id'] = intval($parent['author-id']);
5259 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5262 // There seems to be situation, where both fields are identical:
5263 // https://github.com/friendica/friendica/issues/1010
5264 // This is a bugfix for that.
5265 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5266 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']]);
5267 $in_reply_to['status_id'] = null;
5268 $in_reply_to['user_id'] = null;
5269 $in_reply_to['status_id_str'] = null;
5270 $in_reply_to['user_id_str'] = null;
5271 $in_reply_to['screen_name'] = null;
5275 return $in_reply_to;
5280 * @param string $text
5283 * @throws InternalServerErrorException
5285 function api_clean_plain_items($text)
5287 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5289 $text = BBCode::cleanPictureLinks($text);
5290 $URLSearchString = "^\[\]";
5292 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5294 if ($include_entities == "true") {
5295 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5298 // Simplify "attachment" element
5299 $text = api_clean_attachments($text);
5305 * @brief Removes most sharing information for API text export
5307 * @param string $body The original body
5309 * @return string Cleaned body
5310 * @throws InternalServerErrorException
5312 function api_clean_attachments($body)
5314 $data = BBCode::getAttachmentData($body);
5321 if (isset($data["text"])) {
5322 $body = $data["text"];
5324 if (($body == "") && isset($data["title"])) {
5325 $body = $data["title"];
5327 if (isset($data["url"])) {
5328 $body .= "\n".$data["url"];
5330 $body .= $data["after"];
5337 * @param array $contacts
5341 function api_best_nickname(&$contacts)
5345 if (count($contacts) == 0) {
5349 foreach ($contacts as $contact) {
5350 if ($contact["network"] == "") {
5351 $contact["network"] = "dfrn";
5352 $best_contact = [$contact];
5356 if (sizeof($best_contact) == 0) {
5357 foreach ($contacts as $contact) {
5358 if ($contact["network"] == "dfrn") {
5359 $best_contact = [$contact];
5364 if (sizeof($best_contact) == 0) {
5365 foreach ($contacts as $contact) {
5366 if ($contact["network"] == "dspr") {
5367 $best_contact = [$contact];
5372 if (sizeof($best_contact) == 0) {
5373 foreach ($contacts as $contact) {
5374 if ($contact["network"] == "stat") {
5375 $best_contact = [$contact];
5380 if (sizeof($best_contact) == 0) {
5381 foreach ($contacts as $contact) {
5382 if ($contact["network"] == "pump") {
5383 $best_contact = [$contact];
5388 if (sizeof($best_contact) == 0) {
5389 foreach ($contacts as $contact) {
5390 if ($contact["network"] == "twit") {
5391 $best_contact = [$contact];
5396 if (sizeof($best_contact) == 1) {
5397 $contacts = $best_contact;
5399 $contacts = [$contacts[0]];
5404 * Return all or a specified group of the user with the containing contacts.
5406 * @param string $type Return type (atom, rss, xml, json)
5408 * @return array|string
5409 * @throws BadRequestException
5410 * @throws ForbiddenException
5411 * @throws ImagickException
5412 * @throws InternalServerErrorException
5413 * @throws UnauthorizedException
5415 function api_friendica_group_show($type)
5419 if (api_user() === false) {
5420 throw new ForbiddenException();
5424 $user_info = api_get_user($a);
5425 $gid = defaults($_REQUEST, 'gid', 0);
5426 $uid = $user_info['uid'];
5428 // get data of the specified group id or all groups if not specified
5431 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5435 // error message if specified gid is not in database
5436 if (!DBA::isResult($r)) {
5437 throw new BadRequestException("gid not available");
5441 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5446 // loop through all groups and retrieve all members for adding data in the user array
5448 foreach ($r as $rr) {
5449 $members = Contact::getByGroupId($rr['id']);
5452 if ($type == "xml") {
5453 $user_element = "users";
5455 foreach ($members as $member) {
5456 $user = api_get_user($a, $member['nurl']);
5457 $users[$k++.":user"] = $user;
5460 $user_element = "user";
5461 foreach ($members as $member) {
5462 $user = api_get_user($a, $member['nurl']);
5466 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5468 return api_format_data("groups", $type, ['group' => $grps]);
5470 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5474 * Delete the specified group of the user.
5476 * @param string $type Return type (atom, rss, xml, json)
5478 * @return array|string
5479 * @throws BadRequestException
5480 * @throws ForbiddenException
5481 * @throws ImagickException
5482 * @throws InternalServerErrorException
5483 * @throws UnauthorizedException
5485 function api_friendica_group_delete($type)
5489 if (api_user() === false) {
5490 throw new ForbiddenException();
5494 $user_info = api_get_user($a);
5495 $gid = defaults($_REQUEST, 'gid', 0);
5496 $name = defaults($_REQUEST, 'name', "");
5497 $uid = $user_info['uid'];
5499 // error if no gid specified
5500 if ($gid == 0 || $name == "") {
5501 throw new BadRequestException('gid or name not specified');
5504 // get data of the specified group id
5506 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5510 // error message if specified gid is not in database
5511 if (!DBA::isResult($r)) {
5512 throw new BadRequestException('gid not available');
5515 // get data of the specified group id and group name
5517 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5522 // error message if specified gid is not in database
5523 if (!DBA::isResult($rname)) {
5524 throw new BadRequestException('wrong group name');
5528 $ret = Group::removeByName($uid, $name);
5531 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5532 return api_format_data("group_delete", $type, ['result' => $success]);
5534 throw new BadRequestException('other API error');
5537 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5542 * @param string $type Return type (atom, rss, xml, json)
5544 * @return array|string
5545 * @throws BadRequestException
5546 * @throws ForbiddenException
5547 * @throws ImagickException
5548 * @throws InternalServerErrorException
5549 * @throws UnauthorizedException
5550 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5552 function api_lists_destroy($type)
5556 if (api_user() === false) {
5557 throw new ForbiddenException();
5561 $user_info = api_get_user($a);
5562 $gid = defaults($_REQUEST, 'list_id', 0);
5563 $uid = $user_info['uid'];
5565 // error if no gid specified
5567 throw new BadRequestException('gid not specified');
5570 // get data of the specified group id
5571 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5572 // error message if specified gid is not in database
5574 throw new BadRequestException('gid not available');
5577 if (Group::remove($gid)) {
5579 'name' => $group['name'],
5580 'id' => intval($gid),
5581 'id_str' => (string) $gid,
5582 'user' => $user_info
5585 return api_format_data("lists", $type, ['lists' => $list]);
5588 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5591 * Add a new group to the database.
5593 * @param string $name Group name
5594 * @param int $uid User ID
5595 * @param array $users List of users to add to the group
5598 * @throws BadRequestException
5600 function group_create($name, $uid, $users = [])
5602 // error if no name specified
5604 throw new BadRequestException('group name not specified');
5607 // get data of the specified group name
5609 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5613 // error message if specified group name already exists
5614 if (DBA::isResult($rname)) {
5615 throw new BadRequestException('group name already exists');
5618 // check if specified group name is a deleted group
5620 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5624 // error message if specified group name already exists
5625 if (DBA::isResult($rname)) {
5626 $reactivate_group = true;
5630 $ret = Group::create($uid, $name);
5632 $gid = Group::getIdByName($uid, $name);
5634 throw new BadRequestException('other API error');
5638 $erroraddinguser = false;
5640 foreach ($users as $user) {
5641 $cid = $user['cid'];
5642 // check if user really exists as contact
5644 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5648 if (count($contact)) {
5649 Group::addMember($gid, $cid);
5651 $erroraddinguser = true;
5652 $errorusers[] = $cid;
5656 // return success message incl. missing users in array
5657 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5659 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5663 * Create the specified group with the posted array of contacts.
5665 * @param string $type Return type (atom, rss, xml, json)
5667 * @return array|string
5668 * @throws BadRequestException
5669 * @throws ForbiddenException
5670 * @throws ImagickException
5671 * @throws InternalServerErrorException
5672 * @throws UnauthorizedException
5674 function api_friendica_group_create($type)
5678 if (api_user() === false) {
5679 throw new ForbiddenException();
5683 $user_info = api_get_user($a);
5684 $name = defaults($_REQUEST, 'name', "");
5685 $uid = $user_info['uid'];
5686 $json = json_decode($_POST['json'], true);
5687 $users = $json['user'];
5689 $success = group_create($name, $uid, $users);
5691 return api_format_data("group_create", $type, ['result' => $success]);
5693 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5696 * Create a new group.
5698 * @param string $type Return type (atom, rss, xml, json)
5700 * @return array|string
5701 * @throws BadRequestException
5702 * @throws ForbiddenException
5703 * @throws ImagickException
5704 * @throws InternalServerErrorException
5705 * @throws UnauthorizedException
5706 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5708 function api_lists_create($type)
5712 if (api_user() === false) {
5713 throw new ForbiddenException();
5717 $user_info = api_get_user($a);
5718 $name = defaults($_REQUEST, 'name', "");
5719 $uid = $user_info['uid'];
5721 $success = group_create($name, $uid);
5722 if ($success['success']) {
5724 'name' => $success['name'],
5725 'id' => intval($success['gid']),
5726 'id_str' => (string) $success['gid'],
5727 'user' => $user_info
5730 return api_format_data("lists", $type, ['lists'=>$grp]);
5733 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5736 * Update the specified group with the posted array of contacts.
5738 * @param string $type Return type (atom, rss, xml, json)
5740 * @return array|string
5741 * @throws BadRequestException
5742 * @throws ForbiddenException
5743 * @throws ImagickException
5744 * @throws InternalServerErrorException
5745 * @throws UnauthorizedException
5747 function api_friendica_group_update($type)
5751 if (api_user() === false) {
5752 throw new ForbiddenException();
5756 $user_info = api_get_user($a);
5757 $uid = $user_info['uid'];
5758 $gid = defaults($_REQUEST, 'gid', 0);
5759 $name = defaults($_REQUEST, 'name', "");
5760 $json = json_decode($_POST['json'], true);
5761 $users = $json['user'];
5763 // error if no name specified
5765 throw new BadRequestException('group name not specified');
5768 // error if no gid specified
5770 throw new BadRequestException('gid not specified');
5774 $members = Contact::getByGroupId($gid);
5775 foreach ($members as $member) {
5776 $cid = $member['id'];
5777 foreach ($users as $user) {
5778 $found = ($user['cid'] == $cid ? true : false);
5780 if (!isset($found) || !$found) {
5781 Group::removeMemberByName($uid, $name, $cid);
5786 $erroraddinguser = false;
5788 foreach ($users as $user) {
5789 $cid = $user['cid'];
5790 // check if user really exists as contact
5792 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5797 if (count($contact)) {
5798 Group::addMember($gid, $cid);
5800 $erroraddinguser = true;
5801 $errorusers[] = $cid;
5805 // return success message incl. missing users in array
5806 $status = ($erroraddinguser ? "missing user" : "ok");
5807 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5808 return api_format_data("group_update", $type, ['result' => $success]);
5811 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5814 * Update information about a group.
5816 * @param string $type Return type (atom, rss, xml, json)
5818 * @return array|string
5819 * @throws BadRequestException
5820 * @throws ForbiddenException
5821 * @throws ImagickException
5822 * @throws InternalServerErrorException
5823 * @throws UnauthorizedException
5824 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5826 function api_lists_update($type)
5830 if (api_user() === false) {
5831 throw new ForbiddenException();
5835 $user_info = api_get_user($a);
5836 $gid = defaults($_REQUEST, 'list_id', 0);
5837 $name = defaults($_REQUEST, 'name', "");
5838 $uid = $user_info['uid'];
5840 // error if no gid specified
5842 throw new BadRequestException('gid not specified');
5845 // get data of the specified group id
5846 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5847 // error message if specified gid is not in database
5849 throw new BadRequestException('gid not available');
5852 if (Group::update($gid, $name)) {
5855 'id' => intval($gid),
5856 'id_str' => (string) $gid,
5857 'user' => $user_info
5860 return api_format_data("lists", $type, ['lists' => $list]);
5864 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5868 * @param string $type Return type (atom, rss, xml, json)
5870 * @return array|string
5871 * @throws BadRequestException
5872 * @throws ForbiddenException
5873 * @throws ImagickException
5874 * @throws InternalServerErrorException
5876 function api_friendica_activity($type)
5880 if (api_user() === false) {
5881 throw new ForbiddenException();
5883 $verb = strtolower($a->argv[3]);
5884 $verb = preg_replace("|\..*$|", "", $verb);
5886 $id = defaults($_REQUEST, 'id', 0);
5888 $res = Item::performLike($id, $verb);
5891 if ($type == "xml") {
5896 return api_format_data('ok', $type, ['ok' => $ok]);
5898 throw new BadRequestException('Error adding activity');
5902 /// @TODO move to top of file or somewhere better
5903 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5904 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5905 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5906 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5907 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5908 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5909 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5910 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5911 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5912 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5915 * @brief Returns notifications
5917 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5918 * @return string|array
5919 * @throws BadRequestException
5920 * @throws ForbiddenException
5921 * @throws InternalServerErrorException
5923 function api_friendica_notification($type)
5927 if (api_user() === false) {
5928 throw new ForbiddenException();
5931 throw new BadRequestException("Invalid argument count");
5933 $nm = new NotificationsManager();
5935 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
5937 if ($type == "xml") {
5939 if (!empty($notes)) {
5940 foreach ($notes as $note) {
5941 $xmlnotes[] = ["@attributes" => $note];
5947 return api_format_data("notes", $type, ['note' => $notes]);
5951 * POST request with 'id' param as notification id
5953 * @brief Set notification as seen and returns associated item (if possible)
5955 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5956 * @return string|array
5957 * @throws BadRequestException
5958 * @throws ForbiddenException
5959 * @throws ImagickException
5960 * @throws InternalServerErrorException
5961 * @throws UnauthorizedException
5963 function api_friendica_notification_seen($type)
5966 $user_info = api_get_user($a);
5968 if (api_user() === false || $user_info === false) {
5969 throw new ForbiddenException();
5972 throw new BadRequestException("Invalid argument count");
5975 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5977 $nm = new NotificationsManager();
5978 $note = $nm->getByID($id);
5979 if (is_null($note)) {
5980 throw new BadRequestException("Invalid argument");
5983 $nm->setSeen($note);
5984 if ($note['otype']=='item') {
5985 // would be really better with an ItemsManager and $im->getByID() :-P
5986 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5987 if (DBA::isResult($item)) {
5988 // we found the item, return it to the user
5989 $ret = api_format_items([$item], $user_info, false, $type);
5990 $data = ['status' => $ret];
5991 return api_format_data("status", $type, $data);
5993 // the item can't be found, but we set the note as seen, so we count this as a success
5995 return api_format_data('result', $type, ['result' => "success"]);
5998 /// @TODO move to top of file or somewhere better
5999 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6000 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6003 * @brief update a direct_message to seen state
6005 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6006 * @return string|array (success result=ok, error result=error with error message)
6007 * @throws BadRequestException
6008 * @throws ForbiddenException
6009 * @throws ImagickException
6010 * @throws InternalServerErrorException
6011 * @throws UnauthorizedException
6013 function api_friendica_direct_messages_setseen($type)
6016 if (api_user() === false) {
6017 throw new ForbiddenException();
6021 $user_info = api_get_user($a);
6022 $uid = $user_info['uid'];
6023 $id = defaults($_REQUEST, 'id', 0);
6025 // return error if id is zero
6027 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6028 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6031 // error message if specified id is not in database
6032 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6033 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6034 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6037 // update seen indicator
6038 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6042 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6043 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6045 $answer = ['result' => 'error', 'message' => 'unknown error'];
6046 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6050 /// @TODO move to top of file or somewhere better
6051 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6054 * @brief search for direct_messages containing a searchstring through api
6056 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6057 * @param string $box
6058 * @return string|array (success: success=true if found and search_result contains found messages,
6059 * success=false if nothing was found, search_result='nothing found',
6060 * error: result=error with error message)
6061 * @throws BadRequestException
6062 * @throws ForbiddenException
6063 * @throws ImagickException
6064 * @throws InternalServerErrorException
6065 * @throws UnauthorizedException
6067 function api_friendica_direct_messages_search($type, $box = "")
6071 if (api_user() === false) {
6072 throw new ForbiddenException();
6076 $user_info = api_get_user($a);
6077 $searchstring = defaults($_REQUEST, 'searchstring', "");
6078 $uid = $user_info['uid'];
6080 // error if no searchstring specified
6081 if ($searchstring == "") {
6082 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6083 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6086 // get data for the specified searchstring
6088 "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",
6090 DBA::escape('%'.$searchstring.'%')
6093 $profile_url = $user_info["url"];
6095 // message if nothing was found
6096 if (!DBA::isResult($r)) {
6097 $success = ['success' => false, 'search_results' => 'problem with query'];
6098 } elseif (count($r) == 0) {
6099 $success = ['success' => false, 'search_results' => 'nothing found'];
6102 foreach ($r as $item) {
6103 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6104 $recipient = $user_info;
6105 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6106 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6107 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6108 $sender = $user_info;
6111 if (isset($recipient) && isset($sender)) {
6112 $ret[] = api_format_messages($item, $recipient, $sender);
6115 $success = ['success' => true, 'search_results' => $ret];
6118 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6121 /// @TODO move to top of file or somewhere better
6122 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6125 * @brief return data of all the profiles a user has to the client
6127 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6128 * @return string|array
6129 * @throws BadRequestException
6130 * @throws ForbiddenException
6131 * @throws ImagickException
6132 * @throws InternalServerErrorException
6133 * @throws UnauthorizedException
6135 function api_friendica_profile_show($type)
6139 if (api_user() === false) {
6140 throw new ForbiddenException();
6144 $profile_id = defaults($_REQUEST, 'profile_id', 0);
6146 // retrieve general information about profiles for user
6147 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6148 $directory = Config::get('system', 'directory');
6150 // get data of the specified profile id or all profiles of the user if not specified
6151 if ($profile_id != 0) {
6153 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
6158 // error message if specified gid is not in database
6159 if (!DBA::isResult($r)) {
6160 throw new BadRequestException("profile_id not available");
6164 "SELECT * FROM `profile` WHERE `uid` = %d",
6168 // loop through all returned profiles and retrieve data and users
6171 foreach ($r as $rr) {
6172 $profile = api_format_items_profiles($rr);
6174 // select all users from contact table, loop and prepare standard return for user data
6177 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
6182 foreach ($nurls as $nurl) {
6183 $user = api_get_user($a, $nurl['nurl']);
6184 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6186 $profile['users'] = $users;
6188 // add prepared profile data to array for final return
6189 if ($type == "xml") {
6190 $profiles[$k++ . ":profile"] = $profile;
6192 $profiles[] = $profile;
6196 // return settings, authenticated user and profiles data
6197 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6199 $result = ['multi_profiles' => $multi_profiles ? true : false,
6200 'global_dir' => $directory,
6201 'friendica_owner' => api_get_user($a, $self['nurl']),
6202 'profiles' => $profiles];
6203 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6205 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6208 * Returns a list of saved searches.
6210 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6212 * @param string $type Return format: json or xml
6214 * @return string|array
6217 function api_saved_searches_list($type)
6219 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6222 while ($term = $terms->fetch()) {
6224 'created_at' => api_date(time()),
6225 'id' => intval($term['id']),
6226 'id_str' => $term['id'],
6227 'name' => $term['term'],
6229 'query' => $term['term']
6235 return api_format_data("terms", $type, ['terms' => $result]);
6238 /// @TODO move to top of file or somewhere better
6239 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6242 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6244 * @brief Number of comments
6246 * @param object $data [Status, Status]
6250 function bindComments(&$data)
6252 if (count($data) == 0) {
6258 foreach ($data as $item) {
6259 $ids[] = $item['id'];
6262 $idStr = DBA::escape(implode(', ', $ids));
6263 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6264 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6265 $itemsData = DBA::toArray($items);
6267 foreach ($itemsData as $item) {
6268 $comments[$item['parent']] = $item['comments'];
6271 foreach ($data as $idx => $item) {
6273 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6278 @TODO Maybe open to implement?
6280 [pagename] => api/1.1/statuses/lookup.json
6281 [id] => 605138389168451584
6282 [include_cards] => true
6283 [cards_platform] => Android-12
6284 [include_entities] => true
6285 [include_my_retweet] => 1
6287 [include_reply_count] => true
6288 [include_descendent_reply_count] => true
6292 Not implemented by now:
6293 statuses/retweets_of_me
6298 account/update_location
6299 account/update_profile_background_image
6302 friendica/profile/update
6303 friendica/profile/create
6304 friendica/profile/delete
6306 Not implemented in status.net:
6307 statuses/retweeted_to_me
6308 statuses/retweeted_by_me
6309 direct_messages/destroy
6311 account/update_delivery_device
6312 notifications/follow