Compare commits

..

3 Commits

Author SHA1 Message Date
2f5aa63306
formatting 2024-04-10 11:52:35 +02:00
7f16b67d02
fix regex 2024-04-10 11:34:54 +02:00
4a3bbeec79
formatting 2024-04-10 11:33:44 +02:00
4 changed files with 853 additions and 787 deletions

View File

@ -1,8 +1,12 @@
{
"com.thorlaksson.phpcs.formatOnSave" : true,
"com.thorlaksson.phpcs.runOnChange" : "onSave",
"com.thorlaksson.phpcs.standard" : "phpcs.xml",
"editor.default_syntax" : "php",
"php.validate" : "onSave",
"prettier.format-on-save" : "Disable",
"prettier.format-on-save.ignore-remote" : "Disable",
"prettier.format-on-save.ignore-without-config" : "Disable",
"workspace.color" : 1,
"workspace.name" : "APnutI"
}

View File

@ -18,10 +18,10 @@
<property name="eolChar" value="\n"/>
</properties>
</rule>
<arg name="tab-width" value="2"/>
<arg name="tab-width" value="4"/>
<rule ref="Generic.WhiteSpace.ScopeIndent">
<properties>
<property name="indent" value="2"/>
<property name="indent" value="4"/>
</properties>
</rule>

View File

