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)
938 if (api_user() === false) {
939 throw new ForbiddenException();
942 unset($_REQUEST["user_id"]);
943 unset($_GET["user_id"]);
945 unset($_REQUEST["screen_name"]);
946 unset($_GET["screen_name"]);
948 $skip_status = defaults($_REQUEST, 'skip_status', false);
950 $user_info = api_get_user($a);
952 // "verified" isn't used here in the standard
953 unset($user_info["verified"]);
955 // - Adding last status
957 $user_info["status"] = api_status_show("raw");
958 if (isset($user_info["status"])) {
959 if (!is_array($user_info["status"]) || !count($user_info["status"])) {
960 unset($user_info["status"]);
962 unset($user_info["status"]["user"]);
967 // "uid" and "self" are only needed for some internal stuff, so remove it from here
968 unset($user_info["uid"]);
969 unset($user_info["self"]);
971 return api_format_data("user", $type, ['user' => $user_info]);
974 /// @TODO move to top of file or somewhere better
975 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
978 * Get data from $_POST or $_GET
983 function requestdata($k)
985 if (!empty($_POST[$k])) {
988 if (!empty($_GET[$k])) {
995 * Deprecated function to upload media.
997 * @param string $type Return type (atom, rss, xml, json)
999 * @return array|string
1000 * @throws BadRequestException
1001 * @throws ForbiddenException
1002 * @throws ImagickException
1003 * @throws InternalServerErrorException
1004 * @throws UnauthorizedException
1006 function api_statuses_mediap($type)
1010 if (api_user() === false) {
1011 Logger::log('api_statuses_update: no user');
1012 throw new ForbiddenException();
1014 $user_info = api_get_user($a);
1016 $_REQUEST['profile_uid'] = api_user();
1017 $_REQUEST['api_source'] = true;
1018 $txt = requestdata('status');
1019 /// @TODO old-lost code?
1020 //$txt = urldecode(requestdata('status'));
1022 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1023 $txt = HTML::toBBCodeVideo($txt);
1024 $config = HTMLPurifier_Config::createDefault();
1025 $config->set('Cache.DefinitionImpl', null);
1026 $purifier = new HTMLPurifier($config);
1027 $txt = $purifier->purify($txt);
1029 $txt = HTML::toBBCode($txt);
1031 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1033 $picture = wall_upload_post($a, false);
1035 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1036 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1037 $item_id = item_post($a);
1039 // output the post that we just posted.
1040 return api_status_show($type, $item_id);
1043 /// @TODO move this to top of file or somewhere better!
1044 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1047 * Updates the user’s current status.
1049 * @param string $type Return type (atom, rss, xml, json)
1051 * @return array|string
1052 * @throws BadRequestException
1053 * @throws ForbiddenException
1054 * @throws ImagickException
1055 * @throws InternalServerErrorException
1056 * @throws TooManyRequestsException
1057 * @throws UnauthorizedException
1058 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1060 function api_statuses_update($type)
1064 if (api_user() === false) {
1065 Logger::log('api_statuses_update: no user');
1066 throw new ForbiddenException();
1071 // convert $_POST array items to the form we use for web posts.
1072 if (requestdata('htmlstatus')) {
1073 $txt = requestdata('htmlstatus');
1074 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1075 $txt = HTML::toBBCodeVideo($txt);
1077 $config = HTMLPurifier_Config::createDefault();
1078 $config->set('Cache.DefinitionImpl', null);
1080 $purifier = new HTMLPurifier($config);
1081 $txt = $purifier->purify($txt);
1083 $_REQUEST['body'] = HTML::toBBCode($txt);
1086 $_REQUEST['body'] = requestdata('status');
1089 $_REQUEST['title'] = requestdata('title');
1091 $parent = requestdata('in_reply_to_status_id');
1093 // Twidere sends "-1" if it is no reply ...
1094 if ($parent == -1) {
1098 if (ctype_digit($parent)) {
1099 $_REQUEST['parent'] = $parent;
1101 $_REQUEST['parent_uri'] = $parent;
1104 if (requestdata('lat') && requestdata('long')) {
1105 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1107 $_REQUEST['profile_uid'] = api_user();
1110 // Check for throttling (maximum posts per day, week and month)
1111 $throttle_day = Config::get('system', 'throttle_limit_day');
1112 if ($throttle_day > 0) {
1113 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1115 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1116 $posts_day = DBA::count('thread', $condition);
1118 if ($posts_day > $throttle_day) {
1119 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1120 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1121 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));
1125 $throttle_week = Config::get('system', 'throttle_limit_week');
1126 if ($throttle_week > 0) {
1127 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1129 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1130 $posts_week = DBA::count('thread', $condition);
1132 if ($posts_week > $throttle_week) {
1133 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1134 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1135 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));
1139 $throttle_month = Config::get('system', 'throttle_limit_month');
1140 if ($throttle_month > 0) {
1141 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1143 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1144 $posts_month = DBA::count('thread', $condition);
1146 if ($posts_month > $throttle_month) {
1147 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1148 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1149 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));
1154 if (!empty($_FILES['media'])) {
1155 // upload the image if we have one
1156 $picture = wall_upload_post($a, false);
1157 if (is_array($picture)) {
1158 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1162 // To-Do: Multiple IDs
1163 if (requestdata('media_ids')) {
1165 "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",
1166 intval(requestdata('media_ids')),
1169 if (DBA::isResult($r)) {
1170 $phototypes = Image::supportedTypes();
1171 $ext = $phototypes[$r[0]['type']];
1172 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1173 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1177 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1179 $_REQUEST['api_source'] = true;
1181 if (empty($_REQUEST['source'])) {
1182 $_REQUEST["source"] = api_source();
1185 // call out normal post function
1186 $item_id = item_post($a);
1188 // output the post that we just posted.
1189 return api_status_show($type, $item_id);
1192 /// @TODO move to top of file or somewhere better
1193 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1194 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1197 * Uploads an image to Friendica.
1200 * @throws BadRequestException
1201 * @throws ForbiddenException
1202 * @throws ImagickException
1203 * @throws InternalServerErrorException
1204 * @throws UnauthorizedException
1205 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1207 function api_media_upload()
1211 if (api_user() === false) {
1212 Logger::log('no user');
1213 throw new ForbiddenException();
1218 if (empty($_FILES['media'])) {
1220 throw new BadRequestException("No media.");
1223 $media = wall_upload_post($a, false);
1226 throw new InternalServerErrorException();
1230 $returndata["media_id"] = $media["id"];
1231 $returndata["media_id_string"] = (string)$media["id"];
1232 $returndata["size"] = $media["size"];
1233 $returndata["image"] = ["w" => $media["width"],
1234 "h" => $media["height"],
1235 "image_type" => $media["type"],
1236 "friendica_preview_url" => $media["preview"]];
1238 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1240 return ["media" => $returndata];
1243 /// @TODO move to top of file or somewhere better
1244 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1248 * @param string $type Return type (atom, rss, xml, json)
1250 * @param int $item_id
1251 * @return array|string
1252 * @throws BadRequestException
1253 * @throws ImagickException
1254 * @throws InternalServerErrorException
1255 * @throws UnauthorizedException
1257 function api_status_show($type, $item_id = 0)
1261 $user_info = api_get_user($a);
1263 Logger::log('api_status_show: user_info: '.print_r($user_info, true), Logger::DEBUG);
1265 if (!empty($item_id)) {
1266 // Get the item with the given id
1267 $condition = ['id' => $item_id];
1269 // get last public wall message
1270 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1271 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1274 if ($type == "raw") {
1275 $condition['private'] = false;
1278 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1280 if (DBA::isResult($lastwall)) {
1281 $in_reply_to = api_in_reply_to($lastwall);
1283 $converted = api_convert_item($lastwall);
1285 if ($type == "xml") {
1286 $geo = "georss:point";
1292 'created_at' => api_date($lastwall['created']),
1293 'id' => intval($lastwall['id']),
1294 'id_str' => (string) $lastwall['id'],
1295 'text' => $converted["text"],
1296 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1297 'truncated' => false,
1298 'in_reply_to_status_id' => $in_reply_to['status_id'],
1299 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1300 'in_reply_to_user_id' => $in_reply_to['user_id'],
1301 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1302 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1303 'user' => $user_info,
1305 'coordinates' => '',
1307 'contributors' => '',
1308 'is_quote_status' => false,
1309 'retweet_count' => 0,
1310 'favorite_count' => 0,
1311 'favorited' => $lastwall['starred'] ? true : false,
1312 'retweeted' => false,
1313 'possibly_sensitive' => false,
1315 'statusnet_html' => $converted["html"],
1316 'statusnet_conversation_id' => $lastwall['parent'],
1317 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
1320 if (count($converted["attachments"]) > 0) {
1321 $status_info["attachments"] = $converted["attachments"];
1324 if (count($converted["entities"]) > 0) {
1325 $status_info["entities"] = $converted["entities"];
1328 if ($status_info["source"] == 'web') {
1329 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1330 } elseif (ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) != $status_info["source"]) {
1331 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']).')');
1334 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1335 unset($status_info["user"]["uid"]);
1336 unset($status_info["user"]["self"]);
1338 Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
1340 if ($type == "raw") {
1341 return $status_info;
1344 return api_format_data("statuses", $type, ['status' => $status_info]);
1349 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1350 * The author's most recent status will be returned inline.
1352 * @param string $type Return type (atom, rss, xml, json)
1353 * @return array|string
1354 * @throws BadRequestException
1355 * @throws ImagickException
1356 * @throws InternalServerErrorException
1357 * @throws UnauthorizedException
1358 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1360 function api_users_show($type)
1364 $user_info = api_get_user($a);
1366 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1367 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1368 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1370 if (DBA::isResult($lastwall)) {
1371 $in_reply_to = api_in_reply_to($lastwall);
1373 $converted = api_convert_item($lastwall);
1375 if ($type == "xml") {
1376 $geo = "georss:point";
1381 $user_info['status'] = [
1382 'text' => $converted["text"],
1383 'truncated' => false,
1384 'created_at' => api_date($lastwall['created']),
1385 'in_reply_to_status_id' => $in_reply_to['status_id'],
1386 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1387 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1388 'id' => intval($lastwall['contact-id']),
1389 'id_str' => (string) $lastwall['contact-id'],
1390 'in_reply_to_user_id' => $in_reply_to['user_id'],
1391 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1392 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1394 'favorited' => $lastwall['starred'] ? true : false,
1395 'statusnet_html' => $converted["html"],
1396 'statusnet_conversation_id' => $lastwall['parent'],
1397 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1400 if (count($converted["attachments"]) > 0) {
1401 $user_info["status"]["attachments"] = $converted["attachments"];
1404 if (count($converted["entities"]) > 0) {
1405 $user_info["status"]["entities"] = $converted["entities"];
1408 if ($user_info["status"]["source"] == 'web') {
1409 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1412 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1413 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) . ')');
1417 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1418 unset($user_info["uid"]);
1419 unset($user_info["self"]);
1421 return api_format_data("user", $type, ['user' => $user_info]);
1424 /// @TODO move to top of file or somewhere better
1425 api_register_func('api/users/show', 'api_users_show');
1426 api_register_func('api/externalprofile/show', 'api_users_show');
1429 * Search a public user account.
1431 * @param string $type Return type (atom, rss, xml, json)
1433 * @return array|string
1434 * @throws BadRequestException
1435 * @throws ImagickException
1436 * @throws InternalServerErrorException
1437 * @throws UnauthorizedException
1438 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1440 function api_users_search($type)
1446 if (!empty($_GET['q'])) {
1447 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1449 if (!DBA::isResult($r)) {
1450 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1453 if (DBA::isResult($r)) {
1455 foreach ($r as $user) {
1456 $user_info = api_get_user($a, $user["id"]);
1458 if ($type == "xml") {
1459 $userlist[$k++.":user"] = $user_info;
1461 $userlist[] = $user_info;
1464 $userlist = ["users" => $userlist];
1466 throw new BadRequestException("User ".$_GET["q"]." not found.");
1469 throw new BadRequestException("No user specified.");
1472 return api_format_data("users", $type, $userlist);
1475 /// @TODO move to top of file or somewhere better
1476 api_register_func('api/users/search', 'api_users_search');
1479 * Return user objects
1481 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1483 * @param string $type Return format: json or xml
1485 * @return array|string
1486 * @throws BadRequestException
1487 * @throws ImagickException
1488 * @throws InternalServerErrorException
1489 * @throws NotFoundException if the results are empty.
1490 * @throws UnauthorizedException
1492 function api_users_lookup($type)
1496 if (!empty($_REQUEST['user_id'])) {
1497 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1499 $users[] = api_get_user(get_app(), $id);
1504 if (empty($users)) {
1505 throw new NotFoundException;
1508 return api_format_data("users", $type, ['users' => $users]);
1511 /// @TODO move to top of file or somewhere better
1512 api_register_func('api/users/lookup', 'api_users_lookup', true);
1515 * Returns statuses that match a specified query.
1517 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1519 * @param string $type Return format: json, xml, atom, rss
1521 * @return array|string
1522 * @throws BadRequestException if the "q" parameter is missing.
1523 * @throws ForbiddenException
1524 * @throws ImagickException
1525 * @throws InternalServerErrorException
1526 * @throws UnauthorizedException
1528 function api_search($type)
1531 $user_info = api_get_user($a);
1533 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1535 if (empty($_REQUEST['q'])) {
1536 throw new BadRequestException('q parameter is required.');
1539 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1542 $data['status'] = [];
1544 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1545 if (!empty($_REQUEST['rpp'])) {
1546 $count = $_REQUEST['rpp'];
1547 } elseif (!empty($_REQUEST['count'])) {
1548 $count = $_REQUEST['count'];
1551 $since_id = defaults($_REQUEST, 'since_id', 0);
1552 $max_id = defaults($_REQUEST, 'max_id', 0);
1553 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1554 $start = $page * $count;
1555 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1556 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1557 $searchTerm = $matches[1];
1558 $condition = ["`oid` > ?
1559 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1560 AND `otype` = ? AND `type` = ? AND `term` = ?",
1561 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1563 $condition[0] .= ' AND `oid` <= ?';
1564 $condition[] = $max_id;
1566 $terms = DBA::select('term', ['oid'], $condition, []);
1568 while ($term = DBA::fetch($terms)) {
1569 $itemIds[] = $term['oid'];
1573 if (empty($itemIds)) {
1574 return api_format_data('statuses', $type, $data);
1577 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1578 if ($exclude_replies) {
1579 $preCondition[] = '`id` = `parent`';
1582 $condition = [implode(' AND ', $preCondition)];
1584 $condition = ["`id` > ?
1585 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1586 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1587 AND `body` LIKE CONCAT('%',?,'%')",
1588 $since_id, api_user(), $_REQUEST['q']];
1590 $condition[0] .= ' AND `id` <= ?';
1591 $condition[] = $max_id;
1595 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1597 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1599 bindComments($data['status']);
1601 return api_format_data('statuses', $type, $data);
1604 /// @TODO move to top of file or somewhere better
1605 api_register_func('api/search/tweets', 'api_search', true);
1606 api_register_func('api/search', 'api_search', true);
1609 * Returns the most recent statuses posted by the user and the users they follow.
1611 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1613 * @param string $type Return type (atom, rss, xml, json)
1615 * @return array|string
1616 * @throws BadRequestException
1617 * @throws ForbiddenException
1618 * @throws ImagickException
1619 * @throws InternalServerErrorException
1620 * @throws UnauthorizedException
1621 * @todo Optional parameters
1622 * @todo Add reply info
1624 function api_statuses_home_timeline($type)
1627 $user_info = api_get_user($a);
1629 if (api_user() === false || $user_info === false) {
1630 throw new ForbiddenException();
1633 unset($_REQUEST["user_id"]);
1634 unset($_GET["user_id"]);
1636 unset($_REQUEST["screen_name"]);
1637 unset($_GET["screen_name"]);
1639 // get last network messages
1642 $count = defaults($_REQUEST, 'count', 20);
1643 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1647 $since_id = defaults($_REQUEST, 'since_id', 0);
1648 $max_id = defaults($_REQUEST, 'max_id', 0);
1649 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1650 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1652 $start = $page * $count;
1654 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1655 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1658 $condition[0] .= " AND `item`.`id` <= ?";
1659 $condition[] = $max_id;
1661 if ($exclude_replies) {
1662 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1664 if ($conversation_id > 0) {
1665 $condition[0] .= " AND `item`.`parent` = ?";
1666 $condition[] = $conversation_id;
1669 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1670 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1672 $items = Item::inArray($statuses);
1674 $ret = api_format_items($items, $user_info, false, $type);
1676 // Set all posts from the query above to seen
1678 foreach ($items as $item) {
1679 $idarray[] = intval($item["id"]);
1682 if (!empty($idarray)) {
1683 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1685 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1691 $data = ['status' => $ret];
1696 $data = api_rss_extra($a, $data, $user_info);
1700 return api_format_data("statuses", $type, $data);
1704 /// @TODO move to top of file or somewhere better
1705 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1706 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1709 * Returns the most recent statuses from public users.
1711 * @param string $type Return type (atom, rss, xml, json)
1713 * @return array|string
1714 * @throws BadRequestException
1715 * @throws ForbiddenException
1716 * @throws ImagickException
1717 * @throws InternalServerErrorException
1718 * @throws UnauthorizedException
1720 function api_statuses_public_timeline($type)
1723 $user_info = api_get_user($a);
1725 if (api_user() === false || $user_info === false) {
1726 throw new ForbiddenException();
1729 // get last network messages
1732 $count = defaults($_REQUEST, 'count', 20);
1733 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1737 $since_id = defaults($_REQUEST, 'since_id', 0);
1738 $max_id = defaults($_REQUEST, 'max_id', 0);
1739 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1740 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1742 $start = $page * $count;
1744 if ($exclude_replies && !$conversation_id) {
1745 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1746 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1749 $condition[0] .= " AND `thread`.`iid` <= ?";
1750 $condition[] = $max_id;
1753 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1754 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1756 $r = Item::inArray($statuses);
1758 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1759 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1762 $condition[0] .= " AND `item`.`id` <= ?";
1763 $condition[] = $max_id;
1765 if ($conversation_id > 0) {
1766 $condition[0] .= " AND `item`.`parent` = ?";
1767 $condition[] = $conversation_id;
1770 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1771 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1773 $r = Item::inArray($statuses);
1776 $ret = api_format_items($r, $user_info, false, $type);
1780 $data = ['status' => $ret];
1785 $data = api_rss_extra($a, $data, $user_info);
1789 return api_format_data("statuses", $type, $data);
1792 /// @TODO move to top of file or somewhere better
1793 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1796 * Returns the most recent statuses posted by users this node knows about.
1798 * @brief Returns the list of public federated posts this node knows about
1800 * @param string $type Return format: json, xml, atom, rss
1801 * @return array|string
1802 * @throws BadRequestException
1803 * @throws ForbiddenException
1804 * @throws ImagickException
1805 * @throws InternalServerErrorException
1806 * @throws UnauthorizedException
1808 function api_statuses_networkpublic_timeline($type)
1811 $user_info = api_get_user($a);
1813 if (api_user() === false || $user_info === false) {
1814 throw new ForbiddenException();
1817 $since_id = defaults($_REQUEST, 'since_id', 0);
1818 $max_id = defaults($_REQUEST, 'max_id', 0);
1821 $count = defaults($_REQUEST, 'count', 20);
1822 $page = defaults($_REQUEST, 'page', 1);
1826 $start = ($page - 1) * $count;
1828 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1829 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1832 $condition[0] .= " AND `thread`.`iid` <= ?";
1833 $condition[] = $max_id;
1836 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1837 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1839 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1843 $data = ['status' => $ret];
1848 $data = api_rss_extra($a, $data, $user_info);
1852 return api_format_data("statuses", $type, $data);
1855 /// @TODO move to top of file or somewhere better
1856 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1859 * Returns a single status.
1861 * @param string $type Return type (atom, rss, xml, json)
1863 * @return array|string
1864 * @throws BadRequestException
1865 * @throws ForbiddenException
1866 * @throws ImagickException
1867 * @throws InternalServerErrorException
1868 * @throws UnauthorizedException
1869 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1871 function api_statuses_show($type)
1874 $user_info = api_get_user($a);
1876 if (api_user() === false || $user_info === false) {
1877 throw new ForbiddenException();
1881 $id = intval(defaults($a->argv, 3, 0));
1884 $id = intval(defaults($_REQUEST, 'id', 0));
1889 $id = intval(defaults($a->argv, 4, 0));
1892 Logger::log('API: api_statuses_show: ' . $id);
1894 $conversation = !empty($_REQUEST['conversation']);
1896 // try to fetch the item for the local user - or the public item, if there is no local one
1897 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1898 if (!DBA::isResult($uri_item)) {
1899 throw new BadRequestException("There is no status with this id.");
1902 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1903 if (!DBA::isResult($item)) {
1904 throw new BadRequestException("There is no status with this id.");
1909 if ($conversation) {
1910 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1911 $params = ['order' => ['id' => true]];
1913 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1917 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1919 /// @TODO How about copying this to above methods which don't check $r ?
1920 if (!DBA::isResult($statuses)) {
1921 throw new BadRequestException("There is no status with this id.");
1924 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1926 if ($conversation) {
1927 $data = ['status' => $ret];
1928 return api_format_data("statuses", $type, $data);
1930 $data = ['status' => $ret[0]];
1931 return api_format_data("status", $type, $data);
1935 /// @TODO move to top of file or somewhere better
1936 api_register_func('api/statuses/show', 'api_statuses_show', true);
1940 * @param string $type Return type (atom, rss, xml, json)
1942 * @return array|string
1943 * @throws BadRequestException
1944 * @throws ForbiddenException
1945 * @throws ImagickException
1946 * @throws InternalServerErrorException
1947 * @throws UnauthorizedException
1948 * @todo nothing to say?
1950 function api_conversation_show($type)
1953 $user_info = api_get_user($a);
1955 if (api_user() === false || $user_info === false) {
1956 throw new ForbiddenException();
1960 $id = intval(defaults($a->argv , 3 , 0));
1961 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1962 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1963 $count = intval(defaults($_REQUEST, 'count' , 20));
1964 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1969 $start = $page * $count;
1972 $id = intval(defaults($_REQUEST, 'id', 0));
1977 $id = intval(defaults($a->argv, 4, 0));
1980 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1982 // try to fetch the item for the local user - or the public item, if there is no local one
1983 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1984 if (!DBA::isResult($item)) {
1985 throw new BadRequestException("There is no status with this id.");
1988 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1989 if (!DBA::isResult($parent)) {
1990 throw new BadRequestException("There is no status with this id.");
1993 $id = $parent['id'];
1995 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1996 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1999 $condition[0] .= " AND `item`.`id` <= ?";
2000 $condition[] = $max_id;
2003 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2004 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2006 if (!DBA::isResult($statuses)) {
2007 throw new BadRequestException("There is no status with id $id.");
2010 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2012 $data = ['status' => $ret];
2013 return api_format_data("statuses", $type, $data);
2016 /// @TODO move to top of file or somewhere better
2017 api_register_func('api/conversation/show', 'api_conversation_show', true);
2018 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2023 * @param string $type Return type (atom, rss, xml, json)
2025 * @return array|string
2026 * @throws BadRequestException
2027 * @throws ForbiddenException
2028 * @throws ImagickException
2029 * @throws InternalServerErrorException
2030 * @throws UnauthorizedException
2031 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2033 function api_statuses_repeat($type)
2039 if (api_user() === false) {
2040 throw new ForbiddenException();
2046 $id = intval(defaults($a->argv, 3, 0));
2049 $id = intval(defaults($_REQUEST, 'id', 0));
2054 $id = intval(defaults($a->argv, 4, 0));
2057 Logger::log('API: api_statuses_repeat: '.$id);
2059 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2060 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2062 if (DBA::isResult($item) && $item['body'] != "") {
2063 if (strpos($item['body'], "[/share]") !== false) {
2064 $pos = strpos($item['body'], "[share");
2065 $post = substr($item['body'], $pos);
2067 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2069 $post .= $item['body'];
2070 $post .= "[/share]";
2072 $_REQUEST['body'] = $post;
2073 $_REQUEST['profile_uid'] = api_user();
2074 $_REQUEST['api_source'] = true;
2076 if (empty($_REQUEST['source'])) {
2077 $_REQUEST["source"] = api_source();
2080 $item_id = item_post($a);
2082 throw new ForbiddenException();
2085 // output the post that we just posted.
2087 return api_status_show($type, $item_id);
2090 /// @TODO move to top of file or somewhere better
2091 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2094 * Destroys a specific status.
2096 * @param string $type Return type (atom, rss, xml, json)
2098 * @return array|string
2099 * @throws BadRequestException
2100 * @throws ForbiddenException
2101 * @throws ImagickException
2102 * @throws InternalServerErrorException
2103 * @throws UnauthorizedException
2104 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2106 function api_statuses_destroy($type)
2110 if (api_user() === false) {
2111 throw new ForbiddenException();
2117 $id = intval(defaults($a->argv, 3, 0));
2120 $id = intval(defaults($_REQUEST, 'id', 0));
2125 $id = intval(defaults($a->argv, 4, 0));
2128 Logger::log('API: api_statuses_destroy: '.$id);
2130 $ret = api_statuses_show($type);
2132 Item::deleteForUser(['id' => $id], api_user());
2137 /// @TODO move to top of file or somewhere better
2138 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2141 * Returns the most recent mentions.
2143 * @param string $type Return type (atom, rss, xml, json)
2145 * @return array|string
2146 * @throws BadRequestException
2147 * @throws ForbiddenException
2148 * @throws ImagickException
2149 * @throws InternalServerErrorException
2150 * @throws UnauthorizedException
2151 * @see http://developer.twitter.com/doc/get/statuses/mentions
2153 function api_statuses_mentions($type)
2156 $user_info = api_get_user($a);
2158 if (api_user() === false || $user_info === false) {
2159 throw new ForbiddenException();
2162 unset($_REQUEST["user_id"]);
2163 unset($_GET["user_id"]);
2165 unset($_REQUEST["screen_name"]);
2166 unset($_GET["screen_name"]);
2168 // get last network messages
2171 $since_id = defaults($_REQUEST, 'since_id', 0);
2172 $max_id = defaults($_REQUEST, 'max_id' , 0);
2173 $count = defaults($_REQUEST, 'count' , 20);
2174 $page = defaults($_REQUEST, 'page' , 1);
2179 $start = ($page - 1) * $count;
2181 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2182 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2183 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2186 $condition[0] .= " AND `item`.`id` <= ?";
2187 $condition[] = $max_id;
2190 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2191 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2193 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2195 $data = ['status' => $ret];
2200 $data = api_rss_extra($a, $data, $user_info);
2204 return api_format_data("statuses", $type, $data);
2207 /// @TODO move to top of file or somewhere better
2208 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2209 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2212 * Returns the most recent statuses posted by the user.
2214 * @brief Returns a user's public timeline
2216 * @param string $type Either "json" or "xml"
2217 * @return string|array
2218 * @throws BadRequestException
2219 * @throws ForbiddenException
2220 * @throws ImagickException
2221 * @throws InternalServerErrorException
2222 * @throws UnauthorizedException
2223 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2225 function api_statuses_user_timeline($type)
2228 $user_info = api_get_user($a);
2230 if (api_user() === false || $user_info === false) {
2231 throw new ForbiddenException();
2235 "api_statuses_user_timeline: api_user: ". api_user() .
2236 "\nuser_info: ".print_r($user_info, true) .
2237 "\n_REQUEST: ".print_r($_REQUEST, true),
2241 $since_id = defaults($_REQUEST, 'since_id', 0);
2242 $max_id = defaults($_REQUEST, 'max_id', 0);
2243 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2244 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2247 $count = defaults($_REQUEST, 'count', 20);
2248 $page = defaults($_REQUEST, 'page', 1);
2252 $start = ($page - 1) * $count;
2254 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2255 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2257 if ($user_info['self'] == 1) {
2258 $condition[0] .= ' AND `item`.`wall` ';
2261 if ($exclude_replies) {
2262 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2265 if ($conversation_id > 0) {
2266 $condition[0] .= " AND `item`.`parent` = ?";
2267 $condition[] = $conversation_id;
2271 $condition[0] .= " AND `item`.`id` <= ?";
2272 $condition[] = $max_id;
2275 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2276 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2278 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2282 $data = ['status' => $ret];
2287 $data = api_rss_extra($a, $data, $user_info);
2291 return api_format_data("statuses", $type, $data);
2294 /// @TODO move to top of file or somewhere better
2295 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2298 * Star/unstar an item.
2299 * param: id : id of the item
2301 * @param string $type Return type (atom, rss, xml, json)
2303 * @return array|string
2304 * @throws BadRequestException
2305 * @throws ForbiddenException
2306 * @throws ImagickException
2307 * @throws InternalServerErrorException
2308 * @throws UnauthorizedException
2309 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2311 function api_favorites_create_destroy($type)
2315 if (api_user() === false) {
2316 throw new ForbiddenException();
2319 // for versioned api.
2320 /// @TODO We need a better global soluton
2321 $action_argv_id = 2;
2322 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2323 $action_argv_id = 3;
2326 if ($a->argc <= $action_argv_id) {
2327 throw new BadRequestException("Invalid request.");
2329 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2330 if ($a->argc == $action_argv_id + 2) {
2331 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2333 $itemid = intval(defaults($_REQUEST, 'id', 0));
2336 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2338 if (!DBA::isResult($item)) {
2339 throw new BadRequestException("Invalid item.");
2344 $item['starred'] = 1;
2347 $item['starred'] = 0;
2350 throw new BadRequestException("Invalid action ".$action);
2353 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2356 throw new InternalServerErrorException("DB error");
2360 $user_info = api_get_user($a);
2361 $rets = api_format_items([$item], $user_info, false, $type);
2364 $data = ['status' => $ret];
2369 $data = api_rss_extra($a, $data, $user_info);
2373 return api_format_data("status", $type, $data);
2376 /// @TODO move to top of file or somewhere better
2377 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2378 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2381 * Returns the most recent favorite statuses.
2383 * @param string $type Return type (atom, rss, xml, json)
2385 * @return string|array
2386 * @throws BadRequestException
2387 * @throws ForbiddenException
2388 * @throws ImagickException
2389 * @throws InternalServerErrorException
2390 * @throws UnauthorizedException
2392 function api_favorites($type)
2397 $user_info = api_get_user($a);
2399 if (api_user() === false || $user_info === false) {
2400 throw new ForbiddenException();
2405 // in friendica starred item are private
2406 // return favorites only for self
2407 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2409 if ($user_info['self'] == 0) {
2413 $since_id = defaults($_REQUEST, 'since_id', 0);
2414 $max_id = defaults($_REQUEST, 'max_id', 0);
2415 $count = defaults($_GET, 'count', 20);
2416 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2421 $start = $page*$count;
2423 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2424 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2426 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2429 $condition[0] .= " AND `item`.`id` <= ?";
2430 $condition[] = $max_id;
2433 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2435 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2440 $data = ['status' => $ret];
2445 $data = api_rss_extra($a, $data, $user_info);
2449 return api_format_data("statuses", $type, $data);
2452 /// @TODO move to top of file or somewhere better
2453 api_register_func('api/favorites', 'api_favorites', true);
2457 * @param array $item
2458 * @param array $recipient
2459 * @param array $sender
2462 * @throws InternalServerErrorException
2464 function api_format_messages($item, $recipient, $sender)
2466 // standard meta information
2468 'id' => $item['id'],
2469 'sender_id' => $sender['id'],
2471 'recipient_id' => $recipient['id'],
2472 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2473 'sender_screen_name' => $sender['screen_name'],
2474 'recipient_screen_name' => $recipient['screen_name'],
2475 'sender' => $sender,
2476 'recipient' => $recipient,
2478 'friendica_seen' => defaults($item, 'seen', 0),
2479 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2482 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2483 if (isset($ret['sender']['uid'])) {
2484 unset($ret['sender']['uid']);
2486 if (isset($ret['sender']['self'])) {
2487 unset($ret['sender']['self']);
2489 if (isset($ret['recipient']['uid'])) {
2490 unset($ret['recipient']['uid']);
2492 if (isset($ret['recipient']['self'])) {
2493 unset($ret['recipient']['self']);
2496 //don't send title to regular StatusNET requests to avoid confusing these apps
2497 if (!empty($_GET['getText'])) {
2498 $ret['title'] = $item['title'];
2499 if ($_GET['getText'] == 'html') {
2500 $ret['text'] = BBCode::convert($item['body'], false);
2501 } elseif ($_GET['getText'] == 'plain') {
2502 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2505 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2507 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2508 unset($ret['sender']);
2509 unset($ret['recipient']);
2517 * @param array $item
2520 * @throws InternalServerErrorException
2522 function api_convert_item($item)
2524 $body = $item['body'];
2525 $attachments = api_get_attachments($body);
2527 // Workaround for ostatus messages where the title is identically to the body
2528 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2529 $statusbody = trim(HTML::toPlaintext($html, 0));
2531 // handle data: images
2532 $statusbody = api_format_items_embeded_images($item, $statusbody);
2534 $statustitle = trim($item['title']);
2536 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2537 $statustext = trim($statusbody);
2539 $statustext = trim($statustitle."\n\n".$statusbody);
2542 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2543 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2546 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2548 // Workaround for clients with limited HTML parser functionality
2549 $search = ["<br>", "<blockquote>", "</blockquote>",
2550 "<h1>", "</h1>", "<h2>", "</h2>",
2551 "<h3>", "</h3>", "<h4>", "</h4>",
2552 "<h5>", "</h5>", "<h6>", "</h6>"];
2553 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2554 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2555 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2556 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2557 $statushtml = str_replace($search, $replace, $statushtml);
2559 if ($item['title'] != "") {
2560 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2564 $oldtext = $statushtml;
2565 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2566 } while ($oldtext != $statushtml);
2568 if (substr($statushtml, 0, 4) == '<br>') {
2569 $statushtml = substr($statushtml, 4);
2572 if (substr($statushtml, 0, -4) == '<br>') {
2573 $statushtml = substr($statushtml, -4);
2576 // feeds without body should contain the link
2577 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2578 $statushtml .= BBCode::convert($item['plink']);
2581 $entities = api_get_entitities($statustext, $body);
2584 "text" => $statustext,
2585 "html" => $statushtml,
2586 "attachments" => $attachments,
2587 "entities" => $entities
2593 * @param string $body
2596 * @throws InternalServerErrorException
2598 function api_get_attachments(&$body)
2601 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2603 $URLSearchString = "^\[\]";
2604 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2612 foreach ($images[1] as $image) {
2613 $imagedata = Image::getInfoFromURL($image);
2616 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2620 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2621 foreach ($images[0] as $orig) {
2622 $body = str_replace($orig, "", $body);
2626 return $attachments;
2631 * @param string $text
2632 * @param string $bbcode
2635 * @throws InternalServerErrorException
2636 * @todo Links at the first character of the post
2638 function api_get_entitities(&$text, $bbcode)
2640 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2642 if ($include_entities != "true") {
2643 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2645 foreach ($images[1] as $image) {
2646 $replace = ProxyUtils::proxifyUrl($image);
2647 $text = str_replace($image, $replace, $text);
2652 $bbcode = BBCode::cleanPictureLinks($bbcode);
2654 // Change pure links in text to bbcode uris
2655 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2658 $entities["hashtags"] = [];
2659 $entities["symbols"] = [];
2660 $entities["urls"] = [];
2661 $entities["user_mentions"] = [];
2663 $URLSearchString = "^\[\]";
2665 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2667 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2668 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2669 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2671 $bbcode = preg_replace(
2672 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2673 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2676 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2678 $bbcode = preg_replace(
2679 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2680 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2683 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2685 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2687 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2688 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2691 foreach ($urls[1] as $id => $url) {
2692 //$start = strpos($text, $url, $offset);
2693 $start = iconv_strpos($text, $url, 0, "UTF-8");
2694 if (!($start === false)) {
2695 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2699 ksort($ordered_urls);
2702 //foreach ($urls[1] AS $id=>$url) {
2703 foreach ($ordered_urls as $url) {
2704 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2705 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2707 $display_url = $url["title"];
2709 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2710 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2712 if (strlen($display_url) > 26) {
2713 $display_url = substr($display_url, 0, 25)."…";
2717 //$start = strpos($text, $url, $offset);
2718 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2719 if (!($start === false)) {
2720 $entities["urls"][] = ["url" => $url["url"],
2721 "expanded_url" => $url["url"],
2722 "display_url" => $display_url,
2723 "indices" => [$start, $start+strlen($url["url"])]];
2724 $offset = $start + 1;
2728 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2729 $ordered_images = [];
2730 foreach ($images[1] as $image) {
2731 //$start = strpos($text, $url, $offset);
2732 $start = iconv_strpos($text, $image, 0, "UTF-8");
2733 if (!($start === false)) {
2734 $ordered_images[$start] = $image;
2737 //$entities["media"] = array();
2740 foreach ($ordered_images as $url) {
2741 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2742 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2744 if (strlen($display_url) > 26) {
2745 $display_url = substr($display_url, 0, 25)."…";
2748 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2749 if (!($start === false)) {
2750 $image = Image::getInfoFromURL($url);
2752 // If image cache is activated, then use the following sizes:
2753 // thumb (150), small (340), medium (600) and large (1024)
2754 if (!Config::get("system", "proxy_disabled")) {
2755 $media_url = ProxyUtils::proxifyUrl($url);
2758 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2759 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2761 if (($image[0] > 150) || ($image[1] > 150)) {
2762 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2763 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2766 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2767 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2769 if (($image[0] > 600) || ($image[1] > 600)) {
2770 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2771 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2775 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2778 $entities["media"][] = [
2780 "id_str" => (string) ($start + 1),
2781 "indices" => [$start, $start+strlen($url)],
2782 "media_url" => Strings::normaliseLink($media_url),
2783 "media_url_https" => $media_url,
2785 "display_url" => $display_url,
2786 "expanded_url" => $url,
2790 $offset = $start + 1;
2799 * @param array $item
2800 * @param string $text
2804 function api_format_items_embeded_images($item, $text)
2806 $text = preg_replace_callback(
2807 '|data:image/([^;]+)[^=]+=*|m',
2808 function () use ($item) {
2809 return System::baseUrl() . '/display/' . $item['guid'];
2817 * @brief return <a href='url'>name</a> as array
2819 * @param string $txt text
2824 function api_contactlink_to_array($txt)
2827 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2828 if ($r && count($match)==3) {
2830 'name' => $match[2],
2844 * @brief return likes, dislikes and attend status for item
2846 * @param array $item array
2847 * @param string $type Return type (atom, rss, xml, json)
2850 * likes => int count,
2851 * dislikes => int count
2852 * @throws BadRequestException
2853 * @throws ImagickException
2854 * @throws InternalServerErrorException
2855 * @throws UnauthorizedException
2857 function api_format_items_activities($item, $type = "json")
2866 'attendmaybe' => [],
2869 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2870 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2872 while ($parent_item = Item::fetch($ret)) {
2873 // not used as result should be structured like other user data
2874 //builtin_activity_puller($i, $activities);
2876 // get user data and add it to the array of the activity
2877 $user = api_get_user($a, $parent_item['author-id']);
2878 switch ($parent_item['verb']) {
2880 $activities['like'][] = $user;
2882 case ACTIVITY_DISLIKE:
2883 $activities['dislike'][] = $user;
2885 case ACTIVITY_ATTEND:
2886 $activities['attendyes'][] = $user;
2888 case ACTIVITY_ATTENDNO:
2889 $activities['attendno'][] = $user;
2891 case ACTIVITY_ATTENDMAYBE:
2892 $activities['attendmaybe'][] = $user;
2901 if ($type == "xml") {
2902 $xml_activities = [];
2903 foreach ($activities as $k => $v) {
2904 // change xml element from "like" to "friendica:like"
2905 $xml_activities["friendica:".$k] = $v;
2906 // add user data into xml output
2908 foreach ($v as $user) {
2909 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2912 $activities = $xml_activities;
2920 * @brief return data from profiles
2922 * @param array $profile_row array containing data from db table 'profile'
2924 * @throws InternalServerErrorException
2926 function api_format_items_profiles($profile_row)
2929 'profile_id' => $profile_row['id'],
2930 'profile_name' => $profile_row['profile-name'],
2931 'is_default' => $profile_row['is-default'] ? true : false,
2932 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2933 'profile_photo' => $profile_row['photo'],
2934 'profile_thumb' => $profile_row['thumb'],
2935 'publish' => $profile_row['publish'] ? true : false,
2936 'net_publish' => $profile_row['net-publish'] ? true : false,
2937 'description' => $profile_row['pdesc'],
2938 'date_of_birth' => $profile_row['dob'],
2939 'address' => $profile_row['address'],
2940 'city' => $profile_row['locality'],
2941 'region' => $profile_row['region'],
2942 'postal_code' => $profile_row['postal-code'],
2943 'country' => $profile_row['country-name'],
2944 'hometown' => $profile_row['hometown'],
2945 'gender' => $profile_row['gender'],
2946 'marital' => $profile_row['marital'],
2947 'marital_with' => $profile_row['with'],
2948 'marital_since' => $profile_row['howlong'],
2949 'sexual' => $profile_row['sexual'],
2950 'politic' => $profile_row['politic'],
2951 'religion' => $profile_row['religion'],
2952 'public_keywords' => $profile_row['pub_keywords'],
2953 'private_keywords' => $profile_row['prv_keywords'],
2954 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2955 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2956 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2957 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2958 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2959 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2960 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2961 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2962 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2963 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2964 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2965 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2966 'homepage' => $profile_row['homepage'],
2973 * @brief format items to be returned by api
2975 * @param array $r array of items
2976 * @param array $user_info
2977 * @param bool $filter_user filter items by $user_info
2978 * @param string $type Return type (atom, rss, xml, json)
2980 * @throws BadRequestException
2981 * @throws ImagickException
2982 * @throws InternalServerErrorException
2983 * @throws UnauthorizedException
2985 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2991 foreach ((array)$r as $item) {
2992 localize_item($item);
2993 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2995 // Look if the posts are matching if they should be filtered by user id
2996 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3000 $in_reply_to = api_in_reply_to($item);
3002 $converted = api_convert_item($item);
3004 if ($type == "xml") {
3005 $geo = "georss:point";
3011 'text' => $converted["text"],
3012 'truncated' => false,
3013 'created_at'=> api_date($item['created']),
3014 'in_reply_to_status_id' => $in_reply_to['status_id'],
3015 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3016 'source' => (($item['app']) ? $item['app'] : 'web'),
3017 'id' => intval($item['id']),
3018 'id_str' => (string) intval($item['id']),
3019 'in_reply_to_user_id' => $in_reply_to['user_id'],
3020 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3021 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3023 'favorited' => $item['starred'] ? true : false,
3024 'user' => $status_user,
3025 'friendica_author' => $author_user,
3026 'friendica_owner' => $owner_user,
3027 'friendica_private' => $item['private'] == 1,
3028 //'entities' => NULL,
3029 'statusnet_html' => $converted["html"],
3030 'statusnet_conversation_id' => $item['parent'],
3031 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3032 'friendica_activities' => api_format_items_activities($item, $type),
3035 if (count($converted["attachments"]) > 0) {
3036 $status["attachments"] = $converted["attachments"];
3039 if (count($converted["entities"]) > 0) {
3040 $status["entities"] = $converted["entities"];
3043 if ($status["source"] == 'web') {
3044 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3045 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3046 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3049 if ($item["id"] == $item["parent"]) {
3050 $retweeted_item = api_share_as_retweet($item);
3051 if ($retweeted_item !== false) {
3052 $retweeted_status = $status;
3053 $status['user'] = $status['friendica_owner'];
3055 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3056 } catch (BadRequestException $e) {
3057 // user not found. should be found?
3058 /// @todo check if the user should be always found
3059 $retweeted_status["user"] = [];
3062 $rt_converted = api_convert_item($retweeted_item);
3064 $retweeted_status['text'] = $rt_converted["text"];
3065 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3066 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3067 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3068 $status['retweeted_status'] = $retweeted_status;
3069 $status['friendica_author'] = $retweeted_status['friendica_author'];
3073 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3074 unset($status["user"]["uid"]);
3075 unset($status["user"]["self"]);
3077 if ($item["coord"] != "") {
3078 $coords = explode(' ', $item["coord"]);
3079 if (count($coords) == 2) {
3080 if ($type == "json") {
3081 $status["geo"] = ['type' => 'Point',
3082 'coordinates' => [(float) $coords[0],
3083 (float) $coords[1]]];
3084 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3085 $status["georss:point"] = $item["coord"];
3095 * Returns the remaining number of API requests available to the user before the API limit is reached.
3097 * @param string $type Return type (atom, rss, xml, json)
3099 * @return array|string
3102 function api_account_rate_limit_status($type)
3104 if ($type == "xml") {
3106 'remaining-hits' => '150',
3107 '@attributes' => ["type" => "integer"],
3108 'hourly-limit' => '150',
3109 '@attributes2' => ["type" => "integer"],
3110 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3111 '@attributes3' => ["type" => "datetime"],
3112 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3113 '@attributes4' => ["type" => "integer"],
3117 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3118 'remaining_hits' => '150',
3119 'hourly_limit' => '150',
3120 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3124 return api_format_data('hash', $type, ['hash' => $hash]);
3127 /// @TODO move to top of file or somewhere better
3128 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3131 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3133 * @param string $type Return type (atom, rss, xml, json)
3135 * @return array|string
3137 function api_help_test($type)
3139 if ($type == 'xml') {
3145 return api_format_data('ok', $type, ["ok" => $ok]);
3148 /// @TODO move to top of file or somewhere better
3149 api_register_func('api/help/test', 'api_help_test', false);
3152 * Returns all lists the user subscribes to.
3154 * @param string $type Return type (atom, rss, xml, json)
3156 * @return array|string
3157 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3159 function api_lists_list($type)
3162 /// @TODO $ret is not filled here?
3163 return api_format_data('lists', $type, ["lists_list" => $ret]);
3166 /// @TODO move to top of file or somewhere better
3167 api_register_func('api/lists/list', 'api_lists_list', true);
3168 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3171 * Returns all groups the user owns.
3173 * @param string $type Return type (atom, rss, xml, json)
3175 * @return array|string
3176 * @throws BadRequestException
3177 * @throws ForbiddenException
3178 * @throws ImagickException
3179 * @throws InternalServerErrorException
3180 * @throws UnauthorizedException
3181 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3183 function api_lists_ownerships($type)
3187 if (api_user() === false) {
3188 throw new ForbiddenException();
3192 $user_info = api_get_user($a);
3193 $uid = $user_info['uid'];
3195 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3197 // loop through all groups
3199 foreach ($groups as $group) {
3200 if ($group['visible']) {
3206 'name' => $group['name'],
3207 'id' => intval($group['id']),
3208 'id_str' => (string) $group['id'],
3209 'user' => $user_info,
3213 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3216 /// @TODO move to top of file or somewhere better
3217 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3220 * Returns recent statuses from users in the specified group.
3222 * @param string $type Return type (atom, rss, xml, json)
3224 * @return array|string
3225 * @throws BadRequestException
3226 * @throws ForbiddenException
3227 * @throws ImagickException
3228 * @throws InternalServerErrorException
3229 * @throws UnauthorizedException
3230 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3232 function api_lists_statuses($type)
3236 $user_info = api_get_user($a);
3237 if (api_user() === false || $user_info === false) {
3238 throw new ForbiddenException();
3241 unset($_REQUEST["user_id"]);
3242 unset($_GET["user_id"]);
3244 unset($_REQUEST["screen_name"]);
3245 unset($_GET["screen_name"]);
3247 if (empty($_REQUEST['list_id'])) {
3248 throw new BadRequestException('list_id not specified');
3252 $count = defaults($_REQUEST, 'count', 20);
3253 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3257 $since_id = defaults($_REQUEST, 'since_id', 0);
3258 $max_id = defaults($_REQUEST, 'max_id', 0);
3259 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3260 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3262 $start = $page * $count;
3264 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3265 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3268 $condition[0] .= " AND `item`.`id` <= ?";
3269 $condition[] = $max_id;
3271 if ($exclude_replies > 0) {
3272 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3274 if ($conversation_id > 0) {
3275 $condition[0] .= " AND `item`.`parent` = ?";
3276 $condition[] = $conversation_id;
3279 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3280 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3282 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3284 $data = ['status' => $items];
3289 $data = api_rss_extra($a, $data, $user_info);
3293 return api_format_data("statuses", $type, $data);
3296 /// @TODO move to top of file or somewhere better
3297 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3300 * Considers friends and followers lists to be private and won't return
3301 * anything if any user_id parameter is passed.
3303 * @brief Returns either the friends of the follower list
3305 * @param string $qtype Either "friends" or "followers"
3306 * @return boolean|array
3307 * @throws BadRequestException
3308 * @throws ForbiddenException
3309 * @throws ImagickException
3310 * @throws InternalServerErrorException
3311 * @throws UnauthorizedException
3313 function api_statuses_f($qtype)
3317 if (api_user() === false) {
3318 throw new ForbiddenException();
3322 $count = defaults($_GET, 'count', 20);
3323 $page = defaults($_GET, 'page', 1);
3327 $start = ($page - 1) * $count;
3329 $user_info = api_get_user($a);
3331 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3332 /* this is to stop Hotot to load friends multiple times
3333 * I'm not sure if I'm missing return something or
3334 * is a bug in hotot. Workaround, meantime
3338 return array('$users' => $ret);*/
3343 if ($qtype == 'friends') {
3344 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3345 } elseif ($qtype == 'followers') {
3346 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3349 // friends and followers only for self
3350 if ($user_info['self'] == 0) {
3351 $sql_extra = " AND false ";
3354 if ($qtype == 'blocks') {
3355 $sql_filter = 'AND `blocked` AND NOT `pending`';
3356 } elseif ($qtype == 'incoming') {
3357 $sql_filter = 'AND `pending`';
3359 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3377 foreach ($r as $cid) {
3378 $user = api_get_user($a, $cid['nurl']);
3379 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3380 unset($user["uid"]);
3381 unset($user["self"]);
3388 return ['user' => $ret];
3393 * Returns the user's friends.
3395 * @brief Returns the list of friends of the provided user
3397 * @deprecated By Twitter API in favor of friends/list
3399 * @param string $type Either "json" or "xml"
3400 * @return boolean|string|array
3401 * @throws BadRequestException
3402 * @throws ForbiddenException
3404 function api_statuses_friends($type)
3406 $data = api_statuses_f("friends");
3407 if ($data === false) {
3410 return api_format_data("users", $type, $data);
3414 * Returns the user's followers.
3416 * @brief Returns the list of followers of the provided user
3418 * @deprecated By Twitter API in favor of friends/list
3420 * @param string $type Either "json" or "xml"
3421 * @return boolean|string|array
3422 * @throws BadRequestException
3423 * @throws ForbiddenException
3425 function api_statuses_followers($type)
3427 $data = api_statuses_f("followers");
3428 if ($data === false) {
3431 return api_format_data("users", $type, $data);
3434 /// @TODO move to top of file or somewhere better
3435 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3436 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3439 * Returns the list of blocked users
3441 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3443 * @param string $type Either "json" or "xml"
3445 * @return boolean|string|array
3446 * @throws BadRequestException
3447 * @throws ForbiddenException
3449 function api_blocks_list($type)
3451 $data = api_statuses_f('blocks');
3452 if ($data === false) {
3455 return api_format_data("users", $type, $data);
3458 /// @TODO move to top of file or somewhere better
3459 api_register_func('api/blocks/list', 'api_blocks_list', true);
3462 * Returns the list of pending users IDs
3464 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3466 * @param string $type Either "json" or "xml"
3468 * @return boolean|string|array
3469 * @throws BadRequestException
3470 * @throws ForbiddenException
3472 function api_friendships_incoming($type)
3474 $data = api_statuses_f('incoming');
3475 if ($data === false) {
3480 foreach ($data['user'] as $user) {
3481 $ids[] = $user['id'];
3484 return api_format_data("ids", $type, ['id' => $ids]);
3487 /// @TODO move to top of file or somewhere better
3488 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3491 * Returns the instance's configuration information.
3493 * @param string $type Return type (atom, rss, xml, json)
3495 * @return array|string
3496 * @throws InternalServerErrorException
3498 function api_statusnet_config($type)
3502 $name = Config::get('config', 'sitename');
3503 $server = $a->getHostName();
3504 $logo = System::baseUrl() . '/images/friendica-64.png';
3505 $email = Config::get('config', 'admin_email');
3506 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3507 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3508 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3509 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3510 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3513 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3514 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3515 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3516 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3517 'shorturllength' => '30',
3519 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3520 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3521 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3522 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3527 return api_format_data('config', $type, ['config' => $config]);
3530 /// @TODO move to top of file or somewhere better
3531 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3532 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3536 * @param string $type Return type (atom, rss, xml, json)
3538 * @return array|string
3540 function api_statusnet_version($type)
3543 $fake_statusnet_version = "0.9.7";
3545 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3548 /// @TODO move to top of file or somewhere better
3549 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3550 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3554 * @param string $type Return type (atom, rss, xml, json)
3556 * @return array|string|void
3557 * @throws BadRequestException
3558 * @throws ForbiddenException
3559 * @throws ImagickException
3560 * @throws InternalServerErrorException
3561 * @throws UnauthorizedException
3562 * @todo use api_format_data() to return data
3564 function api_ff_ids($type)
3567 throw new ForbiddenException();
3574 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3577 "SELECT `pcontact`.`id` FROM `contact`
3578 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3579 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3582 if (!DBA::isResult($r)) {
3587 foreach ($r as $rr) {
3588 if ($stringify_ids) {
3591 $ids[] = intval($rr['id']);
3595 return api_format_data("ids", $type, ['id' => $ids]);
3599 * Returns the ID of every user the user is following.
3601 * @param string $type Return type (atom, rss, xml, json)
3603 * @return array|string
3604 * @throws BadRequestException
3605 * @throws ForbiddenException
3606 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3608 function api_friends_ids($type)
3610 return api_ff_ids($type);
3614 * Returns the ID of every user following the user.
3616 * @param string $type Return type (atom, rss, xml, json)
3618 * @return array|string
3619 * @throws BadRequestException
3620 * @throws ForbiddenException
3621 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3623 function api_followers_ids($type)
3625 return api_ff_ids($type);
3628 /// @TODO move to top of file or somewhere better
3629 api_register_func('api/friends/ids', 'api_friends_ids', true);
3630 api_register_func('api/followers/ids', 'api_followers_ids', true);
3633 * Sends a new direct message.
3635 * @param string $type Return type (atom, rss, xml, json)
3637 * @return array|string
3638 * @throws BadRequestException
3639 * @throws ForbiddenException
3640 * @throws ImagickException
3641 * @throws InternalServerErrorException
3642 * @throws NotFoundException
3643 * @throws UnauthorizedException
3644 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3646 function api_direct_messages_new($type)
3650 if (api_user() === false) {
3651 throw new ForbiddenException();
3654 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3658 $sender = api_get_user($a);
3661 if (!empty($_POST['screen_name'])) {
3663 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3665 DBA::escape($_POST['screen_name'])
3668 if (DBA::isResult($r)) {
3669 // Selecting the id by priority, friendica first
3670 api_best_nickname($r);
3672 $recipient = api_get_user($a, $r[0]['nurl']);
3675 $recipient = api_get_user($a, $_POST['user_id']);
3678 if (empty($recipient)) {
3679 throw new NotFoundException('Recipient not found');
3683 if (!empty($_REQUEST['replyto'])) {
3685 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3687 intval($_REQUEST['replyto'])
3689 $replyto = $r[0]['parent-uri'];
3690 $sub = $r[0]['title'];
3692 if (!empty($_REQUEST['title'])) {
3693 $sub = $_REQUEST['title'];
3695 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3699 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3702 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3703 $ret = api_format_messages($r[0], $recipient, $sender);
3705 $ret = ["error"=>$id];
3708 $data = ['direct_message'=>$ret];
3714 $data = api_rss_extra($a, $data, $sender);
3718 return api_format_data("direct-messages", $type, $data);
3721 /// @TODO move to top of file or somewhere better
3722 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3725 * Destroys a direct message.
3727 * @brief delete a direct_message from mail table through api
3729 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3730 * @return string|array
3731 * @throws BadRequestException
3732 * @throws ForbiddenException
3733 * @throws ImagickException
3734 * @throws InternalServerErrorException
3735 * @throws UnauthorizedException
3736 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3738 function api_direct_messages_destroy($type)
3742 if (api_user() === false) {
3743 throw new ForbiddenException();
3747 $user_info = api_get_user($a);
3749 $id = defaults($_REQUEST, 'id', 0);
3751 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3752 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3753 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3755 $uid = $user_info['uid'];
3756 // error if no id or parenturi specified (for clients posting parent-uri as well)
3757 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3758 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3759 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3762 // BadRequestException if no id specified (for clients using Twitter API)
3764 throw new BadRequestException('Message id not specified');
3767 // add parent-uri to sql command if specified by calling app
3768 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3770 // get data of the specified message id
3772 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3777 // error message if specified id is not in database
3778 if (!DBA::isResult($r)) {
3779 if ($verbose == "true") {
3780 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3781 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3783 /// @todo BadRequestException ok for Twitter API clients?
3784 throw new BadRequestException('message id not in database');
3789 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3794 if ($verbose == "true") {
3797 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3798 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3800 $answer = ['result' => 'error', 'message' => 'unknown error'];
3801 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3804 /// @todo return JSON data like Twitter API not yet implemented
3807 /// @TODO move to top of file or somewhere better
3808 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3813 * @brief unfollow contact
3815 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3816 * @return string|array
3817 * @throws BadRequestException
3818 * @throws ForbiddenException
3819 * @throws ImagickException
3820 * @throws InternalServerErrorException
3821 * @throws NotFoundException
3822 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3824 function api_friendships_destroy($type)
3828 if ($uid === false) {
3829 throw new ForbiddenException();
3832 $contact_id = defaults($_REQUEST, 'user_id');
3834 if (empty($contact_id)) {
3835 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3836 throw new BadRequestException("no user_id specified");
3839 // Get Contact by given id
3840 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3842 if(!DBA::isResult($contact)) {
3843 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3844 throw new NotFoundException("no contact found to given ID");
3847 $url = $contact["url"];
3849 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3850 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3851 Strings::normaliseLink($url), $url];
3852 $contact = DBA::selectFirst('contact', [], $condition);
3854 if (!DBA::isResult($contact)) {
3855 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3856 throw new NotFoundException("Not following Contact");
3859 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3860 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3861 throw new ExpectationFailedException("Not supported");
3864 $dissolve = ($contact['rel'] == Contact::SHARING);
3866 $owner = User::getOwnerDataById($uid);
3868 Contact::terminateFriendship($owner, $contact, $dissolve);
3871 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3872 throw new NotFoundException("Error Processing Request");
3875 // Sharing-only contacts get deleted as there no relationship any more
3877 Contact::remove($contact['id']);
3879 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3882 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3883 unset($contact["uid"]);
3884 unset($contact["self"]);
3886 // Set screen_name since Twidere requests it
3887 $contact["screen_name"] = $contact["nick"];
3889 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3891 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3895 * @param string $type Return type (atom, rss, xml, json)
3896 * @param string $box
3897 * @param string $verbose
3899 * @return array|string
3900 * @throws BadRequestException
3901 * @throws ForbiddenException
3902 * @throws ImagickException
3903 * @throws InternalServerErrorException
3904 * @throws UnauthorizedException
3906 function api_direct_messages_box($type, $box, $verbose)
3909 if (api_user() === false) {
3910 throw new ForbiddenException();
3913 $count = defaults($_GET, 'count', 20);
3914 $page = defaults($_REQUEST, 'page', 1) - 1;
3919 $since_id = defaults($_REQUEST, 'since_id', 0);
3920 $max_id = defaults($_REQUEST, 'max_id', 0);
3922 $user_id = defaults($_REQUEST, 'user_id', '');
3923 $screen_name = defaults($_REQUEST, 'screen_name', '');
3926 unset($_REQUEST["user_id"]);
3927 unset($_GET["user_id"]);
3929 unset($_REQUEST["screen_name"]);
3930 unset($_GET["screen_name"]);
3932 $user_info = api_get_user($a);
3933 if ($user_info === false) {
3934 throw new ForbiddenException();
3936 $profile_url = $user_info["url"];
3939 $start = $page * $count;
3944 if ($box=="sentbox") {
3945 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3946 } elseif ($box == "conversation") {
3947 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3948 } elseif ($box == "all") {
3949 $sql_extra = "true";
3950 } elseif ($box == "inbox") {
3951 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3955 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3958 if ($user_id != "") {
3959 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3960 } elseif ($screen_name !="") {
3961 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3965 "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",
3971 if ($verbose == "true" && !DBA::isResult($r)) {
3972 $answer = ['result' => 'error', 'message' => 'no mails available'];
3973 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3977 foreach ($r as $item) {
3978 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3979 $recipient = $user_info;
3980 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3981 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3982 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3983 $sender = $user_info;
3986 if (isset($recipient) && isset($sender)) {
3987 $ret[] = api_format_messages($item, $recipient, $sender);
3992 $data = ['direct_message' => $ret];
3997 $data = api_rss_extra($a, $data, $user_info);
4001 return api_format_data("direct-messages", $type, $data);
4005 * Returns the most recent direct messages sent by the user.
4007 * @param string $type Return type (atom, rss, xml, json)
4009 * @return array|string
4010 * @throws BadRequestException
4011 * @throws ForbiddenException
4012 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4014 function api_direct_messages_sentbox($type)
4016 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4017 return api_direct_messages_box($type, "sentbox", $verbose);
4021 * Returns the most recent direct messages sent to the user.
4023 * @param string $type Return type (atom, rss, xml, json)
4025 * @return array|string
4026 * @throws BadRequestException
4027 * @throws ForbiddenException
4028 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4030 function api_direct_messages_inbox($type)
4032 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4033 return api_direct_messages_box($type, "inbox", $verbose);
4038 * @param string $type Return type (atom, rss, xml, json)
4040 * @return array|string
4041 * @throws BadRequestException
4042 * @throws ForbiddenException
4044 function api_direct_messages_all($type)
4046 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4047 return api_direct_messages_box($type, "all", $verbose);
4052 * @param string $type Return type (atom, rss, xml, json)
4054 * @return array|string
4055 * @throws BadRequestException
4056 * @throws ForbiddenException
4058 function api_direct_messages_conversation($type)
4060 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4061 return api_direct_messages_box($type, "conversation", $verbose);
4064 /// @TODO move to top of file or somewhere better
4065 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4066 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4067 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4068 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4071 * Returns an OAuth Request Token.
4073 * @see https://oauth.net/core/1.0/#auth_step1
4075 function api_oauth_request_token()
4077 $oauth1 = new FKOAuth1();
4079 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4080 } catch (Exception $e) {
4081 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4089 * Returns an OAuth Access Token.
4091 * @return array|string
4092 * @see https://oauth.net/core/1.0/#auth_step3
4094 function api_oauth_access_token()
4096 $oauth1 = new FKOAuth1();
4098 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4099 } catch (Exception $e) {
4100 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4107 /// @TODO move to top of file or somewhere better
4108 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4109 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4113 * @brief delete a complete photoalbum with all containing photos from database through api
4115 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4116 * @return string|array
4117 * @throws BadRequestException
4118 * @throws ForbiddenException
4119 * @throws InternalServerErrorException
4121 function api_fr_photoalbum_delete($type)
4123 if (api_user() === false) {
4124 throw new ForbiddenException();
4127 $album = defaults($_REQUEST, 'album', "");
4129 // we do not allow calls without album string
4131 throw new BadRequestException("no albumname specified");
4133 // check if album is existing
4135 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4139 if (!DBA::isResult($r)) {
4140 throw new BadRequestException("album not available");
4143 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4144 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4145 foreach ($r as $rr) {
4146 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4147 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4149 if (!DBA::isResult($photo_item)) {
4150 throw new InternalServerErrorException("problem with deleting items occured");
4152 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4155 // now let's delete all photos from the album
4156 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4158 // return success of deletion or error message
4160 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4161 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4163 throw new InternalServerErrorException("unknown error - deleting from database failed");
4168 * @brief update the name of the album for all photos of an album
4170 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4171 * @return string|array
4172 * @throws BadRequestException
4173 * @throws ForbiddenException
4174 * @throws InternalServerErrorException
4176 function api_fr_photoalbum_update($type)
4178 if (api_user() === false) {
4179 throw new ForbiddenException();
4182 $album = defaults($_REQUEST, 'album', "");
4183 $album_new = defaults($_REQUEST, 'album_new', "");
4185 // we do not allow calls without album string
4187 throw new BadRequestException("no albumname specified");
4189 if ($album_new == "") {
4190 throw new BadRequestException("no new albumname specified");
4192 // check if album is existing
4193 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4194 throw new BadRequestException("album not available");
4196 // now let's update all photos to the albumname
4197 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4199 // return success of updating or error message
4201 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4202 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4204 throw new InternalServerErrorException("unknown error - updating in database failed");
4210 * @brief list all photos of the authenticated user
4212 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4213 * @return string|array
4214 * @throws ForbiddenException
4215 * @throws InternalServerErrorException
4217 function api_fr_photos_list($type)
4219 if (api_user() === false) {
4220 throw new ForbiddenException();
4223 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4224 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4225 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4226 intval(local_user())
4229 'image/jpeg' => 'jpg',
4230 'image/png' => 'png',
4231 'image/gif' => 'gif'
4233 $data = ['photo'=>[]];
4234 if (DBA::isResult($r)) {
4235 foreach ($r as $rr) {
4237 $photo['id'] = $rr['resource-id'];
4238 $photo['album'] = $rr['album'];
4239 $photo['filename'] = $rr['filename'];
4240 $photo['type'] = $rr['type'];
4241 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4242 $photo['created'] = $rr['created'];
4243 $photo['edited'] = $rr['edited'];
4244 $photo['desc'] = $rr['desc'];
4246 if ($type == "xml") {
4247 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4249 $photo['thumb'] = $thumb;
4250 $data['photo'][] = $photo;
4254 return api_format_data("photos", $type, $data);
4258 * @brief upload a new photo or change an existing photo
4260 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4261 * @return string|array
4262 * @throws BadRequestException
4263 * @throws ForbiddenException
4264 * @throws ImagickException
4265 * @throws InternalServerErrorException
4266 * @throws NotFoundException
4268 function api_fr_photo_create_update($type)
4270 if (api_user() === false) {
4271 throw new ForbiddenException();
4274 $photo_id = defaults($_REQUEST, 'photo_id', null);
4275 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4276 $album = defaults($_REQUEST, 'album', null);
4277 $album_new = defaults($_REQUEST, 'album_new', null);
4278 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4279 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4280 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4281 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4282 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4284 // do several checks on input parameters
4285 // we do not allow calls without album string
4286 if ($album == null) {
4287 throw new BadRequestException("no albumname specified");
4289 // if photo_id == null --> we are uploading a new photo
4290 if ($photo_id == null) {
4293 // error if no media posted in create-mode
4294 if (empty($_FILES['media'])) {
4296 throw new BadRequestException("no media data submitted");
4299 // album_new will be ignored in create-mode
4304 // check if photo is existing in databasei
4305 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4306 throw new BadRequestException("photo not available");
4310 // checks on acl strings provided by clients
4311 $acl_input_error = false;
4312 $acl_input_error |= check_acl_input($allow_cid);
4313 $acl_input_error |= check_acl_input($deny_cid);
4314 $acl_input_error |= check_acl_input($allow_gid);
4315 $acl_input_error |= check_acl_input($deny_gid);
4316 if ($acl_input_error) {
4317 throw new BadRequestException("acl data invalid");
4319 // now let's upload the new media in create-mode
4320 if ($mode == "create") {
4321 $media = $_FILES['media'];
4322 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4324 // return success of updating or error message
4325 if (!is_null($data)) {
4326 return api_format_data("photo_create", $type, $data);
4328 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4332 // now let's do the changes in update-mode
4333 if ($mode == "update") {
4334 $updated_fields = [];
4336 if (!is_null($desc)) {
4337 $updated_fields['desc'] = $desc;
4340 if (!is_null($album_new)) {
4341 $updated_fields['album'] = $album_new;
4344 if (!is_null($allow_cid)) {
4345 $allow_cid = trim($allow_cid);
4346 $updated_fields['allow_cid'] = $allow_cid;
4349 if (!is_null($deny_cid)) {
4350 $deny_cid = trim($deny_cid);
4351 $updated_fields['deny_cid'] = $deny_cid;
4354 if (!is_null($allow_gid)) {
4355 $allow_gid = trim($allow_gid);
4356 $updated_fields['allow_gid'] = $allow_gid;
4359 if (!is_null($deny_gid)) {
4360 $deny_gid = trim($deny_gid);
4361 $updated_fields['deny_gid'] = $deny_gid;
4365 if (count($updated_fields) > 0) {
4366 $nothingtodo = false;
4367 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4369 $nothingtodo = true;
4372 if (!empty($_FILES['media'])) {
4373 $nothingtodo = false;
4374 $media = $_FILES['media'];
4375 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4376 if (!is_null($data)) {
4377 return api_format_data("photo_update", $type, $data);
4381 // return success of updating or error message
4383 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4384 return api_format_data("photo_update", $type, ['$result' => $answer]);
4387 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4388 return api_format_data("photo_update", $type, ['$result' => $answer]);
4390 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4393 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4397 * @brief delete a single photo from the database through api
4399 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4400 * @return string|array
4401 * @throws BadRequestException
4402 * @throws ForbiddenException
4403 * @throws InternalServerErrorException
4405 function api_fr_photo_delete($type)
4407 if (api_user() === false) {
4408 throw new ForbiddenException();
4412 $photo_id = defaults($_REQUEST, 'photo_id', null);
4414 // do several checks on input parameters
4415 // we do not allow calls without photo id
4416 if ($photo_id == null) {
4417 throw new BadRequestException("no photo_id specified");
4420 // check if photo is existing in database
4421 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4422 throw new BadRequestException("photo not available");
4425 // now we can perform on the deletion of the photo
4426 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4428 // return success of deletion or error message
4430 // retrieve the id of the parent element (the photo element)
4431 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4432 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4434 if (!DBA::isResult($photo_item)) {
4435 throw new InternalServerErrorException("problem with deleting items occured");
4437 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4438 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4439 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4441 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4442 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4444 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4450 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4452 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4453 * @return string|array
4454 * @throws BadRequestException
4455 * @throws ForbiddenException
4456 * @throws InternalServerErrorException
4457 * @throws NotFoundException
4459 function api_fr_photo_detail($type)
4461 if (api_user() === false) {
4462 throw new ForbiddenException();
4464 if (empty($_REQUEST['photo_id'])) {
4465 throw new BadRequestException("No photo id.");
4468 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4469 $photo_id = $_REQUEST['photo_id'];
4471 // prepare json/xml output with data from database for the requested photo
4472 $data = prepare_photo_data($type, $scale, $photo_id);
4474 return api_format_data("photo_detail", $type, $data);
4479 * Updates the user’s profile image.
4481 * @brief updates the profile image for the user (either a specified profile or the default profile)
4483 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4485 * @return string|array
4486 * @throws BadRequestException
4487 * @throws ForbiddenException
4488 * @throws ImagickException
4489 * @throws InternalServerErrorException
4490 * @throws NotFoundException
4491 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4493 function api_account_update_profile_image($type)
4495 if (api_user() === false) {
4496 throw new ForbiddenException();
4499 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4501 // error if image data is missing
4502 if (empty($_FILES['image'])) {
4503 throw new BadRequestException("no media data submitted");
4506 // check if specified profile id is valid
4507 if ($profile_id != 0) {
4508 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4509 // error message if specified profile id is not in database
4510 if (!DBA::isResult($profile)) {
4511 throw new BadRequestException("profile_id not available");
4513 $is_default_profile = $profile['is-default'];
4515 $is_default_profile = 1;
4518 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4520 if (!empty($_FILES['image'])) {
4521 $media = $_FILES['image'];
4522 } elseif (!empty($_FILES['media'])) {
4523 $media = $_FILES['media'];
4525 // save new profile image
4526 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4529 if (is_array($media['type'])) {
4530 $filetype = $media['type'][0];
4532 $filetype = $media['type'];
4534 if ($filetype == "image/jpeg") {
4536 } elseif ($filetype == "image/png") {
4539 throw new InternalServerErrorException('Unsupported filetype');
4542 // change specified profile or all profiles to the new resource-id
4543 if ($is_default_profile) {
4544 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4545 Photo::update(['profile' => false], $condition);
4547 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4548 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4549 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4552 Contact::updateSelfFromUserID(api_user(), true);
4554 // Update global directory in background
4555 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4556 if ($url && strlen(Config::get('system', 'directory'))) {
4557 Worker::add(PRIORITY_LOW, "Directory", $url);
4560 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4562 // output for client
4564 return api_account_verify_credentials($type);
4566 // SaveMediaToDatabase failed for some reason
4567 throw new InternalServerErrorException("image upload failed");
4571 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4572 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4573 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4574 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4575 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4576 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4577 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4578 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4579 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4582 * Update user profile
4584 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4586 * @return array|string
4587 * @throws BadRequestException
4588 * @throws ForbiddenException
4589 * @throws ImagickException
4590 * @throws InternalServerErrorException
4591 * @throws UnauthorizedException
4593 function api_account_update_profile($type)
4595 $local_user = api_user();
4596 $api_user = api_get_user(get_app());
4598 if (!empty($_POST['name'])) {
4599 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4600 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4601 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4602 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4605 if (isset($_POST['description'])) {
4606 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4607 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4608 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4611 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4612 // Update global directory in background
4613 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4614 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4617 return api_account_verify_credentials($type);
4620 /// @TODO move to top of file or somewhere better
4621 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4625 * @param string $acl_string
4629 function check_acl_input($acl_string)
4631 if ($acl_string == null || $acl_string == " ") {
4634 $contact_not_found = false;
4636 // split <x><y><z> into array of cid's
4637 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4639 // check for each cid if it is available on server
4640 $cid_array = $array[0];
4641 foreach ($cid_array as $cid) {
4642 $cid = str_replace("<", "", $cid);
4643 $cid = str_replace(">", "", $cid);
4644 $condition = ['id' => $cid, 'uid' => api_user()];
4645 $contact_not_found |= !DBA::exists('contact', $condition);
4647 return $contact_not_found;
4652 * @param string $mediatype
4653 * @param array $media
4654 * @param string $type
4655 * @param string $album
4656 * @param string $allow_cid
4657 * @param string $deny_cid
4658 * @param string $allow_gid
4659 * @param string $deny_gid
4660 * @param string $desc
4661 * @param integer $profile
4662 * @param boolean $visibility
4663 * @param string $photo_id
4665 * @throws BadRequestException
4666 * @throws ForbiddenException
4667 * @throws ImagickException
4668 * @throws InternalServerErrorException
4669 * @throws NotFoundException
4671 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)
4679 if (is_array($media)) {
4680 if (is_array($media['tmp_name'])) {
4681 $src = $media['tmp_name'][0];
4683 $src = $media['tmp_name'];
4685 if (is_array($media['name'])) {
4686 $filename = basename($media['name'][0]);
4688 $filename = basename($media['name']);
4690 if (is_array($media['size'])) {
4691 $filesize = intval($media['size'][0]);
4693 $filesize = intval($media['size']);
4695 if (is_array($media['type'])) {
4696 $filetype = $media['type'][0];
4698 $filetype = $media['type'];
4702 if ($filetype == "") {
4703 $filetype=Image::guessType($filename);
4705 $imagedata = @getimagesize($src);
4707 $filetype = $imagedata['mime'];
4710 "File upload src: " . $src . " - filename: " . $filename .
4711 " - size: " . $filesize . " - type: " . $filetype,
4715 // check if there was a php upload error
4716 if ($filesize == 0 && $media['error'] == 1) {
4717 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4719 // check against max upload size within Friendica instance
4720 $maximagesize = Config::get('system', 'maximagesize');
4721 if ($maximagesize && ($filesize > $maximagesize)) {
4722 $formattedBytes = Strings::formatBytes($maximagesize);
4723 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4726 // create Photo instance with the data of the image
4727 $imagedata = @file_get_contents($src);
4728 $Image = new Image($imagedata, $filetype);
4729 if (!$Image->isValid()) {
4730 throw new InternalServerErrorException("unable to process image data");
4733 // check orientation of image
4734 $Image->orient($src);
4737 // check max length of images on server
4738 $max_length = Config::get('system', 'max_image_length');
4740 $max_length = MAX_IMAGE_LENGTH;
4742 if ($max_length > 0) {
4743 $Image->scaleDown($max_length);
4744 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4746 $width = $Image->getWidth();
4747 $height = $Image->getHeight();
4749 // create a new resource-id if not already provided
4750 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4752 if ($mediatype == "photo") {
4753 // upload normal image (scales 0, 1, 2)
4754 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4756 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4758 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4760 if ($width > 640 || $height > 640) {
4761 $Image->scaleDown(640);
4762 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4764 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4768 if ($width > 320 || $height > 320) {
4769 $Image->scaleDown(320);
4770 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4772 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4775 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4776 } elseif ($mediatype == "profileimage") {
4777 // upload profile image (scales 4, 5, 6)
4778 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4780 if ($width > 300 || $height > 300) {
4781 $Image->scaleDown(300);
4782 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4784 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4788 if ($width > 80 || $height > 80) {
4789 $Image->scaleDown(80);
4790 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4792 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4796 if ($width > 48 || $height > 48) {
4797 $Image->scaleDown(48);
4798 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4800 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4803 $Image->__destruct();
4804 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4807 if (isset($r) && $r) {
4808 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4809 if ($photo_id == null && $mediatype == "photo") {
4810 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4812 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4813 return prepare_photo_data($type, false, $hash);
4815 throw new InternalServerErrorException("image upload failed");
4821 * @param string $hash
4822 * @param string $allow_cid
4823 * @param string $deny_cid
4824 * @param string $allow_gid
4825 * @param string $deny_gid
4826 * @param string $filetype
4827 * @param boolean $visibility
4828 * @throws InternalServerErrorException
4830 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4832 // get data about the api authenticated user
4833 $uri = Item::newURI(intval(api_user()));
4834 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4837 $arr['guid'] = System::createUUID();
4838 $arr['uid'] = intval(api_user());
4840 $arr['parent-uri'] = $uri;
4841 $arr['type'] = 'photo';
4843 $arr['resource-id'] = $hash;
4844 $arr['contact-id'] = $owner_record['id'];
4845 $arr['owner-name'] = $owner_record['name'];
4846 $arr['owner-link'] = $owner_record['url'];
4847 $arr['owner-avatar'] = $owner_record['thumb'];
4848 $arr['author-name'] = $owner_record['name'];
4849 $arr['author-link'] = $owner_record['url'];
4850 $arr['author-avatar'] = $owner_record['thumb'];
4852 $arr['allow_cid'] = $allow_cid;
4853 $arr['allow_gid'] = $allow_gid;
4854 $arr['deny_cid'] = $deny_cid;
4855 $arr['deny_gid'] = $deny_gid;
4856 $arr['visible'] = $visibility;
4860 'image/jpeg' => 'jpg',
4861 'image/png' => 'png',
4862 'image/gif' => 'gif'
4865 // adds link to the thumbnail scale photo
4866 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4867 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4870 // do the magic for storing the item in the database and trigger the federation to other contacts
4876 * @param string $type
4878 * @param string $photo_id
4881 * @throws BadRequestException
4882 * @throws ForbiddenException
4883 * @throws ImagickException
4884 * @throws InternalServerErrorException
4885 * @throws NotFoundException
4886 * @throws UnauthorizedException
4888 function prepare_photo_data($type, $scale, $photo_id)
4891 $user_info = api_get_user($a);
4893 if ($user_info === false) {
4894 throw new ForbiddenException();
4897 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4898 $data_sql = ($scale === false ? "" : "data, ");
4900 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4901 // clients needs to convert this in their way for further processing
4903 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4904 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4905 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4906 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4908 intval(local_user()),
4909 DBA::escape($photo_id),
4914 'image/jpeg' => 'jpg',
4915 'image/png' => 'png',
4916 'image/gif' => 'gif'
4919 // prepare output data for photo
4920 if (DBA::isResult($r)) {
4921 $data = ['photo' => $r[0]];
4922 $data['photo']['id'] = $data['photo']['resource-id'];
4923 if ($scale !== false) {
4924 $data['photo']['data'] = base64_encode($data['photo']['data']);
4926 unset($data['photo']['datasize']); //needed only with scale param
4928 if ($type == "xml") {
4929 $data['photo']['links'] = [];
4930 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4931 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4933 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4936 $data['photo']['link'] = [];
4937 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4939 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4940 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4944 unset($data['photo']['resource-id']);
4945 unset($data['photo']['minscale']);
4946 unset($data['photo']['maxscale']);
4948 throw new NotFoundException();
4951 // retrieve item element for getting activities (like, dislike etc.) related to photo
4952 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4953 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4955 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4957 // retrieve comments on photo
4958 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4959 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4961 $statuses = Item::selectForUser(api_user(), [], $condition);
4963 // prepare output of comments
4964 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4966 if ($type == "xml") {
4968 foreach ($commentData as $comment) {
4969 $comments[$k++ . ":comment"] = $comment;
4972 foreach ($commentData as $comment) {
4973 $comments[] = $comment;
4976 $data['photo']['friendica_comments'] = $comments;
4978 // include info if rights on photo and rights on item are mismatching
4979 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4980 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4981 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4982 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4983 $data['photo']['rights_mismatch'] = $rights_mismatch;
4990 * Similar as /mod/redir.php
4991 * redirect to 'url' after dfrn auth
4993 * Why this when there is mod/redir.php already?
4994 * This use api_user() and api_login()
4997 * c_url: url of remote contact to auth to
4998 * url: string, url to redirect after auth
5000 function api_friendica_remoteauth()
5002 $url = defaults($_GET, 'url', '');
5003 $c_url = defaults($_GET, 'c_url', '');
5005 if ($url === '' || $c_url === '') {
5006 throw new BadRequestException("Wrong parameters.");
5009 $c_url = Strings::normaliseLink($c_url);
5013 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5015 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5016 throw new BadRequestException("Unknown contact");
5019 $cid = $contact['id'];
5021 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
5023 if ($contact['duplex'] && $contact['issued-id']) {
5024 $orig_id = $contact['issued-id'];
5025 $dfrn_id = '1:' . $orig_id;
5027 if ($contact['duplex'] && $contact['dfrn-id']) {
5028 $orig_id = $contact['dfrn-id'];
5029 $dfrn_id = '0:' . $orig_id;
5032 $sec = Strings::getRandomHex();
5034 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5035 'sec' => $sec, 'expire' => time() + 45];
5036 DBA::insert('profile_check', $fields);
5038 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5039 $dest = ($url ? '&destination_url=' . $url : '');
5041 System::externalRedirect(
5042 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5043 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5044 . '&type=profile&sec=' . $sec . $dest
5047 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5050 * @brief Return the item shared, if the item contains only the [share] tag
5052 * @param array $item Sharer item
5053 * @return array|false Shared item or false if not a reshare
5054 * @throws ImagickException
5055 * @throws InternalServerErrorException
5057 function api_share_as_retweet(&$item)
5059 $body = trim($item["body"]);
5061 if (Diaspora::isReshare($body, false) === false) {
5062 if ($item['author-id'] == $item['owner-id']) {
5065 // Reshares from OStatus, ActivityPub and Twitter
5066 $reshared_item = $item;
5067 $reshared_item['owner-id'] = $reshared_item['author-id'];
5068 $reshared_item['owner-link'] = $reshared_item['author-link'];
5069 $reshared_item['owner-name'] = $reshared_item['author-name'];
5070 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5071 return $reshared_item;
5075 /// @TODO "$1" should maybe mean '$1' ?
5076 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5078 * Skip if there is no shared message in there
5079 * we already checked this in diaspora::isReshare()
5080 * but better one more than one less...
5082 if (($body == $attributes) || empty($attributes)) {
5086 // build the fake reshared item
5087 $reshared_item = $item;
5090 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5091 if (!empty($matches[1])) {
5092 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5095 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5096 if (!empty($matches[1])) {
5097 $author = $matches[1];
5101 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5102 if (!empty($matches[1])) {
5103 $profile = $matches[1];
5106 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5107 if (!empty($matches[1])) {
5108 $profile = $matches[1];
5112 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5113 if (!empty($matches[1])) {
5114 $avatar = $matches[1];
5117 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5118 if (!empty($matches[1])) {
5119 $avatar = $matches[1];
5123 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5124 if (!empty($matches[1])) {
5125 $link = $matches[1];
5128 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5129 if (!empty($matches[1])) {
5130 $link = $matches[1];
5134 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5135 if (!empty($matches[1])) {
5136 $posted = $matches[1];
5139 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5140 if (!empty($matches[1])) {
5141 $posted = $matches[1];
5144 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5146 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5150 $reshared_item["body"] = $shared_body;
5151 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5152 $reshared_item["author-name"] = $author;
5153 $reshared_item["author-link"] = $profile;
5154 $reshared_item["author-avatar"] = $avatar;
5155 $reshared_item["plink"] = $link;
5156 $reshared_item["created"] = $posted;
5157 $reshared_item["edited"] = $posted;
5159 return $reshared_item;
5164 * @param string $profile
5166 * @return string|false
5167 * @throws InternalServerErrorException
5168 * @todo remove trailing junk from profile url
5169 * @todo pump.io check has to check the website
5171 function api_get_nick($profile)
5176 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5177 DBA::escape(Strings::normaliseLink($profile))
5180 if (DBA::isResult($r)) {
5181 $nick = $r[0]["nick"];
5186 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5187 DBA::escape(Strings::normaliseLink($profile))
5190 if (DBA::isResult($r)) {
5191 $nick = $r[0]["nick"];
5196 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5197 if ($friendica != $profile) {
5203 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5204 if ($diaspora != $profile) {
5210 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5211 if ($twitter != $profile) {
5218 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5219 if ($StatusnetHost != $profile) {
5220 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5221 if ($StatusnetUser != $profile) {
5222 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5223 $user = json_decode($UserData);
5225 $nick = $user->screen_name;
5231 // To-Do: look at the page if its really a pumpio site
5232 //if (!$nick == "") {
5233 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5234 // if ($pumpio != $profile)
5236 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5249 * @param array $item
5254 function api_in_reply_to($item)
5258 $in_reply_to['status_id'] = null;
5259 $in_reply_to['user_id'] = null;
5260 $in_reply_to['status_id_str'] = null;
5261 $in_reply_to['user_id_str'] = null;
5262 $in_reply_to['screen_name'] = null;
5264 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5265 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5266 if (DBA::isResult($parent)) {
5267 $in_reply_to['status_id'] = intval($parent['id']);
5269 $in_reply_to['status_id'] = intval($item['parent']);
5272 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5274 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5275 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5277 if (DBA::isResult($parent)) {
5278 if ($parent['author-nick'] == "") {
5279 $parent['author-nick'] = api_get_nick($parent['author-link']);
5282 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5283 $in_reply_to['user_id'] = intval($parent['author-id']);
5284 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5287 // There seems to be situation, where both fields are identical:
5288 // https://github.com/friendica/friendica/issues/1010
5289 // This is a bugfix for that.
5290 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5291 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']]);
5292 $in_reply_to['status_id'] = null;
5293 $in_reply_to['user_id'] = null;
5294 $in_reply_to['status_id_str'] = null;
5295 $in_reply_to['user_id_str'] = null;
5296 $in_reply_to['screen_name'] = null;
5300 return $in_reply_to;
5305 * @param string $text
5308 * @throws InternalServerErrorException
5310 function api_clean_plain_items($text)
5312 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5314 $text = BBCode::cleanPictureLinks($text);
5315 $URLSearchString = "^\[\]";
5317 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5319 if ($include_entities == "true") {
5320 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5323 // Simplify "attachment" element
5324 $text = api_clean_attachments($text);
5330 * @brief Removes most sharing information for API text export
5332 * @param string $body The original body
5334 * @return string Cleaned body
5335 * @throws InternalServerErrorException
5337 function api_clean_attachments($body)
5339 $data = BBCode::getAttachmentData($body);
5346 if (isset($data["text"])) {
5347 $body = $data["text"];
5349 if (($body == "") && isset($data["title"])) {
5350 $body = $data["title"];
5352 if (isset($data["url"])) {
5353 $body .= "\n".$data["url"];
5355 $body .= $data["after"];
5362 * @param array $contacts
5366 function api_best_nickname(&$contacts)
5370 if (count($contacts) == 0) {
5374 foreach ($contacts as $contact) {
5375 if ($contact["network"] == "") {
5376 $contact["network"] = "dfrn";
5377 $best_contact = [$contact];
5381 if (sizeof($best_contact) == 0) {
5382 foreach ($contacts as $contact) {
5383 if ($contact["network"] == "dfrn") {
5384 $best_contact = [$contact];
5389 if (sizeof($best_contact) == 0) {
5390 foreach ($contacts as $contact) {
5391 if ($contact["network"] == "dspr") {
5392 $best_contact = [$contact];
5397 if (sizeof($best_contact) == 0) {
5398 foreach ($contacts as $contact) {
5399 if ($contact["network"] == "stat") {
5400 $best_contact = [$contact];
5405 if (sizeof($best_contact) == 0) {
5406 foreach ($contacts as $contact) {
5407 if ($contact["network"] == "pump") {
5408 $best_contact = [$contact];
5413 if (sizeof($best_contact) == 0) {
5414 foreach ($contacts as $contact) {
5415 if ($contact["network"] == "twit") {
5416 $best_contact = [$contact];
5421 if (sizeof($best_contact) == 1) {
5422 $contacts = $best_contact;
5424 $contacts = [$contacts[0]];
5429 * Return all or a specified group of the user with the containing contacts.
5431 * @param string $type Return type (atom, rss, xml, json)
5433 * @return array|string
5434 * @throws BadRequestException
5435 * @throws ForbiddenException
5436 * @throws ImagickException
5437 * @throws InternalServerErrorException
5438 * @throws UnauthorizedException
5440 function api_friendica_group_show($type)
5444 if (api_user() === false) {
5445 throw new ForbiddenException();
5449 $user_info = api_get_user($a);
5450 $gid = defaults($_REQUEST, 'gid', 0);
5451 $uid = $user_info['uid'];
5453 // get data of the specified group id or all groups if not specified
5456 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5460 // error message if specified gid is not in database
5461 if (!DBA::isResult($r)) {
5462 throw new BadRequestException("gid not available");
5466 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5471 // loop through all groups and retrieve all members for adding data in the user array
5473 foreach ($r as $rr) {
5474 $members = Contact::getByGroupId($rr['id']);
5477 if ($type == "xml") {
5478 $user_element = "users";
5480 foreach ($members as $member) {
5481 $user = api_get_user($a, $member['nurl']);
5482 $users[$k++.":user"] = $user;
5485 $user_element = "user";
5486 foreach ($members as $member) {
5487 $user = api_get_user($a, $member['nurl']);
5491 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5493 return api_format_data("groups", $type, ['group' => $grps]);
5495 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5499 * Delete the specified group of the user.
5501 * @param string $type Return type (atom, rss, xml, json)
5503 * @return array|string
5504 * @throws BadRequestException
5505 * @throws ForbiddenException
5506 * @throws ImagickException
5507 * @throws InternalServerErrorException
5508 * @throws UnauthorizedException
5510 function api_friendica_group_delete($type)
5514 if (api_user() === false) {
5515 throw new ForbiddenException();
5519 $user_info = api_get_user($a);
5520 $gid = defaults($_REQUEST, 'gid', 0);
5521 $name = defaults($_REQUEST, 'name', "");
5522 $uid = $user_info['uid'];
5524 // error if no gid specified
5525 if ($gid == 0 || $name == "") {
5526 throw new BadRequestException('gid or name not specified');
5529 // get data of the specified group id
5531 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5535 // error message if specified gid is not in database
5536 if (!DBA::isResult($r)) {
5537 throw new BadRequestException('gid not available');
5540 // get data of the specified group id and group name
5542 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5547 // error message if specified gid is not in database
5548 if (!DBA::isResult($rname)) {
5549 throw new BadRequestException('wrong group name');
5553 $ret = Group::removeByName($uid, $name);
5556 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5557 return api_format_data("group_delete", $type, ['result' => $success]);
5559 throw new BadRequestException('other API error');
5562 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5567 * @param string $type Return type (atom, rss, xml, json)
5569 * @return array|string
5570 * @throws BadRequestException
5571 * @throws ForbiddenException
5572 * @throws ImagickException
5573 * @throws InternalServerErrorException
5574 * @throws UnauthorizedException
5575 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5577 function api_lists_destroy($type)
5581 if (api_user() === false) {
5582 throw new ForbiddenException();
5586 $user_info = api_get_user($a);
5587 $gid = defaults($_REQUEST, 'list_id', 0);
5588 $uid = $user_info['uid'];
5590 // error if no gid specified
5592 throw new BadRequestException('gid not specified');
5595 // get data of the specified group id
5596 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5597 // error message if specified gid is not in database
5599 throw new BadRequestException('gid not available');
5602 if (Group::remove($gid)) {
5604 'name' => $group['name'],
5605 'id' => intval($gid),
5606 'id_str' => (string) $gid,
5607 'user' => $user_info
5610 return api_format_data("lists", $type, ['lists' => $list]);
5613 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5616 * Add a new group to the database.
5618 * @param string $name Group name
5619 * @param int $uid User ID
5620 * @param array $users List of users to add to the group
5623 * @throws BadRequestException
5625 function group_create($name, $uid, $users = [])
5627 // error if no name specified
5629 throw new BadRequestException('group name not specified');
5632 // get data of the specified group name
5634 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5638 // error message if specified group name already exists
5639 if (DBA::isResult($rname)) {
5640 throw new BadRequestException('group name already exists');
5643 // check if specified group name is a deleted group
5645 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5649 // error message if specified group name already exists
5650 if (DBA::isResult($rname)) {
5651 $reactivate_group = true;
5655 $ret = Group::create($uid, $name);
5657 $gid = Group::getIdByName($uid, $name);
5659 throw new BadRequestException('other API error');
5663 $erroraddinguser = false;
5665 foreach ($users as $user) {
5666 $cid = $user['cid'];
5667 // check if user really exists as contact
5669 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5673 if (count($contact)) {
5674 Group::addMember($gid, $cid);
5676 $erroraddinguser = true;
5677 $errorusers[] = $cid;
5681 // return success message incl. missing users in array
5682 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5684 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5688 * Create the specified group with the posted array of contacts.
5690 * @param string $type Return type (atom, rss, xml, json)
5692 * @return array|string
5693 * @throws BadRequestException
5694 * @throws ForbiddenException
5695 * @throws ImagickException
5696 * @throws InternalServerErrorException
5697 * @throws UnauthorizedException
5699 function api_friendica_group_create($type)
5703 if (api_user() === false) {
5704 throw new ForbiddenException();
5708 $user_info = api_get_user($a);
5709 $name = defaults($_REQUEST, 'name', "");
5710 $uid = $user_info['uid'];
5711 $json = json_decode($_POST['json'], true);
5712 $users = $json['user'];
5714 $success = group_create($name, $uid, $users);
5716 return api_format_data("group_create", $type, ['result' => $success]);
5718 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5721 * Create a new group.
5723 * @param string $type Return type (atom, rss, xml, json)
5725 * @return array|string
5726 * @throws BadRequestException
5727 * @throws ForbiddenException
5728 * @throws ImagickException
5729 * @throws InternalServerErrorException
5730 * @throws UnauthorizedException
5731 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5733 function api_lists_create($type)
5737 if (api_user() === false) {
5738 throw new ForbiddenException();
5742 $user_info = api_get_user($a);
5743 $name = defaults($_REQUEST, 'name', "");
5744 $uid = $user_info['uid'];
5746 $success = group_create($name, $uid);
5747 if ($success['success']) {
5749 'name' => $success['name'],
5750 'id' => intval($success['gid']),
5751 'id_str' => (string) $success['gid'],
5752 'user' => $user_info
5755 return api_format_data("lists", $type, ['lists'=>$grp]);
5758 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5761 * Update the specified group with the posted array of contacts.
5763 * @param string $type Return type (atom, rss, xml, json)
5765 * @return array|string
5766 * @throws BadRequestException
5767 * @throws ForbiddenException
5768 * @throws ImagickException
5769 * @throws InternalServerErrorException
5770 * @throws UnauthorizedException
5772 function api_friendica_group_update($type)
5776 if (api_user() === false) {
5777 throw new ForbiddenException();
5781 $user_info = api_get_user($a);
5782 $uid = $user_info['uid'];
5783 $gid = defaults($_REQUEST, 'gid', 0);
5784 $name = defaults($_REQUEST, 'name', "");
5785 $json = json_decode($_POST['json'], true);
5786 $users = $json['user'];
5788 // error if no name specified
5790 throw new BadRequestException('group name not specified');
5793 // error if no gid specified
5795 throw new BadRequestException('gid not specified');
5799 $members = Contact::getByGroupId($gid);
5800 foreach ($members as $member) {
5801 $cid = $member['id'];
5802 foreach ($users as $user) {
5803 $found = ($user['cid'] == $cid ? true : false);
5805 if (!isset($found) || !$found) {
5806 Group::removeMemberByName($uid, $name, $cid);
5811 $erroraddinguser = false;
5813 foreach ($users as $user) {
5814 $cid = $user['cid'];
5815 // check if user really exists as contact
5817 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5822 if (count($contact)) {
5823 Group::addMember($gid, $cid);
5825 $erroraddinguser = true;
5826 $errorusers[] = $cid;
5830 // return success message incl. missing users in array
5831 $status = ($erroraddinguser ? "missing user" : "ok");
5832 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5833 return api_format_data("group_update", $type, ['result' => $success]);
5836 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5839 * Update information about a group.
5841 * @param string $type Return type (atom, rss, xml, json)
5843 * @return array|string
5844 * @throws BadRequestException
5845 * @throws ForbiddenException
5846 * @throws ImagickException
5847 * @throws InternalServerErrorException
5848 * @throws UnauthorizedException
5849 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5851 function api_lists_update($type)
5855 if (api_user() === false) {
5856 throw new ForbiddenException();
5860 $user_info = api_get_user($a);
5861 $gid = defaults($_REQUEST, 'list_id', 0);
5862 $name = defaults($_REQUEST, 'name', "");
5863 $uid = $user_info['uid'];
5865 // error if no gid specified
5867 throw new BadRequestException('gid not specified');
5870 // get data of the specified group id
5871 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5872 // error message if specified gid is not in database
5874 throw new BadRequestException('gid not available');
5877 if (Group::update($gid, $name)) {
5880 'id' => intval($gid),
5881 'id_str' => (string) $gid,
5882 'user' => $user_info
5885 return api_format_data("lists", $type, ['lists' => $list]);
5889 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5893 * @param string $type Return type (atom, rss, xml, json)
5895 * @return array|string
5896 * @throws BadRequestException
5897 * @throws ForbiddenException
5898 * @throws ImagickException
5899 * @throws InternalServerErrorException
5901 function api_friendica_activity($type)
5905 if (api_user() === false) {
5906 throw new ForbiddenException();
5908 $verb = strtolower($a->argv[3]);
5909 $verb = preg_replace("|\..*$|", "", $verb);
5911 $id = defaults($_REQUEST, 'id', 0);
5913 $res = Item::performLike($id, $verb);
5916 if ($type == "xml") {
5921 return api_format_data('ok', $type, ['ok' => $ok]);
5923 throw new BadRequestException('Error adding activity');
5927 /// @TODO move to top of file or somewhere better
5928 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5929 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5930 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5931 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5932 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5933 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5934 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5935 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5936 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5937 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5940 * @brief Returns notifications
5942 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5943 * @return string|array
5944 * @throws BadRequestException
5945 * @throws ForbiddenException
5946 * @throws InternalServerErrorException
5948 function api_friendica_notification($type)
5952 if (api_user() === false) {
5953 throw new ForbiddenException();
5956 throw new BadRequestException("Invalid argument count");
5958 $nm = new NotificationsManager();
5960 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
5962 if ($type == "xml") {
5964 if (!empty($notes)) {
5965 foreach ($notes as $note) {
5966 $xmlnotes[] = ["@attributes" => $note];
5972 return api_format_data("notes", $type, ['note' => $notes]);
5976 * POST request with 'id' param as notification id
5978 * @brief Set notification as seen and returns associated item (if possible)
5980 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5981 * @return string|array
5982 * @throws BadRequestException
5983 * @throws ForbiddenException
5984 * @throws ImagickException
5985 * @throws InternalServerErrorException
5986 * @throws UnauthorizedException
5988 function api_friendica_notification_seen($type)
5991 $user_info = api_get_user($a);
5993 if (api_user() === false || $user_info === false) {
5994 throw new ForbiddenException();
5997 throw new BadRequestException("Invalid argument count");
6000 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
6002 $nm = new NotificationsManager();
6003 $note = $nm->getByID($id);
6004 if (is_null($note)) {
6005 throw new BadRequestException("Invalid argument");
6008 $nm->setSeen($note);
6009 if ($note['otype']=='item') {
6010 // would be really better with an ItemsManager and $im->getByID() :-P
6011 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6012 if (DBA::isResult($item)) {
6013 // we found the item, return it to the user
6014 $ret = api_format_items([$item], $user_info, false, $type);
6015 $data = ['status' => $ret];
6016 return api_format_data("status", $type, $data);
6018 // the item can't be found, but we set the note as seen, so we count this as a success
6020 return api_format_data('result', $type, ['result' => "success"]);
6023 /// @TODO move to top of file or somewhere better
6024 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6025 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6028 * @brief update a direct_message to seen state
6030 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6031 * @return string|array (success result=ok, error result=error with error message)
6032 * @throws BadRequestException
6033 * @throws ForbiddenException
6034 * @throws ImagickException
6035 * @throws InternalServerErrorException
6036 * @throws UnauthorizedException
6038 function api_friendica_direct_messages_setseen($type)
6041 if (api_user() === false) {
6042 throw new ForbiddenException();
6046 $user_info = api_get_user($a);
6047 $uid = $user_info['uid'];
6048 $id = defaults($_REQUEST, 'id', 0);
6050 // return error if id is zero
6052 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6053 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6056 // error message if specified id is not in database
6057 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6058 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6059 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6062 // update seen indicator
6063 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6067 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6068 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6070 $answer = ['result' => 'error', 'message' => 'unknown error'];
6071 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6075 /// @TODO move to top of file or somewhere better
6076 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6079 * @brief search for direct_messages containing a searchstring through api
6081 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6082 * @param string $box
6083 * @return string|array (success: success=true if found and search_result contains found messages,
6084 * success=false if nothing was found, search_result='nothing found',
6085 * error: result=error with error message)
6086 * @throws BadRequestException
6087 * @throws ForbiddenException
6088 * @throws ImagickException
6089 * @throws InternalServerErrorException
6090 * @throws UnauthorizedException
6092 function api_friendica_direct_messages_search($type, $box = "")
6096 if (api_user() === false) {
6097 throw new ForbiddenException();
6101 $user_info = api_get_user($a);
6102 $searchstring = defaults($_REQUEST, 'searchstring', "");
6103 $uid = $user_info['uid'];
6105 // error if no searchstring specified
6106 if ($searchstring == "") {
6107 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6108 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6111 // get data for the specified searchstring
6113 "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",
6115 DBA::escape('%'.$searchstring.'%')
6118 $profile_url = $user_info["url"];
6120 // message if nothing was found
6121 if (!DBA::isResult($r)) {
6122 $success = ['success' => false, 'search_results' => 'problem with query'];
6123 } elseif (count($r) == 0) {
6124 $success = ['success' => false, 'search_results' => 'nothing found'];
6127 foreach ($r as $item) {
6128 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6129 $recipient = $user_info;
6130 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6131 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6132 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6133 $sender = $user_info;
6136 if (isset($recipient) && isset($sender)) {
6137 $ret[] = api_format_messages($item, $recipient, $sender);
6140 $success = ['success' => true, 'search_results' => $ret];
6143 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6146 /// @TODO move to top of file or somewhere better
6147 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6150 * @brief return data of all the profiles a user has to the client
6152 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6153 * @return string|array
6154 * @throws BadRequestException
6155 * @throws ForbiddenException
6156 * @throws ImagickException
6157 * @throws InternalServerErrorException
6158 * @throws UnauthorizedException
6160 function api_friendica_profile_show($type)
6164 if (api_user() === false) {
6165 throw new ForbiddenException();
6169 $profile_id = defaults($_REQUEST, 'profile_id', 0);
6171 // retrieve general information about profiles for user
6172 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6173 $directory = Config::get('system', 'directory');
6175 // get data of the specified profile id or all profiles of the user if not specified
6176 if ($profile_id != 0) {
6178 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
6183 // error message if specified gid is not in database
6184 if (!DBA::isResult($r)) {
6185 throw new BadRequestException("profile_id not available");
6189 "SELECT * FROM `profile` WHERE `uid` = %d",
6193 // loop through all returned profiles and retrieve data and users
6196 foreach ($r as $rr) {
6197 $profile = api_format_items_profiles($rr);
6199 // select all users from contact table, loop and prepare standard return for user data
6202 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
6207 foreach ($nurls as $nurl) {
6208 $user = api_get_user($a, $nurl['nurl']);
6209 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6211 $profile['users'] = $users;
6213 // add prepared profile data to array for final return
6214 if ($type == "xml") {
6215 $profiles[$k++ . ":profile"] = $profile;
6217 $profiles[] = $profile;
6221 // return settings, authenticated user and profiles data
6222 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6224 $result = ['multi_profiles' => $multi_profiles ? true : false,
6225 'global_dir' => $directory,
6226 'friendica_owner' => api_get_user($a, $self['nurl']),
6227 'profiles' => $profiles];
6228 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6230 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6233 * Returns a list of saved searches.
6235 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6237 * @param string $type Return format: json or xml
6239 * @return string|array
6242 function api_saved_searches_list($type)
6244 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6247 while ($term = $terms->fetch()) {
6249 'created_at' => api_date(time()),
6250 'id' => intval($term['id']),
6251 'id_str' => $term['id'],
6252 'name' => $term['term'],
6254 'query' => $term['term']
6260 return api_format_data("terms", $type, ['terms' => $result]);
6263 /// @TODO move to top of file or somewhere better
6264 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6267 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6269 * @brief Number of comments
6271 * @param object $data [Status, Status]
6275 function bindComments(&$data)
6277 if (count($data) == 0) {
6283 foreach ($data as $item) {
6284 $ids[] = $item['id'];
6287 $idStr = DBA::escape(implode(', ', $ids));
6288 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6289 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6290 $itemsData = DBA::toArray($items);
6292 foreach ($itemsData as $item) {
6293 $comments[$item['parent']] = $item['comments'];
6296 foreach ($data as $idx => $item) {
6298 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6303 @TODO Maybe open to implement?
6305 [pagename] => api/1.1/statuses/lookup.json
6306 [id] => 605138389168451584
6307 [include_cards] => true
6308 [cards_platform] => Android-12
6309 [include_entities] => true
6310 [include_my_retweet] => 1
6312 [include_reply_count] => true
6313 [include_descendent_reply_count] => true
6317 Not implemented by now:
6318 statuses/retweets_of_me
6323 account/update_location
6324 account/update_profile_background_image
6327 friendica/profile/update
6328 friendica/profile/create
6329 friendica/profile/delete
6331 Not implemented in status.net:
6332 statuses/retweeted_to_me
6333 statuses/retweeted_by_me
6334 direct_messages/destroy
6336 account/update_delivery_device
6337 notifications/follow