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\Notify;
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);
316 if (!empty($info['auth']) && api_user() === false) {
320 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
321 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
323 $stamp = microtime(true);
324 $return = call_user_func($info['func'], $type);
325 $duration = floatval(microtime(true) - $stamp);
327 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
329 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
331 if (false === $return) {
333 * api function returned false withour throw an
334 * exception. This should not happend, throw a 500
336 throw new InternalServerErrorException();
341 header("Content-Type: text/xml");
344 header("Content-Type: application/json");
345 if (!empty($return)) {
346 $json = json_encode(end($return));
347 if (!empty($_GET['callback'])) {
348 $json = $_GET['callback'] . "(" . $json . ")";
354 header("Content-Type: application/rss+xml");
355 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
358 header("Content-Type: application/atom+xml");
359 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
366 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
367 throw new NotImplementedException();
368 } catch (HTTPException $e) {
369 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
370 return api_error($type, $e, $args);
375 * Format API error string
377 * @param string $type Return type (xml, json, rss, as)
378 * @param object $e HTTPException Error object
379 * @param App\Arguments $args The App arguments
380 * @return string|array error message formatted as $type
382 function api_error($type, $e, App\Arguments $args)
384 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
385 /// @TODO: https://dev.twitter.com/overview/api/response-codes
387 $error = ["error" => $error,
388 "code" => $e->getCode() . " " . $e->httpdesc,
389 "request" => $args->getQueryString()];
391 $return = api_format_data('status', $type, ['status' => $error]);
395 header("Content-Type: text/xml");
398 header("Content-Type: application/json");
399 $return = json_encode($return);
402 header("Content-Type: application/rss+xml");
405 header("Content-Type: application/atom+xml");
413 * Set values for RSS template
416 * @param array $arr Array to be passed to template
417 * @param array $user_info User info
419 * @throws BadRequestException
420 * @throws ImagickException
421 * @throws InternalServerErrorException
422 * @throws UnauthorizedException
423 * @todo find proper type-hints
425 function api_rss_extra(App $a, $arr, $user_info)
427 if (is_null($user_info)) {
428 $user_info = api_get_user($a);
431 $arr['$user'] = $user_info;
433 'alternate' => $user_info['url'],
434 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
435 'base' => DI::baseUrl(),
436 'updated' => api_date(null),
437 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
438 'language' => $user_info['lang'],
439 'logo' => DI::baseUrl() . "/images/friendica-32.png",
447 * Unique contact to contact url.
449 * @param int $id Contact id
450 * @return bool|string
451 * Contact url or False if contact id is unknown
454 function api_unique_id_to_nurl($id)
456 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
458 if (DBA::isResult($r)) {
466 * Get user info array.
469 * @param int|string $contact_id Contact ID or URL
471 * @throws BadRequestException
472 * @throws ImagickException
473 * @throws InternalServerErrorException
474 * @throws UnauthorizedException
476 function api_get_user(App $a, $contact_id = null)
484 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
486 // Searching for contact URL
487 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
488 $user = DBA::escape(Strings::normaliseLink($contact_id));
490 $extra_query = "AND `contact`.`nurl` = '%s' ";
491 if (api_user() !== false) {
492 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
496 // Searching for contact id with uid = 0
497 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
498 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
501 throw new BadRequestException("User ID ".$contact_id." not found.");
505 $extra_query = "AND `contact`.`nurl` = '%s' ";
506 if (api_user() !== false) {
507 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
511 if (is_null($user) && !empty($_GET['user_id'])) {
512 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
515 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
519 $extra_query = "AND `contact`.`nurl` = '%s' ";
520 if (api_user() !== false) {
521 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
524 if (is_null($user) && !empty($_GET['screen_name'])) {
525 $user = DBA::escape($_GET['screen_name']);
526 $extra_query = "AND `contact`.`nick` = '%s' ";
527 if (api_user() !== false) {
528 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
532 if (is_null($user) && !empty($_GET['profileurl'])) {
533 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
534 $extra_query = "AND `contact`.`nurl` = '%s' ";
535 if (api_user() !== false) {
536 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
540 // $called_api is the API path exploded on / and is expected to have at least 2 elements
541 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
542 $argid = count($called_api);
543 if (!empty($a->argv[$argid])) {
544 $data = explode(".", $a->argv[$argid]);
545 if (count($data) > 1) {
546 list($user, $null) = $data;
549 if (is_numeric($user)) {
550 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
554 $extra_query = "AND `contact`.`nurl` = '%s' ";
555 if (api_user() !== false) {
556 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
560 $user = DBA::escape($user);
561 $extra_query = "AND `contact`.`nick` = '%s' ";
562 if (api_user() !== false) {
563 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
568 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
571 if (api_user() === false) {
575 $user = $_SESSION['uid'];
576 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
580 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
584 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
590 // Selecting the id by priority, friendica first
591 if (is_array($uinfo)) {
592 api_best_nickname($uinfo);
595 // if the contact wasn't found, fetch it from the contacts with uid = 0
596 if (!DBA::isResult($uinfo)) {
598 throw new BadRequestException("User not found.");
601 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
603 if (DBA::isResult($contact)) {
605 'id' => $contact["id"],
606 'id_str' => (string) $contact["id"],
607 'name' => $contact["name"],
608 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
609 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
610 'description' => BBCode::toPlaintext($contact["about"]),
611 'profile_image_url' => $contact["micro"],
612 'profile_image_url_https' => $contact["micro"],
613 'profile_image_url_profile_size' => $contact["thumb"],
614 'profile_image_url_large' => $contact["photo"],
615 'url' => $contact["url"],
616 'protected' => false,
617 'followers_count' => 0,
618 'friends_count' => 0,
620 'created_at' => api_date($contact["created"]),
621 'favourites_count' => 0,
623 'time_zone' => 'UTC',
624 'geo_enabled' => false,
626 'statuses_count' => 0,
628 'contributors_enabled' => false,
629 'is_translator' => false,
630 'is_translation_enabled' => false,
631 'following' => false,
632 'follow_request_sent' => false,
633 'statusnet_blocking' => false,
634 'notifications' => false,
635 'statusnet_profile_url' => $contact["url"],
637 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
638 'pid' => Contact::getIdForURL($contact["url"], 0, true),
640 'network' => $contact["network"],
645 throw new BadRequestException("User ".$url." not found.");
649 if ($uinfo[0]['self']) {
650 if ($uinfo[0]['network'] == "") {
651 $uinfo[0]['network'] = Protocol::DFRN;
654 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
655 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
662 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
664 if (!empty($profile['about'])) {
665 $description = $profile['about'];
667 $description = $uinfo[0]["about"];
670 if (!empty($usr['default-location'])) {
671 $location = $usr['default-location'];
672 } elseif (!empty($uinfo[0]["location"])) {
673 $location = $uinfo[0]["location"];
675 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
679 'id' => intval($pcontact_id),
680 'id_str' => (string) intval($pcontact_id),
681 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
682 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
683 'location' => $location,
684 'description' => BBCode::toPlaintext($description),
685 'profile_image_url' => $uinfo[0]['micro'],
686 'profile_image_url_https' => $uinfo[0]['micro'],
687 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
688 'profile_image_url_large' => $uinfo[0]["photo"],
689 'url' => $uinfo[0]['url'],
690 'protected' => false,
691 'followers_count' => intval($countfollowers),
692 'friends_count' => intval($countfriends),
694 'created_at' => api_date($uinfo[0]['created']),
695 'favourites_count' => intval($starred),
697 'time_zone' => 'UTC',
698 'geo_enabled' => false,
700 'statuses_count' => intval($countitems),
702 'contributors_enabled' => false,
703 'is_translator' => false,
704 'is_translation_enabled' => false,
705 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
706 'follow_request_sent' => false,
707 'statusnet_blocking' => false,
708 'notifications' => false,
710 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
711 'statusnet_profile_url' => $uinfo[0]['url'],
712 'uid' => intval($uinfo[0]['uid']),
713 'cid' => intval($uinfo[0]['cid']),
714 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
715 'self' => $uinfo[0]['self'],
716 'network' => $uinfo[0]['network'],
719 // If this is a local user and it uses Frio, we can get its color preferences.
721 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
722 if ($theme_info['theme'] === 'frio') {
723 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
725 if ($schema && ($schema != '---')) {
726 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
727 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
728 require_once $schemefile;
731 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
732 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
733 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
735 if (empty($nav_bg)) {
738 if (empty($link_color)) {
739 $link_color = "#6fdbe8";
741 if (empty($bgcolor)) {
742 $bgcolor = "#ededed";
745 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
746 $ret['profile_link_color'] = str_replace('#', '', $link_color);
747 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
755 * return api-formatted array for item's author and owner
758 * @param array $item item from db
759 * @return array(array:author, array:owner)
760 * @throws BadRequestException
761 * @throws ImagickException
762 * @throws InternalServerErrorException
763 * @throws UnauthorizedException
765 function api_item_get_user(App $a, $item)
767 $status_user = api_get_user($a, $item['author-id'] ?? null);
769 $author_user = $status_user;
771 $status_user["protected"] = $item['private'] ?? 0;
773 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
774 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
776 $owner_user = $author_user;
779 return ([$status_user, $author_user, $owner_user]);
783 * walks recursively through an array with the possibility to change value and key
785 * @param array $array The array to walk through
786 * @param callable $callback The callback function
788 * @return array the transformed array
790 function api_walk_recursive(array &$array, callable $callback)
794 foreach ($array as $k => $v) {
796 if ($callback($v, $k)) {
797 $new_array[$k] = api_walk_recursive($v, $callback);
800 if ($callback($v, $k)) {
811 * Callback function to transform the array in an array that can be transformed in a XML file
813 * @param mixed $item Array item value
814 * @param string $key Array key
816 * @return boolean Should the array item be deleted?
818 function api_reformat_xml(&$item, &$key)
820 if (is_bool($item)) {
821 $item = ($item ? "true" : "false");
824 if (substr($key, 0, 10) == "statusnet_") {
825 $key = "statusnet:".substr($key, 10);
826 } elseif (substr($key, 0, 10) == "friendica_") {
827 $key = "friendica:".substr($key, 10);
829 /// @TODO old-lost code?
831 // $key = "default:".$key;
837 * Creates the XML from a JSON style array
839 * @param array $data JSON style array
840 * @param string $root_element Name of the root element
842 * @return string The XML data
844 function api_create_xml(array $data, $root_element)
846 $childname = key($data);
847 $data2 = array_pop($data);
849 $namespaces = ["" => "http://api.twitter.com",
850 "statusnet" => "http://status.net/schema/api/1/",
851 "friendica" => "http://friendi.ca/schema/api/1/",
852 "georss" => "http://www.georss.org/georss"];
854 /// @todo Auto detection of needed namespaces
855 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
859 if (is_array($data2)) {
861 api_walk_recursive($data2, "api_reformat_xml");
867 foreach ($data2 as $item) {
868 $data4[$i++ . ":" . $childname] = $item;
875 $data3 = [$root_element => $data2];
877 $ret = XML::fromArray($data3, $xml, false, $namespaces);
882 * Formats the data according to the data type
884 * @param string $root_element Name of the root element
885 * @param string $type Return type (atom, rss, xml, json)
886 * @param array $data JSON style array
888 * @return array|string (string|array) XML data or JSON data
890 function api_format_data($root_element, $type, $data)
896 $ret = api_create_xml($data, $root_element);
911 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
912 * returns a 401 status code and an error message if not.
914 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
916 * @param string $type Return type (atom, rss, xml, json)
917 * @return array|string
918 * @throws BadRequestException
919 * @throws ForbiddenException
920 * @throws ImagickException
921 * @throws InternalServerErrorException
922 * @throws UnauthorizedException
924 function api_account_verify_credentials($type)
928 if (api_user() === false) {
929 throw new ForbiddenException();
932 unset($_REQUEST["user_id"]);
933 unset($_GET["user_id"]);
935 unset($_REQUEST["screen_name"]);
936 unset($_GET["screen_name"]);
938 $skip_status = $_REQUEST['skip_status'] ?? false;
940 $user_info = api_get_user($a);
942 // "verified" isn't used here in the standard
943 unset($user_info["verified"]);
945 // - Adding last status
947 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
949 $user_info['status'] = api_format_item($item, $type);
953 // "uid" and "self" are only needed for some internal stuff, so remove it from here
954 unset($user_info["uid"]);
955 unset($user_info["self"]);
957 return api_format_data("user", $type, ['user' => $user_info]);
960 /// @TODO move to top of file or somewhere better
961 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
964 * Get data from $_POST or $_GET
969 function requestdata($k)
971 if (!empty($_POST[$k])) {
974 if (!empty($_GET[$k])) {
981 * Deprecated function to upload media.
983 * @param string $type Return type (atom, rss, xml, json)
985 * @return array|string
986 * @throws BadRequestException
987 * @throws ForbiddenException
988 * @throws ImagickException
989 * @throws InternalServerErrorException
990 * @throws UnauthorizedException
992 function api_statuses_mediap($type)
996 if (api_user() === false) {
997 Logger::log('api_statuses_update: no user');
998 throw new ForbiddenException();
1000 $user_info = api_get_user($a);
1002 $_REQUEST['profile_uid'] = api_user();
1003 $_REQUEST['api_source'] = true;
1004 $txt = requestdata('status');
1005 /// @TODO old-lost code?
1006 //$txt = urldecode(requestdata('status'));
1008 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1009 $txt = HTML::toBBCodeVideo($txt);
1010 $config = HTMLPurifier_Config::createDefault();
1011 $config->set('Cache.DefinitionImpl', null);
1012 $purifier = new HTMLPurifier($config);
1013 $txt = $purifier->purify($txt);
1015 $txt = HTML::toBBCode($txt);
1017 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1019 $picture = wall_upload_post($a, false);
1021 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1022 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1023 $item_id = item_post($a);
1025 // output the post that we just posted.
1026 return api_status_show($type, $item_id);
1029 /// @TODO move this to top of file or somewhere better!
1030 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1033 * Updates the user’s current status.
1035 * @param string $type Return type (atom, rss, xml, json)
1037 * @return array|string
1038 * @throws BadRequestException
1039 * @throws ForbiddenException
1040 * @throws ImagickException
1041 * @throws InternalServerErrorException
1042 * @throws TooManyRequestsException
1043 * @throws UnauthorizedException
1044 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1046 function api_statuses_update($type)
1050 if (api_user() === false) {
1051 Logger::log('api_statuses_update: no user');
1052 throw new ForbiddenException();
1057 // convert $_POST array items to the form we use for web posts.
1058 if (requestdata('htmlstatus')) {
1059 $txt = requestdata('htmlstatus');
1060 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1061 $txt = HTML::toBBCodeVideo($txt);
1063 $config = HTMLPurifier_Config::createDefault();
1064 $config->set('Cache.DefinitionImpl', null);
1066 $purifier = new HTMLPurifier($config);
1067 $txt = $purifier->purify($txt);
1069 $_REQUEST['body'] = HTML::toBBCode($txt);
1072 $_REQUEST['body'] = requestdata('status');
1075 $_REQUEST['title'] = requestdata('title');
1077 $parent = requestdata('in_reply_to_status_id');
1079 // Twidere sends "-1" if it is no reply ...
1080 if ($parent == -1) {
1084 if (ctype_digit($parent)) {
1085 $_REQUEST['parent'] = $parent;
1087 $_REQUEST['parent_uri'] = $parent;
1090 if (requestdata('lat') && requestdata('long')) {
1091 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1093 $_REQUEST['profile_uid'] = api_user();
1096 // Check for throttling (maximum posts per day, week and month)
1097 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1098 if ($throttle_day > 0) {
1099 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1101 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1102 $posts_day = DBA::count('thread', $condition);
1104 if ($posts_day > $throttle_day) {
1105 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1106 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1107 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));
1111 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1112 if ($throttle_week > 0) {
1113 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1115 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1116 $posts_week = DBA::count('thread', $condition);
1118 if ($posts_week > $throttle_week) {
1119 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1120 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1121 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));
1125 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1126 if ($throttle_month > 0) {
1127 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1129 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1130 $posts_month = DBA::count('thread', $condition);
1132 if ($posts_month > $throttle_month) {
1133 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1134 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1135 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));
1140 if (!empty($_FILES['media'])) {
1141 // upload the image if we have one
1142 $picture = wall_upload_post($a, false);
1143 if (is_array($picture)) {
1144 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1148 if (requestdata('media_ids')) {
1149 $ids = explode(',', requestdata('media_ids'));
1150 foreach ($ids as $id) {
1152 "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",
1156 if (DBA::isResult($r)) {
1157 $phototypes = Images::supportedTypes();
1158 $ext = $phototypes[$r[0]['type']];
1159 $description = $r[0]['desc'] ?? '';
1160 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1161 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1166 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1168 $_REQUEST['api_source'] = true;
1170 if (empty($_REQUEST['source'])) {
1171 $_REQUEST["source"] = api_source();
1174 // call out normal post function
1175 $item_id = item_post($a);
1177 // output the post that we just posted.
1178 return api_status_show($type, $item_id);
1181 /// @TODO move to top of file or somewhere better
1182 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1183 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1186 * Uploads an image to Friendica.
1189 * @throws BadRequestException
1190 * @throws ForbiddenException
1191 * @throws ImagickException
1192 * @throws InternalServerErrorException
1193 * @throws UnauthorizedException
1194 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1196 function api_media_upload()
1200 if (api_user() === false) {
1201 Logger::log('no user');
1202 throw new ForbiddenException();
1207 if (empty($_FILES['media'])) {
1209 throw new BadRequestException("No media.");
1212 $media = wall_upload_post($a, false);
1215 throw new InternalServerErrorException();
1219 $returndata["media_id"] = $media["id"];
1220 $returndata["media_id_string"] = (string)$media["id"];
1221 $returndata["size"] = $media["size"];
1222 $returndata["image"] = ["w" => $media["width"],
1223 "h" => $media["height"],
1224 "image_type" => $media["type"],
1225 "friendica_preview_url" => $media["preview"]];
1227 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1229 return ["media" => $returndata];
1232 /// @TODO move to top of file or somewhere better
1233 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1236 * Updates media meta data (picture descriptions)
1238 * @param string $type Return type (atom, rss, xml, json)
1240 * @return array|string
1241 * @throws BadRequestException
1242 * @throws ForbiddenException
1243 * @throws ImagickException
1244 * @throws InternalServerErrorException
1245 * @throws TooManyRequestsException
1246 * @throws UnauthorizedException
1247 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1249 * @todo Compare the corresponding Twitter function for correct return values
1251 function api_media_metadata_create($type)
1255 if (api_user() === false) {
1256 Logger::info('no user');
1257 throw new ForbiddenException();
1262 $postdata = Network::postdata();
1264 if (empty($postdata)) {
1265 throw new BadRequestException("No post data");
1268 $data = json_decode($postdata, true);
1270 throw new BadRequestException("Invalid post data");
1273 if (empty($data['media_id']) || empty($data['alt_text'])) {
1274 throw new BadRequestException("Missing post data values");
1277 if (empty($data['alt_text']['text'])) {
1278 throw new BadRequestException("No alt text.");
1281 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1283 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1284 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1285 if (!DBA::isResult($photo)) {
1286 throw new BadRequestException("Metadata not found.");
1289 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1292 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1295 * @param string $type Return format (atom, rss, xml, json)
1296 * @param int $item_id
1300 function api_status_show($type, $item_id)
1302 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1306 $item = api_get_item(['id' => $item_id]);
1307 if (!empty($item)) {
1308 $status_info = api_format_item($item, $type);
1311 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1313 return api_format_data('statuses', $type, ['status' => $status_info]);
1317 * Retrieves the last public status of the provided user info
1319 * @param int $ownerId Public contact Id
1320 * @param int $uid User Id
1324 function api_get_last_status($ownerId, $uid)
1327 'author-id'=> $ownerId,
1329 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1333 $item = api_get_item($condition);
1339 * Retrieves a single item record based on the provided condition and converts it for API use.
1341 * @param array $condition Item table condition array
1345 function api_get_item(array $condition)
1347 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1353 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1354 * The author's most recent status will be returned inline.
1356 * @param string $type Return type (atom, rss, xml, json)
1357 * @return array|string
1358 * @throws BadRequestException
1359 * @throws ImagickException
1360 * @throws InternalServerErrorException
1361 * @throws UnauthorizedException
1362 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1364 function api_users_show($type)
1366 $a = Friendica\DI::app();
1368 $user_info = api_get_user($a);
1370 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1371 if (!empty($item)) {
1372 $user_info['status'] = api_format_item($item, $type);
1375 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1376 unset($user_info['uid']);
1377 unset($user_info['self']);
1379 return api_format_data('user', $type, ['user' => $user_info]);
1382 /// @TODO move to top of file or somewhere better
1383 api_register_func('api/users/show', 'api_users_show');
1384 api_register_func('api/externalprofile/show', 'api_users_show');
1387 * Search a public user account.
1389 * @param string $type Return type (atom, rss, xml, json)
1391 * @return array|string
1392 * @throws BadRequestException
1393 * @throws ImagickException
1394 * @throws InternalServerErrorException
1395 * @throws UnauthorizedException
1396 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1398 function api_users_search($type)
1404 if (!empty($_GET['q'])) {
1405 $contacts = Contact::selectToArray(
1408 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1416 if (DBA::isResult($contacts)) {
1418 foreach ($contacts as $contact) {
1419 $user_info = api_get_user($a, $contact['id']);
1421 if ($type == 'xml') {
1422 $userlist[$k++ . ':user'] = $user_info;
1424 $userlist[] = $user_info;
1427 $userlist = ['users' => $userlist];
1429 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1432 throw new BadRequestException('No search term specified.');
1435 return api_format_data('users', $type, $userlist);
1438 /// @TODO move to top of file or somewhere better
1439 api_register_func('api/users/search', 'api_users_search');
1442 * Return user objects
1444 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1446 * @param string $type Return format: json or xml
1448 * @return array|string
1449 * @throws BadRequestException
1450 * @throws ImagickException
1451 * @throws InternalServerErrorException
1452 * @throws NotFoundException if the results are empty.
1453 * @throws UnauthorizedException
1455 function api_users_lookup($type)
1459 if (!empty($_REQUEST['user_id'])) {
1460 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1462 $users[] = api_get_user(DI::app(), $id);
1467 if (empty($users)) {
1468 throw new NotFoundException;
1471 return api_format_data("users", $type, ['users' => $users]);
1474 /// @TODO move to top of file or somewhere better
1475 api_register_func('api/users/lookup', 'api_users_lookup', true);
1478 * Returns statuses that match a specified query.
1480 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1482 * @param string $type Return format: json, xml, atom, rss
1484 * @return array|string
1485 * @throws BadRequestException if the "q" parameter is missing.
1486 * @throws ForbiddenException
1487 * @throws ImagickException
1488 * @throws InternalServerErrorException
1489 * @throws UnauthorizedException
1491 function api_search($type)
1494 $user_info = api_get_user($a);
1496 if (api_user() === false || $user_info === false) {
1497 throw new ForbiddenException();
1500 if (empty($_REQUEST['q'])) {
1501 throw new BadRequestException('q parameter is required.');
1504 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1507 $data['status'] = [];
1509 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1510 if (!empty($_REQUEST['rpp'])) {
1511 $count = $_REQUEST['rpp'];
1512 } elseif (!empty($_REQUEST['count'])) {
1513 $count = $_REQUEST['count'];
1516 $since_id = $_REQUEST['since_id'] ?? 0;
1517 $max_id = $_REQUEST['max_id'] ?? 0;
1518 $page = $_REQUEST['page'] ?? 1;
1520 $start = max(0, ($page - 1) * $count);
1522 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1523 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1524 $searchTerm = $matches[1];
1525 $condition = ["`oid` > ?
1526 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1527 AND `otype` = ? AND `type` = ? AND `term` = ?",
1528 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1530 $condition[0] .= ' AND `oid` <= ?';
1531 $condition[] = $max_id;
1533 $terms = DBA::select('term', ['oid'], $condition, []);
1535 while ($term = DBA::fetch($terms)) {
1536 $itemIds[] = $term['oid'];
1540 if (empty($itemIds)) {
1541 return api_format_data('statuses', $type, $data);
1544 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1545 if ($exclude_replies) {
1546 $preCondition[] = '`id` = `parent`';
1549 $condition = [implode(' AND ', $preCondition)];
1551 $condition = ["`id` > ?
1552 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1553 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1554 AND `body` LIKE CONCAT('%',?,'%')",
1555 $since_id, api_user(), $_REQUEST['q']];
1557 $condition[0] .= ' AND `id` <= ?';
1558 $condition[] = $max_id;
1564 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1565 $id = Item::fetchByLink($searchTerm, api_user());
1568 $id = Item::fetchByLink($searchTerm);
1572 $statuses = Item::select([], ['id' => $id]);
1576 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1578 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1580 bindComments($data['status']);
1582 return api_format_data('statuses', $type, $data);
1585 /// @TODO move to top of file or somewhere better
1586 api_register_func('api/search/tweets', 'api_search', true);
1587 api_register_func('api/search', 'api_search', true);
1590 * Returns the most recent statuses posted by the user and the users they follow.
1592 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1594 * @param string $type Return type (atom, rss, xml, json)
1596 * @return array|string
1597 * @throws BadRequestException
1598 * @throws ForbiddenException
1599 * @throws ImagickException
1600 * @throws InternalServerErrorException
1601 * @throws UnauthorizedException
1602 * @todo Optional parameters
1603 * @todo Add reply info
1605 function api_statuses_home_timeline($type)
1608 $user_info = api_get_user($a);
1610 if (api_user() === false || $user_info === false) {
1611 throw new ForbiddenException();
1614 unset($_REQUEST["user_id"]);
1615 unset($_GET["user_id"]);
1617 unset($_REQUEST["screen_name"]);
1618 unset($_GET["screen_name"]);
1620 // get last network messages
1623 $count = $_REQUEST['count'] ?? 20;
1624 $page = $_REQUEST['page']?? 0;
1625 $since_id = $_REQUEST['since_id'] ?? 0;
1626 $max_id = $_REQUEST['max_id'] ?? 0;
1627 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1628 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1630 $start = max(0, ($page - 1) * $count);
1632 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1633 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1636 $condition[0] .= " AND `item`.`id` <= ?";
1637 $condition[] = $max_id;
1639 if ($exclude_replies) {
1640 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1642 if ($conversation_id > 0) {
1643 $condition[0] .= " AND `item`.`parent` = ?";
1644 $condition[] = $conversation_id;
1647 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1648 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1650 $items = Item::inArray($statuses);
1652 $ret = api_format_items($items, $user_info, false, $type);
1654 // Set all posts from the query above to seen
1656 foreach ($items as $item) {
1657 $idarray[] = intval($item["id"]);
1660 if (!empty($idarray)) {
1661 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1663 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1669 $data = ['status' => $ret];
1674 $data = api_rss_extra($a, $data, $user_info);
1678 return api_format_data("statuses", $type, $data);
1682 /// @TODO move to top of file or somewhere better
1683 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1684 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1687 * Returns the most recent statuses from public users.
1689 * @param string $type Return type (atom, rss, xml, json)
1691 * @return array|string
1692 * @throws BadRequestException
1693 * @throws ForbiddenException
1694 * @throws ImagickException
1695 * @throws InternalServerErrorException
1696 * @throws UnauthorizedException
1698 function api_statuses_public_timeline($type)
1701 $user_info = api_get_user($a);
1703 if (api_user() === false || $user_info === false) {
1704 throw new ForbiddenException();
1707 // get last network messages
1710 $count = $_REQUEST['count'] ?? 20;
1711 $page = $_REQUEST['page'] ?? 1;
1712 $since_id = $_REQUEST['since_id'] ?? 0;
1713 $max_id = $_REQUEST['max_id'] ?? 0;
1714 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1715 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1717 $start = max(0, ($page - 1) * $count);
1719 if ($exclude_replies && !$conversation_id) {
1720 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1721 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1724 $condition[0] .= " AND `thread`.`iid` <= ?";
1725 $condition[] = $max_id;
1728 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1729 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1731 $r = Item::inArray($statuses);
1733 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1734 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1737 $condition[0] .= " AND `item`.`id` <= ?";
1738 $condition[] = $max_id;
1740 if ($conversation_id > 0) {
1741 $condition[0] .= " AND `item`.`parent` = ?";
1742 $condition[] = $conversation_id;
1745 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1746 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1748 $r = Item::inArray($statuses);
1751 $ret = api_format_items($r, $user_info, false, $type);
1755 $data = ['status' => $ret];
1760 $data = api_rss_extra($a, $data, $user_info);
1764 return api_format_data("statuses", $type, $data);
1767 /// @TODO move to top of file or somewhere better
1768 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1771 * Returns the most recent statuses posted by users this node knows about.
1773 * @param string $type Return format: json, xml, atom, rss
1774 * @return array|string
1775 * @throws BadRequestException
1776 * @throws ForbiddenException
1777 * @throws ImagickException
1778 * @throws InternalServerErrorException
1779 * @throws UnauthorizedException
1781 function api_statuses_networkpublic_timeline($type)
1784 $user_info = api_get_user($a);
1786 if (api_user() === false || $user_info === false) {
1787 throw new ForbiddenException();
1790 $since_id = $_REQUEST['since_id'] ?? 0;
1791 $max_id = $_REQUEST['max_id'] ?? 0;
1794 $count = $_REQUEST['count'] ?? 20;
1795 $page = $_REQUEST['page'] ?? 1;
1797 $start = max(0, ($page - 1) * $count);
1799 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1800 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1803 $condition[0] .= " AND `thread`.`iid` <= ?";
1804 $condition[] = $max_id;
1807 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1808 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1810 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1814 $data = ['status' => $ret];
1819 $data = api_rss_extra($a, $data, $user_info);
1823 return api_format_data("statuses", $type, $data);
1826 /// @TODO move to top of file or somewhere better
1827 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1830 * Returns a single status.
1832 * @param string $type Return type (atom, rss, xml, json)
1834 * @return array|string
1835 * @throws BadRequestException
1836 * @throws ForbiddenException
1837 * @throws ImagickException
1838 * @throws InternalServerErrorException
1839 * @throws UnauthorizedException
1840 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1842 function api_statuses_show($type)
1845 $user_info = api_get_user($a);
1847 if (api_user() === false || $user_info === false) {
1848 throw new ForbiddenException();
1852 $id = intval($a->argv[3] ?? 0);
1855 $id = intval($_REQUEST['id'] ?? 0);
1860 $id = intval($a->argv[4] ?? 0);
1863 Logger::log('API: api_statuses_show: ' . $id);
1865 $conversation = !empty($_REQUEST['conversation']);
1867 // try to fetch the item for the local user - or the public item, if there is no local one
1868 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1869 if (!DBA::isResult($uri_item)) {
1870 throw new BadRequestException("There is no status with this id.");
1873 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1874 if (!DBA::isResult($item)) {
1875 throw new BadRequestException("There is no status with this id.");
1880 if ($conversation) {
1881 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1882 $params = ['order' => ['id' => true]];
1884 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1888 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1890 /// @TODO How about copying this to above methods which don't check $r ?
1891 if (!DBA::isResult($statuses)) {
1892 throw new BadRequestException("There is no status with this id.");
1895 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1897 if ($conversation) {
1898 $data = ['status' => $ret];
1899 return api_format_data("statuses", $type, $data);
1901 $data = ['status' => $ret[0]];
1902 return api_format_data("status", $type, $data);
1906 /// @TODO move to top of file or somewhere better
1907 api_register_func('api/statuses/show', 'api_statuses_show', true);
1911 * @param string $type Return type (atom, rss, xml, json)
1913 * @return array|string
1914 * @throws BadRequestException
1915 * @throws ForbiddenException
1916 * @throws ImagickException
1917 * @throws InternalServerErrorException
1918 * @throws UnauthorizedException
1919 * @todo nothing to say?
1921 function api_conversation_show($type)
1924 $user_info = api_get_user($a);
1926 if (api_user() === false || $user_info === false) {
1927 throw new ForbiddenException();
1931 $id = intval($a->argv[3] ?? 0);
1932 $since_id = intval($_REQUEST['since_id'] ?? 0);
1933 $max_id = intval($_REQUEST['max_id'] ?? 0);
1934 $count = intval($_REQUEST['count'] ?? 20);
1935 $page = intval($_REQUEST['page'] ?? 1);
1937 $start = max(0, ($page - 1) * $count);
1940 $id = intval($_REQUEST['id'] ?? 0);
1945 $id = intval($a->argv[4] ?? 0);
1948 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1950 // try to fetch the item for the local user - or the public item, if there is no local one
1951 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1952 if (!DBA::isResult($item)) {
1953 throw new BadRequestException("There is no status with this id.");
1956 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1957 if (!DBA::isResult($parent)) {
1958 throw new BadRequestException("There is no status with this id.");
1961 $id = $parent['id'];
1963 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1964 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1967 $condition[0] .= " AND `item`.`id` <= ?";
1968 $condition[] = $max_id;
1971 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1972 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1974 if (!DBA::isResult($statuses)) {
1975 throw new BadRequestException("There is no status with id $id.");
1978 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1980 $data = ['status' => $ret];
1981 return api_format_data("statuses", $type, $data);
1984 /// @TODO move to top of file or somewhere better
1985 api_register_func('api/conversation/show', 'api_conversation_show', true);
1986 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1991 * @param string $type Return type (atom, rss, xml, json)
1993 * @return array|string
1994 * @throws BadRequestException
1995 * @throws ForbiddenException
1996 * @throws ImagickException
1997 * @throws InternalServerErrorException
1998 * @throws UnauthorizedException
1999 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2001 function api_statuses_repeat($type)
2007 if (api_user() === false) {
2008 throw new ForbiddenException();
2014 $id = intval($a->argv[3] ?? 0);
2017 $id = intval($_REQUEST['id'] ?? 0);
2022 $id = intval($a->argv[4] ?? 0);
2025 Logger::log('API: api_statuses_repeat: '.$id);
2027 $fields = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2028 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2030 if (DBA::isResult($item) && $item['body'] != "") {
2031 if (strpos($item['body'], "[/share]") !== false) {
2032 $pos = strpos($item['body'], "[share");
2033 $post = substr($item['body'], $pos);
2035 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2037 if (!empty($item['title'])) {
2038 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2041 $post .= $item['body'];
2042 $post .= "[/share]";
2044 $_REQUEST['body'] = $post;
2045 $_REQUEST['tag'] = $item['tag'];
2046 $_REQUEST['attach'] = $item['attach'];
2047 $_REQUEST['profile_uid'] = api_user();
2048 $_REQUEST['api_source'] = true;
2050 if (empty($_REQUEST['source'])) {
2051 $_REQUEST["source"] = api_source();
2054 $item_id = item_post($a);
2056 throw new ForbiddenException();
2059 // output the post that we just posted.
2061 return api_status_show($type, $item_id);
2064 /// @TODO move to top of file or somewhere better
2065 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2068 * Destroys a specific status.
2070 * @param string $type Return type (atom, rss, xml, json)
2072 * @return array|string
2073 * @throws BadRequestException
2074 * @throws ForbiddenException
2075 * @throws ImagickException
2076 * @throws InternalServerErrorException
2077 * @throws UnauthorizedException
2078 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2080 function api_statuses_destroy($type)
2084 if (api_user() === false) {
2085 throw new ForbiddenException();
2091 $id = intval($a->argv[3] ?? 0);
2094 $id = intval($_REQUEST['id'] ?? 0);
2099 $id = intval($a->argv[4] ?? 0);
2102 Logger::log('API: api_statuses_destroy: '.$id);
2104 $ret = api_statuses_show($type);
2106 Item::deleteForUser(['id' => $id], api_user());
2111 /// @TODO move to top of file or somewhere better
2112 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2115 * Returns the most recent mentions.
2117 * @param string $type Return type (atom, rss, xml, json)
2119 * @return array|string
2120 * @throws BadRequestException
2121 * @throws ForbiddenException
2122 * @throws ImagickException
2123 * @throws InternalServerErrorException
2124 * @throws UnauthorizedException
2125 * @see http://developer.twitter.com/doc/get/statuses/mentions
2127 function api_statuses_mentions($type)
2130 $user_info = api_get_user($a);
2132 if (api_user() === false || $user_info === false) {
2133 throw new ForbiddenException();
2136 unset($_REQUEST["user_id"]);
2137 unset($_GET["user_id"]);
2139 unset($_REQUEST["screen_name"]);
2140 unset($_GET["screen_name"]);
2142 // get last network messages
2145 $since_id = $_REQUEST['since_id'] ?? 0;
2146 $max_id = $_REQUEST['max_id'] ?? 0;
2147 $count = $_REQUEST['count'] ?? 20;
2148 $page = $_REQUEST['page'] ?? 1;
2150 $start = max(0, ($page - 1) * $count);
2152 $query = "SELECT `item`.`id` FROM `user-item`
2153 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2154 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2155 `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2156 AND `user-item`.`iid` > ?";
2157 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2158 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2159 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
2160 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2164 $query .= " AND `item`.`id` <= ?";
2165 $condition[] = $max_id;
2168 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2169 $condition[] = $start;
2170 $condition[] = $count;
2172 $useritems = DBA::p($query, $condition);
2174 while ($useritem = DBA::fetch($useritems)) {
2175 $itemids[] = $useritem['id'];
2177 DBA::close($useritems);
2179 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2180 $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2182 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2184 $data = ['status' => $ret];
2189 $data = api_rss_extra($a, $data, $user_info);
2193 return api_format_data("statuses", $type, $data);
2196 /// @TODO move to top of file or somewhere better
2197 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2198 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2201 * Returns the most recent statuses posted by the user.
2203 * @param string $type Either "json" or "xml"
2204 * @return string|array
2205 * @throws BadRequestException
2206 * @throws ForbiddenException
2207 * @throws ImagickException
2208 * @throws InternalServerErrorException
2209 * @throws UnauthorizedException
2210 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2212 function api_statuses_user_timeline($type)
2215 $user_info = api_get_user($a);
2217 if (api_user() === false || $user_info === false) {
2218 throw new ForbiddenException();
2222 "api_statuses_user_timeline: api_user: ". api_user() .
2223 "\nuser_info: ".print_r($user_info, true) .
2224 "\n_REQUEST: ".print_r($_REQUEST, true),
2228 $since_id = $_REQUEST['since_id'] ?? 0;
2229 $max_id = $_REQUEST['max_id'] ?? 0;
2230 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2231 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2234 $count = $_REQUEST['count'] ?? 20;
2235 $page = $_REQUEST['page'] ?? 1;
2237 $start = max(0, ($page - 1) * $count);
2239 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2240 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2242 if ($user_info['self'] == 1) {
2243 $condition[0] .= ' AND `item`.`wall` ';
2246 if ($exclude_replies) {
2247 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2250 if ($conversation_id > 0) {
2251 $condition[0] .= " AND `item`.`parent` = ?";
2252 $condition[] = $conversation_id;
2256 $condition[0] .= " AND `item`.`id` <= ?";
2257 $condition[] = $max_id;
2260 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2261 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2263 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2267 $data = ['status' => $ret];
2272 $data = api_rss_extra($a, $data, $user_info);
2276 return api_format_data("statuses", $type, $data);
2279 /// @TODO move to top of file or somewhere better
2280 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2283 * Star/unstar an item.
2284 * param: id : id of the item
2286 * @param string $type Return type (atom, rss, xml, json)
2288 * @return array|string
2289 * @throws BadRequestException
2290 * @throws ForbiddenException
2291 * @throws ImagickException
2292 * @throws InternalServerErrorException
2293 * @throws UnauthorizedException
2294 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2296 function api_favorites_create_destroy($type)
2300 if (api_user() === false) {
2301 throw new ForbiddenException();
2304 // for versioned api.
2305 /// @TODO We need a better global soluton
2306 $action_argv_id = 2;
2307 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2308 $action_argv_id = 3;
2311 if ($a->argc <= $action_argv_id) {
2312 throw new BadRequestException("Invalid request.");
2314 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2315 if ($a->argc == $action_argv_id + 2) {
2316 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2318 $itemid = intval($_REQUEST['id'] ?? 0);
2321 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2323 if (!DBA::isResult($item)) {
2324 throw new BadRequestException("Invalid item.");
2329 $item['starred'] = 1;
2332 $item['starred'] = 0;
2335 throw new BadRequestException("Invalid action ".$action);
2338 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2341 throw new InternalServerErrorException("DB error");
2345 $user_info = api_get_user($a);
2346 $rets = api_format_items([$item], $user_info, false, $type);
2349 $data = ['status' => $ret];
2354 $data = api_rss_extra($a, $data, $user_info);
2358 return api_format_data("status", $type, $data);
2361 /// @TODO move to top of file or somewhere better
2362 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2363 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2366 * Returns the most recent favorite statuses.
2368 * @param string $type Return type (atom, rss, xml, json)
2370 * @return string|array
2371 * @throws BadRequestException
2372 * @throws ForbiddenException
2373 * @throws ImagickException
2374 * @throws InternalServerErrorException
2375 * @throws UnauthorizedException
2377 function api_favorites($type)
2382 $user_info = api_get_user($a);
2384 if (api_user() === false || $user_info === false) {
2385 throw new ForbiddenException();
2390 // in friendica starred item are private
2391 // return favorites only for self
2392 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2394 if ($user_info['self'] == 0) {
2398 $since_id = $_REQUEST['since_id'] ?? 0;
2399 $max_id = $_REQUEST['max_id'] ?? 0;
2400 $count = $_GET['count'] ?? 20;
2401 $page = $_REQUEST['page'] ?? 1;
2403 $start = max(0, ($page - 1) * $count);
2405 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2406 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2408 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2411 $condition[0] .= " AND `item`.`id` <= ?";
2412 $condition[] = $max_id;
2415 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2417 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2422 $data = ['status' => $ret];
2427 $data = api_rss_extra($a, $data, $user_info);
2431 return api_format_data("statuses", $type, $data);
2434 /// @TODO move to top of file or somewhere better
2435 api_register_func('api/favorites', 'api_favorites', true);
2439 * @param array $item
2440 * @param array $recipient
2441 * @param array $sender
2444 * @throws InternalServerErrorException
2446 function api_format_messages($item, $recipient, $sender)
2448 // standard meta information
2450 'id' => $item['id'],
2451 'sender_id' => $sender['id'],
2453 'recipient_id' => $recipient['id'],
2454 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2455 'sender_screen_name' => $sender['screen_name'],
2456 'recipient_screen_name' => $recipient['screen_name'],
2457 'sender' => $sender,
2458 'recipient' => $recipient,
2460 'friendica_seen' => $item['seen'] ?? 0,
2461 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2464 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2465 if (isset($ret['sender']['uid'])) {
2466 unset($ret['sender']['uid']);
2468 if (isset($ret['sender']['self'])) {
2469 unset($ret['sender']['self']);
2471 if (isset($ret['recipient']['uid'])) {
2472 unset($ret['recipient']['uid']);
2474 if (isset($ret['recipient']['self'])) {
2475 unset($ret['recipient']['self']);
2478 //don't send title to regular StatusNET requests to avoid confusing these apps
2479 if (!empty($_GET['getText'])) {
2480 $ret['title'] = $item['title'];
2481 if ($_GET['getText'] == 'html') {
2482 $ret['text'] = BBCode::convert($item['body'], false);
2483 } elseif ($_GET['getText'] == 'plain') {
2484 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2487 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2489 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2490 unset($ret['sender']);
2491 unset($ret['recipient']);
2499 * @param array $item
2502 * @throws InternalServerErrorException
2504 function api_convert_item($item)
2506 $body = $item['body'];
2507 $entities = api_get_entitities($statustext, $body);
2509 // Add pictures to the attachment array and remove them from the body
2510 $attachments = api_get_attachments($body);
2512 // Workaround for ostatus messages where the title is identically to the body
2513 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2514 $statusbody = trim(HTML::toPlaintext($html, 0));
2516 // handle data: images
2517 $statusbody = api_format_items_embeded_images($item, $statusbody);
2519 $statustitle = trim($item['title']);
2521 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2522 $statustext = trim($statusbody);
2524 $statustext = trim($statustitle."\n\n".$statusbody);
2527 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2528 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2531 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2533 // Workaround for clients with limited HTML parser functionality
2534 $search = ["<br>", "<blockquote>", "</blockquote>",
2535 "<h1>", "</h1>", "<h2>", "</h2>",
2536 "<h3>", "</h3>", "<h4>", "</h4>",
2537 "<h5>", "</h5>", "<h6>", "</h6>"];
2538 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2539 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2540 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2541 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2542 $statushtml = str_replace($search, $replace, $statushtml);
2544 if ($item['title'] != "") {
2545 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2549 $oldtext = $statushtml;
2550 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2551 } while ($oldtext != $statushtml);
2553 if (substr($statushtml, 0, 4) == '<br>') {
2554 $statushtml = substr($statushtml, 4);
2557 if (substr($statushtml, 0, -4) == '<br>') {
2558 $statushtml = substr($statushtml, -4);
2561 // feeds without body should contain the link
2562 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2563 $statushtml .= BBCode::convert($item['plink']);
2567 "text" => $statustext,
2568 "html" => $statushtml,
2569 "attachments" => $attachments,
2570 "entities" => $entities
2576 * @param string $body
2579 * @throws InternalServerErrorException
2581 function api_get_attachments(&$body)
2583 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2584 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2586 $URLSearchString = "^\[\]";
2587 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2591 // Remove all embedded pictures, since they are added as attachments
2592 foreach ($images[0] as $orig) {
2593 $body = str_replace($orig, '', $body);
2598 foreach ($images[1] as $image) {
2599 $imagedata = Images::getInfoFromURLCached($image);
2602 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2606 return $attachments;
2611 * @param string $text
2612 * @param string $bbcode
2615 * @throws InternalServerErrorException
2616 * @todo Links at the first character of the post
2618 function api_get_entitities(&$text, $bbcode)
2620 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2622 if ($include_entities != "true") {
2623 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2625 foreach ($images[1] as $image) {
2626 $replace = ProxyUtils::proxifyUrl($image);
2627 $text = str_replace($image, $replace, $text);
2632 $bbcode = BBCode::cleanPictureLinks($bbcode);
2634 // Change pure links in text to bbcode uris
2635 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2638 $entities["hashtags"] = [];
2639 $entities["symbols"] = [];
2640 $entities["urls"] = [];
2641 $entities["user_mentions"] = [];
2643 $URLSearchString = "^\[\]";
2645 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2647 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2648 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2650 $bbcode = preg_replace(
2651 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2652 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2655 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2657 $bbcode = preg_replace(
2658 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2659 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2662 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2664 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2666 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2669 foreach ($urls[1] as $id => $url) {
2670 $start = iconv_strpos($text, $url, 0, "UTF-8");
2671 if (!($start === false)) {
2672 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2676 ksort($ordered_urls);
2680 foreach ($ordered_urls as $url) {
2681 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2682 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2684 $display_url = $url["title"];
2686 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2687 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2689 if (strlen($display_url) > 26) {
2690 $display_url = substr($display_url, 0, 25)."…";
2694 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2695 if (!($start === false)) {
2696 $entities["urls"][] = ["url" => $url["url"],
2697 "expanded_url" => $url["url"],
2698 "display_url" => $display_url,
2699 "indices" => [$start, $start+strlen($url["url"])]];
2700 $offset = $start + 1;
2704 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2705 $ordered_images = [];
2706 foreach ($images as $image) {
2707 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2708 if (!($start === false)) {
2709 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2713 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2714 foreach ($images[1] as $image) {
2715 $start = iconv_strpos($text, $image, 0, "UTF-8");
2716 if (!($start === false)) {
2717 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2723 foreach ($ordered_images as $image) {
2724 $url = $image['url'];
2725 $ext_alt_text = $image['alt'];
2727 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2728 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2730 if (strlen($display_url) > 26) {
2731 $display_url = substr($display_url, 0, 25)."…";
2734 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2735 if (!($start === false)) {
2736 $image = Images::getInfoFromURLCached($url);
2738 // If image cache is activated, then use the following sizes:
2739 // thumb (150), small (340), medium (600) and large (1024)
2740 if (!DI::config()->get("system", "proxy_disabled")) {
2741 $media_url = ProxyUtils::proxifyUrl($url);
2744 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2745 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2747 if (($image[0] > 150) || ($image[1] > 150)) {
2748 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2749 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2752 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2753 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2755 if (($image[0] > 600) || ($image[1] > 600)) {
2756 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2757 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2761 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2764 $entities["media"][] = [
2766 "id_str" => (string) ($start + 1),
2767 "indices" => [$start, $start+strlen($url)],
2768 "media_url" => Strings::normaliseLink($media_url),
2769 "media_url_https" => $media_url,
2771 "display_url" => $display_url,
2772 "expanded_url" => $url,
2773 "ext_alt_text" => $ext_alt_text,
2777 $offset = $start + 1;
2786 * @param array $item
2787 * @param string $text
2791 function api_format_items_embeded_images($item, $text)
2793 $text = preg_replace_callback(
2794 '|data:image/([^;]+)[^=]+=*|m',
2795 function () use ($item) {
2796 return DI::baseUrl() . '/display/' . $item['guid'];
2804 * return <a href='url'>name</a> as array
2806 * @param string $txt text
2811 function api_contactlink_to_array($txt)
2814 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2815 if ($r && count($match)==3) {
2817 'name' => $match[2],
2831 * return likes, dislikes and attend status for item
2833 * @param array $item array
2834 * @param string $type Return type (atom, rss, xml, json)
2837 * likes => int count,
2838 * dislikes => int count
2839 * @throws BadRequestException
2840 * @throws ImagickException
2841 * @throws InternalServerErrorException
2842 * @throws UnauthorizedException
2844 function api_format_items_activities($item, $type = "json")
2853 'attendmaybe' => [],
2857 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2858 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2860 while ($parent_item = Item::fetch($ret)) {
2861 // not used as result should be structured like other user data
2862 //builtin_activity_puller($i, $activities);
2864 // get user data and add it to the array of the activity
2865 $user = api_get_user($a, $parent_item['author-id']);
2866 switch ($parent_item['verb']) {
2867 case Activity::LIKE:
2868 $activities['like'][] = $user;
2870 case Activity::DISLIKE:
2871 $activities['dislike'][] = $user;
2873 case Activity::ATTEND:
2874 $activities['attendyes'][] = $user;
2876 case Activity::ATTENDNO:
2877 $activities['attendno'][] = $user;
2879 case Activity::ATTENDMAYBE:
2880 $activities['attendmaybe'][] = $user;
2882 case Activity::ANNOUNCE:
2883 $activities['announce'][] = $user;
2892 if ($type == "xml") {
2893 $xml_activities = [];
2894 foreach ($activities as $k => $v) {
2895 // change xml element from "like" to "friendica:like"
2896 $xml_activities["friendica:".$k] = $v;
2897 // add user data into xml output
2899 foreach ($v as $user) {
2900 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2903 $activities = $xml_activities;
2910 * format items to be returned by api
2912 * @param array $items array of items
2913 * @param array $user_info
2914 * @param bool $filter_user filter items by $user_info
2915 * @param string $type Return type (atom, rss, xml, json)
2917 * @throws BadRequestException
2918 * @throws ImagickException
2919 * @throws InternalServerErrorException
2920 * @throws UnauthorizedException
2922 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2924 $a = Friendica\DI::app();
2928 foreach ((array)$items as $item) {
2929 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2931 // Look if the posts are matching if they should be filtered by user id
2932 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2936 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2945 * @param array $item Item record
2946 * @param string $type Return format (atom, rss, xml, json)
2947 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2948 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2949 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2950 * @return array API-formatted status
2951 * @throws BadRequestException
2952 * @throws ImagickException
2953 * @throws InternalServerErrorException
2954 * @throws UnauthorizedException
2956 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2958 $a = Friendica\DI::app();
2960 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2961 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2964 localize_item($item);
2966 $in_reply_to = api_in_reply_to($item);
2968 $converted = api_convert_item($item);
2970 if ($type == "xml") {
2971 $geo = "georss:point";
2977 'text' => $converted["text"],
2978 'truncated' => false,
2979 'created_at'=> api_date($item['created']),
2980 'in_reply_to_status_id' => $in_reply_to['status_id'],
2981 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2982 'source' => (($item['app']) ? $item['app'] : 'web'),
2983 'id' => intval($item['id']),
2984 'id_str' => (string) intval($item['id']),
2985 'in_reply_to_user_id' => $in_reply_to['user_id'],
2986 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2987 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2989 'favorited' => $item['starred'] ? true : false,
2990 'user' => $status_user,
2991 'friendica_author' => $author_user,
2992 'friendica_owner' => $owner_user,
2993 'friendica_private' => $item['private'] == 1,
2994 //'entities' => NULL,
2995 'statusnet_html' => $converted["html"],
2996 'statusnet_conversation_id' => $item['parent'],
2997 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2998 'friendica_activities' => api_format_items_activities($item, $type),
2999 'friendica_title' => $item['title'],
3000 'friendica_html' => BBCode::convert($item['body'], false)
3003 if (count($converted["attachments"]) > 0) {
3004 $status["attachments"] = $converted["attachments"];
3007 if (count($converted["entities"]) > 0) {
3008 $status["entities"] = $converted["entities"];
3011 if ($status["source"] == 'web') {
3012 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3013 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3014 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3017 $retweeted_item = [];
3020 if ($item["id"] == $item["parent"]) {
3021 $body = $item['body'];
3022 $retweeted_item = api_share_as_retweet($item);
3023 if ($body != $item['body']) {
3024 $quoted_item = $retweeted_item;
3025 $retweeted_item = [];
3029 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3030 $announce = api_get_announce($item);
3031 if (!empty($announce)) {
3032 $retweeted_item = $item;
3034 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3038 if (!empty($quoted_item)) {
3039 if ($quoted_item['id'] != $item['id']) {
3040 $quoted_status = api_format_item($quoted_item);
3041 /// @todo Only remove the attachments that are also contained in the quotes status
3042 unset($status['attachments']);
3043 unset($status['entities']);
3045 $conv_quoted = api_convert_item($quoted_item);
3046 $quoted_status = $status;
3047 unset($quoted_status['attachments']);
3048 unset($quoted_status['entities']);
3049 unset($quoted_status['statusnet_conversation_id']);
3050 $quoted_status['text'] = $conv_quoted['text'];
3051 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3053 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3054 } catch (BadRequestException $e) {
3055 // user not found. should be found?
3056 /// @todo check if the user should be always found
3057 $quoted_status["user"] = [];
3060 unset($quoted_status['friendica_author']);
3061 unset($quoted_status['friendica_owner']);
3062 unset($quoted_status['friendica_activities']);
3063 unset($quoted_status['friendica_private']);
3066 if (!empty($retweeted_item)) {
3067 $retweeted_status = $status;
3068 unset($retweeted_status['friendica_author']);
3069 unset($retweeted_status['friendica_owner']);
3070 unset($retweeted_status['friendica_activities']);
3071 unset($retweeted_status['friendica_private']);
3072 unset($retweeted_status['statusnet_conversation_id']);
3073 $status['user'] = $status['friendica_owner'];
3075 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3076 } catch (BadRequestException $e) {
3077 // user not found. should be found?
3078 /// @todo check if the user should be always found
3079 $retweeted_status["user"] = [];
3082 $rt_converted = api_convert_item($retweeted_item);
3084 $retweeted_status['text'] = $rt_converted["text"];
3085 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3086 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3088 if (!empty($quoted_status)) {
3089 $retweeted_status['quoted_status'] = $quoted_status;
3092 $status['friendica_author'] = $retweeted_status['user'];
3093 $status['retweeted_status'] = $retweeted_status;
3094 } elseif (!empty($quoted_status)) {
3095 $root_status = api_convert_item($item);
3097 $status['text'] = $root_status["text"];
3098 $status['statusnet_html'] = $root_status["html"];
3099 $status['quoted_status'] = $quoted_status;
3102 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3103 unset($status["user"]["uid"]);
3104 unset($status["user"]["self"]);
3106 if ($item["coord"] != "") {
3107 $coords = explode(' ', $item["coord"]);
3108 if (count($coords) == 2) {
3109 if ($type == "json") {
3110 $status["geo"] = ['type' => 'Point',
3111 'coordinates' => [(float) $coords[0],
3112 (float) $coords[1]]];
3113 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3114 $status["georss:point"] = $item["coord"];
3123 * Returns the remaining number of API requests available to the user before the API limit is reached.
3125 * @param string $type Return type (atom, rss, xml, json)
3127 * @return array|string
3130 function api_account_rate_limit_status($type)
3132 if ($type == "xml") {
3134 'remaining-hits' => '150',
3135 '@attributes' => ["type" => "integer"],
3136 'hourly-limit' => '150',
3137 '@attributes2' => ["type" => "integer"],
3138 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3139 '@attributes3' => ["type" => "datetime"],
3140 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3141 '@attributes4' => ["type" => "integer"],
3145 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3146 'remaining_hits' => '150',
3147 'hourly_limit' => '150',
3148 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3152 return api_format_data('hash', $type, ['hash' => $hash]);
3155 /// @TODO move to top of file or somewhere better
3156 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3159 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3161 * @param string $type Return type (atom, rss, xml, json)
3163 * @return array|string
3165 function api_help_test($type)
3167 if ($type == 'xml') {
3173 return api_format_data('ok', $type, ["ok" => $ok]);
3176 /// @TODO move to top of file or somewhere better
3177 api_register_func('api/help/test', 'api_help_test', false);
3180 * Returns all lists the user subscribes to.
3182 * @param string $type Return type (atom, rss, xml, json)
3184 * @return array|string
3185 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3187 function api_lists_list($type)
3190 /// @TODO $ret is not filled here?
3191 return api_format_data('lists', $type, ["lists_list" => $ret]);
3194 /// @TODO move to top of file or somewhere better
3195 api_register_func('api/lists/list', 'api_lists_list', true);
3196 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3199 * Returns all groups the user owns.
3201 * @param string $type Return type (atom, rss, xml, json)
3203 * @return array|string
3204 * @throws BadRequestException
3205 * @throws ForbiddenException
3206 * @throws ImagickException
3207 * @throws InternalServerErrorException
3208 * @throws UnauthorizedException
3209 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3211 function api_lists_ownerships($type)
3215 if (api_user() === false) {
3216 throw new ForbiddenException();
3220 $user_info = api_get_user($a);
3221 $uid = $user_info['uid'];
3223 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3225 // loop through all groups
3227 foreach ($groups as $group) {
3228 if ($group['visible']) {
3234 'name' => $group['name'],
3235 'id' => intval($group['id']),
3236 'id_str' => (string) $group['id'],
3237 'user' => $user_info,
3241 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3244 /// @TODO move to top of file or somewhere better
3245 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3248 * Returns recent statuses from users in the specified group.
3250 * @param string $type Return type (atom, rss, xml, json)
3252 * @return array|string
3253 * @throws BadRequestException
3254 * @throws ForbiddenException
3255 * @throws ImagickException
3256 * @throws InternalServerErrorException
3257 * @throws UnauthorizedException
3258 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3260 function api_lists_statuses($type)
3264 $user_info = api_get_user($a);
3265 if (api_user() === false || $user_info === false) {
3266 throw new ForbiddenException();
3269 unset($_REQUEST["user_id"]);
3270 unset($_GET["user_id"]);
3272 unset($_REQUEST["screen_name"]);
3273 unset($_GET["screen_name"]);
3275 if (empty($_REQUEST['list_id'])) {
3276 throw new BadRequestException('list_id not specified');
3280 $count = $_REQUEST['count'] ?? 20;
3281 $page = $_REQUEST['page'] ?? 1;
3282 $since_id = $_REQUEST['since_id'] ?? 0;
3283 $max_id = $_REQUEST['max_id'] ?? 0;
3284 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3285 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3287 $start = max(0, ($page - 1) * $count);
3289 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3290 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3293 $condition[0] .= " AND `item`.`id` <= ?";
3294 $condition[] = $max_id;
3296 if ($exclude_replies > 0) {
3297 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3299 if ($conversation_id > 0) {
3300 $condition[0] .= " AND `item`.`parent` = ?";
3301 $condition[] = $conversation_id;
3304 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3305 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3307 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3309 $data = ['status' => $items];
3314 $data = api_rss_extra($a, $data, $user_info);
3318 return api_format_data("statuses", $type, $data);
3321 /// @TODO move to top of file or somewhere better
3322 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3325 * Returns either the friends of the follower list
3327 * Considers friends and followers lists to be private and won't return
3328 * anything if any user_id parameter is passed.
3330 * @param string $qtype Either "friends" or "followers"
3331 * @return boolean|array
3332 * @throws BadRequestException
3333 * @throws ForbiddenException
3334 * @throws ImagickException
3335 * @throws InternalServerErrorException
3336 * @throws UnauthorizedException
3338 function api_statuses_f($qtype)
3342 if (api_user() === false) {
3343 throw new ForbiddenException();
3347 $count = $_GET['count'] ?? 20;
3348 $page = $_GET['page'] ?? 1;
3350 $start = max(0, ($page - 1) * $count);
3352 $user_info = api_get_user($a);
3354 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3355 /* this is to stop Hotot to load friends multiple times
3356 * I'm not sure if I'm missing return something or
3357 * is a bug in hotot. Workaround, meantime
3361 return array('$users' => $ret);*/
3366 if ($qtype == 'friends') {
3367 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3368 } elseif ($qtype == 'followers') {
3369 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3372 // friends and followers only for self
3373 if ($user_info['self'] == 0) {
3374 $sql_extra = " AND false ";
3377 if ($qtype == 'blocks') {
3378 $sql_filter = 'AND `blocked` AND NOT `pending`';
3379 } elseif ($qtype == 'incoming') {
3380 $sql_filter = 'AND `pending`';
3382 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3400 foreach ($r as $cid) {
3401 $user = api_get_user($a, $cid['nurl']);
3402 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3403 unset($user["uid"]);
3404 unset($user["self"]);
3411 return ['user' => $ret];
3416 * Returns the list of friends of the provided user
3418 * @deprecated By Twitter API in favor of friends/list
3420 * @param string $type Either "json" or "xml"
3421 * @return boolean|string|array
3422 * @throws BadRequestException
3423 * @throws ForbiddenException
3425 function api_statuses_friends($type)
3427 $data = api_statuses_f("friends");
3428 if ($data === false) {
3431 return api_format_data("users", $type, $data);
3435 * Returns the list of followers of the provided user
3437 * @deprecated By Twitter API in favor of friends/list
3439 * @param string $type Either "json" or "xml"
3440 * @return boolean|string|array
3441 * @throws BadRequestException
3442 * @throws ForbiddenException
3444 function api_statuses_followers($type)
3446 $data = api_statuses_f("followers");
3447 if ($data === false) {
3450 return api_format_data("users", $type, $data);
3453 /// @TODO move to top of file or somewhere better
3454 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3455 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3458 * Returns the list of blocked users
3460 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3462 * @param string $type Either "json" or "xml"
3464 * @return boolean|string|array
3465 * @throws BadRequestException
3466 * @throws ForbiddenException
3468 function api_blocks_list($type)
3470 $data = api_statuses_f('blocks');
3471 if ($data === false) {
3474 return api_format_data("users", $type, $data);
3477 /// @TODO move to top of file or somewhere better
3478 api_register_func('api/blocks/list', 'api_blocks_list', true);
3481 * Returns the list of pending users IDs
3483 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3485 * @param string $type Either "json" or "xml"
3487 * @return boolean|string|array
3488 * @throws BadRequestException
3489 * @throws ForbiddenException
3491 function api_friendships_incoming($type)
3493 $data = api_statuses_f('incoming');
3494 if ($data === false) {
3499 foreach ($data['user'] as $user) {
3500 $ids[] = $user['id'];
3503 return api_format_data("ids", $type, ['id' => $ids]);
3506 /// @TODO move to top of file or somewhere better
3507 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3510 * Returns the instance's configuration information.
3512 * @param string $type Return type (atom, rss, xml, json)
3514 * @return array|string
3515 * @throws InternalServerErrorException
3517 function api_statusnet_config($type)
3519 $name = DI::config()->get('config', 'sitename');
3520 $server = DI::baseUrl()->getHostname();
3521 $logo = DI::baseUrl() . '/images/friendica-64.png';
3522 $email = DI::config()->get('config', 'admin_email');
3523 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3524 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3525 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3526 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3527 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3530 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3531 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3532 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3533 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3534 'shorturllength' => '30',
3536 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3537 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3538 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3539 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3544 return api_format_data('config', $type, ['config' => $config]);
3547 /// @TODO move to top of file or somewhere better
3548 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3549 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3553 * @param string $type Return type (atom, rss, xml, json)
3555 * @return array|string
3557 function api_statusnet_version($type)
3560 $fake_statusnet_version = "0.9.7";
3562 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3565 /// @TODO move to top of file or somewhere better
3566 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3567 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3571 * @param string $type Return type (atom, rss, xml, json)
3573 * @param int $rel A contact relationship constant
3574 * @return array|string|void
3575 * @throws BadRequestException
3576 * @throws ForbiddenException
3577 * @throws ImagickException
3578 * @throws InternalServerErrorException
3579 * @throws UnauthorizedException
3580 * @todo use api_format_data() to return data
3582 function api_ff_ids($type, int $rel)
3585 throw new ForbiddenException();
3592 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3594 $contacts = DBA::p("SELECT `pcontact`.`id`
3596 INNER JOIN `contact` AS `pcontact`
3597 ON `contact`.`nurl` = `pcontact`.`nurl`
3598 AND `pcontact`.`uid` = 0
3599 WHERE `contact`.`uid` = ?
3600 AND NOT `contact`.`self`
3601 AND `contact`.`rel` IN (?, ?)",
3608 foreach (DBA::toArray($contacts) as $contact) {
3609 if ($stringify_ids) {
3610 $ids[] = $contact['id'];
3612 $ids[] = intval($contact['id']);
3616 return api_format_data('ids', $type, ['id' => $ids]);
3620 * Returns the ID of every user the user is following.
3622 * @param string $type Return type (atom, rss, xml, json)
3624 * @return array|string
3625 * @throws BadRequestException
3626 * @throws ForbiddenException
3627 * @throws ImagickException
3628 * @throws InternalServerErrorException
3629 * @throws UnauthorizedException
3630 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3632 function api_friends_ids($type)
3634 return api_ff_ids($type, Contact::SHARING);
3638 * Returns the ID of every user following the user.
3640 * @param string $type Return type (atom, rss, xml, json)
3642 * @return array|string
3643 * @throws BadRequestException
3644 * @throws ForbiddenException
3645 * @throws ImagickException
3646 * @throws InternalServerErrorException
3647 * @throws UnauthorizedException
3648 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3650 function api_followers_ids($type)
3652 return api_ff_ids($type, Contact::FOLLOWER);
3655 /// @TODO move to top of file or somewhere better
3656 api_register_func('api/friends/ids', 'api_friends_ids', true);
3657 api_register_func('api/followers/ids', 'api_followers_ids', true);
3660 * Sends a new direct message.
3662 * @param string $type Return type (atom, rss, xml, json)
3664 * @return array|string
3665 * @throws BadRequestException
3666 * @throws ForbiddenException
3667 * @throws ImagickException
3668 * @throws InternalServerErrorException
3669 * @throws NotFoundException
3670 * @throws UnauthorizedException
3671 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3673 function api_direct_messages_new($type)
3677 if (api_user() === false) {
3678 throw new ForbiddenException();
3681 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3685 $sender = api_get_user($a);
3688 if (!empty($_POST['screen_name'])) {
3690 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3692 DBA::escape($_POST['screen_name'])
3695 if (DBA::isResult($r)) {
3696 // Selecting the id by priority, friendica first
3697 api_best_nickname($r);
3699 $recipient = api_get_user($a, $r[0]['nurl']);
3702 $recipient = api_get_user($a, $_POST['user_id']);
3705 if (empty($recipient)) {
3706 throw new NotFoundException('Recipient not found');
3710 if (!empty($_REQUEST['replyto'])) {
3712 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3714 intval($_REQUEST['replyto'])
3716 $replyto = $r[0]['parent-uri'];
3717 $sub = $r[0]['title'];
3719 if (!empty($_REQUEST['title'])) {
3720 $sub = $_REQUEST['title'];
3722 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3726 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3729 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3730 $ret = api_format_messages($r[0], $recipient, $sender);
3732 $ret = ["error"=>$id];
3735 $data = ['direct_message'=>$ret];
3741 $data = api_rss_extra($a, $data, $sender);
3745 return api_format_data("direct-messages", $type, $data);
3748 /// @TODO move to top of file or somewhere better
3749 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3752 * delete a direct_message from mail table through api
3754 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3755 * @return string|array
3756 * @throws BadRequestException
3757 * @throws ForbiddenException
3758 * @throws ImagickException
3759 * @throws InternalServerErrorException
3760 * @throws UnauthorizedException
3761 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3763 function api_direct_messages_destroy($type)
3767 if (api_user() === false) {
3768 throw new ForbiddenException();
3772 $user_info = api_get_user($a);
3774 $id = $_REQUEST['id'] ?? 0;
3776 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3777 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3778 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3780 $uid = $user_info['uid'];
3781 // error if no id or parenturi specified (for clients posting parent-uri as well)
3782 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3783 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3784 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3787 // BadRequestException if no id specified (for clients using Twitter API)
3789 throw new BadRequestException('Message id not specified');
3792 // add parent-uri to sql command if specified by calling app
3793 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3795 // get data of the specified message id
3797 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3802 // error message if specified id is not in database
3803 if (!DBA::isResult($r)) {
3804 if ($verbose == "true") {
3805 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3806 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3808 /// @todo BadRequestException ok for Twitter API clients?
3809 throw new BadRequestException('message id not in database');
3814 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3819 if ($verbose == "true") {
3822 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3823 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3825 $answer = ['result' => 'error', 'message' => 'unknown error'];
3826 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3829 /// @todo return JSON data like Twitter API not yet implemented
3832 /// @TODO move to top of file or somewhere better
3833 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3838 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3839 * @return string|array
3840 * @throws BadRequestException
3841 * @throws ForbiddenException
3842 * @throws ImagickException
3843 * @throws InternalServerErrorException
3844 * @throws NotFoundException
3845 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3847 function api_friendships_destroy($type)
3851 if ($uid === false) {
3852 throw new ForbiddenException();
3855 $contact_id = $_REQUEST['user_id'] ?? 0;
3857 if (empty($contact_id)) {
3858 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3859 throw new BadRequestException("no user_id specified");
3862 // Get Contact by given id
3863 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3865 if(!DBA::isResult($contact)) {
3866 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3867 throw new NotFoundException("no contact found to given ID");
3870 $url = $contact["url"];
3872 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3873 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3874 Strings::normaliseLink($url), $url];
3875 $contact = DBA::selectFirst('contact', [], $condition);
3877 if (!DBA::isResult($contact)) {
3878 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3879 throw new NotFoundException("Not following Contact");
3882 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3883 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3884 throw new ExpectationFailedException("Not supported");
3887 $dissolve = ($contact['rel'] == Contact::SHARING);
3889 $owner = User::getOwnerDataById($uid);
3891 Contact::terminateFriendship($owner, $contact, $dissolve);
3894 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3895 throw new NotFoundException("Error Processing Request");
3898 // Sharing-only contacts get deleted as there no relationship any more
3900 Contact::remove($contact['id']);
3902 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3905 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3906 unset($contact["uid"]);
3907 unset($contact["self"]);
3909 // Set screen_name since Twidere requests it
3910 $contact["screen_name"] = $contact["nick"];
3912 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3914 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3918 * @param string $type Return type (atom, rss, xml, json)
3919 * @param string $box
3920 * @param string $verbose
3922 * @return array|string
3923 * @throws BadRequestException
3924 * @throws ForbiddenException
3925 * @throws ImagickException
3926 * @throws InternalServerErrorException
3927 * @throws UnauthorizedException
3929 function api_direct_messages_box($type, $box, $verbose)
3932 if (api_user() === false) {
3933 throw new ForbiddenException();
3936 $count = $_GET['count'] ?? 20;
3937 $page = $_REQUEST['page'] ?? 1;
3939 $since_id = $_REQUEST['since_id'] ?? 0;
3940 $max_id = $_REQUEST['max_id'] ?? 0;
3942 $user_id = $_REQUEST['user_id'] ?? '';
3943 $screen_name = $_REQUEST['screen_name'] ?? '';
3946 unset($_REQUEST["user_id"]);
3947 unset($_GET["user_id"]);
3949 unset($_REQUEST["screen_name"]);
3950 unset($_GET["screen_name"]);
3952 $user_info = api_get_user($a);
3953 if ($user_info === false) {
3954 throw new ForbiddenException();
3956 $profile_url = $user_info["url"];
3959 $start = max(0, ($page - 1) * $count);
3964 if ($box=="sentbox") {
3965 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3966 } elseif ($box == "conversation") {
3967 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3968 } elseif ($box == "all") {
3969 $sql_extra = "true";
3970 } elseif ($box == "inbox") {
3971 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3975 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3978 if ($user_id != "") {
3979 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3980 } elseif ($screen_name !="") {
3981 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3985 "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",
3991 if ($verbose == "true" && !DBA::isResult($r)) {
3992 $answer = ['result' => 'error', 'message' => 'no mails available'];
3993 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3997 foreach ($r as $item) {
3998 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3999 $recipient = $user_info;
4000 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4001 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4002 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4003 $sender = $user_info;
4006 if (isset($recipient) && isset($sender)) {
4007 $ret[] = api_format_messages($item, $recipient, $sender);
4012 $data = ['direct_message' => $ret];
4017 $data = api_rss_extra($a, $data, $user_info);
4021 return api_format_data("direct-messages", $type, $data);
4025 * Returns the most recent direct messages sent by the user.
4027 * @param string $type Return type (atom, rss, xml, json)
4029 * @return array|string
4030 * @throws BadRequestException
4031 * @throws ForbiddenException
4032 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4034 function api_direct_messages_sentbox($type)
4036 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4037 return api_direct_messages_box($type, "sentbox", $verbose);
4041 * Returns the most recent direct messages sent to the user.
4043 * @param string $type Return type (atom, rss, xml, json)
4045 * @return array|string
4046 * @throws BadRequestException
4047 * @throws ForbiddenException
4048 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4050 function api_direct_messages_inbox($type)
4052 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4053 return api_direct_messages_box($type, "inbox", $verbose);
4058 * @param string $type Return type (atom, rss, xml, json)
4060 * @return array|string
4061 * @throws BadRequestException
4062 * @throws ForbiddenException
4064 function api_direct_messages_all($type)
4066 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4067 return api_direct_messages_box($type, "all", $verbose);
4072 * @param string $type Return type (atom, rss, xml, json)
4074 * @return array|string
4075 * @throws BadRequestException
4076 * @throws ForbiddenException
4078 function api_direct_messages_conversation($type)
4080 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4081 return api_direct_messages_box($type, "conversation", $verbose);
4084 /// @TODO move to top of file or somewhere better
4085 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4086 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4087 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4088 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4091 * Returns an OAuth Request Token.
4093 * @see https://oauth.net/core/1.0/#auth_step1
4095 function api_oauth_request_token()
4097 $oauth1 = new FKOAuth1();
4099 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4100 } catch (Exception $e) {
4101 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4109 * Returns an OAuth Access Token.
4111 * @return array|string
4112 * @see https://oauth.net/core/1.0/#auth_step3
4114 function api_oauth_access_token()
4116 $oauth1 = new FKOAuth1();
4118 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4119 } catch (Exception $e) {
4120 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4127 /// @TODO move to top of file or somewhere better
4128 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4129 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4133 * delete a complete photoalbum with all containing photos from database through api
4135 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4136 * @return string|array
4137 * @throws BadRequestException
4138 * @throws ForbiddenException
4139 * @throws InternalServerErrorException
4141 function api_fr_photoalbum_delete($type)
4143 if (api_user() === false) {
4144 throw new ForbiddenException();
4147 $album = $_REQUEST['album'] ?? '';
4149 // we do not allow calls without album string
4151 throw new BadRequestException("no albumname specified");
4153 // check if album is existing
4155 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4159 if (!DBA::isResult($r)) {
4160 throw new BadRequestException("album not available");
4163 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4164 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4165 foreach ($r as $rr) {
4166 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4167 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4169 if (!DBA::isResult($photo_item)) {
4170 throw new InternalServerErrorException("problem with deleting items occured");
4172 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4175 // now let's delete all photos from the album
4176 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4178 // return success of deletion or error message
4180 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4181 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4183 throw new InternalServerErrorException("unknown error - deleting from database failed");
4188 * update the name of the album for all photos of an album
4190 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4191 * @return string|array
4192 * @throws BadRequestException
4193 * @throws ForbiddenException
4194 * @throws InternalServerErrorException
4196 function api_fr_photoalbum_update($type)
4198 if (api_user() === false) {
4199 throw new ForbiddenException();
4202 $album = $_REQUEST['album'] ?? '';
4203 $album_new = $_REQUEST['album_new'] ?? '';
4205 // we do not allow calls without album string
4207 throw new BadRequestException("no albumname specified");
4209 if ($album_new == "") {
4210 throw new BadRequestException("no new albumname specified");
4212 // check if album is existing
4213 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4214 throw new BadRequestException("album not available");
4216 // now let's update all photos to the albumname
4217 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4219 // return success of updating or error message
4221 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4222 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4224 throw new InternalServerErrorException("unknown error - updating in database failed");
4230 * list all photos of the authenticated user
4232 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4233 * @return string|array
4234 * @throws ForbiddenException
4235 * @throws InternalServerErrorException
4237 function api_fr_photos_list($type)
4239 if (api_user() === false) {
4240 throw new ForbiddenException();
4243 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4244 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4245 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4246 intval(local_user())
4249 'image/jpeg' => 'jpg',
4250 'image/png' => 'png',
4251 'image/gif' => 'gif'
4253 $data = ['photo'=>[]];
4254 if (DBA::isResult($r)) {
4255 foreach ($r as $rr) {
4257 $photo['id'] = $rr['resource-id'];
4258 $photo['album'] = $rr['album'];
4259 $photo['filename'] = $rr['filename'];
4260 $photo['type'] = $rr['type'];
4261 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4262 $photo['created'] = $rr['created'];
4263 $photo['edited'] = $rr['edited'];
4264 $photo['desc'] = $rr['desc'];
4266 if ($type == "xml") {
4267 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4269 $photo['thumb'] = $thumb;
4270 $data['photo'][] = $photo;
4274 return api_format_data("photos", $type, $data);
4278 * upload a new photo or change an existing photo
4280 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4281 * @return string|array
4282 * @throws BadRequestException
4283 * @throws ForbiddenException
4284 * @throws ImagickException
4285 * @throws InternalServerErrorException
4286 * @throws NotFoundException
4288 function api_fr_photo_create_update($type)
4290 if (api_user() === false) {
4291 throw new ForbiddenException();
4294 $photo_id = $_REQUEST['photo_id'] ?? null;
4295 $desc = $_REQUEST['desc'] ?? null;
4296 $album = $_REQUEST['album'] ?? null;
4297 $album_new = $_REQUEST['album_new'] ?? null;
4298 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4299 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4300 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4301 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4302 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4304 // do several checks on input parameters
4305 // we do not allow calls without album string
4306 if ($album == null) {
4307 throw new BadRequestException("no albumname specified");
4309 // if photo_id == null --> we are uploading a new photo
4310 if ($photo_id == null) {
4313 // error if no media posted in create-mode
4314 if (empty($_FILES['media'])) {
4316 throw new BadRequestException("no media data submitted");
4319 // album_new will be ignored in create-mode
4324 // check if photo is existing in databasei
4325 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4326 throw new BadRequestException("photo not available");
4330 // checks on acl strings provided by clients
4331 $acl_input_error = false;
4332 $acl_input_error |= check_acl_input($allow_cid);
4333 $acl_input_error |= check_acl_input($deny_cid);
4334 $acl_input_error |= check_acl_input($allow_gid);
4335 $acl_input_error |= check_acl_input($deny_gid);
4336 if ($acl_input_error) {
4337 throw new BadRequestException("acl data invalid");
4339 // now let's upload the new media in create-mode
4340 if ($mode == "create") {
4341 $media = $_FILES['media'];
4342 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4344 // return success of updating or error message
4345 if (!is_null($data)) {
4346 return api_format_data("photo_create", $type, $data);
4348 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4352 // now let's do the changes in update-mode
4353 if ($mode == "update") {
4354 $updated_fields = [];
4356 if (!is_null($desc)) {
4357 $updated_fields['desc'] = $desc;
4360 if (!is_null($album_new)) {
4361 $updated_fields['album'] = $album_new;
4364 if (!is_null($allow_cid)) {
4365 $allow_cid = trim($allow_cid);
4366 $updated_fields['allow_cid'] = $allow_cid;
4369 if (!is_null($deny_cid)) {
4370 $deny_cid = trim($deny_cid);
4371 $updated_fields['deny_cid'] = $deny_cid;
4374 if (!is_null($allow_gid)) {
4375 $allow_gid = trim($allow_gid);
4376 $updated_fields['allow_gid'] = $allow_gid;
4379 if (!is_null($deny_gid)) {
4380 $deny_gid = trim($deny_gid);
4381 $updated_fields['deny_gid'] = $deny_gid;
4385 if (count($updated_fields) > 0) {
4386 $nothingtodo = false;
4387 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4389 $nothingtodo = true;
4392 if (!empty($_FILES['media'])) {
4393 $nothingtodo = false;
4394 $media = $_FILES['media'];
4395 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4396 if (!is_null($data)) {
4397 return api_format_data("photo_update", $type, $data);
4401 // return success of updating or error message
4403 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4404 return api_format_data("photo_update", $type, ['$result' => $answer]);
4407 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4408 return api_format_data("photo_update", $type, ['$result' => $answer]);
4410 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4413 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4417 * delete a single photo from the database through api
4419 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4420 * @return string|array
4421 * @throws BadRequestException
4422 * @throws ForbiddenException
4423 * @throws InternalServerErrorException
4425 function api_fr_photo_delete($type)
4427 if (api_user() === false) {
4428 throw new ForbiddenException();
4432 $photo_id = $_REQUEST['photo_id'] ?? null;
4434 // do several checks on input parameters
4435 // we do not allow calls without photo id
4436 if ($photo_id == null) {
4437 throw new BadRequestException("no photo_id specified");
4440 // check if photo is existing in database
4441 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4442 throw new BadRequestException("photo not available");
4445 // now we can perform on the deletion of the photo
4446 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4448 // return success of deletion or error message
4450 // retrieve the id of the parent element (the photo element)
4451 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4452 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4454 if (!DBA::isResult($photo_item)) {
4455 throw new InternalServerErrorException("problem with deleting items occured");
4457 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4458 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4459 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4461 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4462 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4464 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4470 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4472 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4473 * @return string|array
4474 * @throws BadRequestException
4475 * @throws ForbiddenException
4476 * @throws InternalServerErrorException
4477 * @throws NotFoundException
4479 function api_fr_photo_detail($type)
4481 if (api_user() === false) {
4482 throw new ForbiddenException();
4484 if (empty($_REQUEST['photo_id'])) {
4485 throw new BadRequestException("No photo id.");
4488 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4489 $photo_id = $_REQUEST['photo_id'];
4491 // prepare json/xml output with data from database for the requested photo
4492 $data = prepare_photo_data($type, $scale, $photo_id);
4494 return api_format_data("photo_detail", $type, $data);
4499 * updates the profile image for the user (either a specified profile or the default profile)
4501 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4503 * @return string|array
4504 * @throws BadRequestException
4505 * @throws ForbiddenException
4506 * @throws ImagickException
4507 * @throws InternalServerErrorException
4508 * @throws NotFoundException
4509 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4511 function api_account_update_profile_image($type)
4513 if (api_user() === false) {
4514 throw new ForbiddenException();
4517 $profile_id = $_REQUEST['profile_id'] ?? 0;
4519 // error if image data is missing
4520 if (empty($_FILES['image'])) {
4521 throw new BadRequestException("no media data submitted");
4524 // check if specified profile id is valid
4525 if ($profile_id != 0) {
4526 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4527 // error message if specified profile id is not in database
4528 if (!DBA::isResult($profile)) {
4529 throw new BadRequestException("profile_id not available");
4531 $is_default_profile = $profile['is-default'];
4533 $is_default_profile = 1;
4536 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4538 if (!empty($_FILES['image'])) {
4539 $media = $_FILES['image'];
4540 } elseif (!empty($_FILES['media'])) {
4541 $media = $_FILES['media'];
4543 // save new profile image
4544 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4547 if (is_array($media['type'])) {
4548 $filetype = $media['type'][0];
4550 $filetype = $media['type'];
4552 if ($filetype == "image/jpeg") {
4554 } elseif ($filetype == "image/png") {
4557 throw new InternalServerErrorException('Unsupported filetype');
4560 // change specified profile or all profiles to the new resource-id
4561 if ($is_default_profile) {
4562 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4563 Photo::update(['profile' => false], $condition);
4565 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4566 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4567 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4570 Contact::updateSelfFromUserID(api_user(), true);
4572 // Update global directory in background
4573 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4574 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4575 Worker::add(PRIORITY_LOW, "Directory", $url);
4578 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4580 // output for client
4582 return api_account_verify_credentials($type);
4584 // SaveMediaToDatabase failed for some reason
4585 throw new InternalServerErrorException("image upload failed");
4589 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4590 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4591 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4592 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4593 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4594 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4595 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4596 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4597 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4600 * Update user profile
4602 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4604 * @return array|string
4605 * @throws BadRequestException
4606 * @throws ForbiddenException
4607 * @throws ImagickException
4608 * @throws InternalServerErrorException
4609 * @throws UnauthorizedException
4611 function api_account_update_profile($type)
4613 $local_user = api_user();
4614 $api_user = api_get_user(DI::app());
4616 if (!empty($_POST['name'])) {
4617 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4618 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4619 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4620 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4623 if (isset($_POST['description'])) {
4624 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4625 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4626 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4629 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4630 // Update global directory in background
4631 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4632 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4635 return api_account_verify_credentials($type);
4638 /// @TODO move to top of file or somewhere better
4639 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4643 * @param string $acl_string
4647 function check_acl_input($acl_string)
4649 if (empty($acl_string)) {
4653 $contact_not_found = false;
4655 // split <x><y><z> into array of cid's
4656 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4658 // check for each cid if it is available on server
4659 $cid_array = $array[0];
4660 foreach ($cid_array as $cid) {
4661 $cid = str_replace("<", "", $cid);
4662 $cid = str_replace(">", "", $cid);
4663 $condition = ['id' => $cid, 'uid' => api_user()];
4664 $contact_not_found |= !DBA::exists('contact', $condition);
4666 return $contact_not_found;
4670 * @param string $mediatype
4671 * @param array $media
4672 * @param string $type
4673 * @param string $album
4674 * @param string $allow_cid
4675 * @param string $deny_cid
4676 * @param string $allow_gid
4677 * @param string $deny_gid
4678 * @param string $desc
4679 * @param integer $profile
4680 * @param boolean $visibility
4681 * @param string $photo_id
4683 * @throws BadRequestException
4684 * @throws ForbiddenException
4685 * @throws ImagickException
4686 * @throws InternalServerErrorException
4687 * @throws NotFoundException
4688 * @throws UnauthorizedException
4690 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)
4698 if (is_array($media)) {
4699 if (is_array($media['tmp_name'])) {
4700 $src = $media['tmp_name'][0];
4702 $src = $media['tmp_name'];
4704 if (is_array($media['name'])) {
4705 $filename = basename($media['name'][0]);
4707 $filename = basename($media['name']);
4709 if (is_array($media['size'])) {
4710 $filesize = intval($media['size'][0]);
4712 $filesize = intval($media['size']);
4714 if (is_array($media['type'])) {
4715 $filetype = $media['type'][0];
4717 $filetype = $media['type'];
4721 if ($filetype == "") {
4722 $filetype = Images::guessType($filename);
4724 $imagedata = @getimagesize($src);
4726 $filetype = $imagedata['mime'];
4729 "File upload src: " . $src . " - filename: " . $filename .
4730 " - size: " . $filesize . " - type: " . $filetype,
4734 // check if there was a php upload error
4735 if ($filesize == 0 && $media['error'] == 1) {
4736 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4738 // check against max upload size within Friendica instance
4739 $maximagesize = DI::config()->get('system', 'maximagesize');
4740 if ($maximagesize && ($filesize > $maximagesize)) {
4741 $formattedBytes = Strings::formatBytes($maximagesize);
4742 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4745 // create Photo instance with the data of the image
4746 $imagedata = @file_get_contents($src);
4747 $Image = new Image($imagedata, $filetype);
4748 if (!$Image->isValid()) {
4749 throw new InternalServerErrorException("unable to process image data");
4752 // check orientation of image
4753 $Image->orient($src);
4756 // check max length of images on server
4757 $max_length = DI::config()->get('system', 'max_image_length');
4759 $max_length = MAX_IMAGE_LENGTH;
4761 if ($max_length > 0) {
4762 $Image->scaleDown($max_length);
4763 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4765 $width = $Image->getWidth();
4766 $height = $Image->getHeight();
4768 // create a new resource-id if not already provided
4769 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4771 if ($mediatype == "photo") {
4772 // upload normal image (scales 0, 1, 2)
4773 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4775 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4777 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4779 if ($width > 640 || $height > 640) {
4780 $Image->scaleDown(640);
4781 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4783 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4787 if ($width > 320 || $height > 320) {
4788 $Image->scaleDown(320);
4789 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4791 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4794 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4795 } elseif ($mediatype == "profileimage") {
4796 // upload profile image (scales 4, 5, 6)
4797 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4799 if ($width > 300 || $height > 300) {
4800 $Image->scaleDown(300);
4801 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4803 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4807 if ($width > 80 || $height > 80) {
4808 $Image->scaleDown(80);
4809 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4811 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4815 if ($width > 48 || $height > 48) {
4816 $Image->scaleDown(48);
4817 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4819 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4822 $Image->__destruct();
4823 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4826 if (isset($r) && $r) {
4827 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4828 if ($photo_id == null && $mediatype == "photo") {
4829 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4831 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4832 return prepare_photo_data($type, false, $resource_id);
4834 throw new InternalServerErrorException("image upload failed");
4840 * @param string $hash
4841 * @param string $allow_cid
4842 * @param string $deny_cid
4843 * @param string $allow_gid
4844 * @param string $deny_gid
4845 * @param string $filetype
4846 * @param boolean $visibility
4847 * @throws InternalServerErrorException
4849 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4851 // get data about the api authenticated user
4852 $uri = Item::newURI(intval(api_user()));
4853 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4856 $arr['guid'] = System::createUUID();
4857 $arr['uid'] = intval(api_user());
4859 $arr['parent-uri'] = $uri;
4860 $arr['type'] = 'photo';
4862 $arr['resource-id'] = $hash;
4863 $arr['contact-id'] = $owner_record['id'];
4864 $arr['owner-name'] = $owner_record['name'];
4865 $arr['owner-link'] = $owner_record['url'];
4866 $arr['owner-avatar'] = $owner_record['thumb'];
4867 $arr['author-name'] = $owner_record['name'];
4868 $arr['author-link'] = $owner_record['url'];
4869 $arr['author-avatar'] = $owner_record['thumb'];
4871 $arr['allow_cid'] = $allow_cid;
4872 $arr['allow_gid'] = $allow_gid;
4873 $arr['deny_cid'] = $deny_cid;
4874 $arr['deny_gid'] = $deny_gid;
4875 $arr['visible'] = $visibility;
4879 'image/jpeg' => 'jpg',
4880 'image/png' => 'png',
4881 'image/gif' => 'gif'
4884 // adds link to the thumbnail scale photo
4885 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4886 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4889 // do the magic for storing the item in the database and trigger the federation to other contacts
4895 * @param string $type
4897 * @param string $photo_id
4900 * @throws BadRequestException
4901 * @throws ForbiddenException
4902 * @throws ImagickException
4903 * @throws InternalServerErrorException
4904 * @throws NotFoundException
4905 * @throws UnauthorizedException
4907 function prepare_photo_data($type, $scale, $photo_id)
4910 $user_info = api_get_user($a);
4912 if ($user_info === false) {
4913 throw new ForbiddenException();
4916 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4917 $data_sql = ($scale === false ? "" : "data, ");
4919 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4920 // clients needs to convert this in their way for further processing
4922 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4923 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4924 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4925 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4926 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4927 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4929 intval(local_user()),
4930 DBA::escape($photo_id),
4935 'image/jpeg' => 'jpg',
4936 'image/png' => 'png',
4937 'image/gif' => 'gif'
4940 // prepare output data for photo
4941 if (DBA::isResult($r)) {
4942 $data = ['photo' => $r[0]];
4943 $data['photo']['id'] = $data['photo']['resource-id'];
4944 if ($scale !== false) {
4945 $data['photo']['data'] = base64_encode($data['photo']['data']);
4947 unset($data['photo']['datasize']); //needed only with scale param
4949 if ($type == "xml") {
4950 $data['photo']['links'] = [];
4951 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4952 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4954 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4957 $data['photo']['link'] = [];
4958 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4960 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4961 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4965 unset($data['photo']['resource-id']);
4966 unset($data['photo']['minscale']);
4967 unset($data['photo']['maxscale']);
4969 throw new NotFoundException();
4972 // retrieve item element for getting activities (like, dislike etc.) related to photo
4973 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4974 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4975 if (!DBA::isResult($item)) {
4976 throw new NotFoundException('Photo-related item not found.');
4979 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4981 // retrieve comments on photo
4982 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4983 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4985 $statuses = Item::selectForUser(api_user(), [], $condition);
4987 // prepare output of comments
4988 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4990 if ($type == "xml") {
4992 foreach ($commentData as $comment) {
4993 $comments[$k++ . ":comment"] = $comment;
4996 foreach ($commentData as $comment) {
4997 $comments[] = $comment;
5000 $data['photo']['friendica_comments'] = $comments;
5002 // include info if rights on photo and rights on item are mismatching
5003 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5004 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5005 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5006 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5007 $data['photo']['rights_mismatch'] = $rights_mismatch;
5014 * Similar as /mod/redir.php
5015 * redirect to 'url' after dfrn auth
5017 * Why this when there is mod/redir.php already?
5018 * This use api_user() and api_login()
5021 * c_url: url of remote contact to auth to
5022 * url: string, url to redirect after auth
5024 function api_friendica_remoteauth()
5026 $url = $_GET['url'] ?? '';
5027 $c_url = $_GET['c_url'] ?? '';
5029 if ($url === '' || $c_url === '') {
5030 throw new BadRequestException("Wrong parameters.");
5033 $c_url = Strings::normaliseLink($c_url);
5037 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5038 if (!DBA::isResult($contact)) {
5039 throw new BadRequestException("Unknown contact");
5042 $cid = $contact['id'];
5044 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5046 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5047 System::externalRedirect($url ?: $c_url);
5050 if ($contact['duplex'] && $contact['issued-id']) {
5051 $orig_id = $contact['issued-id'];
5052 $dfrn_id = '1:' . $orig_id;
5054 if ($contact['duplex'] && $contact['dfrn-id']) {
5055 $orig_id = $contact['dfrn-id'];
5056 $dfrn_id = '0:' . $orig_id;
5059 $sec = Strings::getRandomHex();
5061 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5062 'sec' => $sec, 'expire' => time() + 45];
5063 DBA::insert('profile_check', $fields);
5065 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5066 $dest = ($url ? '&destination_url=' . $url : '');
5068 System::externalRedirect(
5069 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5070 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5071 . '&type=profile&sec=' . $sec . $dest
5074 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5077 * Return an item with announcer data if it had been announced
5079 * @param array $item Item array
5080 * @return array Item array with announce data
5082 function api_get_announce($item)
5084 // Quit if the item already has got a different owner and author
5085 if ($item['owner-id'] != $item['author-id']) {
5089 // Don't change original or Diaspora posts
5090 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5094 // Quit if we do now the original author and it had been a post from a native network
5095 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5099 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5100 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5101 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5102 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5103 if (!DBA::isResult($announce)) {
5107 return array_merge($item, $announce);
5111 * Return the item shared, if the item contains only the [share] tag
5113 * @param array $item Sharer item
5114 * @return array|false Shared item or false if not a reshare
5115 * @throws ImagickException
5116 * @throws InternalServerErrorException
5118 function api_share_as_retweet(&$item)
5120 $body = trim($item["body"]);
5122 if (Diaspora::isReshare($body, false) === false) {
5123 if ($item['author-id'] == $item['owner-id']) {
5126 // Reshares from OStatus, ActivityPub and Twitter
5127 $reshared_item = $item;
5128 $reshared_item['owner-id'] = $reshared_item['author-id'];
5129 $reshared_item['owner-link'] = $reshared_item['author-link'];
5130 $reshared_item['owner-name'] = $reshared_item['author-name'];
5131 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5132 return $reshared_item;
5136 $reshared = Item::getShareArray($item);
5137 if (empty($reshared)) {
5141 $reshared_item = $item;
5143 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5147 if (!empty($reshared['comment'])) {
5148 $item['body'] = $reshared['comment'];
5151 $reshared_item["share-pre-body"] = $reshared['comment'];
5152 $reshared_item["body"] = $reshared['shared'];
5153 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5154 $reshared_item["author-name"] = $reshared['author'];
5155 $reshared_item["author-link"] = $reshared['profile'];
5156 $reshared_item["author-avatar"] = $reshared['avatar'];
5157 $reshared_item["plink"] = $reshared['link'] ?? '';
5158 $reshared_item["created"] = $reshared['posted'];
5159 $reshared_item["edited"] = $reshared['posted'];
5161 // Try to fetch the original item
5162 if (!empty($reshared['guid'])) {
5163 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5164 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5165 $condition = ['id' => $original_id];
5170 if (!empty($condition)) {
5171 $original_item = Item::selectFirst([], $condition);
5172 if (DBA::isResult($original_item)) {
5173 $reshared_item = array_merge($reshared_item, $original_item);
5177 return $reshared_item;
5182 * @param array $item
5187 function api_in_reply_to($item)
5191 $in_reply_to['status_id'] = null;
5192 $in_reply_to['user_id'] = null;
5193 $in_reply_to['status_id_str'] = null;
5194 $in_reply_to['user_id_str'] = null;
5195 $in_reply_to['screen_name'] = null;
5197 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5198 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5199 if (DBA::isResult($parent)) {
5200 $in_reply_to['status_id'] = intval($parent['id']);
5202 $in_reply_to['status_id'] = intval($item['parent']);
5205 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5207 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5208 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5210 if (DBA::isResult($parent)) {
5211 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5212 $in_reply_to['user_id'] = intval($parent['author-id']);
5213 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5216 // There seems to be situation, where both fields are identical:
5217 // https://github.com/friendica/friendica/issues/1010
5218 // This is a bugfix for that.
5219 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5220 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']]);
5221 $in_reply_to['status_id'] = null;
5222 $in_reply_to['user_id'] = null;
5223 $in_reply_to['status_id_str'] = null;
5224 $in_reply_to['user_id_str'] = null;
5225 $in_reply_to['screen_name'] = null;
5229 return $in_reply_to;
5234 * @param string $text
5237 * @throws InternalServerErrorException
5239 function api_clean_plain_items($text)
5241 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5243 $text = BBCode::cleanPictureLinks($text);
5244 $URLSearchString = "^\[\]";
5246 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5248 if ($include_entities == "true") {
5249 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5252 // Simplify "attachment" element
5253 $text = BBCode::removeAttachment($text);
5260 * @param array $contacts
5264 function api_best_nickname(&$contacts)
5268 if (count($contacts) == 0) {
5272 foreach ($contacts as $contact) {
5273 if ($contact["network"] == "") {
5274 $contact["network"] = "dfrn";
5275 $best_contact = [$contact];
5279 if (sizeof($best_contact) == 0) {
5280 foreach ($contacts as $contact) {
5281 if ($contact["network"] == "dfrn") {
5282 $best_contact = [$contact];
5287 if (sizeof($best_contact) == 0) {
5288 foreach ($contacts as $contact) {
5289 if ($contact["network"] == "dspr") {
5290 $best_contact = [$contact];
5295 if (sizeof($best_contact) == 0) {
5296 foreach ($contacts as $contact) {
5297 if ($contact["network"] == "stat") {
5298 $best_contact = [$contact];
5303 if (sizeof($best_contact) == 0) {
5304 foreach ($contacts as $contact) {
5305 if ($contact["network"] == "pump") {
5306 $best_contact = [$contact];
5311 if (sizeof($best_contact) == 0) {
5312 foreach ($contacts as $contact) {
5313 if ($contact["network"] == "twit") {
5314 $best_contact = [$contact];
5319 if (sizeof($best_contact) == 1) {
5320 $contacts = $best_contact;
5322 $contacts = [$contacts[0]];
5327 * Return all or a specified group of the user with the containing contacts.
5329 * @param string $type Return type (atom, rss, xml, json)
5331 * @return array|string
5332 * @throws BadRequestException
5333 * @throws ForbiddenException
5334 * @throws ImagickException
5335 * @throws InternalServerErrorException
5336 * @throws UnauthorizedException
5338 function api_friendica_group_show($type)
5342 if (api_user() === false) {
5343 throw new ForbiddenException();
5347 $user_info = api_get_user($a);
5348 $gid = $_REQUEST['gid'] ?? 0;
5349 $uid = $user_info['uid'];
5351 // get data of the specified group id or all groups if not specified
5354 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5358 // error message if specified gid is not in database
5359 if (!DBA::isResult($r)) {
5360 throw new BadRequestException("gid not available");
5364 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5369 // loop through all groups and retrieve all members for adding data in the user array
5371 foreach ($r as $rr) {
5372 $members = Contact::getByGroupId($rr['id']);
5375 if ($type == "xml") {
5376 $user_element = "users";
5378 foreach ($members as $member) {
5379 $user = api_get_user($a, $member['nurl']);
5380 $users[$k++.":user"] = $user;
5383 $user_element = "user";
5384 foreach ($members as $member) {
5385 $user = api_get_user($a, $member['nurl']);
5389 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5391 return api_format_data("groups", $type, ['group' => $grps]);
5393 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5397 * Delete the specified group of the user.
5399 * @param string $type Return type (atom, rss, xml, json)
5401 * @return array|string
5402 * @throws BadRequestException
5403 * @throws ForbiddenException
5404 * @throws ImagickException
5405 * @throws InternalServerErrorException
5406 * @throws UnauthorizedException
5408 function api_friendica_group_delete($type)
5412 if (api_user() === false) {
5413 throw new ForbiddenException();
5417 $user_info = api_get_user($a);
5418 $gid = $_REQUEST['gid'] ?? 0;
5419 $name = $_REQUEST['name'] ?? '';
5420 $uid = $user_info['uid'];
5422 // error if no gid specified
5423 if ($gid == 0 || $name == "") {
5424 throw new BadRequestException('gid or name not specified');
5427 // get data of the specified group id
5429 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5433 // error message if specified gid is not in database
5434 if (!DBA::isResult($r)) {
5435 throw new BadRequestException('gid not available');
5438 // get data of the specified group id and group name
5440 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5445 // error message if specified gid is not in database
5446 if (!DBA::isResult($rname)) {
5447 throw new BadRequestException('wrong group name');
5451 $ret = Group::removeByName($uid, $name);
5454 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5455 return api_format_data("group_delete", $type, ['result' => $success]);
5457 throw new BadRequestException('other API error');
5460 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5465 * @param string $type Return type (atom, rss, xml, json)
5467 * @return array|string
5468 * @throws BadRequestException
5469 * @throws ForbiddenException
5470 * @throws ImagickException
5471 * @throws InternalServerErrorException
5472 * @throws UnauthorizedException
5473 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5475 function api_lists_destroy($type)
5479 if (api_user() === false) {
5480 throw new ForbiddenException();
5484 $user_info = api_get_user($a);
5485 $gid = $_REQUEST['list_id'] ?? 0;
5486 $uid = $user_info['uid'];
5488 // error if no gid specified
5490 throw new BadRequestException('gid not specified');
5493 // get data of the specified group id
5494 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5495 // error message if specified gid is not in database
5497 throw new BadRequestException('gid not available');
5500 if (Group::remove($gid)) {
5502 'name' => $group['name'],
5503 'id' => intval($gid),
5504 'id_str' => (string) $gid,
5505 'user' => $user_info
5508 return api_format_data("lists", $type, ['lists' => $list]);
5511 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5514 * Add a new group to the database.
5516 * @param string $name Group name
5517 * @param int $uid User ID
5518 * @param array $users List of users to add to the group
5521 * @throws BadRequestException
5523 function group_create($name, $uid, $users = [])
5525 // error if no name specified
5527 throw new BadRequestException('group name not specified');
5530 // get data of the specified group name
5532 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5536 // error message if specified group name already exists
5537 if (DBA::isResult($rname)) {
5538 throw new BadRequestException('group name already exists');
5541 // check if specified group name is a deleted group
5543 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5547 // error message if specified group name already exists
5548 if (DBA::isResult($rname)) {
5549 $reactivate_group = true;
5553 $ret = Group::create($uid, $name);
5555 $gid = Group::getIdByName($uid, $name);
5557 throw new BadRequestException('other API error');
5561 $erroraddinguser = false;
5563 foreach ($users as $user) {
5564 $cid = $user['cid'];
5565 // check if user really exists as contact
5567 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5571 if (count($contact)) {
5572 Group::addMember($gid, $cid);
5574 $erroraddinguser = true;
5575 $errorusers[] = $cid;
5579 // return success message incl. missing users in array
5580 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5582 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5586 * Create the specified group with the posted array of contacts.
5588 * @param string $type Return type (atom, rss, xml, json)
5590 * @return array|string
5591 * @throws BadRequestException
5592 * @throws ForbiddenException
5593 * @throws ImagickException
5594 * @throws InternalServerErrorException
5595 * @throws UnauthorizedException
5597 function api_friendica_group_create($type)
5601 if (api_user() === false) {
5602 throw new ForbiddenException();
5606 $user_info = api_get_user($a);
5607 $name = $_REQUEST['name'] ?? '';
5608 $uid = $user_info['uid'];
5609 $json = json_decode($_POST['json'], true);
5610 $users = $json['user'];
5612 $success = group_create($name, $uid, $users);
5614 return api_format_data("group_create", $type, ['result' => $success]);
5616 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5619 * Create a new group.
5621 * @param string $type Return type (atom, rss, xml, json)
5623 * @return array|string
5624 * @throws BadRequestException
5625 * @throws ForbiddenException
5626 * @throws ImagickException
5627 * @throws InternalServerErrorException
5628 * @throws UnauthorizedException
5629 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5631 function api_lists_create($type)
5635 if (api_user() === false) {
5636 throw new ForbiddenException();
5640 $user_info = api_get_user($a);
5641 $name = $_REQUEST['name'] ?? '';
5642 $uid = $user_info['uid'];
5644 $success = group_create($name, $uid);
5645 if ($success['success']) {
5647 'name' => $success['name'],
5648 'id' => intval($success['gid']),
5649 'id_str' => (string) $success['gid'],
5650 'user' => $user_info
5653 return api_format_data("lists", $type, ['lists'=>$grp]);
5656 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5659 * Update the specified group with the posted array of contacts.
5661 * @param string $type Return type (atom, rss, xml, json)
5663 * @return array|string
5664 * @throws BadRequestException
5665 * @throws ForbiddenException
5666 * @throws ImagickException
5667 * @throws InternalServerErrorException
5668 * @throws UnauthorizedException
5670 function api_friendica_group_update($type)
5674 if (api_user() === false) {
5675 throw new ForbiddenException();
5679 $user_info = api_get_user($a);
5680 $uid = $user_info['uid'];
5681 $gid = $_REQUEST['gid'] ?? 0;
5682 $name = $_REQUEST['name'] ?? '';
5683 $json = json_decode($_POST['json'], true);
5684 $users = $json['user'];
5686 // error if no name specified
5688 throw new BadRequestException('group name not specified');
5691 // error if no gid specified
5693 throw new BadRequestException('gid not specified');
5697 $members = Contact::getByGroupId($gid);
5698 foreach ($members as $member) {
5699 $cid = $member['id'];
5700 foreach ($users as $user) {
5701 $found = ($user['cid'] == $cid ? true : false);
5703 if (!isset($found) || !$found) {
5704 Group::removeMemberByName($uid, $name, $cid);
5709 $erroraddinguser = false;
5711 foreach ($users as $user) {
5712 $cid = $user['cid'];
5713 // check if user really exists as contact
5715 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5720 if (count($contact)) {
5721 Group::addMember($gid, $cid);
5723 $erroraddinguser = true;
5724 $errorusers[] = $cid;
5728 // return success message incl. missing users in array
5729 $status = ($erroraddinguser ? "missing user" : "ok");
5730 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5731 return api_format_data("group_update", $type, ['result' => $success]);
5734 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5737 * Update information about a group.
5739 * @param string $type Return type (atom, rss, xml, json)
5741 * @return array|string
5742 * @throws BadRequestException
5743 * @throws ForbiddenException
5744 * @throws ImagickException
5745 * @throws InternalServerErrorException
5746 * @throws UnauthorizedException
5747 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5749 function api_lists_update($type)
5753 if (api_user() === false) {
5754 throw new ForbiddenException();
5758 $user_info = api_get_user($a);
5759 $gid = $_REQUEST['list_id'] ?? 0;
5760 $name = $_REQUEST['name'] ?? '';
5761 $uid = $user_info['uid'];
5763 // error if no gid specified
5765 throw new BadRequestException('gid not specified');
5768 // get data of the specified group id
5769 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5770 // error message if specified gid is not in database
5772 throw new BadRequestException('gid not available');
5775 if (Group::update($gid, $name)) {
5778 'id' => intval($gid),
5779 'id_str' => (string) $gid,
5780 'user' => $user_info
5783 return api_format_data("lists", $type, ['lists' => $list]);
5787 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5791 * @param string $type Return type (atom, rss, xml, json)
5793 * @return array|string
5794 * @throws BadRequestException
5795 * @throws ForbiddenException
5796 * @throws ImagickException
5797 * @throws InternalServerErrorException
5799 function api_friendica_activity($type)
5803 if (api_user() === false) {
5804 throw new ForbiddenException();
5806 $verb = strtolower($a->argv[3]);
5807 $verb = preg_replace("|\..*$|", "", $verb);
5809 $id = $_REQUEST['id'] ?? 0;
5811 $res = Item::performLike($id, $verb);
5814 if ($type == "xml") {
5819 return api_format_data('ok', $type, ['ok' => $ok]);
5821 throw new BadRequestException('Error adding activity');
5825 /// @TODO move to top of file or somewhere better
5826 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5827 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5828 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5829 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5830 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5831 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5832 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5833 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5834 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5835 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5838 * Returns notifications
5840 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5842 * @return string|array
5843 * @throws ForbiddenException
5844 * @throws BadRequestException
5847 function api_friendica_notification($type)
5851 if (api_user() === false) {
5852 throw new ForbiddenException();
5855 throw new BadRequestException("Invalid argument count");
5858 $notifications = DI::notification()->getApiList(local_user());
5860 if ($type == "xml") {
5862 if (!empty($notifications)) {
5863 foreach ($notifications as $notification) {
5864 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5868 $result = $xmlnotes;
5869 } elseif (count($notifications) > 0) {
5870 $result = $notifications->getArrayCopy();
5875 return api_format_data("notes", $type, ['note' => $result]);
5879 * Set notification as seen and returns associated item (if possible)
5881 * POST request with 'id' param as notification id
5883 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5884 * @return string|array
5885 * @throws BadRequestException
5886 * @throws ForbiddenException
5887 * @throws ImagickException
5888 * @throws InternalServerErrorException
5889 * @throws UnauthorizedException
5891 function api_friendica_notification_seen($type)
5894 $user_info = api_get_user($a);
5896 if (api_user() === false || $user_info === false) {
5897 throw new ForbiddenException();
5899 if ($a->argc !== 4) {
5900 throw new BadRequestException("Invalid argument count");
5903 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5906 $notify = DI::notify()->getByID($id);
5907 DI::notify()->setSeen(true, $notify);
5909 if ($notify->otype === Notify::OTYPE_ITEM) {
5910 $item = Item::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5911 if (DBA::isResult($item)) {
5912 // we found the item, return it to the user
5913 $ret = api_format_items([$item], $user_info, false, $type);
5914 $data = ['status' => $ret];
5915 return api_format_data("status", $type, $data);
5917 // the item can't be found, but we set the notification as seen, so we count this as a success
5919 return api_format_data('result', $type, ['result' => "success"]);
5920 } catch (NotFoundException $e) {
5921 throw new BadRequestException('Invalid argument', $e);
5922 } catch (Exception $e) {
5923 throw new InternalServerErrorException('Internal Server exception', $e);
5927 /// @TODO move to top of file or somewhere better
5928 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5929 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5932 * update a direct_message to seen state
5934 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5935 * @return string|array (success result=ok, error result=error with error message)
5936 * @throws BadRequestException
5937 * @throws ForbiddenException
5938 * @throws ImagickException
5939 * @throws InternalServerErrorException
5940 * @throws UnauthorizedException
5942 function api_friendica_direct_messages_setseen($type)
5945 if (api_user() === false) {
5946 throw new ForbiddenException();
5950 $user_info = api_get_user($a);
5951 $uid = $user_info['uid'];
5952 $id = $_REQUEST['id'] ?? 0;
5954 // return error if id is zero
5956 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5957 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5960 // error message if specified id is not in database
5961 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5962 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5963 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5966 // update seen indicator
5967 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5971 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5972 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5974 $answer = ['result' => 'error', 'message' => 'unknown error'];
5975 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5979 /// @TODO move to top of file or somewhere better
5980 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5983 * search for direct_messages containing a searchstring through api
5985 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5986 * @param string $box
5987 * @return string|array (success: success=true if found and search_result contains found messages,
5988 * success=false if nothing was found, search_result='nothing found',
5989 * error: result=error with error message)
5990 * @throws BadRequestException
5991 * @throws ForbiddenException
5992 * @throws ImagickException
5993 * @throws InternalServerErrorException
5994 * @throws UnauthorizedException
5996 function api_friendica_direct_messages_search($type, $box = "")
6000 if (api_user() === false) {
6001 throw new ForbiddenException();
6005 $user_info = api_get_user($a);
6006 $searchstring = $_REQUEST['searchstring'] ?? '';
6007 $uid = $user_info['uid'];
6009 // error if no searchstring specified
6010 if ($searchstring == "") {
6011 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6012 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6015 // get data for the specified searchstring
6017 "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",
6019 DBA::escape('%'.$searchstring.'%')
6022 $profile_url = $user_info["url"];
6024 // message if nothing was found
6025 if (!DBA::isResult($r)) {
6026 $success = ['success' => false, 'search_results' => 'problem with query'];
6027 } elseif (count($r) == 0) {
6028 $success = ['success' => false, 'search_results' => 'nothing found'];
6031 foreach ($r as $item) {
6032 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6033 $recipient = $user_info;
6034 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6035 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6036 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6037 $sender = $user_info;
6040 if (isset($recipient) && isset($sender)) {
6041 $ret[] = api_format_messages($item, $recipient, $sender);
6044 $success = ['success' => true, 'search_results' => $ret];
6047 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6050 /// @TODO move to top of file or somewhere better
6051 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6054 * Returns a list of saved searches.
6056 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6058 * @param string $type Return format: json or xml
6060 * @return string|array
6063 function api_saved_searches_list($type)
6065 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6068 while ($term = DBA::fetch($terms)) {
6070 'created_at' => api_date(time()),
6071 'id' => intval($term['id']),
6072 'id_str' => $term['id'],
6073 'name' => $term['term'],
6075 'query' => $term['term']
6081 return api_format_data("terms", $type, ['terms' => $result]);
6084 /// @TODO move to top of file or somewhere better
6085 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6088 * Number of comments
6090 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6092 * @param object $data [Status, Status]
6096 function bindComments(&$data)
6098 if (count($data) == 0) {
6104 foreach ($data as $item) {
6105 $ids[] = $item['id'];
6108 $idStr = DBA::escape(implode(', ', $ids));
6109 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6110 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6111 $itemsData = DBA::toArray($items);
6113 foreach ($itemsData as $item) {
6114 $comments[$item['parent']] = $item['comments'];
6117 foreach ($data as $idx => $item) {
6119 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6124 @TODO Maybe open to implement?
6126 [pagename] => api/1.1/statuses/lookup.json
6127 [id] => 605138389168451584
6128 [include_cards] => true
6129 [cards_platform] => Android-12
6130 [include_entities] => true
6131 [include_my_retweet] => 1
6133 [include_reply_count] => true
6134 [include_descendent_reply_count] => true
6138 Not implemented by now:
6139 statuses/retweets_of_me
6144 account/update_location
6145 account/update_profile_background_image
6148 friendica/profile/update
6149 friendica/profile/create
6150 friendica/profile/delete
6152 Not implemented in status.net:
6153 statuses/retweeted_to_me
6154 statuses/retweeted_by_me
6155 direct_messages/destroy
6157 account/update_delivery_device
6158 notifications/follow