@ -7,7 +7,6 @@ use APnutI\Entities\Poll;
use APnutI\Entities\User;
use APnutI\Entities\Channel;
use APnutI\Exceptions\PnutException;
use APnutI\Exceptions\NotFoundException;
use APnutI\Exceptions\NotAuthorizedException;
use APnutI\Exceptions\HttpPnutException;
use APnutI\Exceptions\HttpPnutRedirectException;
@ -26,7 +25,7 @@ class APnutI
protected string $auth_url = 'https://pnut.io/oauth/authenticate';
protected string $client_secret;
protected string $client_id;
protected string $scope = "";
protected string $scope = '';
protected string $redirect_uri;
protected int $rate_limit = 40;
protected int $rate_limit_remaining = 40;
@ -84,12 +83,13 @@ class APnutI
if (empty($log_level)) {
$log_level = Logger::INFO;
} elseif (is_string($log_level)) {
$log_level = constant('Monolog\Logger::'.$log_level);
$log_level = constant('Monolog\Logger::' . $log_level);
}
$this->logger = empty($log_path) ? new NullLogger() : new Logger($this->app_name);
$this->token_session_key = $this->app_name.'access_token';
$this->token_redirect_after_auth = $this->app_name
.'redirect_after_auth';
$this->logger = empty($log_path)
? new NullLogger()
: new Logger($this->app_name);
$this->token_session_key = $this->app_name . 'access_token';
$this->token_redirect_after_auth = $this->app_name . 'redirect_after_auth';
$handler = new RotatingFileHandler($log_path, 5, $log_level, true);
$this->logger->pushHandler($handler);
$this->server_token = null;
@ -151,16 +151,16 @@ class APnutI
if (count($header) < 2) {
continue;
}
list($k,$v) = $header;
list($k, $v) = $header;
switch ($k) {
case 'X-RateLimit-Remaining':
$this->rate_limit_remaining = (int)$v;
$this->rate_limit_remaining = (int) $v;
break;
case 'X-RateLimit-Limit':
$this->rate_limit = (int)$v;
$this->rate_limit = (int) $v;
break;
case 'X-RateLimit-Reset':
$this->rate_limit_reset = (int)$v;
$this->rate_limit_reset = (int) $v;
break;
case 'X-OAuth-Scopes':
$this->scope = $v;
@ -169,11 +169,9 @@ class APnutI
case 'location':
case 'Location':
$this->logger->debug(
'Is redirect. Headers: '.json_encode($this->headers)
);
$this->logger->debug(
'Is redirect. Target: '. $v
'Is redirect. Headers: ' . json_encode($this->headers)
);
$this->logger->debug('Is redirect. Target: ' . $v);
$this->redirect_target = $v;
break;
}
@ -188,11 +186,10 @@ class APnutI
string $content_type = 'application/x-www-form-urlencoded',
bool $follow_redirect = true
): array {
$this->redirect_target = null;
$this->meta = null;
$method = strtoupper($method);
$url = $this->api_url.$end_point;
$url = $this->api_url . $end_point;
$this->logger->info("{$method} Request to {$url}");
$ch = curl_init($url);
$headers = [];
@ -201,26 +198,29 @@ class APnutI
// if they passed an array, build a list of parameters from it
curl_setopt($ch, CURLOPT_POST, true);
if (is_array($parameters) && $method !== 'POST-RAW') {
$parameters = $content_type === 'application/json' ? json_encode($parameters) : http_build_query($parameters);
$parameters =
$content_type === 'application/json'
? json_encode($parameters)
: http_build_query($parameters);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
$headers[] = "Content-Type: ".$content_type;
$headers[] = 'Content-Type: ' . $content_type;
}
if ($method !== 'POST' && $method !== 'POST-RAW') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
}
if ($method === 'GET' && isset($parameters['access_token'])) {
$this->logger->info("Using provided token for auth");
$headers[] = 'Authorization: Bearer '.$params['access_token'];
$this->logger->info('Using provided token for auth');
$headers[] = 'Authorization: Bearer ' . $parameters['access_token'];
} elseif (!empty($this->access_token)) {
$this->logger->info("Using access token for auth");
$headers[] = 'Authorization: Bearer '.$this->access_token;
$this->logger->info('Using access token for auth');
$headers[] = 'Authorization: Bearer ' . $this->access_token;
} elseif (!empty($this->server_token)) {
$use_server_token = true;
$this->logger->info("Using server token for auth");
$headers[] = 'Authorization: Bearer '.$this->server_token;
$this->logger->info('Using server token for auth');
$headers[] = 'Authorization: Bearer ' . $this->server_token;
} else {
$this->logger->info("Using no auth");
$this->logger->info('Using no auth');
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
@ -231,15 +231,18 @@ class APnutI
$response = curl_exec($ch);
$request = curl_getinfo($ch, CURLINFO_HEADER_OUT);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$effectiveURL = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
$this->logger->debug("{$method} Request to {$url}. Received status: {$http_status}. Response: {$response}");
$this->logger->debug(
"{$method} Request to {$url}. Received status: {$http_status}. Response: {$response}"
);
if ($http_status === 0) {
throw new \Exception('Unable to connect to Pnut ' . $url);
}
if ($request === false) {
if (!curl_getinfo($ch, CURLINFO_SSL_VERIFYRESULT)) {
throw new \Exception('SSL verification failed, connection terminated: ' . $url);
throw new \Exception(
'SSL verification failed, connection terminated: ' . $url
);
}
}
if (!empty($response)) {
@ -281,18 +284,24 @@ class APnutI
// look for errors
if (isset($response['error'])) {
if (is_array($response['error'])) {
throw new PnutException($response['error']['message'], $response['error']['code']);
throw new PnutException(
$response['error']['message'],
$response['error']['code']
);
} else {
throw new PnutException($response['error']);
}
// look for response migration errors
} elseif (isset($response['meta'], $response['meta']['error_message'])) {
throw new PnutException($response['meta']['error_message'], $response['meta']['code']);
throw new PnutException(
$response['meta']['error_message'],
$response['meta']['code']
);
}
}
}
if ($http_status < 200 || $http_status >= 300) {
throw new HttpPnutException('HTTP error '.$http_status);
throw new HttpPnutException('HTTP error ' . $http_status);
} elseif (isset($response['meta'], $response['data'])) {
return $response['data'];
} elseif (isset($response['access_token'])) {
@ -300,7 +309,11 @@ class APnutI
} elseif (!empty($this->redirect_target)) {
return [$this->redirect_target];
} else {
throw new PnutException("No response ".json_encode($response).", http status: ${http_status}");
throw new PnutException(
'No response ' .
json_encode($response) .
", http status: {$http_status}"
);
}
}
@ -313,10 +326,8 @@ class APnutI
return $this->makeRequest($method, $end_point, $parameters, $content_type);
}
public function postJson(
string $end_point,
array $parameters
): array {
public function postJson(string $end_point, array $parameters): array
{
return $this->post($end_point, $parameters, 'application/json');
}
@ -332,35 +343,50 @@ class APnutI
$end_point .= $separator . http_build_query($parameters);
$parameters = [];
}
return $this->makeRequest('get', $end_point, $parameters, $content_type, $follow_redirect);
return $this->makeRequest(
'get',
$end_point,
$parameters,
$content_type,
$follow_redirect
);
}
public function getAuthURL()
public function getAuthURL($append_redirect_query_string = null)
{
$url = $this->auth_url
. '?client_id='
. $this->client_id
. '&redirect_uri='
. urlencode($this->redirect_uri)
. '&scope='.$this->needed_scope
. '&response_type=code';
$redirect_uri = $this->redirect_uri;
if (!empty($append_redirect_query_string)) {
$redirect_uri .= $append_redirect_query_string;
}
$url =
$this->auth_url .
'?client_id=' .
$this->client_id .
'&redirect_uri=' .
urlencode($redirect_uri) .
'&scope=' .
$this->needed_scope .
'&response_type=code';
$this->logger->debug('Auth URL: ' . $url);
return $url;
}
//TODO: Ping server and validate token
public function isAuthenticated(bool $allow_server_token = false, bool $skip_verify_token = false): bool
{
$is_authenticated = ($allow_server_token && !empty($this->server_token))
|| isset($this->access_token);
$log_str = $is_authenticated
? 'Authenticated'
: 'Not authenticated';
public function isAuthenticated(
bool $allow_server_token = false,
bool $skip_verify_token = false
): bool {
$is_authenticated =
($allow_server_token && !empty($this->server_token)) ||
isset($this->access_token);
$log_str = $is_authenticated ? 'Authenticated' : 'Not authenticated';
$this->logger->info(
"Checking auth status for app: {$this->app_name}: {$log_str}"
);
if (isset($_SERVER['HTTP_REFERER'])) {
$this->logger->info('Referrer: '.($_SERVER['HTTP_REFERER'] ?? 'Unknown'));
$this->logger->info(
'Referrer: ' . ($_SERVER['HTTP_REFERER'] ?? 'Unknown')
);
$_SESSION[$this->token_redirect_after_auth] = $_SERVER['HTTP_REFERER'];
}
return $is_authenticated;
@ -374,7 +400,7 @@ class APnutI
'client_secret' => $this->client_secret,
'code' => $auth_code,
'redirect_uri' => $this->redirect_uri,
'grant_type'=> 'authorization_code'
'grant_type' => 'authorization_code',
];
$resp = $this->post(
'/oauth/access_token',
@ -383,7 +409,7 @@ class APnutI
);
if (empty($resp['access_token'])) {
$this->logger->error("No access token ".json_encode($resp));
$this->logger->error('No access token ' . json_encode($resp));
return false;
} else {
$this->logger->debug('Received access token ' . $resp['access_token']);
@ -415,7 +441,7 @@ class APnutI
}
*/
if (mb_substr($username, 0, 1) !== '@') {
$username = '@'.$username;
$username = '@' . $username;
}
$params = [];
if ($count > 0) {
@ -454,9 +480,7 @@ class APnutI
foreach ($posts as $post) {
$post_obj[] = new Post($post, $this);
}
} while ($this->meta != null
&& $this->meta->more
&& (count($post_obj) < $count || $count !== 0));
} while ($this->meta != null && $this->meta->more && (count($post_obj) < $count || $count !== 0));
return $post_obj;
}
@ -472,7 +496,7 @@ class APnutI
'include_html' => false,
'include_mention_posts' => false,
'include_copy_mentions' => false,
'include_post_raw' => true
'include_post_raw' => true,
];
foreach ($params as $param => $value) {
$parameters[$param] = $value;
@ -500,7 +524,7 @@ class APnutI
$res = $this->get($endpoint, $args);
return new Poll($res, $this);
} catch (NotSupportedPollException $e) {
$this->logger->error('Poll not supported: '.json_encode($res));
$this->logger->error('Poll not supported: ' . json_encode($res));
throw $e;
} catch (HttpPnutForbiddenException $fe) {
$this->logger->error('Poll token required and not provided!');
@ -511,8 +535,10 @@ class APnutI
}
}
public function getPollFromToken(int $poll_id, ?string $poll_token = null): Poll
{
public function getPollFromToken(
int $poll_id,
?string $poll_token = null
): Poll {
$poll_token_query = empty($poll_token) ? '' : '?poll_token=' . $poll_token;
return $this->getPollFromEndpoint('/polls/' . $poll_id . $poll_token_query);
}
@ -524,18 +550,19 @@ class APnutI
}
$this->logger->debug('Poll token provided');
$re = '/((http(s)?:\/\/)?((posts)|(beta))\.pnut\.io\/(@.*\/)?)?(?(1)|^)(?<postid>\d+)/';
$re =
'/((http(s)?:\/\/)?((posts)|(beta))\.pnut\.io\/(@.*\/)?)?(?(1)|^)(?<postid>\d+)/$';
preg_match($re, $poll_token, $matches);
if (!empty($matches['postid'])) {
$this->logger->debug('Poll token is post ' . $matches['postid']);
$post_id = (int)$matches['postid'];
$post_id = (int) $matches['postid'];
$args = [
'include_raw' => true,
'include_counts' => false,
'include_html' => false,
'include_post_raw' => true
'include_post_raw' => true,
];
return $this->getPollFromEndpoint('/posts/' . $post_id, $arg);
return $this->getPollFromEndpoint('/posts/' . $post_id, $args);
} else {
$this->logger->debug('Poll token seems to be an actual poll token');
return $this->getPollFromToken($poll_id, $poll_token);
@ -553,13 +580,16 @@ class APnutI
$poll_types = Poll::$poll_types;
$poll_types[] = Poll::$notice_type;
$poll_types_param = implode(',', $poll_types);
$this->logger->info('No list of polls provided, using post search for poll types: '.$poll_types_param);
$endpoint = '/posts/search?raw_types='.$poll_types_param;
$this->logger->info(
'No list of polls provided, using post search for poll types: ' .
$poll_types_param
);
$endpoint = '/posts/search?raw_types=' . $poll_types_param;
$params = [
'include_raw' => true,
'include_counts' => false,
'include_html' => false,
'include_post_raw' => true
'include_post_raw' => true,
];
}
try {
@ -571,21 +601,24 @@ class APnutI
}
return $polls;
} catch (NotSupportedPollException $e) {
$this->logger->error('Poll not supported: '.json_encode($res));
$this->logger->error('Poll not supported: ' . json_encode($res));
throw $e;
} catch (HttpPnutForbiddenException $fe) {
} catch (HttpPnutForbiddenException) {
$this->logger->error('Poll token required and not provided!');
throw new PollAccessRestrictedException();
} catch (NotAuthorizedException $nauth) {
} catch (NotAuthorizedException) {
$this->logger->error('Not authorized when fetching poll');
throw new PollAccessRestrictedException();
}
}
public function voteInPoll(int $poll_id, array $options, ?string $poll_token): Poll
{
public function voteInPoll(
int $poll_id,
array $options,
?string $poll_token
): Poll {
$params = [
'positions' => $options
'positions' => $options,
];
if (!empty($poll_token)) {
$params['poll_token'] = $poll_token;
@ -609,7 +642,7 @@ class APnutI
public function getUser(int $user_id, array $args = [])
{
return new User($this->get('/users/'.$user_id, $args), $this);
return new User($this->get('/users/' . $user_id, $args), $this);
}
public function getPost(int $post_id, array $args = [])
@ -617,15 +650,15 @@ class APnutI
if (!empty($this->access_token)) {
#$this->logger->info("AT:".$this->access_token);
} else {
$this->logger->info("No AT");
$this->logger->info('No AT');
}
// Remove in production again
try {
$p = new Post($this->get('/posts/'.$post_id, $args), $this);
$p = new Post($this->get('/posts/' . $post_id, $args), $this);
$this->logger->debug(json_encode($p));
return $p;
} catch (NotAuthorizedException $nae) {
} catch (NotAuthorizedException) {
$this->logger->warning(
'NotAuthorizedException when getting post, trying without access token'
);
@ -646,11 +679,18 @@ class APnutI
//get returns an array with the url at idx 0
$r = null;
try {
$r = $this->get('/users/'.$user_id.'/avatar', $args, 'application/json', false);
$r = $this->get(
'/users/' . $user_id . '/avatar',
$args,
'application/json',
false
);
} catch (HttpPnutRedirectException $re) {
return $re->response;
}
$this->logger->error('Could not fetch avatar: No redirection! ' . json_encode($r));
$this->logger->error(
'Could not fetch avatar: No redirection! ' . json_encode($r)
);
throw new PnutException('Could not fetch avatar: No redirection!');
}
@ -705,7 +745,7 @@ class APnutI
bool $auto_crop = false,
array $raw = []
): Post {
return createPost($text, $reply_to, $is_nsfw, $auto_crop, $raw);
return $this->createPost($text, $reply_to, $is_nsfw, $auto_crop, $raw);
}
public function createPost(
@ -724,7 +764,10 @@ class APnutI
if (!empty($raw)) {
$parameters['raw'] = $parameters;
}
return new Post($this->post('/posts', $parameters, 'application/json'), $this);
return new Post(
$this->post('/posts', $parameters, 'application/json'),
$this
);
}
public function createPostWithParameters(
@ -739,20 +782,28 @@ class APnutI
$parameters = array_merge($parameters, $params);
$this->logger->debug('Post with params');
$this->logger->debug(json_encode($parameters));
return new Post($this->post('/posts', $parameters, 'application/json'), $this);
return new Post(
$this->post('/posts', $parameters, 'application/json'),
$this
);
}
public function getChannel(int $channel_id): Channel
{
# Always include channel raw, it contains the channel name
$parameters = [
'include_channel_raw' => true
'include_channel_raw' => true,
];
return new Channel($this->get('/channels/'.$channel_id, $parameters), $this);
return new Channel(
$this->get('/channels/' . $channel_id, $parameters),
$this
);
}
public function getSubscribedChannels(bool $include_pms = true, bool $include_channels = true): array
{
public function getSubscribedChannels(
bool $include_pms = true,
bool $include_channels = true
): array {
# Always include channel raw, it contains the channel name
$channel_types = [];
if ($include_pms) {
@ -764,7 +815,7 @@ class APnutI
$parameters = [
'include_channel_raw' => true,
'channel_types' => implode(',', $channel_types)
'channel_types' => implode(',', $channel_types),
];
$channels = [];
$resp = $this->get('/users/me/channels/subscribed', $parameters);
@ -780,19 +831,28 @@ class APnutI
self::$POST_MAX_LENGTH = $config['post']['max_length'];
//self::$POST_MAX_LENGTH_REPOST = $config['post']['repost_max_length'];
self::$POST_MAX_LENGTH_REPOST = self::$POST_MAX_LENGTH;
self::$POST_SECONDS_BETWEEN_DUPLICATES = $config['post']['seconds_between_duplicates'];
self::$POST_SECONDS_BETWEEN_DUPLICATES =
$config['post']['seconds_between_duplicates'];
self::$MESSAGE_MAX_LENGTH = $config['message']['max_length'];
self::$RAW_MAX_LENGTH = $config['raw']['max_length'];
self::$USER_DESCRIPTION_MAX_LENGTH = $config['user']['description_max_length'];
self::$USER_DESCRIPTION_MAX_LENGTH =
$config['user']['description_max_length'];
self::$USER_USERNAME_MAX_LENGTH = $config['user']['username_max_length'];
$this->logger->info('-----------Pnut API config-----------');
$this->logger->info('');
$this->logger->info("Max post length: ".self::$POST_MAX_LENGTH);
$this->logger->info("Max repost length: ".self::$POST_MAX_LENGTH_REPOST);
$this->logger->info("Seconds between post duplicates: ".self::$POST_SECONDS_BETWEEN_DUPLICATES);
$this->logger->info("Max raw length: ".self::$RAW_MAX_LENGTH);
$this->logger->info("Max user description length: ".self::$USER_DESCRIPTION_MAX_LENGTH);
$this->logger->info("Max username length: ".self::$USER_USERNAME_MAX_LENGTH);
$this->logger->info('Max post length: ' . self::$POST_MAX_LENGTH);
$this->logger->info('Max repost length: ' . self::$POST_MAX_LENGTH_REPOST);
$this->logger->info(
'Seconds between post duplicates: ' .
self::$POST_SECONDS_BETWEEN_DUPLICATES
);
$this->logger->info('Max raw length: ' . self::$RAW_MAX_LENGTH);
$this->logger->info(
'Max user description length: ' . self::$USER_DESCRIPTION_MAX_LENGTH
);
$this->logger->info(
'Max username length: ' . self::$USER_USERNAME_MAX_LENGTH
);
$this->logger->info('--------------------------------------');
}
@ -808,7 +868,7 @@ class APnutI
{
$token = $this->getServerToken();
$this->server_token = $token;
$this->logger->info("ST:".$this->server_token);
$this->logger->info('ST:' . $this->server_token);
}
protected function getServerToken(): string
@ -817,14 +877,16 @@ class APnutI
$params = [
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'grant_type' => 'client_credentials'
'grant_type' => 'client_credentials',
];
$resp = $this->post('/oauth/access_token', $params);
if (!empty($resp['access_token'])) {
$this->logger->info(json_encode($resp));
return $resp['access_token'];
} else {
throw new PnutException("Error retrieving app access token: ".json_encode($resp));
throw new PnutException(
'Error retrieving app access token: ' . json_encode($resp)
);
}
}