*/
use Friendica\App;
-use Friendica\Collection\Api\Notifications as ApiNotifications;
use Friendica\Content\ContactSelector;
use Friendica\Content\Text\BBCode;
use Friendica\Content\Text\HTML;
-use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Core\Protocol;
use Friendica\Core\System;
use Friendica\Model\Profile;
use Friendica\Model\User;
use Friendica\Model\Verb;
+use Friendica\Module\Api\ApiResponse;
+use Friendica\Module\BaseApi;
use Friendica\Network\HTTPException;
use Friendica\Network\HTTPException\BadRequestException;
-use Friendica\Network\HTTPException\ExpectationFailedException;
use Friendica\Network\HTTPException\ForbiddenException;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Network\HTTPException\MethodNotAllowedException;
use Friendica\Network\HTTPException\NotFoundException;
use Friendica\Network\HTTPException\TooManyRequestsException;
use Friendica\Network\HTTPException\UnauthorizedException;
-use Friendica\Object\Api\Friendica\Notification as ApiNotification;
use Friendica\Object\Image;
use Friendica\Protocol\Activity;
-use Friendica\Protocol\Diaspora;
+use Friendica\Security\BasicAuth;
use Friendica\Security\OAuth;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Images;
use Friendica\Util\Network;
+use Friendica\Util\Proxy;
use Friendica\Util\Strings;
-use Friendica\Util\XML;
require_once __DIR__ . '/../mod/item.php';
require_once __DIR__ . '/../mod/wall_upload.php';
];
}
-/**
- * Log in user via Simple HTTP Auth.
- * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
- *
- * @param App $a App
- * @throws ForbiddenException
- * @throws InternalServerErrorException
- * @throws UnauthorizedException
- * @hook 'authenticate'
- * array $addon_auth
- * 'username' => username from login form
- * 'password' => password from login form
- * 'authenticated' => return status,
- * 'user_record' => return authenticated user record
- */
-function api_login(App $a)
-{
- $_SESSION["allow_api"] = false;
-
- // workaround for HTTP-auth in CGI mode
- if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
- $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
- if (strlen($userpass)) {
- list($name, $password) = explode(':', $userpass);
- $_SERVER['PHP_AUTH_USER'] = $name;
- $_SERVER['PHP_AUTH_PW'] = $password;
- }
- }
-
- if (empty($_SERVER['PHP_AUTH_USER'])) {
- Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
- header('WWW-Authenticate: Basic realm="Friendica"');
- throw new UnauthorizedException("This API requires login");
- }
-
- $user = $_SERVER['PHP_AUTH_USER'] ?? '';
- $password = $_SERVER['PHP_AUTH_PW'] ?? '';
-
- // allow "user@server" login (but ignore 'server' part)
- $at = strstr($user, "@", true);
- if ($at) {
- $user = $at;
- }
-
- // next code from mod/auth.php. needs better solution
- $record = null;
-
- $addon_auth = [
- 'username' => trim($user),
- 'password' => trim($password),
- 'authenticated' => 0,
- 'user_record' => null,
- ];
-
- /*
- * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
- * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
- * and later addons should not interfere with an earlier one that succeeded.
- */
- Hook::callAll('authenticate', $addon_auth);
-
- if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
- $record = $addon_auth['user_record'];
- } else {
- $user_id = User::authenticate(trim($user), trim($password), true);
- if ($user_id !== false) {
- $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
- }
- }
-
- if (!DBA::isResult($record)) {
- Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
- header('WWW-Authenticate: Basic realm="Friendica"');
- //header('HTTP/1.0 401 Unauthorized');
- //die('This api requires login');
- throw new UnauthorizedException("This API requires login");
- }
-
- // Don't refresh the login date more often than twice a day to spare database writes
- $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
-
- DI::auth()->setForUser($a, $record, false, false, $login_refresh);
-
- $_SESSION["allow_api"] = true;
-
- Hook::callAll('logged_in', $record);
-}
-
/**
* Check HTTP method of called API
*
$called_api = explode("/", $p);
if (!empty($info['auth']) && api_user() === false) {
- api_login($a);
+ BasicAuth::getCurrentUserID(true);
Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
}
Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
throw new NotFoundException();
} catch (HTTPException $e) {
- header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
- return api_error($type, $e, $args);
+ DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
}
}
-/**
- * Format API error string
- *
- * @param string $type Return type (xml, json, rss, as)
- * @param object $e HTTPException Error object
- * @param App\Arguments $args The App arguments
- * @return string|array error message formatted as $type
- */
-function api_error($type, $e, App\Arguments $args)
-{
- $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
- /// @TODO: https://dev.twitter.com/overview/api/response-codes
-
- $error = ["error" => $error,
- "code" => $e->getCode() . " " . $e->httpdesc,
- "request" => $args->getQueryString()];
-
- $return = api_format_data('status', $type, ['status' => $error]);
-
- switch ($type) {
- case "xml":
- header("Content-Type: text/xml");
- break;
- case "json":
- header("Content-Type: application/json");
- $return = json_encode($return);
- break;
- case "rss":
- header("Content-Type: application/rss+xml");
- break;
- case "atom":
- header("Content-Type: application/atom+xml");
- break;
- }
-
- return $return;
-}
-
/**
* Set values for RSS template
*
function api_rss_extra(App $a, $arr, $user_info)
{
if (is_null($user_info)) {
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
}
$arr['$user'] = $user_info;
* @throws InternalServerErrorException
* @throws UnauthorizedException
*/
-function api_get_user(App $a, $contact_id = null)
+function api_get_user($contact_id = null)
{
global $called_api;
if (!empty(DI::args()->getArgv()[$argid])) {
$data = explode(".", DI::args()->getArgv()[$argid]);
if (count($data) > 1) {
- list($user, $null) = $data;
+ [$user, $null] = $data;
}
}
if (is_numeric($user)) {
if (!$user) {
if (api_user() === false) {
- api_login($a);
+ BasicAuth::getCurrentUserID(true);
return false;
} else {
$user = api_user();
'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
'description' => BBCode::toPlaintext($contact["about"] ?? ''),
- 'profile_image_url' => $contact["micro"],
- 'profile_image_url_https' => $contact["micro"],
- 'profile_image_url_profile_size' => $contact["thumb"],
- 'profile_image_url_large' => $contact["photo"],
+ 'profile_image_url' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_MICRO),
+ 'profile_image_url_https' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_MICRO),
+ 'profile_image_url_profile_size' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_THUMB),
+ 'profile_image_url_large' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_SMALL),
'url' => $contact["url"],
'protected' => false,
'followers_count' => 0,
'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
'location' => $location,
'description' => BBCode::toPlaintext($description ?? ''),
- 'profile_image_url' => $uinfo[0]['micro'],
- 'profile_image_url_https' => $uinfo[0]['micro'],
- 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
- 'profile_image_url_large' => $uinfo[0]["photo"],
+ 'profile_image_url' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_MICRO),
+ 'profile_image_url_https' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_MICRO),
+ 'profile_image_url_profile_size' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_THUMB),
+ 'profile_image_url_large' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_SMALL),
'url' => $uinfo[0]['url'],
'protected' => false,
'followers_count' => intval($countfollowers),
*/
function api_item_get_user(App $a, $item)
{
- $status_user = api_get_user($a, $item['author-id'] ?? null);
+ $status_user = api_get_user($item['author-id'] ?? null);
$author_user = $status_user;
$status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
- $owner_user = api_get_user($a, $item['owner-id'] ?? null);
+ $owner_user = api_get_user($item['owner-id'] ?? null);
} else {
$owner_user = $author_user;
}
return ([$status_user, $author_user, $owner_user]);
}
-/**
- * walks recursively through an array with the possibility to change value and key
- *
- * @param array $array The array to walk through
- * @param callable $callback The callback function
- *
- * @return array the transformed array
- */
-function api_walk_recursive(array &$array, callable $callback)
-{
- $new_array = [];
-
- foreach ($array as $k => $v) {
- if (is_array($v)) {
- if ($callback($v, $k)) {
- $new_array[$k] = api_walk_recursive($v, $callback);
- }
- } else {
- if ($callback($v, $k)) {
- $new_array[$k] = $v;
- }
- }
- }
- $array = $new_array;
-
- return $array;
-}
-
-/**
- * Callback function to transform the array in an array that can be transformed in a XML file
- *
- * @param mixed $item Array item value
- * @param string $key Array key
- *
- * @return boolean Should the array item be deleted?
- */
-function api_reformat_xml(&$item, &$key)
-{
- if (is_bool($item)) {
- $item = ($item ? "true" : "false");
- }
-
- if (substr($key, 0, 10) == "statusnet_") {
- $key = "statusnet:".substr($key, 10);
- } elseif (substr($key, 0, 10) == "friendica_") {
- $key = "friendica:".substr($key, 10);
- }
- /// @TODO old-lost code?
- //else
- // $key = "default:".$key;
-
- return true;
-}
-
-/**
- * Creates the XML from a JSON style array
- *
- * @param array $data JSON style array
- * @param string $root_element Name of the root element
- *
- * @return string The XML data
- */
-function api_create_xml(array $data, $root_element)
-{
- $childname = key($data);
- $data2 = array_pop($data);
-
- $namespaces = ["" => "http://api.twitter.com",
- "statusnet" => "http://status.net/schema/api/1/",
- "friendica" => "http://friendi.ca/schema/api/1/",
- "georss" => "http://www.georss.org/georss"];
-
- /// @todo Auto detection of needed namespaces
- if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
- $namespaces = [];
- }
-
- if (is_array($data2)) {
- $key = key($data2);
- api_walk_recursive($data2, "api_reformat_xml");
-
- if ($key == "0") {
- $data4 = [];
- $i = 1;
-
- foreach ($data2 as $item) {
- $data4[$i++ . ":" . $childname] = $item;
- }
-
- $data2 = $data4;
- }
- }
-
- $data3 = [$root_element => $data2];
-
- $ret = XML::fromArray($data3, $xml, false, $namespaces);
- return $ret;
-}
-
-/**
- * Formats the data according to the data type
- *
- * @param string $root_element Name of the root element
- * @param string $type Return type (atom, rss, xml, json)
- * @param array $data JSON style array
- *
- * @return array|string (string|array) XML data or JSON data
- */
-function api_format_data($root_element, $type, $data)
-{
- switch ($type) {
- case "atom":
- case "rss":
- case "xml":
- $ret = api_create_xml($data, $root_element);
- break;
- case "json":
- default:
- $ret = $data;
- break;
- }
- return $ret;
-}
-
/**
* TWITTER API
*/
$skip_status = $_REQUEST['skip_status'] ?? false;
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
// "verified" isn't used here in the standard
unset($user_info["verified"]);
unset($user_info["uid"]);
unset($user_info["self"]);
- return api_format_data("user", $type, ['user' => $user_info]);
+ return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
}
/// @TODO move to top of file or somewhere better
logger::notice('api_statuses_update: no user');
throw new ForbiddenException();
}
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
$_REQUEST['profile_uid'] = api_user();
$_REQUEST['api_source'] = true;
throw new ForbiddenException();
}
- api_get_user($a);
+ api_get_user();
// convert $_POST array items to the form we use for web posts.
if (requestdata('htmlstatus')) {
throw new ForbiddenException();
}
- api_get_user($a);
+ api_get_user();
if (empty($_FILES['media'])) {
// Output error
throw new ForbiddenException();
}
- api_get_user($a);
+ api_get_user();
$postdata = Network::postdata();
Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
- return api_format_data('statuses', $type, ['status' => $status_info]);
+ return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
}
/**
{
$a = Friendica\DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
$item = api_get_last_status($user_info['pid'], $user_info['uid']);
if (!empty($item)) {
unset($user_info['uid']);
unset($user_info['self']);
- return api_format_data('user', $type, ['user' => $user_info]);
+ return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
}
/// @TODO move to top of file or somewhere better
if (DBA::isResult($contacts)) {
$k = 0;
foreach ($contacts as $contact) {
- $user_info = api_get_user($a, $contact['id']);
+ $user_info = api_get_user($contact['id']);
if ($type == 'xml') {
$userlist[$k++ . ':user'] = $user_info;
throw new BadRequestException('No search term specified.');
}
- return api_format_data('users', $type, $userlist);
+ return DI::apiResponse()->formatData('users', $type, $userlist);
}
/// @TODO move to top of file or somewhere better
if (!empty($_REQUEST['user_id'])) {
foreach (explode(',', $_REQUEST['user_id']) as $id) {
if (!empty($id)) {
- $users[] = api_get_user(DI::app(), $id);
+ $users[] = api_get_user($id);
}
}
}
throw new NotFoundException;
}
- return api_format_data("users", $type, ['users' => $users]);
+ return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
}
/// @TODO move to top of file or somewhere better
function api_search($type)
{
$a = DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
DBA::close($tags);
if (empty($uriids)) {
- return api_format_data('statuses', $type, $data);
+ return DI::apiResponse()->formatData('statuses', $type, $data);
}
$condition = ['uri-id' => $uriids];
bindComments($data['status']);
- return api_format_data('statuses', $type, $data);
+ return DI::apiResponse()->formatData('statuses', $type, $data);
}
/// @TODO move to top of file or somewhere better
function api_statuses_home_timeline($type)
{
$a = DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
break;
}
- return api_format_data("statuses", $type, $data);
+ return DI::apiResponse()->formatData("statuses", $type, $data);
}
function api_statuses_public_timeline($type)
{
$a = DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
break;
}
- return api_format_data("statuses", $type, $data);
+ return DI::apiResponse()->formatData("statuses", $type, $data);
}
/// @TODO move to top of file or somewhere better
function api_statuses_networkpublic_timeline($type)
{
$a = DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
break;
}
- return api_format_data("statuses", $type, $data);
+ return DI::apiResponse()->formatData("statuses", $type, $data);
}
/// @TODO move to top of file or somewhere better
function api_statuses_show($type)
{
$a = DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
if ($conversation) {
$data = ['status' => $ret];
- return api_format_data("statuses", $type, $data);
+ return DI::apiResponse()->formatData("statuses", $type, $data);
} else {
$data = ['status' => $ret[0]];
- return api_format_data("status", $type, $data);
+ return DI::apiResponse()->formatData("status", $type, $data);
}
}
function api_conversation_show($type)
{
$a = DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
// try to fetch the item for the local user - or the public item, if there is no local one
$item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
if (!DBA::isResult($item)) {
- throw new BadRequestException("There is no status with this id.");
+ throw new BadRequestException("There is no status with the id $id.");
}
$parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
$ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
$data = ['status' => $ret];
- return api_format_data("statuses", $type, $data);
+ return DI::apiResponse()->formatData("statuses", $type, $data);
}
/// @TODO move to top of file or somewhere better
throw new ForbiddenException();
}
- api_get_user($a);
+ api_get_user();
// params
$id = intval(DI::args()->getArgv()[3] ?? 0);
throw new ForbiddenException();
}
- api_get_user($a);
+ api_get_user();
// params
$id = intval(DI::args()->getArgv()[3] ?? 0);
function api_statuses_mentions($type)
{
$a = DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
break;
}
- return api_format_data("statuses", $type, $data);
+ return DI::apiResponse()->formatData("statuses", $type, $data);
}
/// @TODO move to top of file or somewhere better
function api_statuses_user_timeline($type)
{
$a = DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
break;
}
- return api_format_data("statuses", $type, $data);
+ return DI::apiResponse()->formatData("statuses", $type, $data);
}
/// @TODO move to top of file or somewhere better
}
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
$rets = api_format_items([$item], $user_info, false, $type);
$ret = $rets[0];
break;
}
- return api_format_data("status", $type, $data);
+ return DI::apiResponse()->formatData("status", $type, $data);
}
/// @TODO move to top of file or somewhere better
global $called_api;
$a = DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
break;
}
- return api_format_data("statuses", $type, $data);
+ return DI::apiResponse()->formatData("statuses", $type, $data);
}
/// @TODO move to top of file or somewhere better
//builtin_activity_puller($i, $activities);
// get user data and add it to the array of the activity
- $user = api_get_user($a, $parent_item['author-id']);
+ $user = api_get_user($parent_item['author-id']);
switch ($parent_item['verb']) {
case Activity::LIKE:
$activities['like'][] = $user;
}
foreach ((array)$items as $item) {
- list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
+ [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
// Look if the posts are matching if they should be filtered by user id
if ($filter_user && ($status_user["id"] != $user_info["id"])) {
$a = Friendica\DI::app();
if (empty($status_user) || empty($author_user) || empty($owner_user)) {
- list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
+ [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
}
DI::contentItem()->localize($item);
if (!empty($announce)) {
$retweeted_item = $item;
$item = $announce;
- $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
+ $status['friendica_owner'] = api_get_user($announce['author-id']);
}
}
$quoted_status['text'] = $conv_quoted['text'];
$quoted_status['statusnet_html'] = $conv_quoted['html'];
try {
- $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
+ $quoted_status["user"] = api_get_user($quoted_item["author-id"]);
} catch (BadRequestException $e) {
// user not found. should be found?
/// @todo check if the user should be always found
unset($retweeted_status['statusnet_conversation_id']);
$status['user'] = $status['friendica_owner'];
try {
- $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
+ $retweeted_status["user"] = api_get_user($retweeted_item["author-id"]);
} catch (BadRequestException $e) {
// user not found. should be found?
/// @todo check if the user should be always found
return $status;
}
-/**
- * Returns the remaining number of API requests available to the user before the API limit is reached.
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- * @throws Exception
- */
-function api_account_rate_limit_status($type)
-{
- if ($type == "xml") {
- $hash = [
- 'remaining-hits' => '150',
- '@attributes' => ["type" => "integer"],
- 'hourly-limit' => '150',
- '@attributes2' => ["type" => "integer"],
- 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
- '@attributes3' => ["type" => "datetime"],
- 'reset_time_in_seconds' => strtotime('now + 1 hour'),
- '@attributes4' => ["type" => "integer"],
- ];
- } else {
- $hash = [
- 'reset_time_in_seconds' => strtotime('now + 1 hour'),
- 'remaining_hits' => '150',
- 'hourly_limit' => '150',
- 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
- ];
- }
-
- return api_format_data('hash', $type, ['hash' => $hash]);
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
-
-/**
- * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- */
-function api_help_test($type)
-{
- if ($type == 'xml') {
- $ok = "true";
- } else {
- $ok = "ok";
- }
-
- return api_format_data('ok', $type, ["ok" => $ok]);
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/help/test', 'api_help_test', false);
-
/**
* Returns all lists the user subscribes to.
*
{
$ret = [];
/// @TODO $ret is not filled here?
- return api_format_data('lists', $type, ["lists_list" => $ret]);
+ return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
}
/// @TODO move to top of file or somewhere better
}
// params
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
$uid = $user_info['uid'];
$groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
'mode' => $mode
];
}
- return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
+ return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
}
/// @TODO move to top of file or somewhere better
{
$a = DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
}
break;
}
- return api_format_data("statuses", $type, $data);
+ return DI::apiResponse()->formatData("statuses", $type, $data);
}
/// @TODO move to top of file or somewhere better
$start = max(0, ($page - 1) * $count);
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
/* this is to stop Hotot to load friends multiple times
$ret = [];
foreach ($r as $cid) {
- $user = api_get_user($a, $cid['nurl']);
+ $user = api_get_user($cid['nurl']);
// "uid" and "self" are only needed for some internal stuff, so remove it from here
unset($user["uid"]);
unset($user["self"]);
if ($data === false) {
return false;
}
- return api_format_data("users", $type, $data);
+ return DI::apiResponse()->formatData("users", $type, $data);
}
/**
if ($data === false) {
return false;
}
- return api_format_data("users", $type, $data);
+ return DI::apiResponse()->formatData("users", $type, $data);
}
/// @TODO move to top of file or somewhere better
if ($data === false) {
return false;
}
- return api_format_data("users", $type, $data);
+ return DI::apiResponse()->formatData("users", $type, $data);
}
/// @TODO move to top of file or somewhere better
$ids[] = $user['id'];
}
- return api_format_data("ids", $type, ['id' => $ids]);
+ return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
}
/// @TODO move to top of file or somewhere better
api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
-/**
- * Returns the instance's configuration information.
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- * @throws InternalServerErrorException
- */
-function api_statusnet_config($type)
-{
- $name = DI::config()->get('config', 'sitename');
- $server = DI::baseUrl()->getHostname();
- $logo = DI::baseUrl() . '/images/friendica-64.png';
- $email = DI::config()->get('config', 'admin_email');
- $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
- $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
- $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
- $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
- $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
-
- $config = [
- 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
- 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
- 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
- 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
- 'shorturllength' => '30',
- 'friendica' => [
- 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
- 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
- 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
- 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
- ]
- ],
- ];
-
- return api_format_data('config', $type, ['config' => $config]);
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
-api_register_func('api/statusnet/config', 'api_statusnet_config', false);
-
-/**
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- */
-function api_statusnet_version($type)
-{
- // liar
- $fake_statusnet_version = "0.9.7";
-
- return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
-api_register_func('api/statusnet/version', 'api_statusnet_version', false);
-
/**
* Sends a new direct message.
*
return;
}
- $sender = api_get_user($a);
+ $sender = api_get_user();
$recipient = null;
if (!empty($_POST['screen_name'])) {
// Selecting the id by priority, friendica first
api_best_nickname($contacts);
- $recipient = api_get_user($a, $contacts[0]['nurl']);
+ $recipient = api_get_user($contacts[0]['nurl']);
}
} else {
- $recipient = api_get_user($a, $_POST['user_id']);
+ $recipient = api_get_user($_POST['user_id']);
}
if (empty($recipient)) {
break;
}
- return api_format_data("direct-messages", $type, $data);
+ return DI::apiResponse()->formatData("direct-messages", $type, $data);
}
/// @TODO move to top of file or somewhere better
}
// params
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
//required
$id = $_REQUEST['id'] ?? 0;
// optional
// error if no id or parenturi specified (for clients posting parent-uri as well)
if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
$answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
- return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
+ return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
}
// BadRequestException if no id specified (for clients using Twitter API)
if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
if ($verbose == "true") {
$answer = ['result' => 'error', 'message' => 'message id not in database'];
- return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
+ return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
}
/// @todo BadRequestException ok for Twitter API clients?
throw new BadRequestException('message id not in database');
if ($result) {
// return success
$answer = ['result' => 'ok', 'message' => 'message deleted'];
- return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
+ return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
} else {
$answer = ['result' => 'error', 'message' => 'unknown error'];
- return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
+ return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
}
}
/// @todo return JSON data like Twitter API not yet implemented
// Set screen_name since Twidere requests it
$contact['screen_name'] = $contact['nick'];
- return api_format_data('friendships-destroy', $type, ['user' => $contact]);
+ return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
}
+
api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
/**
unset($_REQUEST["screen_name"]);
unset($_GET["screen_name"]);
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if ($user_info === false) {
throw new ForbiddenException();
}
));
if ($verbose == "true" && !DBA::isResult($r)) {
$answer = ['result' => 'error', 'message' => 'no mails available'];
- return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
+ return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
}
$ret = [];
foreach ($r as $item) {
if ($box == "inbox" || $item['from-url'] != $profile_url) {
$recipient = $user_info;
- $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
+ $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
} elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
- $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
+ $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
$sender = $user_info;
}
break;
}
- return api_format_data("direct-messages", $type, $data);
+ return DI::apiResponse()->formatData("direct-messages", $type, $data);
}
/**
api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
-/**
- * delete a complete photoalbum with all containing photos from database through api
- *
- * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string|array
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws InternalServerErrorException
- */
-function api_fr_photoalbum_delete($type)
-{
- if (api_user() === false) {
- throw new ForbiddenException();
- }
- // input params
- $album = $_REQUEST['album'] ?? '';
-
- // we do not allow calls without album string
- if ($album == "") {
- throw new BadRequestException("no albumname specified");
- }
- // check if album is existing
-
- $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
- if (!DBA::isResult($photos)) {
- throw new BadRequestException("album not available");
- }
-
- $resourceIds = array_column($photos, 'resource-id');
-
- // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
- // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
- $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
- Item::deleteForUser($condition, api_user());
-
- // now let's delete all photos from the album
- $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
-
- // return success of deletion or error message
- if ($result) {
- $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
- return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
- } else {
- throw new InternalServerErrorException("unknown error - deleting from database failed");
- }
-}
-
-/**
- * update the name of the album for all photos of an album
- *
- * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string|array
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws InternalServerErrorException
- */
-function api_fr_photoalbum_update($type)
-{
- if (api_user() === false) {
- throw new ForbiddenException();
- }
- // input params
- $album = $_REQUEST['album'] ?? '';
- $album_new = $_REQUEST['album_new'] ?? '';
-
- // we do not allow calls without album string
- if ($album == "") {
- throw new BadRequestException("no albumname specified");
- }
- if ($album_new == "") {
- throw new BadRequestException("no new albumname specified");
- }
- // check if album is existing
- if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
- throw new BadRequestException("album not available");
- }
- // now let's update all photos to the albumname
- $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
-
- // return success of updating or error message
- if ($result) {
- $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
- return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
- } else {
- throw new InternalServerErrorException("unknown error - updating in database failed");
- }
-}
-
-
/**
* list all photos of the authenticated user
*
$r = DBA::toArray(DBA::p(
"SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
- WHERE `uid` = ? AND NOT `album` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
- local_user(), Photo::CONTACT_PHOTOS, DI::l10n()->t(Photo::CONTACT_PHOTOS)
+ WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
+ local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
));
$typetoext = [
'image/jpeg' => 'jpg',
}
}
}
- return api_format_data("photos", $type, $data);
+ return DI::apiResponse()->formatData("photos", $type, $data);
}
/**
// now let's upload the new media in create-mode
if ($mode == "create") {
$media = $_FILES['media'];
- $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
+ $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, Photo::DEFAULT, $visibility);
// return success of updating or error message
if (!is_null($data)) {
- return api_format_data("photo_create", $type, $data);
+ return DI::apiResponse()->formatData("photo_create", $type, $data);
} else {
throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
}
if (!empty($_FILES['media'])) {
$nothingtodo = false;
$media = $_FILES['media'];
- $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
+ $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
if (!is_null($data)) {
- return api_format_data("photo_update", $type, $data);
+ return DI::apiResponse()->formatData("photo_update", $type, $data);
}
}
// return success of updating or error message
if ($result) {
$answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
- return api_format_data("photo_update", $type, ['$result' => $answer]);
+ return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
} else {
if ($nothingtodo) {
$answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
- return api_format_data("photo_update", $type, ['$result' => $answer]);
+ return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
}
throw new InternalServerErrorException("unknown error - update photo entry in database failed");
}
throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
}
-/**
- * delete a single photo from the database through api
- *
- * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string|array
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws InternalServerErrorException
- */
-function api_fr_photo_delete($type)
-{
- if (api_user() === false) {
- throw new ForbiddenException();
- }
-
- // input params
- $photo_id = $_REQUEST['photo_id'] ?? null;
-
- // do several checks on input parameters
- // we do not allow calls without photo id
- if ($photo_id == null) {
- throw new BadRequestException("no photo_id specified");
- }
-
- // check if photo is existing in database
- if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
- throw new BadRequestException("photo not available");
- }
-
- // now we can perform on the deletion of the photo
- $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
-
- // return success of deletion or error message
- if ($result) {
- // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
- // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
- $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
- Item::deleteForUser($condition, api_user());
-
- $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
- return api_format_data("photo_delete", $type, ['$result' => $result]);
- } else {
- throw new InternalServerErrorException("unknown error on deleting photo from database table");
- }
-}
-
-
/**
* returns the details of a specified photo id, if scale is given, returns the photo data in base 64
*
// prepare json/xml output with data from database for the requested photo
$data = prepare_photo_data($type, $scale, $photo_id);
- return api_format_data("photo_detail", $type, $data);
+ return DI::apiResponse()->formatData("photo_detail", $type, $data);
}
$media = $_FILES['media'];
}
// save new profile image
- $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
+ $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
// get filetype
if (is_array($media['type'])) {
// change specified profile or all profiles to the new resource-id
if ($is_default_profile) {
$condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
- Photo::update(['profile' => false], $condition);
+ Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
} else {
$fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
}
// place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
-api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
-api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
-api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
function api_account_update_profile($type)
{
$local_user = api_user();
- $api_user = api_get_user(DI::app());
+ $api_user = api_get_user();
if (!empty($_POST['name'])) {
DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
* @param string $allow_gid
* @param string $deny_gid
* @param string $desc
- * @param integer $profile
+ * @param integer $phototype
* @param boolean $visibility
* @param string $photo_id
* @return array
* @throws NotFoundException
* @throws UnauthorizedException
*/
-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)
+function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype = 0, $visibility = false, $photo_id = null)
{
$visitor = 0;
$src = "";
// check max length of images on server
$max_length = DI::config()->get('system', 'max_image_length');
- if (!$max_length) {
- $max_length = MAX_IMAGE_LENGTH;
- }
if ($max_length > 0) {
$Image->scaleDown($max_length);
logger::info("File upload: Scaling picture to new size " . $max_length);
// upload normal image (scales 0, 1, 2)
logger::info("photo upload: starting new photo upload");
- $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
+ $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
logger::notice("photo upload: image upload with scale 0 (original size) failed");
}
if ($width > 640 || $height > 640) {
$Image->scaleDown(640);
- $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
+ $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
logger::notice("photo upload: image upload with scale 1 (640x640) failed");
}
if ($width > 320 || $height > 320) {
$Image->scaleDown(320);
- $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
+ $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
logger::notice("photo upload: image upload with scale 2 (320x320) failed");
}
if ($width > 300 || $height > 300) {
$Image->scaleDown(300);
- $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
+ $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
}
if ($width > 80 || $height > 80) {
$Image->scaleDown(80);
- $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
+ $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
}
if ($width > 48 || $height > 48) {
$Image->scaleDown(48);
- $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
+ $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
}
function prepare_photo_data($type, $scale, $photo_id)
{
$a = DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if ($user_info === false) {
throw new ForbiddenException();
`type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
- `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
- `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
+ `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
+ `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
local_user(),
$photo_id
));
}
// params
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
$gid = $_REQUEST['gid'] ?? 0;
$uid = $user_info['uid'];
$user_element = "users";
$k = 0;
foreach ($members as $member) {
- $user = api_get_user($a, $member['nurl']);
+ $user = api_get_user($member['nurl']);
$users[$k++.":user"] = $user;
}
} else {
$user_element = "user";
foreach ($members as $member) {
- $user = api_get_user($a, $member['nurl']);
+ $user = api_get_user($member['nurl']);
$users[] = $user;
}
}
$grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
}
- return api_format_data("groups", $type, ['group' => $grps]);
+ return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
}
-api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
-
-
-/**
- * Delete the specified group of the user.
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws ImagickException
- * @throws InternalServerErrorException
- * @throws UnauthorizedException
- */
-function api_friendica_group_delete($type)
-{
- $a = DI::app();
-
- if (api_user() === false) {
- throw new ForbiddenException();
- }
-
- // params
- $user_info = api_get_user($a);
- $gid = $_REQUEST['gid'] ?? 0;
- $name = $_REQUEST['name'] ?? '';
- $uid = $user_info['uid'];
- // error if no gid specified
- if ($gid == 0 || $name == "") {
- throw new BadRequestException('gid or name not specified');
- }
-
- // error message if specified gid is not in database
- if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid])) {
- throw new BadRequestException('gid not available');
- }
-
- // error message if specified gid is not in database
- if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid, 'name' => $name])) {
- throw new BadRequestException('wrong group name');
- }
-
- // delete group
- $ret = Group::removeByName($uid, $name);
- if ($ret) {
- // return success
- $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
- return api_format_data("group_delete", $type, ['result' => $success]);
- } else {
- throw new BadRequestException('other API error');
- }
-}
-api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
+api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
/**
* Delete a group.
}
// params
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
$gid = $_REQUEST['list_id'] ?? 0;
$uid = $user_info['uid'];
'user' => $user_info
];
- return api_format_data("lists", $type, ['lists' => $list]);
+ return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
}
}
+
api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
/**
}
// params
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
$name = $_REQUEST['name'] ?? '';
$uid = $user_info['uid'];
$json = json_decode($_POST['json'], true);
$success = group_create($name, $uid, $users);
- return api_format_data("group_create", $type, ['result' => $success]);
+ return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
}
+
api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
/**
}
// params
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
$name = $_REQUEST['name'] ?? '';
$uid = $user_info['uid'];
'user' => $user_info
];
- return api_format_data("lists", $type, ['lists'=>$grp]);
+ return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
}
}
+
api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
/**
}
// params
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
$uid = $user_info['uid'];
$gid = $_REQUEST['gid'] ?? 0;
$name = $_REQUEST['name'] ?? '';
$found = ($user['cid'] == $cid ? true : false);
}
if (!isset($found) || !$found) {
- Group::removeMemberByName($uid, $name, $cid);
+ $gid = Group::getIdByName($uid, $name);
+ Group::removeMember($gid, $cid);
}
}
// return success message incl. missing users in array
$status = ($erroraddinguser ? "missing user" : "ok");
$success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
- return api_format_data("group_update", $type, ['result' => $success]);
+ return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
}
api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
}
// params
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
$gid = $_REQUEST['list_id'] ?? 0;
$name = $_REQUEST['name'] ?? '';
$uid = $user_info['uid'];
'user' => $user_info
];
- return api_format_data("lists", $type, ['lists' => $list]);
+ return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
}
}
api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
-/**
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws ImagickException
- * @throws InternalServerErrorException
- */
-function api_friendica_activity($type)
-{
- $a = DI::app();
-
- if (api_user() === false) {
- throw new ForbiddenException();
- }
- $verb = strtolower(DI::args()->getArgv()[3]);
- $verb = preg_replace("|\..*$|", "", $verb);
-
- $id = $_REQUEST['id'] ?? 0;
-
- $res = Item::performActivity($id, $verb, api_user());
-
- if ($res) {
- if ($type == "xml") {
- $ok = "true";
- } else {
- $ok = "ok";
- }
- return api_format_data('ok', $type, ['ok' => $ok]);
- } else {
- throw new BadRequestException('Error adding activity');
- }
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
-
-/**
- * Returns notifications
- *
- * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- *
- * @return string|array
- * @throws ForbiddenException
- * @throws BadRequestException
- * @throws Exception
- */
-function api_friendica_notification($type)
-{
- if (api_user() === false) {
- throw new ForbiddenException();
- }
- if (DI::args()->getArgc()!==3) {
- throw new BadRequestException('Invalid argument count');
- }
-
- $Notifies = DI::notify()->selectAllForUser(local_user(), 50);
-
- $notifications = new ApiNotifications();
- foreach ($Notifies as $Notify) {
- $notifications[] = new ApiNotification($Notify);
- }
-
- if ($type == 'xml') {
- $xmlnotes = [];
- foreach ($notifications as $notification) {
- $xmlnotes[] = ['@attributes' => $notification->toArray()];
- }
-
- $result = $xmlnotes;
- } elseif (count($notifications) > 0) {
- $result = $notifications->getArrayCopy();
- } else {
- $result = false;
- }
-
- return api_format_data('notes', $type, ['note' => $result]);
-}
-
/**
* Set notification as seen and returns associated item (if possible)
*
function api_friendica_notification_seen($type)
{
$a = DI::app();
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
// we found the item, return it to the user
$ret = api_format_items([$item], $user_info, false, $type);
$data = ['status' => $ret];
- return api_format_data('status', $type, $data);
+ return DI::apiResponse()->formatData('status', $type, $data);
}
// the item can't be found, but we set the notification as seen, so we count this as a success
}
- return api_format_data('result', $type, ['result' => 'success']);
+ return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
} catch (NotFoundException $e) {
throw new BadRequestException('Invalid argument', $e);
} catch (Exception $e) {
/// @TODO move to top of file or somewhere better
api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
-api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
-
-/**
- * update a direct_message to seen state
- *
- * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string|array (success result=ok, error result=error with error message)
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws ImagickException
- * @throws InternalServerErrorException
- * @throws UnauthorizedException
- */
-function api_friendica_direct_messages_setseen($type)
-{
- $a = DI::app();
- if (api_user() === false) {
- throw new ForbiddenException();
- }
-
- // params
- $user_info = api_get_user($a);
- $uid = $user_info['uid'];
- $id = $_REQUEST['id'] ?? 0;
-
- // return error if id is zero
- if ($id == "") {
- $answer = ['result' => 'error', 'message' => 'message id not specified'];
- return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
- }
-
- // error message if specified id is not in database
- if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
- $answer = ['result' => 'error', 'message' => 'message id not in database'];
- return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
- }
-
- // update seen indicator
- $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
-
- if ($result) {
- // return success
- $answer = ['result' => 'ok', 'message' => 'message set to seen'];
- return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
- } else {
- $answer = ['result' => 'error', 'message' => 'unknown error'];
- return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
- }
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
/**
* search for direct_messages containing a searchstring through api
}
// params
- $user_info = api_get_user($a);
+ $user_info = api_get_user();
$searchstring = $_REQUEST['searchstring'] ?? '';
$uid = $user_info['uid'];
// error if no searchstring specified
if ($searchstring == "") {
$answer = ['result' => 'error', 'message' => 'searchstring not specified'];
- return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
+ return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
}
// get data for the specified searchstring
foreach ($r as $item) {
if ($box == "inbox" || $item['from-url'] != $profile_url) {
$recipient = $user_info;
- $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
+ $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
} elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
- $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
+ $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
$sender = $user_info;
}
$success = ['success' => true, 'search_results' => $ret];
}
- return api_format_data("direct_message_search", $type, ['$result' => $success]);
+ return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
}
/// @TODO move to top of file or somewhere better
api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
-/**
- * Returns a list of saved searches.
- *
- * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
- *
- * @param string $type Return format: json or xml
- *
- * @return string|array
- * @throws Exception
- */
-function api_saved_searches_list($type)
-{
- $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
-
- $result = [];
- while ($term = DBA::fetch($terms)) {
- $result[] = [
- 'created_at' => api_date(time()),
- 'id' => intval($term['id']),
- 'id_str' => $term['id'],
- 'name' => $term['term'],
- 'position' => null,
- 'query' => $term['term']
- ];
- }
-
- DBA::close($terms);
-
- return api_format_data("terms", $type, ['terms' => $result]);
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
-
/*
* Number of comments
*