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\Hook;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Protocol;
17 use Friendica\Core\Session;
18 use Friendica\Core\System;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBA;
22 use Friendica\Model\Contact;
23 use Friendica\Model\Group;
24 use Friendica\Model\Item;
25 use Friendica\Model\Mail;
26 use Friendica\Model\Notification;
27 use Friendica\Model\Photo;
28 use Friendica\Model\Profile;
29 use Friendica\Model\User;
30 use Friendica\Model\UserItem;
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\Activity;
44 use Friendica\Protocol\Diaspora;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Images;
47 use Friendica\Util\Network;
48 use Friendica\Util\Proxy as ProxyUtils;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
52 require_once __DIR__ . '/../mod/share.php';
53 require_once __DIR__ . '/../mod/item.php';
54 require_once __DIR__ . '/../mod/wall_upload.php';
56 define('API_METHOD_ANY', '*');
57 define('API_METHOD_GET', 'GET');
58 define('API_METHOD_POST', 'POST,PUT');
59 define('API_METHOD_DELETE', 'POST,DELETE');
61 define('API_LOG_PREFIX', 'API {action} - ');
69 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
70 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
71 * into a page, and visitors will post something without noticing it).
75 if (!empty($_SESSION['allow_api'])) {
83 * Get source name from API client
85 * Clients can send 'source' parameter to be show in post metadata
86 * as "sent via <source>".
87 * Some clients doesn't send a source param, we support ones we know
91 * Client source name, default to "api" if unset/unknown
96 if (requestdata('source')) {
97 return requestdata('source');
100 // Support for known clients that doesn't send a source name
101 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
102 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
106 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
108 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
115 * Format date for API
117 * @param string $str Source date, as UTC
118 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
121 function api_date($str)
123 // Wed May 23 06:01:13 +0000 2007
124 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
128 * Register a function to be the endpoint for defined API path.
130 * @param string $path API URL path, relative to DI::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
162 * @throws ForbiddenException
163 * @throws InternalServerErrorException
164 * @throws UnauthorizedException
165 * @hook 'authenticate'
167 * 'username' => username from login form
168 * 'password' => password from login form
169 * 'authenticated' => return status,
170 * 'user_record' => return authenticated user record
172 function api_login(App $a)
174 $oauth1 = new FKOAuth1();
177 $request = OAuthRequest::from_request();
178 list($consumer, $token) = $oauth1->verify_request($request);
179 if (!is_null($token)) {
180 $oauth1->loginUser($token->uid);
181 Session::set('allow_api', true);
184 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
185 var_dump($consumer, $token);
187 } catch (Exception $e) {
188 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
191 // workaround for HTTP-auth in CGI mode
192 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
193 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
194 if (strlen($userpass)) {
195 list($name, $password) = explode(':', $userpass);
196 $_SERVER['PHP_AUTH_USER'] = $name;
197 $_SERVER['PHP_AUTH_PW'] = $password;
201 if (empty($_SERVER['PHP_AUTH_USER'])) {
202 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
203 header('WWW-Authenticate: Basic realm="Friendica"');
204 throw new UnauthorizedException("This API requires login");
207 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
208 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
210 // allow "user@server" login (but ignore 'server' part)
211 $at = strstr($user, "@", true);
216 // next code from mod/auth.php. needs better solution
220 'username' => trim($user),
221 'password' => trim($password),
222 'authenticated' => 0,
223 'user_record' => null,
227 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
228 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
229 * and later addons should not interfere with an earlier one that succeeded.
231 Hook::callAll('authenticate', $addon_auth);
233 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
234 $record = $addon_auth['user_record'];
236 $user_id = User::authenticate(trim($user), trim($password), true);
237 if ($user_id !== false) {
238 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
242 if (!DBA::isResult($record)) {
243 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
244 header('WWW-Authenticate: Basic realm="Friendica"');
245 //header('HTTP/1.0 401 Unauthorized');
246 //die('This api requires login');
247 throw new UnauthorizedException("This API requires login");
250 DI::auth()->setForUser($a, $record);
252 $_SESSION["allow_api"] = true;
254 Hook::callAll('logged_in', $a->user);
258 * Check HTTP method of called API
260 * API endpoints can define which HTTP method to accept when called.
261 * This function check the current HTTP method agains endpoint
264 * @param string $method Required methods, uppercase, separated by comma
267 function api_check_method($method)
269 if ($method == "*") {
272 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
276 * Main API entry point
278 * Authenticate user, call registered API function, set HTTP headers
281 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
282 * @return string|array API call result
285 function api_call(App $a, App\Arguments $args = null)
287 global $API, $called_api;
294 if (strpos($args->getQueryString(), ".xml") > 0) {
297 if (strpos($args->getQueryString(), ".json") > 0) {
300 if (strpos($args->getQueryString(), ".rss") > 0) {
303 if (strpos($args->getQueryString(), ".atom") > 0) {
308 foreach ($API as $p => $info) {
309 if (strpos($args->getQueryString(), $p) === 0) {
310 if (!api_check_method($info['method'])) {
311 throw new MethodNotAllowedException();
314 $called_api = explode("/", $p);
315 //unset($_SERVER['PHP_AUTH_USER']);
317 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
318 if (!empty($info['auth']) && api_user() === false) {
322 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
323 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
325 $stamp = microtime(true);
326 $return = call_user_func($info['func'], $type);
327 $duration = floatval(microtime(true) - $stamp);
329 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
331 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
333 if (false === $return) {
335 * api function returned false withour throw an
336 * exception. This should not happend, throw a 500
338 throw new InternalServerErrorException();
343 header("Content-Type: text/xml");
346 header("Content-Type: application/json");
347 if (!empty($return)) {
348 $json = json_encode(end($return));
349 if (!empty($_GET['callback'])) {
350 $json = $_GET['callback'] . "(" . $json . ")";
356 header("Content-Type: application/rss+xml");
357 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
360 header("Content-Type: application/atom+xml");
361 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
368 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
369 throw new NotImplementedException();
370 } catch (HTTPException $e) {
371 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
372 return api_error($type, $e, $args);
377 * Format API error string
379 * @param string $type Return type (xml, json, rss, as)
380 * @param object $e HTTPException Error object
381 * @param App\Arguments $args The App arguments
382 * @return string|array error message formatted as $type
384 function api_error($type, $e, App\Arguments $args)
386 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
387 /// @TODO: https://dev.twitter.com/overview/api/response-codes
389 $error = ["error" => $error,
390 "code" => $e->getCode() . " " . $e->httpdesc,
391 "request" => $args->getQueryString()];
393 $return = api_format_data('status', $type, ['status' => $error]);
397 header("Content-Type: text/xml");
400 header("Content-Type: application/json");
401 $return = json_encode($return);
404 header("Content-Type: application/rss+xml");
407 header("Content-Type: application/atom+xml");
415 * Set values for RSS template
418 * @param array $arr Array to be passed to template
419 * @param array $user_info User info
421 * @throws BadRequestException
422 * @throws ImagickException
423 * @throws InternalServerErrorException
424 * @throws UnauthorizedException
425 * @todo find proper type-hints
427 function api_rss_extra(App $a, $arr, $user_info)
429 if (is_null($user_info)) {
430 $user_info = api_get_user($a);
433 $arr['$user'] = $user_info;
435 'alternate' => $user_info['url'],
436 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
437 'base' => DI::baseUrl(),
438 'updated' => api_date(null),
439 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
440 'language' => $user_info['lang'],
441 'logo' => DI::baseUrl() . "/images/friendica-32.png",
449 * Unique contact to contact url.
451 * @param int $id Contact id
452 * @return bool|string
453 * Contact url or False if contact id is unknown
456 function api_unique_id_to_nurl($id)
458 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
460 if (DBA::isResult($r)) {
468 * Get user info array.
471 * @param int|string $contact_id Contact ID or URL
473 * @throws BadRequestException
474 * @throws ImagickException
475 * @throws InternalServerErrorException
476 * @throws UnauthorizedException
478 function api_get_user(App $a, $contact_id = null)
486 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
488 // Searching for contact URL
489 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
490 $user = DBA::escape(Strings::normaliseLink($contact_id));
492 $extra_query = "AND `contact`.`nurl` = '%s' ";
493 if (api_user() !== false) {
494 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
498 // Searching for contact id with uid = 0
499 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
500 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
503 throw new BadRequestException("User ID ".$contact_id." not found.");
507 $extra_query = "AND `contact`.`nurl` = '%s' ";
508 if (api_user() !== false) {
509 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
513 if (is_null($user) && !empty($_GET['user_id'])) {
514 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
517 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
521 $extra_query = "AND `contact`.`nurl` = '%s' ";
522 if (api_user() !== false) {
523 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
526 if (is_null($user) && !empty($_GET['screen_name'])) {
527 $user = DBA::escape($_GET['screen_name']);
528 $extra_query = "AND `contact`.`nick` = '%s' ";
529 if (api_user() !== false) {
530 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
534 if (is_null($user) && !empty($_GET['profileurl'])) {
535 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
536 $extra_query = "AND `contact`.`nurl` = '%s' ";
537 if (api_user() !== false) {
538 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
542 // $called_api is the API path exploded on / and is expected to have at least 2 elements
543 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
544 $argid = count($called_api);
545 if (!empty($a->argv[$argid])) {
546 $data = explode(".", $a->argv[$argid]);
547 if (count($data) > 1) {
548 list($user, $null) = $data;
551 if (is_numeric($user)) {
552 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
556 $extra_query = "AND `contact`.`nurl` = '%s' ";
557 if (api_user() !== false) {
558 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
562 $user = DBA::escape($user);
563 $extra_query = "AND `contact`.`nick` = '%s' ";
564 if (api_user() !== false) {
565 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
570 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
573 if (api_user() === false) {
577 $user = $_SESSION['uid'];
578 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
582 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
586 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
592 // Selecting the id by priority, friendica first
593 if (is_array($uinfo)) {
594 api_best_nickname($uinfo);
597 // if the contact wasn't found, fetch it from the contacts with uid = 0
598 if (!DBA::isResult($uinfo)) {
600 throw new BadRequestException("User not found.");
603 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
605 if (DBA::isResult($contact)) {
607 'id' => $contact["id"],
608 'id_str' => (string) $contact["id"],
609 'name' => $contact["name"],
610 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
611 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
612 'description' => BBCode::toPlaintext($contact["about"]),
613 'profile_image_url' => $contact["micro"],
614 'profile_image_url_https' => $contact["micro"],
615 'profile_image_url_profile_size' => $contact["thumb"],
616 'profile_image_url_large' => $contact["photo"],
617 'url' => $contact["url"],
618 'protected' => false,
619 'followers_count' => 0,
620 'friends_count' => 0,
622 'created_at' => api_date($contact["created"]),
623 'favourites_count' => 0,
625 'time_zone' => 'UTC',
626 'geo_enabled' => false,
628 'statuses_count' => 0,
630 'contributors_enabled' => false,
631 'is_translator' => false,
632 'is_translation_enabled' => false,
633 'following' => false,
634 'follow_request_sent' => false,
635 'statusnet_blocking' => false,
636 'notifications' => false,
637 'statusnet_profile_url' => $contact["url"],
639 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
640 'pid' => Contact::getIdForURL($contact["url"], 0, true),
642 'network' => $contact["network"],
647 throw new BadRequestException("User ".$url." not found.");
651 if ($uinfo[0]['self']) {
652 if ($uinfo[0]['network'] == "") {
653 $uinfo[0]['network'] = Protocol::DFRN;
656 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
657 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
664 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
666 if (!empty($profile['about'])) {
667 $description = $profile['about'];
669 $description = $uinfo[0]["about"];
672 if (!empty($usr['default-location'])) {
673 $location = $usr['default-location'];
674 } elseif (!empty($uinfo[0]["location"])) {
675 $location = $uinfo[0]["location"];
677 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
681 'id' => intval($pcontact_id),
682 'id_str' => (string) intval($pcontact_id),
683 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
684 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
685 'location' => $location,
686 'description' => BBCode::toPlaintext($description),
687 'profile_image_url' => $uinfo[0]['micro'],
688 'profile_image_url_https' => $uinfo[0]['micro'],
689 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
690 'profile_image_url_large' => $uinfo[0]["photo"],
691 'url' => $uinfo[0]['url'],
692 'protected' => false,
693 'followers_count' => intval($countfollowers),
694 'friends_count' => intval($countfriends),
696 'created_at' => api_date($uinfo[0]['created']),
697 'favourites_count' => intval($starred),
699 'time_zone' => 'UTC',
700 'geo_enabled' => false,
702 'statuses_count' => intval($countitems),
704 'contributors_enabled' => false,
705 'is_translator' => false,
706 'is_translation_enabled' => false,
707 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
708 'follow_request_sent' => false,
709 'statusnet_blocking' => false,
710 'notifications' => false,
712 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
713 'statusnet_profile_url' => $uinfo[0]['url'],
714 'uid' => intval($uinfo[0]['uid']),
715 'cid' => intval($uinfo[0]['cid']),
716 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
717 'self' => $uinfo[0]['self'],
718 'network' => $uinfo[0]['network'],
721 // If this is a local user and it uses Frio, we can get its color preferences.
723 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
724 if ($theme_info['theme'] === 'frio') {
725 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
727 if ($schema && ($schema != '---')) {
728 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
729 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
730 require_once $schemefile;
733 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
734 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
735 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
737 if (empty($nav_bg)) {
740 if (empty($link_color)) {
741 $link_color = "#6fdbe8";
743 if (empty($bgcolor)) {
744 $bgcolor = "#ededed";
747 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
748 $ret['profile_link_color'] = str_replace('#', '', $link_color);
749 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
757 * return api-formatted array for item's author and owner
760 * @param array $item item from db
761 * @return array(array:author, array:owner)
762 * @throws BadRequestException
763 * @throws ImagickException
764 * @throws InternalServerErrorException
765 * @throws UnauthorizedException
767 function api_item_get_user(App $a, $item)
769 $status_user = api_get_user($a, $item['author-id'] ?? null);
771 $author_user = $status_user;
773 $status_user["protected"] = $item['private'] ?? 0;
775 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
776 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
778 $owner_user = $author_user;
781 return ([$status_user, $author_user, $owner_user]);
785 * walks recursively through an array with the possibility to change value and key
787 * @param array $array The array to walk through
788 * @param callable $callback The callback function
790 * @return array the transformed array
792 function api_walk_recursive(array &$array, callable $callback)
796 foreach ($array as $k => $v) {
798 if ($callback($v, $k)) {
799 $new_array[$k] = api_walk_recursive($v, $callback);
802 if ($callback($v, $k)) {
813 * Callback function to transform the array in an array that can be transformed in a XML file
815 * @param mixed $item Array item value
816 * @param string $key Array key
818 * @return boolean Should the array item be deleted?
820 function api_reformat_xml(&$item, &$key)
822 if (is_bool($item)) {
823 $item = ($item ? "true" : "false");
826 if (substr($key, 0, 10) == "statusnet_") {
827 $key = "statusnet:".substr($key, 10);
828 } elseif (substr($key, 0, 10) == "friendica_") {
829 $key = "friendica:".substr($key, 10);
831 /// @TODO old-lost code?
833 // $key = "default:".$key;
839 * Creates the XML from a JSON style array
841 * @param array $data JSON style array
842 * @param string $root_element Name of the root element
844 * @return string The XML data
846 function api_create_xml(array $data, $root_element)
848 $childname = key($data);
849 $data2 = array_pop($data);
851 $namespaces = ["" => "http://api.twitter.com",
852 "statusnet" => "http://status.net/schema/api/1/",
853 "friendica" => "http://friendi.ca/schema/api/1/",
854 "georss" => "http://www.georss.org/georss"];
856 /// @todo Auto detection of needed namespaces
857 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
861 if (is_array($data2)) {
863 api_walk_recursive($data2, "api_reformat_xml");
869 foreach ($data2 as $item) {
870 $data4[$i++ . ":" . $childname] = $item;
877 $data3 = [$root_element => $data2];
879 $ret = XML::fromArray($data3, $xml, false, $namespaces);
884 * Formats the data according to the data type
886 * @param string $root_element Name of the root element
887 * @param string $type Return type (atom, rss, xml, json)
888 * @param array $data JSON style array
890 * @return array|string (string|array) XML data or JSON data
892 function api_format_data($root_element, $type, $data)
898 $ret = api_create_xml($data, $root_element);
913 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
914 * returns a 401 status code and an error message if not.
916 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
918 * @param string $type Return type (atom, rss, xml, json)
919 * @return array|string
920 * @throws BadRequestException
921 * @throws ForbiddenException
922 * @throws ImagickException
923 * @throws InternalServerErrorException
924 * @throws UnauthorizedException
926 function api_account_verify_credentials($type)
930 if (api_user() === false) {
931 throw new ForbiddenException();
934 unset($_REQUEST["user_id"]);
935 unset($_GET["user_id"]);
937 unset($_REQUEST["screen_name"]);
938 unset($_GET["screen_name"]);
940 $skip_status = $_REQUEST['skip_status'] ?? false;
942 $user_info = api_get_user($a);
944 // "verified" isn't used here in the standard
945 unset($user_info["verified"]);
947 // - Adding last status
949 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
951 $user_info['status'] = api_format_item($item, $type);
955 // "uid" and "self" are only needed for some internal stuff, so remove it from here
956 unset($user_info["uid"]);
957 unset($user_info["self"]);
959 return api_format_data("user", $type, ['user' => $user_info]);
962 /// @TODO move to top of file or somewhere better
963 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
966 * Get data from $_POST or $_GET
971 function requestdata($k)
973 if (!empty($_POST[$k])) {
976 if (!empty($_GET[$k])) {
983 * Deprecated function to upload media.
985 * @param string $type Return type (atom, rss, xml, json)
987 * @return array|string
988 * @throws BadRequestException
989 * @throws ForbiddenException
990 * @throws ImagickException
991 * @throws InternalServerErrorException
992 * @throws UnauthorizedException
994 function api_statuses_mediap($type)
998 if (api_user() === false) {
999 Logger::log('api_statuses_update: no user');
1000 throw new ForbiddenException();
1002 $user_info = api_get_user($a);
1004 $_REQUEST['profile_uid'] = api_user();
1005 $_REQUEST['api_source'] = true;
1006 $txt = requestdata('status');
1007 /// @TODO old-lost code?
1008 //$txt = urldecode(requestdata('status'));
1010 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1011 $txt = HTML::toBBCodeVideo($txt);
1012 $config = HTMLPurifier_Config::createDefault();
1013 $config->set('Cache.DefinitionImpl', null);
1014 $purifier = new HTMLPurifier($config);
1015 $txt = $purifier->purify($txt);
1017 $txt = HTML::toBBCode($txt);
1019 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1021 $picture = wall_upload_post($a, false);
1023 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1024 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1025 $item_id = item_post($a);
1027 // output the post that we just posted.
1028 return api_status_show($type, $item_id);
1031 /// @TODO move this to top of file or somewhere better!
1032 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1035 * Updates the user’s current status.
1037 * @param string $type Return type (atom, rss, xml, json)
1039 * @return array|string
1040 * @throws BadRequestException
1041 * @throws ForbiddenException
1042 * @throws ImagickException
1043 * @throws InternalServerErrorException
1044 * @throws TooManyRequestsException
1045 * @throws UnauthorizedException
1046 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1048 function api_statuses_update($type)
1052 if (api_user() === false) {
1053 Logger::log('api_statuses_update: no user');
1054 throw new ForbiddenException();
1059 // convert $_POST array items to the form we use for web posts.
1060 if (requestdata('htmlstatus')) {
1061 $txt = requestdata('htmlstatus');
1062 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1063 $txt = HTML::toBBCodeVideo($txt);
1065 $config = HTMLPurifier_Config::createDefault();
1066 $config->set('Cache.DefinitionImpl', null);
1068 $purifier = new HTMLPurifier($config);
1069 $txt = $purifier->purify($txt);
1071 $_REQUEST['body'] = HTML::toBBCode($txt);
1074 $_REQUEST['body'] = requestdata('status');
1077 $_REQUEST['title'] = requestdata('title');
1079 $parent = requestdata('in_reply_to_status_id');
1081 // Twidere sends "-1" if it is no reply ...
1082 if ($parent == -1) {
1086 if (ctype_digit($parent)) {
1087 $_REQUEST['parent'] = $parent;
1089 $_REQUEST['parent_uri'] = $parent;
1092 if (requestdata('lat') && requestdata('long')) {
1093 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1095 $_REQUEST['profile_uid'] = api_user();
1098 // Check for throttling (maximum posts per day, week and month)
1099 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1100 if ($throttle_day > 0) {
1101 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1103 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1104 $posts_day = DBA::count('thread', $condition);
1106 if ($posts_day > $throttle_day) {
1107 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1108 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1109 throw new TooManyRequestsException(DI::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));
1113 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1114 if ($throttle_week > 0) {
1115 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1117 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1118 $posts_week = DBA::count('thread', $condition);
1120 if ($posts_week > $throttle_week) {
1121 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1122 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1123 throw new TooManyRequestsException(DI::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));
1127 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1128 if ($throttle_month > 0) {
1129 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1131 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1132 $posts_month = DBA::count('thread', $condition);
1134 if ($posts_month > $throttle_month) {
1135 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1136 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1137 throw new TooManyRequestsException(DI::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));
1142 if (!empty($_FILES['media'])) {
1143 // upload the image if we have one
1144 $picture = wall_upload_post($a, false);
1145 if (is_array($picture)) {
1146 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1150 if (requestdata('media_ids')) {
1151 $ids = explode(',', requestdata('media_ids'));
1152 foreach ($ids as $id) {
1154 "SELECT `resource-id`, `scale`, `nickname`, `type`, `desc` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1158 if (DBA::isResult($r)) {
1159 $phototypes = Images::supportedTypes();
1160 $ext = $phototypes[$r[0]['type']];
1161 $description = $r[0]['desc'] ?? '';
1162 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1163 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1168 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1170 $_REQUEST['api_source'] = true;
1172 if (empty($_REQUEST['source'])) {
1173 $_REQUEST["source"] = api_source();
1176 // call out normal post function
1177 $item_id = item_post($a);
1179 // output the post that we just posted.
1180 return api_status_show($type, $item_id);
1183 /// @TODO move to top of file or somewhere better
1184 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1185 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1188 * Uploads an image to Friendica.
1191 * @throws BadRequestException
1192 * @throws ForbiddenException
1193 * @throws ImagickException
1194 * @throws InternalServerErrorException
1195 * @throws UnauthorizedException
1196 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1198 function api_media_upload()
1202 if (api_user() === false) {
1203 Logger::log('no user');
1204 throw new ForbiddenException();
1209 if (empty($_FILES['media'])) {
1211 throw new BadRequestException("No media.");
1214 $media = wall_upload_post($a, false);
1217 throw new InternalServerErrorException();
1221 $returndata["media_id"] = $media["id"];
1222 $returndata["media_id_string"] = (string)$media["id"];
1223 $returndata["size"] = $media["size"];
1224 $returndata["image"] = ["w" => $media["width"],
1225 "h" => $media["height"],
1226 "image_type" => $media["type"],
1227 "friendica_preview_url" => $media["preview"]];
1229 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1231 return ["media" => $returndata];
1234 /// @TODO move to top of file or somewhere better
1235 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1238 * Updates media meta data (picture descriptions)
1240 * @param string $type Return type (atom, rss, xml, json)
1242 * @return array|string
1243 * @throws BadRequestException
1244 * @throws ForbiddenException
1245 * @throws ImagickException
1246 * @throws InternalServerErrorException
1247 * @throws TooManyRequestsException
1248 * @throws UnauthorizedException
1249 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1251 * @todo Compare the corresponding Twitter function for correct return values
1253 function api_media_metadata_create($type)
1257 if (api_user() === false) {
1258 Logger::info('no user');
1259 throw new ForbiddenException();
1264 $postdata = Network::postdata();
1266 if (empty($postdata)) {
1267 throw new BadRequestException("No post data");
1270 $data = json_decode($postdata, true);
1272 throw new BadRequestException("Invalid post data");
1275 if (empty($data['media_id']) || empty($data['alt_text'])) {
1276 throw new BadRequestException("Missing post data values");
1279 if (empty($data['alt_text']['text'])) {
1280 throw new BadRequestException("No alt text.");
1283 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1285 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1286 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1287 if (!DBA::isResult($photo)) {
1288 throw new BadRequestException("Metadata not found.");
1291 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1294 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1297 * @param string $type Return format (atom, rss, xml, json)
1298 * @param int $item_id
1302 function api_status_show($type, $item_id)
1304 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1308 $item = api_get_item(['id' => $item_id]);
1309 if (!empty($item)) {
1310 $status_info = api_format_item($item, $type);
1313 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1315 return api_format_data('statuses', $type, ['status' => $status_info]);
1319 * Retrieves the last public status of the provided user info
1321 * @param int $ownerId Public contact Id
1322 * @param int $uid User Id
1326 function api_get_last_status($ownerId, $uid)
1329 'author-id'=> $ownerId,
1331 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1335 $item = api_get_item($condition);
1341 * Retrieves a single item record based on the provided condition and converts it for API use.
1343 * @param array $condition Item table condition array
1347 function api_get_item(array $condition)
1349 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1355 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1356 * The author's most recent status will be returned inline.
1358 * @param string $type Return type (atom, rss, xml, json)
1359 * @return array|string
1360 * @throws BadRequestException
1361 * @throws ImagickException
1362 * @throws InternalServerErrorException
1363 * @throws UnauthorizedException
1364 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1366 function api_users_show($type)
1368 $a = Friendica\DI::app();
1370 $user_info = api_get_user($a);
1372 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1373 if (!empty($item)) {
1374 $user_info['status'] = api_format_item($item, $type);
1377 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1378 unset($user_info['uid']);
1379 unset($user_info['self']);
1381 return api_format_data('user', $type, ['user' => $user_info]);
1384 /// @TODO move to top of file or somewhere better
1385 api_register_func('api/users/show', 'api_users_show');
1386 api_register_func('api/externalprofile/show', 'api_users_show');
1389 * Search a public user account.
1391 * @param string $type Return type (atom, rss, xml, json)
1393 * @return array|string
1394 * @throws BadRequestException
1395 * @throws ImagickException
1396 * @throws InternalServerErrorException
1397 * @throws UnauthorizedException
1398 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1400 function api_users_search($type)
1406 if (!empty($_GET['q'])) {
1407 $contacts = Contact::selectToArray(
1410 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1418 if (DBA::isResult($contacts)) {
1420 foreach ($contacts as $contact) {
1421 $user_info = api_get_user($a, $contact['id']);
1423 if ($type == 'xml') {
1424 $userlist[$k++ . ':user'] = $user_info;
1426 $userlist[] = $user_info;
1429 $userlist = ['users' => $userlist];
1431 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1434 throw new BadRequestException('No search term specified.');
1437 return api_format_data('users', $type, $userlist);
1440 /// @TODO move to top of file or somewhere better
1441 api_register_func('api/users/search', 'api_users_search');
1444 * Return user objects
1446 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1448 * @param string $type Return format: json or xml
1450 * @return array|string
1451 * @throws BadRequestException
1452 * @throws ImagickException
1453 * @throws InternalServerErrorException
1454 * @throws NotFoundException if the results are empty.
1455 * @throws UnauthorizedException
1457 function api_users_lookup($type)
1461 if (!empty($_REQUEST['user_id'])) {
1462 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1464 $users[] = api_get_user(DI::app(), $id);
1469 if (empty($users)) {
1470 throw new NotFoundException;
1473 return api_format_data("users", $type, ['users' => $users]);
1476 /// @TODO move to top of file or somewhere better
1477 api_register_func('api/users/lookup', 'api_users_lookup', true);
1480 * Returns statuses that match a specified query.
1482 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1484 * @param string $type Return format: json, xml, atom, rss
1486 * @return array|string
1487 * @throws BadRequestException if the "q" parameter is missing.
1488 * @throws ForbiddenException
1489 * @throws ImagickException
1490 * @throws InternalServerErrorException
1491 * @throws UnauthorizedException
1493 function api_search($type)
1496 $user_info = api_get_user($a);
1498 if (api_user() === false || $user_info === false) {
1499 throw new ForbiddenException();
1502 if (empty($_REQUEST['q'])) {
1503 throw new BadRequestException('q parameter is required.');
1506 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1509 $data['status'] = [];
1511 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1512 if (!empty($_REQUEST['rpp'])) {
1513 $count = $_REQUEST['rpp'];
1514 } elseif (!empty($_REQUEST['count'])) {
1515 $count = $_REQUEST['count'];
1518 $since_id = $_REQUEST['since_id'] ?? 0;
1519 $max_id = $_REQUEST['max_id'] ?? 0;
1520 $page = $_REQUEST['page'] ?? 1;
1522 $start = max(0, ($page - 1) * $count);
1524 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1525 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1526 $searchTerm = $matches[1];
1527 $condition = ["`oid` > ?
1528 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1529 AND `otype` = ? AND `type` = ? AND `term` = ?",
1530 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1532 $condition[0] .= ' AND `oid` <= ?';
1533 $condition[] = $max_id;
1535 $terms = DBA::select('term', ['oid'], $condition, []);
1537 while ($term = DBA::fetch($terms)) {
1538 $itemIds[] = $term['oid'];
1542 if (empty($itemIds)) {
1543 return api_format_data('statuses', $type, $data);
1546 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1547 if ($exclude_replies) {
1548 $preCondition[] = '`id` = `parent`';
1551 $condition = [implode(' AND ', $preCondition)];
1553 $condition = ["`id` > ?
1554 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1555 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1556 AND `body` LIKE CONCAT('%',?,'%')",
1557 $since_id, api_user(), $_REQUEST['q']];
1559 $condition[0] .= ' AND `id` <= ?';
1560 $condition[] = $max_id;
1566 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1567 $id = Item::fetchByLink($searchTerm, api_user());
1570 $id = Item::fetchByLink($searchTerm);
1574 $statuses = Item::select([], ['id' => $id]);
1578 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1580 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1582 bindComments($data['status']);
1584 return api_format_data('statuses', $type, $data);
1587 /// @TODO move to top of file or somewhere better
1588 api_register_func('api/search/tweets', 'api_search', true);
1589 api_register_func('api/search', 'api_search', true);
1592 * Returns the most recent statuses posted by the user and the users they follow.
1594 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1596 * @param string $type Return type (atom, rss, xml, json)
1598 * @return array|string
1599 * @throws BadRequestException
1600 * @throws ForbiddenException
1601 * @throws ImagickException
1602 * @throws InternalServerErrorException
1603 * @throws UnauthorizedException
1604 * @todo Optional parameters
1605 * @todo Add reply info
1607 function api_statuses_home_timeline($type)
1610 $user_info = api_get_user($a);
1612 if (api_user() === false || $user_info === false) {
1613 throw new ForbiddenException();
1616 unset($_REQUEST["user_id"]);
1617 unset($_GET["user_id"]);
1619 unset($_REQUEST["screen_name"]);
1620 unset($_GET["screen_name"]);
1622 // get last network messages
1625 $count = $_REQUEST['count'] ?? 20;
1626 $page = $_REQUEST['page']?? 0;
1627 $since_id = $_REQUEST['since_id'] ?? 0;
1628 $max_id = $_REQUEST['max_id'] ?? 0;
1629 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1630 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1632 $start = max(0, ($page - 1) * $count);
1634 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1635 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1638 $condition[0] .= " AND `item`.`id` <= ?";
1639 $condition[] = $max_id;
1641 if ($exclude_replies) {
1642 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1644 if ($conversation_id > 0) {
1645 $condition[0] .= " AND `item`.`parent` = ?";
1646 $condition[] = $conversation_id;
1649 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1650 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1652 $items = Item::inArray($statuses);
1654 $ret = api_format_items($items, $user_info, false, $type);
1656 // Set all posts from the query above to seen
1658 foreach ($items as $item) {
1659 $idarray[] = intval($item["id"]);
1662 if (!empty($idarray)) {
1663 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1665 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1671 $data = ['status' => $ret];
1676 $data = api_rss_extra($a, $data, $user_info);
1680 return api_format_data("statuses", $type, $data);
1684 /// @TODO move to top of file or somewhere better
1685 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1686 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1689 * Returns the most recent statuses from public users.
1691 * @param string $type Return type (atom, rss, xml, json)
1693 * @return array|string
1694 * @throws BadRequestException
1695 * @throws ForbiddenException
1696 * @throws ImagickException
1697 * @throws InternalServerErrorException
1698 * @throws UnauthorizedException
1700 function api_statuses_public_timeline($type)
1703 $user_info = api_get_user($a);
1705 if (api_user() === false || $user_info === false) {
1706 throw new ForbiddenException();
1709 // get last network messages
1712 $count = $_REQUEST['count'] ?? 20;
1713 $page = $_REQUEST['page'] ?? 1;
1714 $since_id = $_REQUEST['since_id'] ?? 0;
1715 $max_id = $_REQUEST['max_id'] ?? 0;
1716 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1717 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1719 $start = max(0, ($page - 1) * $count);
1721 if ($exclude_replies && !$conversation_id) {
1722 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1723 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1726 $condition[0] .= " AND `thread`.`iid` <= ?";
1727 $condition[] = $max_id;
1730 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1731 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1733 $r = Item::inArray($statuses);
1735 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1736 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1739 $condition[0] .= " AND `item`.`id` <= ?";
1740 $condition[] = $max_id;
1742 if ($conversation_id > 0) {
1743 $condition[0] .= " AND `item`.`parent` = ?";
1744 $condition[] = $conversation_id;
1747 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1748 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1750 $r = Item::inArray($statuses);
1753 $ret = api_format_items($r, $user_info, false, $type);
1757 $data = ['status' => $ret];
1762 $data = api_rss_extra($a, $data, $user_info);
1766 return api_format_data("statuses", $type, $data);
1769 /// @TODO move to top of file or somewhere better
1770 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1773 * Returns the most recent statuses posted by users this node knows about.
1775 * @param string $type Return format: json, xml, atom, rss
1776 * @return array|string
1777 * @throws BadRequestException
1778 * @throws ForbiddenException
1779 * @throws ImagickException
1780 * @throws InternalServerErrorException
1781 * @throws UnauthorizedException
1783 function api_statuses_networkpublic_timeline($type)
1786 $user_info = api_get_user($a);
1788 if (api_user() === false || $user_info === false) {
1789 throw new ForbiddenException();
1792 $since_id = $_REQUEST['since_id'] ?? 0;
1793 $max_id = $_REQUEST['max_id'] ?? 0;
1796 $count = $_REQUEST['count'] ?? 20;
1797 $page = $_REQUEST['page'] ?? 1;
1799 $start = max(0, ($page - 1) * $count);
1801 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1802 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1805 $condition[0] .= " AND `thread`.`iid` <= ?";
1806 $condition[] = $max_id;
1809 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1810 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1812 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1816 $data = ['status' => $ret];
1821 $data = api_rss_extra($a, $data, $user_info);
1825 return api_format_data("statuses", $type, $data);
1828 /// @TODO move to top of file or somewhere better
1829 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1832 * Returns a single status.
1834 * @param string $type Return type (atom, rss, xml, json)
1836 * @return array|string
1837 * @throws BadRequestException
1838 * @throws ForbiddenException
1839 * @throws ImagickException
1840 * @throws InternalServerErrorException
1841 * @throws UnauthorizedException
1842 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1844 function api_statuses_show($type)
1847 $user_info = api_get_user($a);
1849 if (api_user() === false || $user_info === false) {
1850 throw new ForbiddenException();
1854 $id = intval($a->argv[3] ?? 0);
1857 $id = intval($_REQUEST['id'] ?? 0);
1862 $id = intval($a->argv[4] ?? 0);
1865 Logger::log('API: api_statuses_show: ' . $id);
1867 $conversation = !empty($_REQUEST['conversation']);
1869 // try to fetch the item for the local user - or the public item, if there is no local one
1870 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1871 if (!DBA::isResult($uri_item)) {
1872 throw new BadRequestException("There is no status with this id.");
1875 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1876 if (!DBA::isResult($item)) {
1877 throw new BadRequestException("There is no status with this id.");
1882 if ($conversation) {
1883 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1884 $params = ['order' => ['id' => true]];
1886 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1890 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1892 /// @TODO How about copying this to above methods which don't check $r ?
1893 if (!DBA::isResult($statuses)) {
1894 throw new BadRequestException("There is no status with this id.");
1897 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1899 if ($conversation) {
1900 $data = ['status' => $ret];
1901 return api_format_data("statuses", $type, $data);
1903 $data = ['status' => $ret[0]];
1904 return api_format_data("status", $type, $data);
1908 /// @TODO move to top of file or somewhere better
1909 api_register_func('api/statuses/show', 'api_statuses_show', true);
1913 * @param string $type Return type (atom, rss, xml, json)
1915 * @return array|string
1916 * @throws BadRequestException
1917 * @throws ForbiddenException
1918 * @throws ImagickException
1919 * @throws InternalServerErrorException
1920 * @throws UnauthorizedException
1921 * @todo nothing to say?
1923 function api_conversation_show($type)
1926 $user_info = api_get_user($a);
1928 if (api_user() === false || $user_info === false) {
1929 throw new ForbiddenException();
1933 $id = intval($a->argv[3] ?? 0);
1934 $since_id = intval($_REQUEST['since_id'] ?? 0);
1935 $max_id = intval($_REQUEST['max_id'] ?? 0);
1936 $count = intval($_REQUEST['count'] ?? 20);
1937 $page = intval($_REQUEST['page'] ?? 1);
1939 $start = max(0, ($page - 1) * $count);
1942 $id = intval($_REQUEST['id'] ?? 0);
1947 $id = intval($a->argv[4] ?? 0);
1950 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1952 // try to fetch the item for the local user - or the public item, if there is no local one
1953 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1954 if (!DBA::isResult($item)) {
1955 throw new BadRequestException("There is no status with this id.");
1958 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1959 if (!DBA::isResult($parent)) {
1960 throw new BadRequestException("There is no status with this id.");
1963 $id = $parent['id'];
1965 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1966 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1969 $condition[0] .= " AND `item`.`id` <= ?";
1970 $condition[] = $max_id;
1973 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1974 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1976 if (!DBA::isResult($statuses)) {
1977 throw new BadRequestException("There is no status with id $id.");
1980 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1982 $data = ['status' => $ret];
1983 return api_format_data("statuses", $type, $data);
1986 /// @TODO move to top of file or somewhere better
1987 api_register_func('api/conversation/show', 'api_conversation_show', true);
1988 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1993 * @param string $type Return type (atom, rss, xml, json)
1995 * @return array|string
1996 * @throws BadRequestException
1997 * @throws ForbiddenException
1998 * @throws ImagickException
1999 * @throws InternalServerErrorException
2000 * @throws UnauthorizedException
2001 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2003 function api_statuses_repeat($type)
2009 if (api_user() === false) {
2010 throw new ForbiddenException();
2016 $id = intval($a->argv[3] ?? 0);
2019 $id = intval($_REQUEST['id'] ?? 0);
2024 $id = intval($a->argv[4] ?? 0);
2027 Logger::log('API: api_statuses_repeat: '.$id);
2029 $fields = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2030 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2032 if (DBA::isResult($item) && $item['body'] != "") {
2033 if (strpos($item['body'], "[/share]") !== false) {
2034 $pos = strpos($item['body'], "[share");
2035 $post = substr($item['body'], $pos);
2037 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2039 if (!empty($item['title'])) {
2040 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2043 $post .= $item['body'];
2044 $post .= "[/share]";
2046 $_REQUEST['body'] = $post;
2047 $_REQUEST['tag'] = $item['tag'];
2048 $_REQUEST['attach'] = $item['attach'];
2049 $_REQUEST['profile_uid'] = api_user();
2050 $_REQUEST['api_source'] = true;
2052 if (empty($_REQUEST['source'])) {
2053 $_REQUEST["source"] = api_source();
2056 $item_id = item_post($a);
2058 throw new ForbiddenException();
2061 // output the post that we just posted.
2063 return api_status_show($type, $item_id);
2066 /// @TODO move to top of file or somewhere better
2067 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2070 * Destroys a specific status.
2072 * @param string $type Return type (atom, rss, xml, json)
2074 * @return array|string
2075 * @throws BadRequestException
2076 * @throws ForbiddenException
2077 * @throws ImagickException
2078 * @throws InternalServerErrorException
2079 * @throws UnauthorizedException
2080 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2082 function api_statuses_destroy($type)
2086 if (api_user() === false) {
2087 throw new ForbiddenException();
2093 $id = intval($a->argv[3] ?? 0);
2096 $id = intval($_REQUEST['id'] ?? 0);
2101 $id = intval($a->argv[4] ?? 0);
2104 Logger::log('API: api_statuses_destroy: '.$id);
2106 $ret = api_statuses_show($type);
2108 Item::deleteForUser(['id' => $id], api_user());
2113 /// @TODO move to top of file or somewhere better
2114 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2117 * Returns the most recent mentions.
2119 * @param string $type Return type (atom, rss, xml, json)
2121 * @return array|string
2122 * @throws BadRequestException
2123 * @throws ForbiddenException
2124 * @throws ImagickException
2125 * @throws InternalServerErrorException
2126 * @throws UnauthorizedException
2127 * @see http://developer.twitter.com/doc/get/statuses/mentions
2129 function api_statuses_mentions($type)
2132 $user_info = api_get_user($a);
2134 if (api_user() === false || $user_info === false) {
2135 throw new ForbiddenException();
2138 unset($_REQUEST["user_id"]);
2139 unset($_GET["user_id"]);
2141 unset($_REQUEST["screen_name"]);
2142 unset($_GET["screen_name"]);
2144 // get last network messages
2147 $since_id = $_REQUEST['since_id'] ?? 0;
2148 $max_id = $_REQUEST['max_id'] ?? 0;
2149 $count = $_REQUEST['count'] ?? 20;
2150 $page = $_REQUEST['page'] ?? 1;
2152 $start = max(0, ($page - 1) * $count);
2154 $query = "SELECT `item`.`id` FROM `user-item`
2155 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2156 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2157 `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2158 AND `user-item`.`iid` > ?";
2159 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2160 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2161 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
2162 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2166 $query .= " AND `item`.`id` <= ?";
2167 $condition[] = $max_id;
2170 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2171 $condition[] = $start;
2172 $condition[] = $count;
2174 $useritems = DBA::p($query, $condition);
2176 while ($useritem = DBA::fetch($useritems)) {
2177 $itemids[] = $useritem['id'];
2179 DBA::close($useritems);
2181 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2182 $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2184 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2186 $data = ['status' => $ret];
2191 $data = api_rss_extra($a, $data, $user_info);
2195 return api_format_data("statuses", $type, $data);
2198 /// @TODO move to top of file or somewhere better
2199 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2200 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2203 * Returns the most recent statuses posted by the user.
2205 * @param string $type Either "json" or "xml"
2206 * @return string|array
2207 * @throws BadRequestException
2208 * @throws ForbiddenException
2209 * @throws ImagickException
2210 * @throws InternalServerErrorException
2211 * @throws UnauthorizedException
2212 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2214 function api_statuses_user_timeline($type)
2217 $user_info = api_get_user($a);
2219 if (api_user() === false || $user_info === false) {
2220 throw new ForbiddenException();
2224 "api_statuses_user_timeline: api_user: ". api_user() .
2225 "\nuser_info: ".print_r($user_info, true) .
2226 "\n_REQUEST: ".print_r($_REQUEST, true),
2230 $since_id = $_REQUEST['since_id'] ?? 0;
2231 $max_id = $_REQUEST['max_id'] ?? 0;
2232 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2233 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2236 $count = $_REQUEST['count'] ?? 20;
2237 $page = $_REQUEST['page'] ?? 1;
2239 $start = max(0, ($page - 1) * $count);
2241 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2242 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2244 if ($user_info['self'] == 1) {
2245 $condition[0] .= ' AND `item`.`wall` ';
2248 if ($exclude_replies) {
2249 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2252 if ($conversation_id > 0) {
2253 $condition[0] .= " AND `item`.`parent` = ?";
2254 $condition[] = $conversation_id;
2258 $condition[0] .= " AND `item`.`id` <= ?";
2259 $condition[] = $max_id;
2262 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2263 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2265 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2269 $data = ['status' => $ret];
2274 $data = api_rss_extra($a, $data, $user_info);
2278 return api_format_data("statuses", $type, $data);
2281 /// @TODO move to top of file or somewhere better
2282 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2285 * Star/unstar an item.
2286 * param: id : id of the item
2288 * @param string $type Return type (atom, rss, xml, json)
2290 * @return array|string
2291 * @throws BadRequestException
2292 * @throws ForbiddenException
2293 * @throws ImagickException
2294 * @throws InternalServerErrorException
2295 * @throws UnauthorizedException
2296 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2298 function api_favorites_create_destroy($type)
2302 if (api_user() === false) {
2303 throw new ForbiddenException();
2306 // for versioned api.
2307 /// @TODO We need a better global soluton
2308 $action_argv_id = 2;
2309 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2310 $action_argv_id = 3;
2313 if ($a->argc <= $action_argv_id) {
2314 throw new BadRequestException("Invalid request.");
2316 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2317 if ($a->argc == $action_argv_id + 2) {
2318 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2320 $itemid = intval($_REQUEST['id'] ?? 0);
2323 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2325 if (!DBA::isResult($item)) {
2326 throw new BadRequestException("Invalid item.");
2331 $item['starred'] = 1;
2334 $item['starred'] = 0;
2337 throw new BadRequestException("Invalid action ".$action);
2340 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2343 throw new InternalServerErrorException("DB error");
2347 $user_info = api_get_user($a);
2348 $rets = api_format_items([$item], $user_info, false, $type);
2351 $data = ['status' => $ret];
2356 $data = api_rss_extra($a, $data, $user_info);
2360 return api_format_data("status", $type, $data);
2363 /// @TODO move to top of file or somewhere better
2364 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2365 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2368 * Returns the most recent favorite statuses.
2370 * @param string $type Return type (atom, rss, xml, json)
2372 * @return string|array
2373 * @throws BadRequestException
2374 * @throws ForbiddenException
2375 * @throws ImagickException
2376 * @throws InternalServerErrorException
2377 * @throws UnauthorizedException
2379 function api_favorites($type)
2384 $user_info = api_get_user($a);
2386 if (api_user() === false || $user_info === false) {
2387 throw new ForbiddenException();
2392 // in friendica starred item are private
2393 // return favorites only for self
2394 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2396 if ($user_info['self'] == 0) {
2400 $since_id = $_REQUEST['since_id'] ?? 0;
2401 $max_id = $_REQUEST['max_id'] ?? 0;
2402 $count = $_GET['count'] ?? 20;
2403 $page = $_REQUEST['page'] ?? 1;
2405 $start = max(0, ($page - 1) * $count);
2407 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2408 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2410 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2413 $condition[0] .= " AND `item`.`id` <= ?";
2414 $condition[] = $max_id;
2417 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2419 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2424 $data = ['status' => $ret];
2429 $data = api_rss_extra($a, $data, $user_info);
2433 return api_format_data("statuses", $type, $data);
2436 /// @TODO move to top of file or somewhere better
2437 api_register_func('api/favorites', 'api_favorites', true);
2441 * @param array $item
2442 * @param array $recipient
2443 * @param array $sender
2446 * @throws InternalServerErrorException
2448 function api_format_messages($item, $recipient, $sender)
2450 // standard meta information
2452 'id' => $item['id'],
2453 'sender_id' => $sender['id'],
2455 'recipient_id' => $recipient['id'],
2456 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2457 'sender_screen_name' => $sender['screen_name'],
2458 'recipient_screen_name' => $recipient['screen_name'],
2459 'sender' => $sender,
2460 'recipient' => $recipient,
2462 'friendica_seen' => $item['seen'] ?? 0,
2463 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2466 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2467 if (isset($ret['sender']['uid'])) {
2468 unset($ret['sender']['uid']);
2470 if (isset($ret['sender']['self'])) {
2471 unset($ret['sender']['self']);
2473 if (isset($ret['recipient']['uid'])) {
2474 unset($ret['recipient']['uid']);
2476 if (isset($ret['recipient']['self'])) {
2477 unset($ret['recipient']['self']);
2480 //don't send title to regular StatusNET requests to avoid confusing these apps
2481 if (!empty($_GET['getText'])) {
2482 $ret['title'] = $item['title'];
2483 if ($_GET['getText'] == 'html') {
2484 $ret['text'] = BBCode::convert($item['body'], false);
2485 } elseif ($_GET['getText'] == 'plain') {
2486 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2489 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2491 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2492 unset($ret['sender']);
2493 unset($ret['recipient']);
2501 * @param array $item
2504 * @throws InternalServerErrorException
2506 function api_convert_item($item)
2508 $body = $item['body'];
2509 $entities = api_get_entitities($statustext, $body);
2511 // Add pictures to the attachment array and remove them from the body
2512 $attachments = api_get_attachments($body);
2514 // Workaround for ostatus messages where the title is identically to the body
2515 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2516 $statusbody = trim(HTML::toPlaintext($html, 0));
2518 // handle data: images
2519 $statusbody = api_format_items_embeded_images($item, $statusbody);
2521 $statustitle = trim($item['title']);
2523 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2524 $statustext = trim($statusbody);
2526 $statustext = trim($statustitle."\n\n".$statusbody);
2529 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2530 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2533 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2535 // Workaround for clients with limited HTML parser functionality
2536 $search = ["<br>", "<blockquote>", "</blockquote>",
2537 "<h1>", "</h1>", "<h2>", "</h2>",
2538 "<h3>", "</h3>", "<h4>", "</h4>",
2539 "<h5>", "</h5>", "<h6>", "</h6>"];
2540 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2541 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2542 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2543 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2544 $statushtml = str_replace($search, $replace, $statushtml);
2546 if ($item['title'] != "") {
2547 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2551 $oldtext = $statushtml;
2552 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2553 } while ($oldtext != $statushtml);
2555 if (substr($statushtml, 0, 4) == '<br>') {
2556 $statushtml = substr($statushtml, 4);
2559 if (substr($statushtml, 0, -4) == '<br>') {
2560 $statushtml = substr($statushtml, -4);
2563 // feeds without body should contain the link
2564 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2565 $statushtml .= BBCode::convert($item['plink']);
2569 "text" => $statustext,
2570 "html" => $statushtml,
2571 "attachments" => $attachments,
2572 "entities" => $entities
2578 * @param string $body
2581 * @throws InternalServerErrorException
2583 function api_get_attachments(&$body)
2585 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2586 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2588 $URLSearchString = "^\[\]";
2589 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2593 // Remove all embedded pictures, since they are added as attachments
2594 foreach ($images[0] as $orig) {
2595 $body = str_replace($orig, '', $body);
2600 foreach ($images[1] as $image) {
2601 $imagedata = Images::getInfoFromURLCached($image);
2604 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2608 return $attachments;
2613 * @param string $text
2614 * @param string $bbcode
2617 * @throws InternalServerErrorException
2618 * @todo Links at the first character of the post
2620 function api_get_entitities(&$text, $bbcode)
2622 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2624 if ($include_entities != "true") {
2625 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2627 foreach ($images[1] as $image) {
2628 $replace = ProxyUtils::proxifyUrl($image);
2629 $text = str_replace($image, $replace, $text);
2634 $bbcode = BBCode::cleanPictureLinks($bbcode);
2636 // Change pure links in text to bbcode uris
2637 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2640 $entities["hashtags"] = [];
2641 $entities["symbols"] = [];
2642 $entities["urls"] = [];
2643 $entities["user_mentions"] = [];
2645 $URLSearchString = "^\[\]";
2647 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2649 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2650 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2652 $bbcode = preg_replace(
2653 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2654 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2657 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2659 $bbcode = preg_replace(
2660 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2661 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2664 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2666 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2668 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2671 foreach ($urls[1] as $id => $url) {
2672 $start = iconv_strpos($text, $url, 0, "UTF-8");
2673 if (!($start === false)) {
2674 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2678 ksort($ordered_urls);
2682 foreach ($ordered_urls as $url) {
2683 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2684 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2686 $display_url = $url["title"];
2688 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2689 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2691 if (strlen($display_url) > 26) {
2692 $display_url = substr($display_url, 0, 25)."…";
2696 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2697 if (!($start === false)) {
2698 $entities["urls"][] = ["url" => $url["url"],
2699 "expanded_url" => $url["url"],
2700 "display_url" => $display_url,
2701 "indices" => [$start, $start+strlen($url["url"])]];
2702 $offset = $start + 1;
2706 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2707 $ordered_images = [];
2708 foreach ($images as $image) {
2709 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2710 if (!($start === false)) {
2711 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2715 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2716 foreach ($images[1] as $image) {
2717 $start = iconv_strpos($text, $image, 0, "UTF-8");
2718 if (!($start === false)) {
2719 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2725 foreach ($ordered_images as $image) {
2726 $url = $image['url'];
2727 $ext_alt_text = $image['alt'];
2729 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2730 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2732 if (strlen($display_url) > 26) {
2733 $display_url = substr($display_url, 0, 25)."…";
2736 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2737 if (!($start === false)) {
2738 $image = Images::getInfoFromURLCached($url);
2740 // If image cache is activated, then use the following sizes:
2741 // thumb (150), small (340), medium (600) and large (1024)
2742 if (!DI::config()->get("system", "proxy_disabled")) {
2743 $media_url = ProxyUtils::proxifyUrl($url);
2746 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2747 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2749 if (($image[0] > 150) || ($image[1] > 150)) {
2750 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2751 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2754 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2755 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2757 if (($image[0] > 600) || ($image[1] > 600)) {
2758 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2759 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2763 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2766 $entities["media"][] = [
2768 "id_str" => (string) ($start + 1),
2769 "indices" => [$start, $start+strlen($url)],
2770 "media_url" => Strings::normaliseLink($media_url),
2771 "media_url_https" => $media_url,
2773 "display_url" => $display_url,
2774 "expanded_url" => $url,
2775 "ext_alt_text" => $ext_alt_text,
2779 $offset = $start + 1;
2788 * @param array $item
2789 * @param string $text
2793 function api_format_items_embeded_images($item, $text)
2795 $text = preg_replace_callback(
2796 '|data:image/([^;]+)[^=]+=*|m',
2797 function () use ($item) {
2798 return DI::baseUrl() . '/display/' . $item['guid'];
2806 * return <a href='url'>name</a> as array
2808 * @param string $txt text
2813 function api_contactlink_to_array($txt)
2816 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2817 if ($r && count($match)==3) {
2819 'name' => $match[2],
2833 * return likes, dislikes and attend status for item
2835 * @param array $item array
2836 * @param string $type Return type (atom, rss, xml, json)
2839 * likes => int count,
2840 * dislikes => int count
2841 * @throws BadRequestException
2842 * @throws ImagickException
2843 * @throws InternalServerErrorException
2844 * @throws UnauthorizedException
2846 function api_format_items_activities($item, $type = "json")
2855 'attendmaybe' => [],
2859 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2860 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2862 while ($parent_item = Item::fetch($ret)) {
2863 // not used as result should be structured like other user data
2864 //builtin_activity_puller($i, $activities);
2866 // get user data and add it to the array of the activity
2867 $user = api_get_user($a, $parent_item['author-id']);
2868 switch ($parent_item['verb']) {
2869 case Activity::LIKE:
2870 $activities['like'][] = $user;
2872 case Activity::DISLIKE:
2873 $activities['dislike'][] = $user;
2875 case Activity::ATTEND:
2876 $activities['attendyes'][] = $user;
2878 case Activity::ATTENDNO:
2879 $activities['attendno'][] = $user;
2881 case Activity::ATTENDMAYBE:
2882 $activities['attendmaybe'][] = $user;
2884 case Activity::ANNOUNCE:
2885 $activities['announce'][] = $user;
2894 if ($type == "xml") {
2895 $xml_activities = [];
2896 foreach ($activities as $k => $v) {
2897 // change xml element from "like" to "friendica:like"
2898 $xml_activities["friendica:".$k] = $v;
2899 // add user data into xml output
2901 foreach ($v as $user) {
2902 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2905 $activities = $xml_activities;
2913 * return data from profiles
2915 * @param array $profile_row array containing data from db table 'profile'
2917 * @throws InternalServerErrorException
2919 function api_format_items_profiles($profile_row)
2922 'profile_id' => $profile_row['id'],
2923 'profile_name' => $profile_row['profile-name'],
2924 'is_default' => $profile_row['is-default'] ? true : false,
2925 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2926 'profile_photo' => $profile_row['photo'],
2927 'profile_thumb' => $profile_row['thumb'],
2928 'publish' => $profile_row['publish'] ? true : false,
2929 'net_publish' => $profile_row['net-publish'] ? true : false,
2930 'description' => $profile_row['pdesc'],
2931 'date_of_birth' => $profile_row['dob'],
2932 'address' => $profile_row['address'],
2933 'city' => $profile_row['locality'],
2934 'region' => $profile_row['region'],
2935 'postal_code' => $profile_row['postal-code'],
2936 'country' => $profile_row['country-name'],
2937 'hometown' => $profile_row['hometown'],
2938 'gender' => $profile_row['gender'],
2939 'marital' => $profile_row['marital'],
2940 'marital_with' => $profile_row['with'],
2941 'marital_since' => $profile_row['howlong'],
2942 'sexual' => $profile_row['sexual'],
2943 'politic' => $profile_row['politic'],
2944 'religion' => $profile_row['religion'],
2945 'public_keywords' => $profile_row['pub_keywords'],
2946 'private_keywords' => $profile_row['prv_keywords'],
2947 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2948 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2949 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2950 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2951 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2952 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2953 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2954 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2955 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2956 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2957 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2958 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2959 'homepage' => $profile_row['homepage'],
2966 * format items to be returned by api
2968 * @param array $items array of items
2969 * @param array $user_info
2970 * @param bool $filter_user filter items by $user_info
2971 * @param string $type Return type (atom, rss, xml, json)
2973 * @throws BadRequestException
2974 * @throws ImagickException
2975 * @throws InternalServerErrorException
2976 * @throws UnauthorizedException
2978 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2980 $a = Friendica\DI::app();
2984 foreach ((array)$items as $item) {
2985 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2987 // Look if the posts are matching if they should be filtered by user id
2988 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2992 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
3001 * @param array $item Item record
3002 * @param string $type Return format (atom, rss, xml, json)
3003 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3004 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3005 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3006 * @return array API-formatted status
3007 * @throws BadRequestException
3008 * @throws ImagickException
3009 * @throws InternalServerErrorException
3010 * @throws UnauthorizedException
3012 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3014 $a = Friendica\DI::app();
3016 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3017 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3020 localize_item($item);
3022 $in_reply_to = api_in_reply_to($item);
3024 $converted = api_convert_item($item);
3026 if ($type == "xml") {
3027 $geo = "georss:point";
3033 'text' => $converted["text"],
3034 'truncated' => false,
3035 'created_at'=> api_date($item['created']),
3036 'in_reply_to_status_id' => $in_reply_to['status_id'],
3037 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3038 'source' => (($item['app']) ? $item['app'] : 'web'),
3039 'id' => intval($item['id']),
3040 'id_str' => (string) intval($item['id']),
3041 'in_reply_to_user_id' => $in_reply_to['user_id'],
3042 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3043 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3045 'favorited' => $item['starred'] ? true : false,
3046 'user' => $status_user,
3047 'friendica_author' => $author_user,
3048 'friendica_owner' => $owner_user,
3049 'friendica_private' => $item['private'] == 1,
3050 //'entities' => NULL,
3051 'statusnet_html' => $converted["html"],
3052 'statusnet_conversation_id' => $item['parent'],
3053 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3054 'friendica_activities' => api_format_items_activities($item, $type),
3055 'friendica_title' => $item['title'],
3056 'friendica_html' => BBCode::convert($item['body'], false)
3059 if (count($converted["attachments"]) > 0) {
3060 $status["attachments"] = $converted["attachments"];
3063 if (count($converted["entities"]) > 0) {
3064 $status["entities"] = $converted["entities"];
3067 if ($status["source"] == 'web') {
3068 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3069 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3070 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3073 $retweeted_item = [];
3076 if ($item["id"] == $item["parent"]) {
3077 $body = $item['body'];
3078 $retweeted_item = api_share_as_retweet($item);
3079 if ($body != $item['body']) {
3080 $quoted_item = $retweeted_item;
3081 $retweeted_item = [];
3085 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3086 $announce = api_get_announce($item);
3087 if (!empty($announce)) {
3088 $retweeted_item = $item;
3090 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3094 if (!empty($quoted_item)) {
3095 if ($quoted_item['id'] != $item['id']) {
3096 $quoted_status = api_format_item($quoted_item);
3097 /// @todo Only remove the attachments that are also contained in the quotes status
3098 unset($status['attachments']);
3099 unset($status['entities']);
3101 $conv_quoted = api_convert_item($quoted_item);
3102 $quoted_status = $status;
3103 unset($quoted_status['attachments']);
3104 unset($quoted_status['entities']);
3105 unset($quoted_status['statusnet_conversation_id']);
3106 $quoted_status['text'] = $conv_quoted['text'];
3107 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3109 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3110 } catch (BadRequestException $e) {
3111 // user not found. should be found?
3112 /// @todo check if the user should be always found
3113 $quoted_status["user"] = [];
3116 unset($quoted_status['friendica_author']);
3117 unset($quoted_status['friendica_owner']);
3118 unset($quoted_status['friendica_activities']);
3119 unset($quoted_status['friendica_private']);
3122 if (!empty($retweeted_item)) {
3123 $retweeted_status = $status;
3124 unset($retweeted_status['friendica_author']);
3125 unset($retweeted_status['friendica_owner']);
3126 unset($retweeted_status['friendica_activities']);
3127 unset($retweeted_status['friendica_private']);
3128 unset($retweeted_status['statusnet_conversation_id']);
3129 $status['user'] = $status['friendica_owner'];
3131 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3132 } catch (BadRequestException $e) {
3133 // user not found. should be found?
3134 /// @todo check if the user should be always found
3135 $retweeted_status["user"] = [];
3138 $rt_converted = api_convert_item($retweeted_item);
3140 $retweeted_status['text'] = $rt_converted["text"];
3141 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3142 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3144 if (!empty($quoted_status)) {
3145 $retweeted_status['quoted_status'] = $quoted_status;
3148 $status['friendica_author'] = $retweeted_status['user'];
3149 $status['retweeted_status'] = $retweeted_status;
3150 } elseif (!empty($quoted_status)) {
3151 $root_status = api_convert_item($item);
3153 $status['text'] = $root_status["text"];
3154 $status['statusnet_html'] = $root_status["html"];
3155 $status['quoted_status'] = $quoted_status;
3158 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3159 unset($status["user"]["uid"]);
3160 unset($status["user"]["self"]);
3162 if ($item["coord"] != "") {
3163 $coords = explode(' ', $item["coord"]);
3164 if (count($coords) == 2) {
3165 if ($type == "json") {
3166 $status["geo"] = ['type' => 'Point',
3167 'coordinates' => [(float) $coords[0],
3168 (float) $coords[1]]];
3169 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3170 $status["georss:point"] = $item["coord"];
3179 * Returns the remaining number of API requests available to the user before the API limit is reached.
3181 * @param string $type Return type (atom, rss, xml, json)
3183 * @return array|string
3186 function api_account_rate_limit_status($type)
3188 if ($type == "xml") {
3190 'remaining-hits' => '150',
3191 '@attributes' => ["type" => "integer"],
3192 'hourly-limit' => '150',
3193 '@attributes2' => ["type" => "integer"],
3194 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3195 '@attributes3' => ["type" => "datetime"],
3196 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3197 '@attributes4' => ["type" => "integer"],
3201 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3202 'remaining_hits' => '150',
3203 'hourly_limit' => '150',
3204 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3208 return api_format_data('hash', $type, ['hash' => $hash]);
3211 /// @TODO move to top of file or somewhere better
3212 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3215 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3217 * @param string $type Return type (atom, rss, xml, json)
3219 * @return array|string
3221 function api_help_test($type)
3223 if ($type == 'xml') {
3229 return api_format_data('ok', $type, ["ok" => $ok]);
3232 /// @TODO move to top of file or somewhere better
3233 api_register_func('api/help/test', 'api_help_test', false);
3236 * Returns all lists the user subscribes to.
3238 * @param string $type Return type (atom, rss, xml, json)
3240 * @return array|string
3241 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3243 function api_lists_list($type)
3246 /// @TODO $ret is not filled here?
3247 return api_format_data('lists', $type, ["lists_list" => $ret]);
3250 /// @TODO move to top of file or somewhere better
3251 api_register_func('api/lists/list', 'api_lists_list', true);
3252 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3255 * Returns all groups the user owns.
3257 * @param string $type Return type (atom, rss, xml, json)
3259 * @return array|string
3260 * @throws BadRequestException
3261 * @throws ForbiddenException
3262 * @throws ImagickException
3263 * @throws InternalServerErrorException
3264 * @throws UnauthorizedException
3265 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3267 function api_lists_ownerships($type)
3271 if (api_user() === false) {
3272 throw new ForbiddenException();
3276 $user_info = api_get_user($a);
3277 $uid = $user_info['uid'];
3279 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3281 // loop through all groups
3283 foreach ($groups as $group) {
3284 if ($group['visible']) {
3290 'name' => $group['name'],
3291 'id' => intval($group['id']),
3292 'id_str' => (string) $group['id'],
3293 'user' => $user_info,
3297 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3300 /// @TODO move to top of file or somewhere better
3301 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3304 * Returns recent statuses from users in the specified group.
3306 * @param string $type Return type (atom, rss, xml, json)
3308 * @return array|string
3309 * @throws BadRequestException
3310 * @throws ForbiddenException
3311 * @throws ImagickException
3312 * @throws InternalServerErrorException
3313 * @throws UnauthorizedException
3314 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3316 function api_lists_statuses($type)
3320 $user_info = api_get_user($a);
3321 if (api_user() === false || $user_info === false) {
3322 throw new ForbiddenException();
3325 unset($_REQUEST["user_id"]);
3326 unset($_GET["user_id"]);
3328 unset($_REQUEST["screen_name"]);
3329 unset($_GET["screen_name"]);
3331 if (empty($_REQUEST['list_id'])) {
3332 throw new BadRequestException('list_id not specified');
3336 $count = $_REQUEST['count'] ?? 20;
3337 $page = $_REQUEST['page'] ?? 1;
3338 $since_id = $_REQUEST['since_id'] ?? 0;
3339 $max_id = $_REQUEST['max_id'] ?? 0;
3340 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3341 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3343 $start = max(0, ($page - 1) * $count);
3345 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3346 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3349 $condition[0] .= " AND `item`.`id` <= ?";
3350 $condition[] = $max_id;
3352 if ($exclude_replies > 0) {
3353 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3355 if ($conversation_id > 0) {
3356 $condition[0] .= " AND `item`.`parent` = ?";
3357 $condition[] = $conversation_id;
3360 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3361 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3363 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3365 $data = ['status' => $items];
3370 $data = api_rss_extra($a, $data, $user_info);
3374 return api_format_data("statuses", $type, $data);
3377 /// @TODO move to top of file or somewhere better
3378 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3381 * Returns either the friends of the follower list
3383 * Considers friends and followers lists to be private and won't return
3384 * anything if any user_id parameter is passed.
3386 * @param string $qtype Either "friends" or "followers"
3387 * @return boolean|array
3388 * @throws BadRequestException
3389 * @throws ForbiddenException
3390 * @throws ImagickException
3391 * @throws InternalServerErrorException
3392 * @throws UnauthorizedException
3394 function api_statuses_f($qtype)
3398 if (api_user() === false) {
3399 throw new ForbiddenException();
3403 $count = $_GET['count'] ?? 20;
3404 $page = $_GET['page'] ?? 1;
3406 $start = max(0, ($page - 1) * $count);
3408 $user_info = api_get_user($a);
3410 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3411 /* this is to stop Hotot to load friends multiple times
3412 * I'm not sure if I'm missing return something or
3413 * is a bug in hotot. Workaround, meantime
3417 return array('$users' => $ret);*/
3422 if ($qtype == 'friends') {
3423 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3424 } elseif ($qtype == 'followers') {
3425 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3428 // friends and followers only for self
3429 if ($user_info['self'] == 0) {
3430 $sql_extra = " AND false ";
3433 if ($qtype == 'blocks') {
3434 $sql_filter = 'AND `blocked` AND NOT `pending`';
3435 } elseif ($qtype == 'incoming') {
3436 $sql_filter = 'AND `pending`';
3438 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3456 foreach ($r as $cid) {
3457 $user = api_get_user($a, $cid['nurl']);
3458 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3459 unset($user["uid"]);
3460 unset($user["self"]);
3467 return ['user' => $ret];
3472 * Returns the list of friends of the provided user
3474 * @deprecated By Twitter API in favor of friends/list
3476 * @param string $type Either "json" or "xml"
3477 * @return boolean|string|array
3478 * @throws BadRequestException
3479 * @throws ForbiddenException
3481 function api_statuses_friends($type)
3483 $data = api_statuses_f("friends");
3484 if ($data === false) {
3487 return api_format_data("users", $type, $data);
3491 * Returns the list of followers of the provided user
3493 * @deprecated By Twitter API in favor of friends/list
3495 * @param string $type Either "json" or "xml"
3496 * @return boolean|string|array
3497 * @throws BadRequestException
3498 * @throws ForbiddenException
3500 function api_statuses_followers($type)
3502 $data = api_statuses_f("followers");
3503 if ($data === false) {
3506 return api_format_data("users", $type, $data);
3509 /// @TODO move to top of file or somewhere better
3510 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3511 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3514 * Returns the list of blocked users
3516 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3518 * @param string $type Either "json" or "xml"
3520 * @return boolean|string|array
3521 * @throws BadRequestException
3522 * @throws ForbiddenException
3524 function api_blocks_list($type)
3526 $data = api_statuses_f('blocks');
3527 if ($data === false) {
3530 return api_format_data("users", $type, $data);
3533 /// @TODO move to top of file or somewhere better
3534 api_register_func('api/blocks/list', 'api_blocks_list', true);
3537 * Returns the list of pending users IDs
3539 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3541 * @param string $type Either "json" or "xml"
3543 * @return boolean|string|array
3544 * @throws BadRequestException
3545 * @throws ForbiddenException
3547 function api_friendships_incoming($type)
3549 $data = api_statuses_f('incoming');
3550 if ($data === false) {
3555 foreach ($data['user'] as $user) {
3556 $ids[] = $user['id'];
3559 return api_format_data("ids", $type, ['id' => $ids]);
3562 /// @TODO move to top of file or somewhere better
3563 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3566 * Returns the instance's configuration information.
3568 * @param string $type Return type (atom, rss, xml, json)
3570 * @return array|string
3571 * @throws InternalServerErrorException
3573 function api_statusnet_config($type)
3575 $name = DI::config()->get('config', 'sitename');
3576 $server = DI::baseUrl()->getHostname();
3577 $logo = DI::baseUrl() . '/images/friendica-64.png';
3578 $email = DI::config()->get('config', 'admin_email');
3579 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3580 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3581 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3582 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3583 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3586 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3587 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3588 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3589 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3590 'shorturllength' => '30',
3592 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3593 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3594 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3595 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3600 return api_format_data('config', $type, ['config' => $config]);
3603 /// @TODO move to top of file or somewhere better
3604 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3605 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3609 * @param string $type Return type (atom, rss, xml, json)
3611 * @return array|string
3613 function api_statusnet_version($type)
3616 $fake_statusnet_version = "0.9.7";
3618 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3621 /// @TODO move to top of file or somewhere better
3622 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3623 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3627 * @param string $type Return type (atom, rss, xml, json)
3629 * @param int $rel A contact relationship constant
3630 * @return array|string|void
3631 * @throws BadRequestException
3632 * @throws ForbiddenException
3633 * @throws ImagickException
3634 * @throws InternalServerErrorException
3635 * @throws UnauthorizedException
3636 * @todo use api_format_data() to return data
3638 function api_ff_ids($type, int $rel)
3641 throw new ForbiddenException();
3648 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3650 $contacts = DBA::p("SELECT `pcontact`.`id`
3652 INNER JOIN `contact` AS `pcontact`
3653 ON `contact`.`nurl` = `pcontact`.`nurl`
3654 AND `pcontact`.`uid` = 0
3655 WHERE `contact`.`uid` = ?
3656 AND NOT `contact`.`self`
3657 AND `contact`.`rel` IN (?, ?)",
3664 foreach (DBA::toArray($contacts) as $contact) {
3665 if ($stringify_ids) {
3666 $ids[] = $contact['id'];
3668 $ids[] = intval($contact['id']);
3672 return api_format_data('ids', $type, ['id' => $ids]);
3676 * Returns the ID of every user the user is following.
3678 * @param string $type Return type (atom, rss, xml, json)
3680 * @return array|string
3681 * @throws BadRequestException
3682 * @throws ForbiddenException
3683 * @throws ImagickException
3684 * @throws InternalServerErrorException
3685 * @throws UnauthorizedException
3686 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3688 function api_friends_ids($type)
3690 return api_ff_ids($type, Contact::SHARING);
3694 * Returns the ID of every user following the user.
3696 * @param string $type Return type (atom, rss, xml, json)
3698 * @return array|string
3699 * @throws BadRequestException
3700 * @throws ForbiddenException
3701 * @throws ImagickException
3702 * @throws InternalServerErrorException
3703 * @throws UnauthorizedException
3704 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3706 function api_followers_ids($type)
3708 return api_ff_ids($type, Contact::FOLLOWER);
3711 /// @TODO move to top of file or somewhere better
3712 api_register_func('api/friends/ids', 'api_friends_ids', true);
3713 api_register_func('api/followers/ids', 'api_followers_ids', true);
3716 * Sends a new direct message.
3718 * @param string $type Return type (atom, rss, xml, json)
3720 * @return array|string
3721 * @throws BadRequestException
3722 * @throws ForbiddenException
3723 * @throws ImagickException
3724 * @throws InternalServerErrorException
3725 * @throws NotFoundException
3726 * @throws UnauthorizedException
3727 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3729 function api_direct_messages_new($type)
3733 if (api_user() === false) {
3734 throw new ForbiddenException();
3737 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3741 $sender = api_get_user($a);
3744 if (!empty($_POST['screen_name'])) {
3746 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3748 DBA::escape($_POST['screen_name'])
3751 if (DBA::isResult($r)) {
3752 // Selecting the id by priority, friendica first
3753 api_best_nickname($r);
3755 $recipient = api_get_user($a, $r[0]['nurl']);
3758 $recipient = api_get_user($a, $_POST['user_id']);
3761 if (empty($recipient)) {
3762 throw new NotFoundException('Recipient not found');
3766 if (!empty($_REQUEST['replyto'])) {
3768 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3770 intval($_REQUEST['replyto'])
3772 $replyto = $r[0]['parent-uri'];
3773 $sub = $r[0]['title'];
3775 if (!empty($_REQUEST['title'])) {
3776 $sub = $_REQUEST['title'];
3778 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3782 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3785 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3786 $ret = api_format_messages($r[0], $recipient, $sender);
3788 $ret = ["error"=>$id];
3791 $data = ['direct_message'=>$ret];
3797 $data = api_rss_extra($a, $data, $sender);
3801 return api_format_data("direct-messages", $type, $data);
3804 /// @TODO move to top of file or somewhere better
3805 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3808 * delete a direct_message from mail table through api
3810 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3811 * @return string|array
3812 * @throws BadRequestException
3813 * @throws ForbiddenException
3814 * @throws ImagickException
3815 * @throws InternalServerErrorException
3816 * @throws UnauthorizedException
3817 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3819 function api_direct_messages_destroy($type)
3823 if (api_user() === false) {
3824 throw new ForbiddenException();
3828 $user_info = api_get_user($a);
3830 $id = $_REQUEST['id'] ?? 0;
3832 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3833 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3834 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3836 $uid = $user_info['uid'];
3837 // error if no id or parenturi specified (for clients posting parent-uri as well)
3838 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3839 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3840 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3843 // BadRequestException if no id specified (for clients using Twitter API)
3845 throw new BadRequestException('Message id not specified');
3848 // add parent-uri to sql command if specified by calling app
3849 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3851 // get data of the specified message id
3853 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3858 // error message if specified id is not in database
3859 if (!DBA::isResult($r)) {
3860 if ($verbose == "true") {
3861 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3862 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3864 /// @todo BadRequestException ok for Twitter API clients?
3865 throw new BadRequestException('message id not in database');
3870 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3875 if ($verbose == "true") {
3878 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3879 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3881 $answer = ['result' => 'error', 'message' => 'unknown error'];
3882 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3885 /// @todo return JSON data like Twitter API not yet implemented
3888 /// @TODO move to top of file or somewhere better
3889 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3894 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3895 * @return string|array
3896 * @throws BadRequestException
3897 * @throws ForbiddenException
3898 * @throws ImagickException
3899 * @throws InternalServerErrorException
3900 * @throws NotFoundException
3901 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3903 function api_friendships_destroy($type)
3907 if ($uid === false) {
3908 throw new ForbiddenException();
3911 $contact_id = $_REQUEST['user_id'] ?? 0;
3913 if (empty($contact_id)) {
3914 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3915 throw new BadRequestException("no user_id specified");
3918 // Get Contact by given id
3919 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3921 if(!DBA::isResult($contact)) {
3922 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3923 throw new NotFoundException("no contact found to given ID");
3926 $url = $contact["url"];
3928 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3929 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3930 Strings::normaliseLink($url), $url];
3931 $contact = DBA::selectFirst('contact', [], $condition);
3933 if (!DBA::isResult($contact)) {
3934 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3935 throw new NotFoundException("Not following Contact");
3938 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3939 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3940 throw new ExpectationFailedException("Not supported");
3943 $dissolve = ($contact['rel'] == Contact::SHARING);
3945 $owner = User::getOwnerDataById($uid);
3947 Contact::terminateFriendship($owner, $contact, $dissolve);
3950 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3951 throw new NotFoundException("Error Processing Request");
3954 // Sharing-only contacts get deleted as there no relationship any more
3956 Contact::remove($contact['id']);
3958 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3961 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3962 unset($contact["uid"]);
3963 unset($contact["self"]);
3965 // Set screen_name since Twidere requests it
3966 $contact["screen_name"] = $contact["nick"];
3968 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3970 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3974 * @param string $type Return type (atom, rss, xml, json)
3975 * @param string $box
3976 * @param string $verbose
3978 * @return array|string
3979 * @throws BadRequestException
3980 * @throws ForbiddenException
3981 * @throws ImagickException
3982 * @throws InternalServerErrorException
3983 * @throws UnauthorizedException
3985 function api_direct_messages_box($type, $box, $verbose)
3988 if (api_user() === false) {
3989 throw new ForbiddenException();
3992 $count = $_GET['count'] ?? 20;
3993 $page = $_REQUEST['page'] ?? 1;
3995 $since_id = $_REQUEST['since_id'] ?? 0;
3996 $max_id = $_REQUEST['max_id'] ?? 0;
3998 $user_id = $_REQUEST['user_id'] ?? '';
3999 $screen_name = $_REQUEST['screen_name'] ?? '';
4002 unset($_REQUEST["user_id"]);
4003 unset($_GET["user_id"]);
4005 unset($_REQUEST["screen_name"]);
4006 unset($_GET["screen_name"]);
4008 $user_info = api_get_user($a);
4009 if ($user_info === false) {
4010 throw new ForbiddenException();
4012 $profile_url = $user_info["url"];
4015 $start = max(0, ($page - 1) * $count);
4020 if ($box=="sentbox") {
4021 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
4022 } elseif ($box == "conversation") {
4023 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
4024 } elseif ($box == "all") {
4025 $sql_extra = "true";
4026 } elseif ($box == "inbox") {
4027 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4031 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4034 if ($user_id != "") {
4035 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4036 } elseif ($screen_name !="") {
4037 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4041 "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",
4047 if ($verbose == "true" && !DBA::isResult($r)) {
4048 $answer = ['result' => 'error', 'message' => 'no mails available'];
4049 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4053 foreach ($r as $item) {
4054 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4055 $recipient = $user_info;
4056 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4057 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4058 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4059 $sender = $user_info;
4062 if (isset($recipient) && isset($sender)) {
4063 $ret[] = api_format_messages($item, $recipient, $sender);
4068 $data = ['direct_message' => $ret];
4073 $data = api_rss_extra($a, $data, $user_info);
4077 return api_format_data("direct-messages", $type, $data);
4081 * Returns the most recent direct messages sent by the user.
4083 * @param string $type Return type (atom, rss, xml, json)
4085 * @return array|string
4086 * @throws BadRequestException
4087 * @throws ForbiddenException
4088 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4090 function api_direct_messages_sentbox($type)
4092 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4093 return api_direct_messages_box($type, "sentbox", $verbose);
4097 * Returns the most recent direct messages sent to the user.
4099 * @param string $type Return type (atom, rss, xml, json)
4101 * @return array|string
4102 * @throws BadRequestException
4103 * @throws ForbiddenException
4104 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4106 function api_direct_messages_inbox($type)
4108 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4109 return api_direct_messages_box($type, "inbox", $verbose);
4114 * @param string $type Return type (atom, rss, xml, json)
4116 * @return array|string
4117 * @throws BadRequestException
4118 * @throws ForbiddenException
4120 function api_direct_messages_all($type)
4122 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4123 return api_direct_messages_box($type, "all", $verbose);
4128 * @param string $type Return type (atom, rss, xml, json)
4130 * @return array|string
4131 * @throws BadRequestException
4132 * @throws ForbiddenException
4134 function api_direct_messages_conversation($type)
4136 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4137 return api_direct_messages_box($type, "conversation", $verbose);
4140 /// @TODO move to top of file or somewhere better
4141 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4142 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4143 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4144 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4147 * Returns an OAuth Request Token.
4149 * @see https://oauth.net/core/1.0/#auth_step1
4151 function api_oauth_request_token()
4153 $oauth1 = new FKOAuth1();
4155 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4156 } catch (Exception $e) {
4157 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4165 * Returns an OAuth Access Token.
4167 * @return array|string
4168 * @see https://oauth.net/core/1.0/#auth_step3
4170 function api_oauth_access_token()
4172 $oauth1 = new FKOAuth1();
4174 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4175 } catch (Exception $e) {
4176 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4183 /// @TODO move to top of file or somewhere better
4184 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4185 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4189 * delete a complete photoalbum with all containing photos from database through api
4191 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4192 * @return string|array
4193 * @throws BadRequestException
4194 * @throws ForbiddenException
4195 * @throws InternalServerErrorException
4197 function api_fr_photoalbum_delete($type)
4199 if (api_user() === false) {
4200 throw new ForbiddenException();
4203 $album = $_REQUEST['album'] ?? '';
4205 // we do not allow calls without album string
4207 throw new BadRequestException("no albumname specified");
4209 // check if album is existing
4211 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4215 if (!DBA::isResult($r)) {
4216 throw new BadRequestException("album not available");
4219 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4220 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4221 foreach ($r as $rr) {
4222 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4223 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4225 if (!DBA::isResult($photo_item)) {
4226 throw new InternalServerErrorException("problem with deleting items occured");
4228 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4231 // now let's delete all photos from the album
4232 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4234 // return success of deletion or error message
4236 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4237 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4239 throw new InternalServerErrorException("unknown error - deleting from database failed");
4244 * update the name of the album for all photos of an album
4246 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4247 * @return string|array
4248 * @throws BadRequestException
4249 * @throws ForbiddenException
4250 * @throws InternalServerErrorException
4252 function api_fr_photoalbum_update($type)
4254 if (api_user() === false) {
4255 throw new ForbiddenException();
4258 $album = $_REQUEST['album'] ?? '';
4259 $album_new = $_REQUEST['album_new'] ?? '';
4261 // we do not allow calls without album string
4263 throw new BadRequestException("no albumname specified");
4265 if ($album_new == "") {
4266 throw new BadRequestException("no new albumname specified");
4268 // check if album is existing
4269 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4270 throw new BadRequestException("album not available");
4272 // now let's update all photos to the albumname
4273 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4275 // return success of updating or error message
4277 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4278 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4280 throw new InternalServerErrorException("unknown error - updating in database failed");
4286 * list all photos of the authenticated user
4288 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4289 * @return string|array
4290 * @throws ForbiddenException
4291 * @throws InternalServerErrorException
4293 function api_fr_photos_list($type)
4295 if (api_user() === false) {
4296 throw new ForbiddenException();
4299 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4300 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4301 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4302 intval(local_user())
4305 'image/jpeg' => 'jpg',
4306 'image/png' => 'png',
4307 'image/gif' => 'gif'
4309 $data = ['photo'=>[]];
4310 if (DBA::isResult($r)) {
4311 foreach ($r as $rr) {
4313 $photo['id'] = $rr['resource-id'];
4314 $photo['album'] = $rr['album'];
4315 $photo['filename'] = $rr['filename'];
4316 $photo['type'] = $rr['type'];
4317 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4318 $photo['created'] = $rr['created'];
4319 $photo['edited'] = $rr['edited'];
4320 $photo['desc'] = $rr['desc'];
4322 if ($type == "xml") {
4323 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4325 $photo['thumb'] = $thumb;
4326 $data['photo'][] = $photo;
4330 return api_format_data("photos", $type, $data);
4334 * upload a new photo or change an existing photo
4336 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4337 * @return string|array
4338 * @throws BadRequestException
4339 * @throws ForbiddenException
4340 * @throws ImagickException
4341 * @throws InternalServerErrorException
4342 * @throws NotFoundException
4344 function api_fr_photo_create_update($type)
4346 if (api_user() === false) {
4347 throw new ForbiddenException();
4350 $photo_id = $_REQUEST['photo_id'] ?? null;
4351 $desc = $_REQUEST['desc'] ?? null;
4352 $album = $_REQUEST['album'] ?? null;
4353 $album_new = $_REQUEST['album_new'] ?? null;
4354 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4355 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4356 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4357 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4358 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4360 // do several checks on input parameters
4361 // we do not allow calls without album string
4362 if ($album == null) {
4363 throw new BadRequestException("no albumname specified");
4365 // if photo_id == null --> we are uploading a new photo
4366 if ($photo_id == null) {
4369 // error if no media posted in create-mode
4370 if (empty($_FILES['media'])) {
4372 throw new BadRequestException("no media data submitted");
4375 // album_new will be ignored in create-mode
4380 // check if photo is existing in databasei
4381 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4382 throw new BadRequestException("photo not available");
4386 // checks on acl strings provided by clients
4387 $acl_input_error = false;
4388 $acl_input_error |= check_acl_input($allow_cid);
4389 $acl_input_error |= check_acl_input($deny_cid);
4390 $acl_input_error |= check_acl_input($allow_gid);
4391 $acl_input_error |= check_acl_input($deny_gid);
4392 if ($acl_input_error) {
4393 throw new BadRequestException("acl data invalid");
4395 // now let's upload the new media in create-mode
4396 if ($mode == "create") {
4397 $media = $_FILES['media'];
4398 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4400 // return success of updating or error message
4401 if (!is_null($data)) {
4402 return api_format_data("photo_create", $type, $data);
4404 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4408 // now let's do the changes in update-mode
4409 if ($mode == "update") {
4410 $updated_fields = [];
4412 if (!is_null($desc)) {
4413 $updated_fields['desc'] = $desc;
4416 if (!is_null($album_new)) {
4417 $updated_fields['album'] = $album_new;
4420 if (!is_null($allow_cid)) {
4421 $allow_cid = trim($allow_cid);
4422 $updated_fields['allow_cid'] = $allow_cid;
4425 if (!is_null($deny_cid)) {
4426 $deny_cid = trim($deny_cid);
4427 $updated_fields['deny_cid'] = $deny_cid;
4430 if (!is_null($allow_gid)) {
4431 $allow_gid = trim($allow_gid);
4432 $updated_fields['allow_gid'] = $allow_gid;
4435 if (!is_null($deny_gid)) {
4436 $deny_gid = trim($deny_gid);
4437 $updated_fields['deny_gid'] = $deny_gid;
4441 if (count($updated_fields) > 0) {
4442 $nothingtodo = false;
4443 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4445 $nothingtodo = true;
4448 if (!empty($_FILES['media'])) {
4449 $nothingtodo = false;
4450 $media = $_FILES['media'];
4451 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4452 if (!is_null($data)) {
4453 return api_format_data("photo_update", $type, $data);
4457 // return success of updating or error message
4459 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4460 return api_format_data("photo_update", $type, ['$result' => $answer]);
4463 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4464 return api_format_data("photo_update", $type, ['$result' => $answer]);
4466 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4469 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4473 * delete a single photo from the database through api
4475 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4476 * @return string|array
4477 * @throws BadRequestException
4478 * @throws ForbiddenException
4479 * @throws InternalServerErrorException
4481 function api_fr_photo_delete($type)
4483 if (api_user() === false) {
4484 throw new ForbiddenException();
4488 $photo_id = $_REQUEST['photo_id'] ?? null;
4490 // do several checks on input parameters
4491 // we do not allow calls without photo id
4492 if ($photo_id == null) {
4493 throw new BadRequestException("no photo_id specified");
4496 // check if photo is existing in database
4497 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4498 throw new BadRequestException("photo not available");
4501 // now we can perform on the deletion of the photo
4502 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4504 // return success of deletion or error message
4506 // retrieve the id of the parent element (the photo element)
4507 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4508 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4510 if (!DBA::isResult($photo_item)) {
4511 throw new InternalServerErrorException("problem with deleting items occured");
4513 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4514 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4515 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4517 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4518 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4520 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4526 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4528 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4529 * @return string|array
4530 * @throws BadRequestException
4531 * @throws ForbiddenException
4532 * @throws InternalServerErrorException
4533 * @throws NotFoundException
4535 function api_fr_photo_detail($type)
4537 if (api_user() === false) {
4538 throw new ForbiddenException();
4540 if (empty($_REQUEST['photo_id'])) {
4541 throw new BadRequestException("No photo id.");
4544 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4545 $photo_id = $_REQUEST['photo_id'];
4547 // prepare json/xml output with data from database for the requested photo
4548 $data = prepare_photo_data($type, $scale, $photo_id);
4550 return api_format_data("photo_detail", $type, $data);
4555 * updates the profile image for the user (either a specified profile or the default profile)
4557 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4559 * @return string|array
4560 * @throws BadRequestException
4561 * @throws ForbiddenException
4562 * @throws ImagickException
4563 * @throws InternalServerErrorException
4564 * @throws NotFoundException
4565 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4567 function api_account_update_profile_image($type)
4569 if (api_user() === false) {
4570 throw new ForbiddenException();
4573 $profile_id = $_REQUEST['profile_id'] ?? 0;
4575 // error if image data is missing
4576 if (empty($_FILES['image'])) {
4577 throw new BadRequestException("no media data submitted");
4580 // check if specified profile id is valid
4581 if ($profile_id != 0) {
4582 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4583 // error message if specified profile id is not in database
4584 if (!DBA::isResult($profile)) {
4585 throw new BadRequestException("profile_id not available");
4587 $is_default_profile = $profile['is-default'];
4589 $is_default_profile = 1;
4592 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4594 if (!empty($_FILES['image'])) {
4595 $media = $_FILES['image'];
4596 } elseif (!empty($_FILES['media'])) {
4597 $media = $_FILES['media'];
4599 // save new profile image
4600 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4603 if (is_array($media['type'])) {
4604 $filetype = $media['type'][0];
4606 $filetype = $media['type'];
4608 if ($filetype == "image/jpeg") {
4610 } elseif ($filetype == "image/png") {
4613 throw new InternalServerErrorException('Unsupported filetype');
4616 // change specified profile or all profiles to the new resource-id
4617 if ($is_default_profile) {
4618 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4619 Photo::update(['profile' => false], $condition);
4621 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4622 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4623 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4626 Contact::updateSelfFromUserID(api_user(), true);
4628 // Update global directory in background
4629 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4630 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4631 Worker::add(PRIORITY_LOW, "Directory", $url);
4634 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4636 // output for client
4638 return api_account_verify_credentials($type);
4640 // SaveMediaToDatabase failed for some reason
4641 throw new InternalServerErrorException("image upload failed");
4645 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4646 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4647 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4648 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4649 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4650 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4651 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4652 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4653 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4656 * Update user profile
4658 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4660 * @return array|string
4661 * @throws BadRequestException
4662 * @throws ForbiddenException
4663 * @throws ImagickException
4664 * @throws InternalServerErrorException
4665 * @throws UnauthorizedException
4667 function api_account_update_profile($type)
4669 $local_user = api_user();
4670 $api_user = api_get_user(DI::app());
4672 if (!empty($_POST['name'])) {
4673 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4674 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4675 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4676 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4679 if (isset($_POST['description'])) {
4680 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4681 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4682 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4685 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4686 // Update global directory in background
4687 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4688 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4691 return api_account_verify_credentials($type);
4694 /// @TODO move to top of file or somewhere better
4695 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4699 * @param string $acl_string
4703 function check_acl_input($acl_string)
4705 if (empty($acl_string)) {
4709 $contact_not_found = false;
4711 // split <x><y><z> into array of cid's
4712 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4714 // check for each cid if it is available on server
4715 $cid_array = $array[0];
4716 foreach ($cid_array as $cid) {
4717 $cid = str_replace("<", "", $cid);
4718 $cid = str_replace(">", "", $cid);
4719 $condition = ['id' => $cid, 'uid' => api_user()];
4720 $contact_not_found |= !DBA::exists('contact', $condition);
4722 return $contact_not_found;
4726 * @param string $mediatype
4727 * @param array $media
4728 * @param string $type
4729 * @param string $album
4730 * @param string $allow_cid
4731 * @param string $deny_cid
4732 * @param string $allow_gid
4733 * @param string $deny_gid
4734 * @param string $desc
4735 * @param integer $profile
4736 * @param boolean $visibility
4737 * @param string $photo_id
4739 * @throws BadRequestException
4740 * @throws ForbiddenException
4741 * @throws ImagickException
4742 * @throws InternalServerErrorException
4743 * @throws NotFoundException
4744 * @throws UnauthorizedException
4746 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)
4754 if (is_array($media)) {
4755 if (is_array($media['tmp_name'])) {
4756 $src = $media['tmp_name'][0];
4758 $src = $media['tmp_name'];
4760 if (is_array($media['name'])) {
4761 $filename = basename($media['name'][0]);
4763 $filename = basename($media['name']);
4765 if (is_array($media['size'])) {
4766 $filesize = intval($media['size'][0]);
4768 $filesize = intval($media['size']);
4770 if (is_array($media['type'])) {
4771 $filetype = $media['type'][0];
4773 $filetype = $media['type'];
4777 if ($filetype == "") {
4778 $filetype = Images::guessType($filename);
4780 $imagedata = @getimagesize($src);
4782 $filetype = $imagedata['mime'];
4785 "File upload src: " . $src . " - filename: " . $filename .
4786 " - size: " . $filesize . " - type: " . $filetype,
4790 // check if there was a php upload error
4791 if ($filesize == 0 && $media['error'] == 1) {
4792 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4794 // check against max upload size within Friendica instance
4795 $maximagesize = DI::config()->get('system', 'maximagesize');
4796 if ($maximagesize && ($filesize > $maximagesize)) {
4797 $formattedBytes = Strings::formatBytes($maximagesize);
4798 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4801 // create Photo instance with the data of the image
4802 $imagedata = @file_get_contents($src);
4803 $Image = new Image($imagedata, $filetype);
4804 if (!$Image->isValid()) {
4805 throw new InternalServerErrorException("unable to process image data");
4808 // check orientation of image
4809 $Image->orient($src);
4812 // check max length of images on server
4813 $max_length = DI::config()->get('system', 'max_image_length');
4815 $max_length = MAX_IMAGE_LENGTH;
4817 if ($max_length > 0) {
4818 $Image->scaleDown($max_length);
4819 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4821 $width = $Image->getWidth();
4822 $height = $Image->getHeight();
4824 // create a new resource-id if not already provided
4825 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4827 if ($mediatype == "photo") {
4828 // upload normal image (scales 0, 1, 2)
4829 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4831 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4833 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4835 if ($width > 640 || $height > 640) {
4836 $Image->scaleDown(640);
4837 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4839 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4843 if ($width > 320 || $height > 320) {
4844 $Image->scaleDown(320);
4845 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4847 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4850 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4851 } elseif ($mediatype == "profileimage") {
4852 // upload profile image (scales 4, 5, 6)
4853 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4855 if ($width > 300 || $height > 300) {
4856 $Image->scaleDown(300);
4857 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4859 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4863 if ($width > 80 || $height > 80) {
4864 $Image->scaleDown(80);
4865 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4867 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4871 if ($width > 48 || $height > 48) {
4872 $Image->scaleDown(48);
4873 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4875 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4878 $Image->__destruct();
4879 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4882 if (isset($r) && $r) {
4883 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4884 if ($photo_id == null && $mediatype == "photo") {
4885 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4887 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4888 return prepare_photo_data($type, false, $resource_id);
4890 throw new InternalServerErrorException("image upload failed");
4896 * @param string $hash
4897 * @param string $allow_cid
4898 * @param string $deny_cid
4899 * @param string $allow_gid
4900 * @param string $deny_gid
4901 * @param string $filetype
4902 * @param boolean $visibility
4903 * @throws InternalServerErrorException
4905 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4907 // get data about the api authenticated user
4908 $uri = Item::newURI(intval(api_user()));
4909 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4912 $arr['guid'] = System::createUUID();
4913 $arr['uid'] = intval(api_user());
4915 $arr['parent-uri'] = $uri;
4916 $arr['type'] = 'photo';
4918 $arr['resource-id'] = $hash;
4919 $arr['contact-id'] = $owner_record['id'];
4920 $arr['owner-name'] = $owner_record['name'];
4921 $arr['owner-link'] = $owner_record['url'];
4922 $arr['owner-avatar'] = $owner_record['thumb'];
4923 $arr['author-name'] = $owner_record['name'];
4924 $arr['author-link'] = $owner_record['url'];
4925 $arr['author-avatar'] = $owner_record['thumb'];
4927 $arr['allow_cid'] = $allow_cid;
4928 $arr['allow_gid'] = $allow_gid;
4929 $arr['deny_cid'] = $deny_cid;
4930 $arr['deny_gid'] = $deny_gid;
4931 $arr['visible'] = $visibility;
4935 'image/jpeg' => 'jpg',
4936 'image/png' => 'png',
4937 'image/gif' => 'gif'
4940 // adds link to the thumbnail scale photo
4941 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4942 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4945 // do the magic for storing the item in the database and trigger the federation to other contacts
4951 * @param string $type
4953 * @param string $photo_id
4956 * @throws BadRequestException
4957 * @throws ForbiddenException
4958 * @throws ImagickException
4959 * @throws InternalServerErrorException
4960 * @throws NotFoundException
4961 * @throws UnauthorizedException
4963 function prepare_photo_data($type, $scale, $photo_id)
4966 $user_info = api_get_user($a);
4968 if ($user_info === false) {
4969 throw new ForbiddenException();
4972 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4973 $data_sql = ($scale === false ? "" : "data, ");
4975 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4976 // clients needs to convert this in their way for further processing
4978 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4979 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4980 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4981 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4982 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4983 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4985 intval(local_user()),
4986 DBA::escape($photo_id),
4991 'image/jpeg' => 'jpg',
4992 'image/png' => 'png',
4993 'image/gif' => 'gif'
4996 // prepare output data for photo
4997 if (DBA::isResult($r)) {
4998 $data = ['photo' => $r[0]];
4999 $data['photo']['id'] = $data['photo']['resource-id'];
5000 if ($scale !== false) {
5001 $data['photo']['data'] = base64_encode($data['photo']['data']);
5003 unset($data['photo']['datasize']); //needed only with scale param
5005 if ($type == "xml") {
5006 $data['photo']['links'] = [];
5007 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5008 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
5010 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
5013 $data['photo']['link'] = [];
5014 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
5016 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5017 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
5021 unset($data['photo']['resource-id']);
5022 unset($data['photo']['minscale']);
5023 unset($data['photo']['maxscale']);
5025 throw new NotFoundException();
5028 // retrieve item element for getting activities (like, dislike etc.) related to photo
5029 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5030 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5032 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5034 // retrieve comments on photo
5035 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5036 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5038 $statuses = Item::selectForUser(api_user(), [], $condition);
5040 // prepare output of comments
5041 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5043 if ($type == "xml") {
5045 foreach ($commentData as $comment) {
5046 $comments[$k++ . ":comment"] = $comment;
5049 foreach ($commentData as $comment) {
5050 $comments[] = $comment;
5053 $data['photo']['friendica_comments'] = $comments;
5055 // include info if rights on photo and rights on item are mismatching
5056 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5057 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5058 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5059 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5060 $data['photo']['rights_mismatch'] = $rights_mismatch;
5067 * Similar as /mod/redir.php
5068 * redirect to 'url' after dfrn auth
5070 * Why this when there is mod/redir.php already?
5071 * This use api_user() and api_login()
5074 * c_url: url of remote contact to auth to
5075 * url: string, url to redirect after auth
5077 function api_friendica_remoteauth()
5079 $url = $_GET['url'] ?? '';
5080 $c_url = $_GET['c_url'] ?? '';
5082 if ($url === '' || $c_url === '') {
5083 throw new BadRequestException("Wrong parameters.");
5086 $c_url = Strings::normaliseLink($c_url);
5090 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5091 if (!DBA::isResult($contact)) {
5092 throw new BadRequestException("Unknown contact");
5095 $cid = $contact['id'];
5097 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5099 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5100 System::externalRedirect($url ?: $c_url);
5103 if ($contact['duplex'] && $contact['issued-id']) {
5104 $orig_id = $contact['issued-id'];
5105 $dfrn_id = '1:' . $orig_id;
5107 if ($contact['duplex'] && $contact['dfrn-id']) {
5108 $orig_id = $contact['dfrn-id'];
5109 $dfrn_id = '0:' . $orig_id;
5112 $sec = Strings::getRandomHex();
5114 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5115 'sec' => $sec, 'expire' => time() + 45];
5116 DBA::insert('profile_check', $fields);
5118 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5119 $dest = ($url ? '&destination_url=' . $url : '');
5121 System::externalRedirect(
5122 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5123 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5124 . '&type=profile&sec=' . $sec . $dest
5127 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5130 * Return an item with announcer data if it had been announced
5132 * @param array $item Item array
5133 * @return array Item array with announce data
5135 function api_get_announce($item)
5137 // Quit if the item already has got a different owner and author
5138 if ($item['owner-id'] != $item['author-id']) {
5142 // Don't change original or Diaspora posts
5143 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5147 // Quit if we do now the original author and it had been a post from a native network
5148 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5152 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5153 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5154 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5155 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5156 if (!DBA::isResult($announce)) {
5160 return array_merge($item, $announce);
5164 * Return the item shared, if the item contains only the [share] tag
5166 * @param array $item Sharer item
5167 * @return array|false Shared item or false if not a reshare
5168 * @throws ImagickException
5169 * @throws InternalServerErrorException
5171 function api_share_as_retweet(&$item)
5173 $body = trim($item["body"]);
5175 if (Diaspora::isReshare($body, false) === false) {
5176 if ($item['author-id'] == $item['owner-id']) {
5179 // Reshares from OStatus, ActivityPub and Twitter
5180 $reshared_item = $item;
5181 $reshared_item['owner-id'] = $reshared_item['author-id'];
5182 $reshared_item['owner-link'] = $reshared_item['author-link'];
5183 $reshared_item['owner-name'] = $reshared_item['author-name'];
5184 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5185 return $reshared_item;
5189 $reshared = Item::getShareArray($item);
5190 if (empty($reshared)) {
5194 $reshared_item = $item;
5196 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5200 if (!empty($reshared['comment'])) {
5201 $item['body'] = $reshared['comment'];
5204 $reshared_item["share-pre-body"] = $reshared['comment'];
5205 $reshared_item["body"] = $reshared['shared'];
5206 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5207 $reshared_item["author-name"] = $reshared['author'];
5208 $reshared_item["author-link"] = $reshared['profile'];
5209 $reshared_item["author-avatar"] = $reshared['avatar'];
5210 $reshared_item["plink"] = $reshared['link'] ?? '';
5211 $reshared_item["created"] = $reshared['posted'];
5212 $reshared_item["edited"] = $reshared['posted'];
5214 // Try to fetch the original item
5215 if (!empty($reshared['guid'])) {
5216 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5217 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5218 $condition = ['id' => $original_id];
5223 if (!empty($condition)) {
5224 $original_item = Item::selectFirst([], $condition);
5225 if (DBA::isResult($original_item)) {
5226 $reshared_item = array_merge($reshared_item, $original_item);
5230 return $reshared_item;
5235 * @param array $item
5240 function api_in_reply_to($item)
5244 $in_reply_to['status_id'] = null;
5245 $in_reply_to['user_id'] = null;
5246 $in_reply_to['status_id_str'] = null;
5247 $in_reply_to['user_id_str'] = null;
5248 $in_reply_to['screen_name'] = null;
5250 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5251 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5252 if (DBA::isResult($parent)) {
5253 $in_reply_to['status_id'] = intval($parent['id']);
5255 $in_reply_to['status_id'] = intval($item['parent']);
5258 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5260 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5261 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5263 if (DBA::isResult($parent)) {
5264 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5265 $in_reply_to['user_id'] = intval($parent['author-id']);
5266 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5269 // There seems to be situation, where both fields are identical:
5270 // https://github.com/friendica/friendica/issues/1010
5271 // This is a bugfix for that.
5272 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5273 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']]);
5274 $in_reply_to['status_id'] = null;
5275 $in_reply_to['user_id'] = null;
5276 $in_reply_to['status_id_str'] = null;
5277 $in_reply_to['user_id_str'] = null;
5278 $in_reply_to['screen_name'] = null;
5282 return $in_reply_to;
5287 * @param string $text
5290 * @throws InternalServerErrorException
5292 function api_clean_plain_items($text)
5294 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5296 $text = BBCode::cleanPictureLinks($text);
5297 $URLSearchString = "^\[\]";
5299 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5301 if ($include_entities == "true") {
5302 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5305 // Simplify "attachment" element
5306 $text = BBCode::removeAttachment($text);
5313 * @param array $contacts
5317 function api_best_nickname(&$contacts)
5321 if (count($contacts) == 0) {
5325 foreach ($contacts as $contact) {
5326 if ($contact["network"] == "") {
5327 $contact["network"] = "dfrn";
5328 $best_contact = [$contact];
5332 if (sizeof($best_contact) == 0) {
5333 foreach ($contacts as $contact) {
5334 if ($contact["network"] == "dfrn") {
5335 $best_contact = [$contact];
5340 if (sizeof($best_contact) == 0) {
5341 foreach ($contacts as $contact) {
5342 if ($contact["network"] == "dspr") {
5343 $best_contact = [$contact];
5348 if (sizeof($best_contact) == 0) {
5349 foreach ($contacts as $contact) {
5350 if ($contact["network"] == "stat") {
5351 $best_contact = [$contact];
5356 if (sizeof($best_contact) == 0) {
5357 foreach ($contacts as $contact) {
5358 if ($contact["network"] == "pump") {
5359 $best_contact = [$contact];
5364 if (sizeof($best_contact) == 0) {
5365 foreach ($contacts as $contact) {
5366 if ($contact["network"] == "twit") {
5367 $best_contact = [$contact];
5372 if (sizeof($best_contact) == 1) {
5373 $contacts = $best_contact;
5375 $contacts = [$contacts[0]];
5380 * Return all or a specified group of the user with the containing contacts.
5382 * @param string $type Return type (atom, rss, xml, json)
5384 * @return array|string
5385 * @throws BadRequestException
5386 * @throws ForbiddenException
5387 * @throws ImagickException
5388 * @throws InternalServerErrorException
5389 * @throws UnauthorizedException
5391 function api_friendica_group_show($type)
5395 if (api_user() === false) {
5396 throw new ForbiddenException();
5400 $user_info = api_get_user($a);
5401 $gid = $_REQUEST['gid'] ?? 0;
5402 $uid = $user_info['uid'];
5404 // get data of the specified group id or all groups if not specified
5407 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5411 // error message if specified gid is not in database
5412 if (!DBA::isResult($r)) {
5413 throw new BadRequestException("gid not available");
5417 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5422 // loop through all groups and retrieve all members for adding data in the user array
5424 foreach ($r as $rr) {
5425 $members = Contact::getByGroupId($rr['id']);
5428 if ($type == "xml") {
5429 $user_element = "users";
5431 foreach ($members as $member) {
5432 $user = api_get_user($a, $member['nurl']);
5433 $users[$k++.":user"] = $user;
5436 $user_element = "user";
5437 foreach ($members as $member) {
5438 $user = api_get_user($a, $member['nurl']);
5442 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5444 return api_format_data("groups", $type, ['group' => $grps]);
5446 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5450 * Delete the specified group of the user.
5452 * @param string $type Return type (atom, rss, xml, json)
5454 * @return array|string
5455 * @throws BadRequestException
5456 * @throws ForbiddenException
5457 * @throws ImagickException
5458 * @throws InternalServerErrorException
5459 * @throws UnauthorizedException
5461 function api_friendica_group_delete($type)
5465 if (api_user() === false) {
5466 throw new ForbiddenException();
5470 $user_info = api_get_user($a);
5471 $gid = $_REQUEST['gid'] ?? 0;
5472 $name = $_REQUEST['name'] ?? '';
5473 $uid = $user_info['uid'];
5475 // error if no gid specified
5476 if ($gid == 0 || $name == "") {
5477 throw new BadRequestException('gid or name not specified');
5480 // get data of the specified group id
5482 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5486 // error message if specified gid is not in database
5487 if (!DBA::isResult($r)) {
5488 throw new BadRequestException('gid not available');
5491 // get data of the specified group id and group name
5493 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5498 // error message if specified gid is not in database
5499 if (!DBA::isResult($rname)) {
5500 throw new BadRequestException('wrong group name');
5504 $ret = Group::removeByName($uid, $name);
5507 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5508 return api_format_data("group_delete", $type, ['result' => $success]);
5510 throw new BadRequestException('other API error');
5513 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5518 * @param string $type Return type (atom, rss, xml, json)
5520 * @return array|string
5521 * @throws BadRequestException
5522 * @throws ForbiddenException
5523 * @throws ImagickException
5524 * @throws InternalServerErrorException
5525 * @throws UnauthorizedException
5526 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5528 function api_lists_destroy($type)
5532 if (api_user() === false) {
5533 throw new ForbiddenException();
5537 $user_info = api_get_user($a);
5538 $gid = $_REQUEST['list_id'] ?? 0;
5539 $uid = $user_info['uid'];
5541 // error if no gid specified
5543 throw new BadRequestException('gid not specified');
5546 // get data of the specified group id
5547 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5548 // error message if specified gid is not in database
5550 throw new BadRequestException('gid not available');
5553 if (Group::remove($gid)) {
5555 'name' => $group['name'],
5556 'id' => intval($gid),
5557 'id_str' => (string) $gid,
5558 'user' => $user_info
5561 return api_format_data("lists", $type, ['lists' => $list]);
5564 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5567 * Add a new group to the database.
5569 * @param string $name Group name
5570 * @param int $uid User ID
5571 * @param array $users List of users to add to the group
5574 * @throws BadRequestException
5576 function group_create($name, $uid, $users = [])
5578 // error if no name specified
5580 throw new BadRequestException('group name not specified');
5583 // get data of the specified group name
5585 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5589 // error message if specified group name already exists
5590 if (DBA::isResult($rname)) {
5591 throw new BadRequestException('group name already exists');
5594 // check if specified group name is a deleted group
5596 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5600 // error message if specified group name already exists
5601 if (DBA::isResult($rname)) {
5602 $reactivate_group = true;
5606 $ret = Group::create($uid, $name);
5608 $gid = Group::getIdByName($uid, $name);
5610 throw new BadRequestException('other API error');
5614 $erroraddinguser = false;
5616 foreach ($users as $user) {
5617 $cid = $user['cid'];
5618 // check if user really exists as contact
5620 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5624 if (count($contact)) {
5625 Group::addMember($gid, $cid);
5627 $erroraddinguser = true;
5628 $errorusers[] = $cid;
5632 // return success message incl. missing users in array
5633 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5635 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5639 * Create the specified group with the posted array of contacts.
5641 * @param string $type Return type (atom, rss, xml, json)
5643 * @return array|string
5644 * @throws BadRequestException
5645 * @throws ForbiddenException
5646 * @throws ImagickException
5647 * @throws InternalServerErrorException
5648 * @throws UnauthorizedException
5650 function api_friendica_group_create($type)
5654 if (api_user() === false) {
5655 throw new ForbiddenException();
5659 $user_info = api_get_user($a);
5660 $name = $_REQUEST['name'] ?? '';
5661 $uid = $user_info['uid'];
5662 $json = json_decode($_POST['json'], true);
5663 $users = $json['user'];
5665 $success = group_create($name, $uid, $users);
5667 return api_format_data("group_create", $type, ['result' => $success]);
5669 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5672 * Create a new group.
5674 * @param string $type Return type (atom, rss, xml, json)
5676 * @return array|string
5677 * @throws BadRequestException
5678 * @throws ForbiddenException
5679 * @throws ImagickException
5680 * @throws InternalServerErrorException
5681 * @throws UnauthorizedException
5682 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5684 function api_lists_create($type)
5688 if (api_user() === false) {
5689 throw new ForbiddenException();
5693 $user_info = api_get_user($a);
5694 $name = $_REQUEST['name'] ?? '';
5695 $uid = $user_info['uid'];
5697 $success = group_create($name, $uid);
5698 if ($success['success']) {
5700 'name' => $success['name'],
5701 'id' => intval($success['gid']),
5702 'id_str' => (string) $success['gid'],
5703 'user' => $user_info
5706 return api_format_data("lists", $type, ['lists'=>$grp]);
5709 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5712 * Update the specified group with the posted array of contacts.
5714 * @param string $type Return type (atom, rss, xml, json)
5716 * @return array|string
5717 * @throws BadRequestException
5718 * @throws ForbiddenException
5719 * @throws ImagickException
5720 * @throws InternalServerErrorException
5721 * @throws UnauthorizedException
5723 function api_friendica_group_update($type)
5727 if (api_user() === false) {
5728 throw new ForbiddenException();
5732 $user_info = api_get_user($a);
5733 $uid = $user_info['uid'];
5734 $gid = $_REQUEST['gid'] ?? 0;
5735 $name = $_REQUEST['name'] ?? '';
5736 $json = json_decode($_POST['json'], true);
5737 $users = $json['user'];
5739 // error if no name specified
5741 throw new BadRequestException('group name not specified');
5744 // error if no gid specified
5746 throw new BadRequestException('gid not specified');
5750 $members = Contact::getByGroupId($gid);
5751 foreach ($members as $member) {
5752 $cid = $member['id'];
5753 foreach ($users as $user) {
5754 $found = ($user['cid'] == $cid ? true : false);
5756 if (!isset($found) || !$found) {
5757 Group::removeMemberByName($uid, $name, $cid);
5762 $erroraddinguser = false;
5764 foreach ($users as $user) {
5765 $cid = $user['cid'];
5766 // check if user really exists as contact
5768 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5773 if (count($contact)) {
5774 Group::addMember($gid, $cid);
5776 $erroraddinguser = true;
5777 $errorusers[] = $cid;
5781 // return success message incl. missing users in array
5782 $status = ($erroraddinguser ? "missing user" : "ok");
5783 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5784 return api_format_data("group_update", $type, ['result' => $success]);
5787 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5790 * Update information about a group.
5792 * @param string $type Return type (atom, rss, xml, json)
5794 * @return array|string
5795 * @throws BadRequestException
5796 * @throws ForbiddenException
5797 * @throws ImagickException
5798 * @throws InternalServerErrorException
5799 * @throws UnauthorizedException
5800 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5802 function api_lists_update($type)
5806 if (api_user() === false) {
5807 throw new ForbiddenException();
5811 $user_info = api_get_user($a);
5812 $gid = $_REQUEST['list_id'] ?? 0;
5813 $name = $_REQUEST['name'] ?? '';
5814 $uid = $user_info['uid'];
5816 // error if no gid specified
5818 throw new BadRequestException('gid not specified');
5821 // get data of the specified group id
5822 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5823 // error message if specified gid is not in database
5825 throw new BadRequestException('gid not available');
5828 if (Group::update($gid, $name)) {
5831 'id' => intval($gid),
5832 'id_str' => (string) $gid,
5833 'user' => $user_info
5836 return api_format_data("lists", $type, ['lists' => $list]);
5840 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5844 * @param string $type Return type (atom, rss, xml, json)
5846 * @return array|string
5847 * @throws BadRequestException
5848 * @throws ForbiddenException
5849 * @throws ImagickException
5850 * @throws InternalServerErrorException
5852 function api_friendica_activity($type)
5856 if (api_user() === false) {
5857 throw new ForbiddenException();
5859 $verb = strtolower($a->argv[3]);
5860 $verb = preg_replace("|\..*$|", "", $verb);
5862 $id = $_REQUEST['id'] ?? 0;
5864 $res = Item::performLike($id, $verb);
5867 if ($type == "xml") {
5872 return api_format_data('ok', $type, ['ok' => $ok]);
5874 throw new BadRequestException('Error adding activity');
5878 /// @TODO move to top of file or somewhere better
5879 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5880 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5881 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5882 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5883 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5884 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5885 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5886 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5887 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5888 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5891 * Returns notifications
5893 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5894 * @return string|array
5895 * @throws BadRequestException
5896 * @throws ForbiddenException
5897 * @throws InternalServerErrorException
5899 function api_friendica_notification($type)
5903 if (api_user() === false) {
5904 throw new ForbiddenException();
5907 throw new BadRequestException("Invalid argument count");
5910 $notifications = DI::notification()->select(['uid' => api_user()], ['order' => ['seen' => 'ASC', 'date' => 'DESC'], 'limit' => 50]);
5912 if ($type == "xml") {
5914 if (!empty($notifications)) {
5915 foreach ($notifications as $notification) {
5916 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5920 $result = $xmlnotes;
5921 } elseif (count($notifications) > 0) {
5922 $result = $notifications->getArrayCopy();
5927 return api_format_data("notes", $type, ['note' => $result]);
5931 * Set notification as seen and returns associated item (if possible)
5933 * POST request with 'id' param as notification id
5935 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5936 * @return string|array
5937 * @throws BadRequestException
5938 * @throws ForbiddenException
5939 * @throws ImagickException
5940 * @throws InternalServerErrorException
5941 * @throws UnauthorizedException
5943 function api_friendica_notification_seen($type)
5946 $user_info = api_get_user($a);
5948 if (api_user() === false || $user_info === false) {
5949 throw new ForbiddenException();
5951 if ($a->argc !== 4) {
5952 throw new BadRequestException("Invalid argument count");
5955 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5958 $notification = DI::notification()->getByID($id);
5959 $notification->setSeen();
5961 if ($notification->otype === Notification::OTYPE_ITEM) {
5962 $item = Item::selectFirstForUser(api_user(), [], ['id' => $notification->iid, 'uid' => api_user()]);
5963 if (DBA::isResult($item)) {
5964 // we found the item, return it to the user
5965 $ret = api_format_items([$item], $user_info, false, $type);
5966 $data = ['status' => $ret];
5967 return api_format_data("status", $type, $data);
5969 // the item can't be found, but we set the notification as seen, so we count this as a success
5971 return api_format_data('result', $type, ['result' => "success"]);
5972 } catch (NotFoundException $e) {
5973 throw new BadRequestException('Invalid argument');
5977 /// @TODO move to top of file or somewhere better
5978 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5979 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5982 * update a direct_message to seen state
5984 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5985 * @return string|array (success result=ok, error result=error with error message)
5986 * @throws BadRequestException
5987 * @throws ForbiddenException
5988 * @throws ImagickException
5989 * @throws InternalServerErrorException
5990 * @throws UnauthorizedException
5992 function api_friendica_direct_messages_setseen($type)
5995 if (api_user() === false) {
5996 throw new ForbiddenException();
6000 $user_info = api_get_user($a);
6001 $uid = $user_info['uid'];
6002 $id = $_REQUEST['id'] ?? 0;
6004 // return error if id is zero
6006 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6007 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6010 // error message if specified id is not in database
6011 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6012 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6013 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6016 // update seen indicator
6017 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6021 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6022 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6024 $answer = ['result' => 'error', 'message' => 'unknown error'];
6025 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6029 /// @TODO move to top of file or somewhere better
6030 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6033 * search for direct_messages containing a searchstring through api
6035 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6036 * @param string $box
6037 * @return string|array (success: success=true if found and search_result contains found messages,
6038 * success=false if nothing was found, search_result='nothing found',
6039 * error: result=error with error message)
6040 * @throws BadRequestException
6041 * @throws ForbiddenException
6042 * @throws ImagickException
6043 * @throws InternalServerErrorException
6044 * @throws UnauthorizedException
6046 function api_friendica_direct_messages_search($type, $box = "")
6050 if (api_user() === false) {
6051 throw new ForbiddenException();
6055 $user_info = api_get_user($a);
6056 $searchstring = $_REQUEST['searchstring'] ?? '';
6057 $uid = $user_info['uid'];
6059 // error if no searchstring specified
6060 if ($searchstring == "") {
6061 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6062 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6065 // get data for the specified searchstring
6067 "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",
6069 DBA::escape('%'.$searchstring.'%')
6072 $profile_url = $user_info["url"];
6074 // message if nothing was found
6075 if (!DBA::isResult($r)) {
6076 $success = ['success' => false, 'search_results' => 'problem with query'];
6077 } elseif (count($r) == 0) {
6078 $success = ['success' => false, 'search_results' => 'nothing found'];
6081 foreach ($r as $item) {
6082 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6083 $recipient = $user_info;
6084 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6085 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6086 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6087 $sender = $user_info;
6090 if (isset($recipient) && isset($sender)) {
6091 $ret[] = api_format_messages($item, $recipient, $sender);
6094 $success = ['success' => true, 'search_results' => $ret];
6097 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6100 /// @TODO move to top of file or somewhere better
6101 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6104 * return data of all the profiles a user has to the client
6106 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6107 * @return string|array
6108 * @throws BadRequestException
6109 * @throws ForbiddenException
6110 * @throws ImagickException
6111 * @throws InternalServerErrorException
6112 * @throws UnauthorizedException
6114 function api_friendica_profile_show($type)
6118 if (api_user() === false) {
6119 throw new ForbiddenException();
6123 $profile_id = $_REQUEST['profile_id'] ?? 0;
6125 // retrieve general information about profiles for user
6126 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6127 $directory = DI::config()->get('system', 'directory');
6129 // get data of the specified profile id or all profiles of the user if not specified
6130 if ($profile_id != 0) {
6131 $r = Profile::getById(api_user(), $profile_id);
6132 // error message if specified gid is not in database
6133 if (!DBA::isResult($r)) {
6134 throw new BadRequestException("profile_id not available");
6137 $r = Profile::getListByUser(api_user());
6139 // loop through all returned profiles and retrieve data and users
6142 if (DBA::isResult($r)) {
6143 foreach ($r as $rr) {
6144 $profile = api_format_items_profiles($rr);
6146 // select all users from contact table, loop and prepare standard return for user data
6148 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6149 foreach ($nurls as $nurl) {
6150 $user = api_get_user($a, $nurl['nurl']);
6151 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6153 $profile['users'] = $users;
6155 // add prepared profile data to array for final return
6156 if ($type == "xml") {
6157 $profiles[$k++ . ":profile"] = $profile;
6159 $profiles[] = $profile;
6164 // return settings, authenticated user and profiles data
6165 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6167 $result = ['multi_profiles' => $multi_profiles ? true : false,
6168 'global_dir' => $directory,
6169 'friendica_owner' => api_get_user($a, $self['nurl']),
6170 'profiles' => $profiles];
6171 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6173 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6176 * Returns a list of saved searches.
6178 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6180 * @param string $type Return format: json or xml
6182 * @return string|array
6185 function api_saved_searches_list($type)
6187 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6190 while ($term = DBA::fetch($terms)) {
6192 'created_at' => api_date(time()),
6193 'id' => intval($term['id']),
6194 'id_str' => $term['id'],
6195 'name' => $term['term'],
6197 'query' => $term['term']
6203 return api_format_data("terms", $type, ['terms' => $result]);
6206 /// @TODO move to top of file or somewhere better
6207 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6210 * Number of comments
6212 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6214 * @param object $data [Status, Status]
6218 function bindComments(&$data)
6220 if (count($data) == 0) {
6226 foreach ($data as $item) {
6227 $ids[] = $item['id'];
6230 $idStr = DBA::escape(implode(', ', $ids));
6231 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6232 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6233 $itemsData = DBA::toArray($items);
6235 foreach ($itemsData as $item) {
6236 $comments[$item['parent']] = $item['comments'];
6239 foreach ($data as $idx => $item) {
6241 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6246 @TODO Maybe open to implement?
6248 [pagename] => api/1.1/statuses/lookup.json
6249 [id] => 605138389168451584
6250 [include_cards] => true
6251 [cards_platform] => Android-12
6252 [include_entities] => true
6253 [include_my_retweet] => 1
6255 [include_reply_count] => true
6256 [include_descendent_reply_count] => true
6260 Not implemented by now:
6261 statuses/retweets_of_me
6266 account/update_location
6267 account/update_profile_background_image
6270 friendica/profile/update
6271 friendica/profile/create
6272 friendica/profile/delete
6274 Not implemented in status.net:
6275 statuses/retweeted_to_me
6276 statuses/retweeted_by_me
6277 direct_messages/destroy
6279 account/update_delivery_device
6280 notifications/follow