Convert some constants to enums

This commit is contained in:
Alex Cabal 2024-05-11 13:23:15 -05:00
parent 06425d3dd6
commit ee7c8343dd
52 changed files with 282 additions and 268 deletions

View file

@ -2,7 +2,7 @@ CREATE TABLE `Payments` (
`PaymentId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`UserId` int(10) unsigned DEFAULT NULL,
`Created` datetime NOT NULL,
`ChannelId` tinyint(4) unsigned NOT NULL,
`Processor` enum('fractured_atlas') NOT NULL,
`TransactionId` varchar(80) NOT NULL,
`Amount` decimal(7,2) unsigned NOT NULL,
`Fee` decimal(7,2) unsigned NOT NULL DEFAULT 0.00,

View file

@ -1,6 +1,6 @@
CREATE TABLE `PendingPayments` (
`Created` datetime NOT NULL,
`ChannelId` tinyint(4) unsigned NOT NULL,
`Processor` enum('fractured_atlas') NOT NULL,
`TransactionId` varchar(80) NOT NULL,
`ProcessedOn` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

View file

@ -654,7 +654,9 @@ class Artwork{
}
/**
* @throws Exceptions\ValidationException
* @throws Exceptions\InvalidArtworkException
* @throws Exceptions\InvalidArtworkTagException
* @throws Exceptions\InvalidArtistException
* @throws Exceptions\InvalidImageUploadException
*/
public function Create(?string $imagePath = null): void{
@ -874,23 +876,23 @@ class Artwork{
$artwork = new Artwork();
$artwork->Artist = new Artist();
$artwork->Artist->Name = HttpInput::Str(POST, 'artist-name');
$artwork->Artist->DeathYear = HttpInput::Int(POST, 'artist-year-of-death');
$artwork->Artist->Name = HttpInput::Str(HttpVariableSource::Post, 'artist-name');
$artwork->Artist->DeathYear = HttpInput::Int(HttpVariableSource::Post, 'artist-year-of-death');
$artwork->Name = HttpInput::Str(POST, 'artwork-name');
$artwork->CompletedYear = HttpInput::Int(POST, 'artwork-year');
$artwork->CompletedYearIsCirca = HttpInput::Bool(POST, 'artwork-year-is-circa') ?? false;
$artwork->Tags = HttpInput::Str(POST, 'artwork-tags') ?? [];
$artwork->Status = ArtworkStatus::tryFrom(HttpInput::Str(POST, 'artwork-status') ?? '') ?? ArtworkStatus::Unverified;
$artwork->EbookUrl = HttpInput::Str(POST, 'artwork-ebook-url');
$artwork->IsPublishedInUs = HttpInput::Bool(POST, 'artwork-is-published-in-us') ?? false;
$artwork->PublicationYear = HttpInput::Int(POST, 'artwork-publication-year');
$artwork->PublicationYearPageUrl = HttpInput::Str(POST, 'artwork-publication-year-page-url');
$artwork->CopyrightPageUrl = HttpInput::Str(POST, 'artwork-copyright-page-url');
$artwork->ArtworkPageUrl = HttpInput::Str(POST, 'artwork-artwork-page-url');
$artwork->MuseumUrl = HttpInput::Str(POST, 'artwork-museum-url');
$artwork->Exception = HttpInput::Str(POST, 'artwork-exception');
$artwork->Notes = HttpInput::Str(POST, 'artwork-notes');
$artwork->Name = HttpInput::Str(HttpVariableSource::Post, 'artwork-name');
$artwork->CompletedYear = HttpInput::Int(HttpVariableSource::Post, 'artwork-year');
$artwork->CompletedYearIsCirca = HttpInput::Bool(HttpVariableSource::Post, 'artwork-year-is-circa') ?? false;
$artwork->Tags = HttpInput::Str(HttpVariableSource::Post, 'artwork-tags') ?? [];
$artwork->Status = ArtworkStatus::tryFrom(HttpInput::Str(HttpVariableSource::Post, 'artwork-status') ?? '') ?? ArtworkStatus::Unverified;
$artwork->EbookUrl = HttpInput::Str(HttpVariableSource::Post, 'artwork-ebook-url');
$artwork->IsPublishedInUs = HttpInput::Bool(HttpVariableSource::Post, 'artwork-is-published-in-us') ?? false;
$artwork->PublicationYear = HttpInput::Int(HttpVariableSource::Post, 'artwork-publication-year');
$artwork->PublicationYearPageUrl = HttpInput::Str(HttpVariableSource::Post, 'artwork-publication-year-page-url');
$artwork->CopyrightPageUrl = HttpInput::Str(HttpVariableSource::Post, 'artwork-copyright-page-url');
$artwork->ArtworkPageUrl = HttpInput::Str(HttpVariableSource::Post, 'artwork-artwork-page-url');
$artwork->MuseumUrl = HttpInput::Str(HttpVariableSource::Post, 'artwork-museum-url');
$artwork->Exception = HttpInput::Str(HttpVariableSource::Post, 'artwork-exception');
$artwork->Notes = HttpInput::Str(HttpVariableSource::Post, 'artwork-notes');
return $artwork;
}

View file

@ -54,31 +54,8 @@ define('EMAIL_SMTP_USERNAME', get_cfg_var('se.secrets.postmark.username'));
const EMAIL_SMTP_HOST = 'smtp.postmarkapp.com';
const EMAIL_POSTMARK_STREAM_BROADCAST = 'the-standard-ebooks-newsletter';
const REST = 0;
const WEB = 1;
const GET = 'GET';
const POST = 'POST';
const COOKIE = 'COOKIE';
const SESSION = 'SESSION';
const HTTP_VAR_INT = 0;
const HTTP_VAR_STR = 1;
const HTTP_VAR_BOOL = 2;
const HTTP_VAR_DEC = 3;
const HTTP_VAR_ARRAY = 4;
const HTTP_GET = 0;
const HTTP_POST = 1;
const HTTP_PATCH = 2;
const HTTP_PUT = 3;
const HTTP_DELETE = 4;
const HTTP_HEAD = 5;
const AVERAGE_READING_WORDS_PER_MINUTE = 275;
const PAYMENT_CHANNEL_FA = 0;
const FA_FEE_PERCENT = 0.87;
const GITHUB_IGNORED_REPOS = ['tools', 'manual', 'web']; // If we get GitHub push requests featuring these repos, silently ignore instead of returning an error.

View file

@ -0,0 +1,5 @@
<?
namespace Exceptions;
class HttpMethodNotAllowedException extends AppException{
}

View file

@ -0,0 +1,5 @@
<?
namespace Exceptions;
class InvalidHttpMethodException extends AppException{
}

View file

@ -3,23 +3,47 @@ use function Safe\ini_get;
use function Safe\preg_match;
class HttpInput{
public static function RequestMethod(): int{
$method = $_POST['_method'] ?? $_SERVER['REQUEST_METHOD'];
switch($method){
case 'POST':
return HTTP_POST;
case 'PUT':
return HTTP_PUT;
case 'DELETE':
return HTTP_DELETE;
case 'PATCH':
return HTTP_PATCH;
case 'HEAD':
return HTTP_HEAD;
/**
* @param ?array<HttpMethod> $allowedHttpMethods An array containing a list of allowed HTTP methods, or null if any valid HTTP method is allowed.
* @param bool $throwException If true, in case of errors throw an exception; if false, in case of errors output HTTP 405 and exit the script immediately.
* @throws Exceptions\InvalidHttpMethodException If the HTTP method is not recognized.
* @throws Exceptions\HttpMethodNotAllowedException If the HTTP method is not in the list of allowed methods.
*/
public static function ValidateRequestMethod(?array $allowedHttpMethods = null, bool $throwException = false): HttpMethod{
try{
$requestMethod = HttpMethod::from($_POST['_method'] ?? $_SERVER['REQUEST_METHOD']);
if($allowedHttpMethods !== null){
$isRequestMethodAllowed = false;
foreach($allowedHttpMethods as $allowedHttpMethod){
if($requestMethod == $allowedHttpMethod){
$isRequestMethodAllowed = true;
}
}
return HTTP_GET;
if(!$isRequestMethodAllowed){
throw new Exceptions\HttpMethodNotAllowedException();
}
}
}
catch(\ValueError | Exceptions\HttpMethodNotAllowedException $ex){
if($throwException){
if($ex instanceof \ValueError){
throw new Exceptions\InvalidHttpMethodException();
}
else{
throw $ex;
}
}
else{
if($allowedHttpMethods !== null){
header('Allow: ' . implode(',', array_map(fn($httpMethod): string => $httpMethod->value, $allowedHttpMethods)));
}
http_response_code(405);
exit();
}
}
return $requestMethod;
}
public static function GetMaxPostSize(): int{ // bytes
@ -45,12 +69,12 @@ class HttpInput{
return false;
}
public static function RequestType(): int{
return preg_match('/\btext\/html\b/ius', $_SERVER['HTTP_ACCEPT'] ?? '') ? WEB : REST;
public static function RequestType(): HttpRequestType{
return preg_match('/\btext\/html\b/ius', $_SERVER['HTTP_ACCEPT'] ?? '') ? HttpRequestType::Web : HttpRequestType::Rest;
}
public static function Str(string $type, string $variable, bool $allowEmptyString = false): ?string{
$var = self::GetHttpVar($variable, HTTP_VAR_STR, $type);
public static function Str(HttpVariableSource $set, string $variable, bool $allowEmptyString = false): ?string{
$var = self::GetHttpVar($variable, HttpVariableType::String, $set);
if(is_array($var)){
return null;
@ -63,50 +87,50 @@ class HttpInput{
return $var;
}
public static function Int(string $type, string $variable): ?int{
return self::GetHttpVar($variable, HTTP_VAR_INT, $type);
public static function Int(HttpVariableSource $set, string $variable): ?int{
return self::GetHttpVar($variable, HttpVariableType::Integer, $set);
}
public static function Bool(string $type, string $variable): ?bool{
return self::GetHttpVar($variable, HTTP_VAR_BOOL, $type);
public static function Bool(HttpVariableSource $set, string $variable): ?bool{
return self::GetHttpVar($variable, HttpVariableType::Boolean, $set);
}
public static function Dec(string $type, string $variable): ?float{
return self::GetHttpVar($variable, HTTP_VAR_DEC, $type);
public static function Dec(HttpVariableSource $set, string $variable): ?float{
return self::GetHttpVar($variable, HttpVariableType::Decimal, $set);
}
/**
* @param string $variable
* @return array<string>
*/
public static function GetArray(string $variable): ?array{
return self::GetHttpVar($variable, HTTP_VAR_ARRAY, GET);
public static function Array(HttpVariableSource $set, string $variable): ?array{
return self::GetHttpVar($variable, HttpVariableType::Array, $set);
}
private static function GetHttpVar(string $variable, int $type, string $set): mixed{
private static function GetHttpVar(string $variable, HttpVariableType $type, HttpVariableSource $set): mixed{
$vars = [];
switch($set){
case GET:
case HttpVariableSource::Get:
$vars = $_GET;
break;
case POST:
case HttpVariableSource::Post:
$vars = $_POST;
break;
case COOKIE:
case HttpVariableSource::Cookie:
$vars = $_COOKIE;
break;
case SESSION:
case HttpVariableSource::Session:
$vars = $_SESSION;
break;
}
if(isset($vars[$variable])){
if($type == HTTP_VAR_ARRAY && is_array($vars[$variable])){
if($type == HttpVariableType::Array && is_array($vars[$variable])){
// We asked for an array, and we got one
return $vars[$variable];
}
elseif($type !== HTTP_VAR_ARRAY && is_array($vars[$variable])){
elseif($type !== HttpVariableType::Array && is_array($vars[$variable])){
// We asked for not an array, but we got an array
return null;
}
@ -115,9 +139,9 @@ class HttpInput{
}
switch($type){
case HTTP_VAR_STR:
case HttpVariableType::String:
return $var;
case HTTP_VAR_INT:
case HttpVariableType::Integer:
// Can't use ctype_digit because we may want negative integers
if(is_numeric($var) && mb_strpos($var, '.') === false){
try{
@ -128,14 +152,14 @@ class HttpInput{
}
}
break;
case HTTP_VAR_BOOL:
case HttpVariableType::Boolean:
if($var === '0' || strtolower($var) == 'false' || strtolower($var) == 'off'){
return false;
}
else{
return true;
}
case HTTP_VAR_DEC:
case HttpVariableType::Decimal:
if(is_numeric($var)){
try{
return floatval($var);

9
lib/HttpMethod.php Normal file
View file

@ -0,0 +1,9 @@
<?
enum HttpMethod: string{
case Delete = 'DELETE';
case Get = 'GET';
case Head = 'HEAD';
case Patch = 'PATCH';
case Post = 'POST';
case Put = 'PUT';
}

5
lib/HttpRequestType.php Normal file
View file

@ -0,0 +1,5 @@
<?
enum HttpRequestType{
case Rest;
case Web;
}

View file

@ -0,0 +1,7 @@
<?
enum HttpVariableSource{
case Get;
case Post;
case Session;
case Cookie;
}

8
lib/HttpVariableType.php Normal file
View file

@ -0,0 +1,8 @@
<?
enum HttpVariableType{
case Array;
case Boolean;
case Decimal;
case Integer;
case String;
}

View file

@ -10,7 +10,7 @@ class Payment{
public int $PaymentId;
public ?int $UserId = null;
public DateTimeImmutable $Created;
public int $ChannelId;
public PaymentProcessor $Processor;
public string $TransactionId;
public float $Amount;
public float $Fee;
@ -64,7 +64,7 @@ class Payment{
try{
Db::Query('
INSERT into Payments (UserId, Created, ChannelId, TransactionId, Amount, Fee, IsRecurring, IsMatchingDonation)
INSERT into Payments (UserId, Created, Processor, TransactionId, Amount, Fee, IsRecurring, IsMatchingDonation)
values(?,
?,
?,
@ -73,7 +73,7 @@ class Payment{
?,
?,
?)
', [$this->UserId, $this->Created, $this->ChannelId, $this->TransactionId, $this->Amount, $this->Fee, $this->IsRecurring, $this->IsMatchingDonation]);
', [$this->UserId, $this->Created, $this->Processor, $this->TransactionId, $this->Amount, $this->Fee, $this->IsRecurring, $this->IsMatchingDonation]);
}
catch(Exceptions\DuplicateDatabaseKeyException){
throw new Exceptions\PaymentExistsException();

4
lib/PaymentProcessor.php Normal file
View file

@ -0,0 +1,4 @@
<?
enum PaymentProcessor: string{
case FracturedAtlas = 'fractured_atlas';
}

View file

@ -81,7 +81,7 @@ class Session{
}
public static function GetLoggedInUser(): ?User{
$sessionId = HttpInput::Str(COOKIE, 'sessionid');
$sessionId = HttpInput::Str(HttpVariableSource::Cookie, 'sessionid');
if($sessionId !== null){
$result = Db::Query('

View file

@ -65,12 +65,12 @@ function InsertTransaction($transactionId){
if(!$exists){
Db::Query('INSERT into PendingPayments
(Created,
ChannelId,
Processor,
TransactionId)
values (utc_timestamp(),
?,
?)',
[PAYMENT_CHANNEL_FA, $transactionId]);
[PaymentProcessor::FracturedAtlas, $transactionId]);
return true;
}

View file

@ -69,7 +69,8 @@ try{
$driver = FirefoxDriver::start($capabilities);
foreach($pendingPayments as $pendingPayment){
if($pendingPayment->ChannelId == PAYMENT_CHANNEL_FA){
$pendingPayment->Processor = PaymentProcessor::from($pendingPayment->Processor);
if($pendingPayment->Processor == PaymentProcessor::FracturedAtlas){
$log->Write('Processing donation ' . $pendingPayment->TransactionId . ' ...');
if(Db::QueryInt('
@ -121,7 +122,7 @@ try{
$payment = new Payment();
$payment->User = new User();
$payment->ChannelId = $pendingPayment->ChannelId;
$payment->Processor = $pendingPayment->Processor;
try{
// If the donation is via a foundation (like American Online Giving Foundation) then there will be a 'soft credit' <th> element.
if(sizeof($detailsRow->findElements(WebDriverBy::xpath('//th[normalize-space(.) = "Soft Credit Donor Info"]'))) > 0){

View file

@ -14,7 +14,7 @@ if($isSubmitterView){
}
try{
$artworks = Library::GetArtworksByArtist(HttpInput::Str(GET, 'artist-url-name'), $filterArtworkStatus, $submitterUserId);
$artworks = Library::GetArtworksByArtist(HttpInput::Str(HttpVariableSource::Get, 'artist-url-name'), $filterArtworkStatus, $submitterUserId);
if(sizeof($artworks) == 0){
throw new Exceptions\ArtistNotFoundException();

View file

@ -13,7 +13,7 @@ try{
}
if($artwork === null){
$artwork = Artwork::GetByUrl(HttpInput::Str(GET, 'artist-url-name'), HttpInput::Str(GET, 'artwork-url-name'));
$artwork = Artwork::GetByUrl(HttpInput::Str(HttpVariableSource::Get, 'artist-url-name'), HttpInput::Str(HttpVariableSource::Get, 'artwork-url-name'));
}
if(!$artwork->CanBeEditedBy($GLOBALS['User'])){

View file

@ -3,11 +3,11 @@ use function Safe\session_unset;
session_start();
$saved = HttpInput::Bool(SESSION, 'artwork-saved') ?? false;
$saved = HttpInput::Bool(HttpVariableSource::Session, 'artwork-saved') ?? false;
$exception = $_SESSION['exception'] ?? null;
try{
$artwork = Artwork::GetByUrl(HttpInput::Str(GET, 'artist-url-name'), HttpInput::Str(GET, 'artwork-url-name'));
$artwork = Artwork::GetByUrl(HttpInput::Str(HttpVariableSource::Get, 'artist-url-name'), HttpInput::Str(HttpVariableSource::Get, 'artwork-url-name'));
$isReviewerView = $GLOBALS['User']->Benefits->CanReviewArtwork ?? false;
$isAdminView = $GLOBALS['User']->Benefits->CanReviewOwnArtwork ?? false;

View file

@ -1,11 +1,11 @@
<?
$page = HttpInput::Int(GET, 'page') ?? 1;
$perPage = HttpInput::Int(GET, 'per-page') ?? ARTWORK_PER_PAGE;
$query = HttpInput::Str(GET, 'query');
$queryEbookUrl = HttpInput::Str(GET, 'query-ebook-url');
$status = HttpInput::Str(GET, 'status');
$page = HttpInput::Int(HttpVariableSource::Get, 'page') ?? 1;
$perPage = HttpInput::Int(HttpVariableSource::Get, 'per-page') ?? ARTWORK_PER_PAGE;
$query = HttpInput::Str(HttpVariableSource::Get, 'query');
$queryEbookUrl = HttpInput::Str(HttpVariableSource::Get, 'query-ebook-url');
$status = HttpInput::Str(HttpVariableSource::Get, 'status');
$filterArtworkStatus = $status;
$sort = ArtworkSort::tryFrom(HttpInput::Str(GET, 'sort') ?? '');
$sort = ArtworkSort::tryFrom(HttpInput::Str(HttpVariableSource::Get, 'sort') ?? '');
$pages = 0;
$totalArtworkCount = 0;
$pageDescription = '';

View file

@ -3,7 +3,7 @@ use function Safe\session_unset;
session_start();
$created = HttpInput::Bool(SESSION, 'artwork-created') ?? false;
$created = HttpInput::Bool(HttpVariableSource::Session, 'artwork-created') ?? false;
$exception = $_SESSION['exception'] ?? null;
/** @var Artwork $artwork */
$artwork = $_SESSION['artwork'] ?? null;

View file

@ -1,13 +1,9 @@
<?
try{
session_start();
$httpMethod =HttpInput::RequestMethod();
$httpMethod = HttpInput::ValidateRequestMethod([HttpMethod::Post, HttpMethod::Patch, HttpMethod::Put]);
$exceptionRedirectUrl = '/artworks/new';
if($httpMethod != HTTP_POST && $httpMethod != HTTP_PATCH && $httpMethod != HTTP_PUT){
throw new Exceptions\InvalidRequestException();
}
if(HttpInput::IsRequestTooLarge()){
throw new Exceptions\InvalidRequestException('File upload too large.');
}
@ -17,7 +13,7 @@ try{
}
// POSTing a new artwork
if($httpMethod == HTTP_POST){
if($httpMethod == HttpMethod::Post){
if(!$GLOBALS['User']->Benefits->CanUploadArtwork){
throw new Exceptions\InvalidPermissionsException();
}
@ -56,8 +52,8 @@ try{
}
// PUTing an artwork
if($httpMethod == HTTP_PUT){
$originalArtwork = Artwork::GetByUrl(HttpInput::Str(GET, 'artist-url-name'), HttpInput::Str(GET, 'artwork-url-name'));
if($httpMethod == HttpMethod::Put){
$originalArtwork = Artwork::GetByUrl(HttpInput::Str(HttpVariableSource::Get, 'artist-url-name'), HttpInput::Str(HttpVariableSource::Get, 'artwork-url-name'));
if(!$originalArtwork->CanBeEditedBy($GLOBALS['User'])){
throw new Exceptions\InvalidPermissionsException();
@ -71,7 +67,7 @@ try{
$artwork->SubmitterUserId = $originalArtwork->SubmitterUserId;
$artwork->Status = $originalArtwork->Status; // Overwrite any value got from POST because we need permission to change the status
$newStatus = ArtworkStatus::tryFrom(HttpInput::Str(POST, 'artwork-status') ?? '');
$newStatus = ArtworkStatus::tryFrom(HttpInput::Str(HttpVariableSource::Post, 'artwork-status') ?? '');
if($newStatus !== null){
if($originalArtwork->Status != $newStatus && !$originalArtwork->CanStatusBeChangedBy($GLOBALS['User'])){
throw new Exceptions\InvalidPermissionsException();
@ -105,14 +101,14 @@ try{
}
// PATCHing a new artwork
if($httpMethod == HTTP_PATCH){
$artwork = Artwork::GetByUrl(HttpInput::Str(GET, 'artist-url-name'), HttpInput::Str(GET, 'artwork-url-name'));
if($httpMethod == HttpMethod::Patch){
$artwork = Artwork::GetByUrl(HttpInput::Str(HttpVariableSource::Get, 'artist-url-name'), HttpInput::Str(HttpVariableSource::Get, 'artwork-url-name'));
$exceptionRedirectUrl = $artwork->Url;
// We can PATCH the status, the ebook www filesystem path, or both.
if(isset($_POST['artwork-status'])){
$newStatus = ArtworkStatus::tryFrom(HttpInput::Str(POST, 'artwork-status') ?? '');
$newStatus = ArtworkStatus::tryFrom(HttpInput::Str(HttpVariableSource::Post, 'artwork-status') ?? '');
if($newStatus !== null){
if($artwork->Status != $newStatus && !$artwork->CanStatusBeChangedBy($GLOBALS['User'])){
throw new Exceptions\InvalidPermissionsException();
@ -125,7 +121,7 @@ try{
}
if(isset($_POST['artwork-ebook-url'])){
$newEbookUrl = HttpInput::Str(POST, 'artwork-ebook-url');
$newEbookUrl = HttpInput::Str(HttpVariableSource::Post, 'artwork-ebook-url');
if($artwork->EbookUrl != $newEbookUrl && !$artwork->CanEbookUrlBeChangedBy($GLOBALS['User'])){
throw new Exceptions\InvalidPermissionsException();
}
@ -142,9 +138,6 @@ try{
header('Location: ' . $artwork->Url);
}
}
catch(Exceptions\InvalidRequestException){
http_response_code(405);
}
catch(Exceptions\LoginRequiredException){
Template::RedirectToLogin();
}
@ -154,9 +147,9 @@ catch(Exceptions\InvalidPermissionsException){
catch(Exceptions\ArtworkNotFoundException){
Template::Emit404();
}
catch(Exceptions\AppException $exception){
catch(Exceptions\InvalidArtworkException | Exceptions\InvalidArtworkTagException | Exceptions\InvalidArtistException | Exceptions\InvalidImageUploadException | Exceptions\ArtworkNotFoundException $ex){
$_SESSION['artwork'] = $artwork;
$_SESSION['exception'] = $exception;
$_SESSION['exception'] = $ex;
http_response_code(303);
header('Location: ' . $exceptionRedirectUrl);

View file

@ -3,7 +3,7 @@ use function Safe\apcu_fetch;
use function Safe\preg_replace;
$canDownload = false;
$class = HttpInput::Str(GET, 'class');
$class = HttpInput::Str(HttpVariableSource::Get, 'class');
if($class === null || ($class != 'authors' && $class != 'collections' && $class != 'subjects' && $class != 'months')){
Template::Emit404();

View file

@ -1,7 +1,7 @@
<?
use function Safe\preg_match;
$path = HttpInput::Str(GET, 'path') ?? '';
$path = HttpInput::Str(HttpVariableSource::Get, 'path') ?? '';
try{
$path = '/bulk-downloads/' . $path;

View file

@ -2,9 +2,9 @@
use function Safe\apcu_fetch;
$collection = null;
$collectionUrlName = HttpInput::Str(GET, 'collection');
$collectionUrlName = HttpInput::Str(HttpVariableSource::Get, 'collection');
$collection = null;
$authorUrlName = HttpInput::Str(GET, 'author');
$authorUrlName = HttpInput::Str(HttpVariableSource::Get, 'author');
$canDownload = false;
try{

View file

@ -2,7 +2,7 @@
use function Safe\preg_replace;
try{
$collection = HttpInput::Str(GET, 'collection') ?? '';
$collection = HttpInput::Str(HttpVariableSource::Get, 'collection') ?? '';
$collectionObject = null;
$collectionName = '';
$collectionType = '';

View file

@ -4,7 +4,7 @@ $author = '';
$authorUrl = '';
try{
$urlPath = trim(str_replace('.', '', HttpInput::Str(GET, 'url-path') ?? ''), '/'); // Contains the portion of the URL (without query string) that comes after https://standardebooks.org/ebooks/
$urlPath = trim(str_replace('.', '', HttpInput::Str(HttpVariableSource::Get, 'url-path') ?? ''), '/'); // Contains the portion of the URL (without query string) that comes after https://standardebooks.org/ebooks/
$wwwFilesystemPath = EBOOKS_DIST_PATH . $urlPath; // Path to the deployed WWW files for this ebook
if($urlPath == '' || mb_stripos($wwwFilesystemPath, EBOOKS_DIST_PATH) !== 0 || !is_dir($wwwFilesystemPath)){

View file

@ -10,8 +10,8 @@ $showThankYouPage = $GLOBALS['User'] === null && $downloadCount < 5;
$downloadUrl = null;
try{
$urlPath = HttpInput::Str(GET, 'url-path') ?? null;
$format = EbookFormat::tryFrom(HttpInput::Str(GET, 'format') ?? '') ?? EbookFormat::Epub;
$urlPath = HttpInput::Str(HttpVariableSource::Get, 'url-path') ?? null;
$format = EbookFormat::tryFrom(HttpInput::Str(HttpVariableSource::Get, 'format') ?? '') ?? EbookFormat::Epub;
$wwwFilesystemPath = EBOOKS_DIST_PATH . $urlPath;
// Do we have the ebook cached?

View file

@ -14,7 +14,7 @@ $carousel = [];
$carouselTag = null;
try{
$urlPath = trim(str_replace('.', '', HttpInput::Str(GET, 'url-path') ?? ''), '/'); // Contains the portion of the URL (without query string) that comes after https://standardebooks.org/ebooks/
$urlPath = trim(str_replace('.', '', HttpInput::Str(HttpVariableSource::Get, 'url-path') ?? ''), '/'); // Contains the portion of the URL (without query string) that comes after https://standardebooks.org/ebooks/
$wwwFilesystemPath = EBOOKS_DIST_PATH . $urlPath; // Path to the deployed WWW files for this ebook
if($urlPath == '' || mb_stripos($wwwFilesystemPath, EBOOKS_DIST_PATH) !== 0){

View file

@ -1,13 +1,13 @@
<?
use function Safe\preg_replace;
$page = HttpInput::Int(GET, 'page') ?? 1;
$page = HttpInput::Int(HttpVariableSource::Get, 'page') ?? 1;
$pages = 0;
$perPage = HttpInput::Int(GET, 'per-page') ?? EBOOKS_PER_PAGE;
$query = HttpInput::Str(GET, 'query') ?? '';
$tags = HttpInput::GetArray('tags') ?? [];
$view = ViewType::tryFrom(HttpInput::Str(GET, 'view') ?? '');
$sort = EbookSort::tryFrom(HttpInput::Str(GET, 'sort') ?? '');
$perPage = HttpInput::Int(HttpVariableSource::Get, 'per-page') ?? EBOOKS_PER_PAGE;
$query = HttpInput::Str(HttpVariableSource::Get, 'query') ?? '';
$tags = HttpInput::Array(HttpVariableSource::Get, 'tags') ?? [];
$view = ViewType::tryFrom(HttpInput::Str(HttpVariableSource::Get, 'view') ?? '');
$sort = EbookSort::tryFrom(HttpInput::Str(HttpVariableSource::Get, 'sort') ?? '');
$queryString = '';
$queryStringParams = [];
$queryStringWithoutPage = '';

View file

@ -4,7 +4,7 @@ use Safe\DateTimeImmutable;
$ebooks = [];
try{
$query = HttpInput::Str(GET, 'query') ?? '';
$query = HttpInput::Str(HttpVariableSource::Get, 'query') ?? '';
if($query !== ''){
$ebooks = Library::Search($query);

View file

@ -4,8 +4,8 @@ use function Safe\glob;
use function Safe\preg_replace;
use function Safe\usort;
$class = HttpInput::Str(GET, 'class') ?? '';
$type = HttpInput::Str(GET, 'type') ?? '';
$class = HttpInput::Str(HttpVariableSource::Get, 'class') ?? '';
$type = HttpInput::Str(HttpVariableSource::Get, 'type') ?? '';
if($class != 'authors' && $class != 'collections' && $class != 'subjects'){
Template::Emit404();

View file

@ -5,7 +5,7 @@ use function Safe\preg_match;
// Basic authorization is handled in Core.php. By the time we get here,
// a valid user has a session.
$path = HttpInput::Str(GET, 'path') ?? '';
$path = HttpInput::Str(HttpVariableSource::Get, 'path') ?? '';
try{
$path = '/feeds/' . $path;

View file

@ -1,8 +1,8 @@
<?
use function Safe\exec;
$author = HttpInput::Str(GET, 'author');
$collection = HttpInput::Str(GET, 'collection');
$author = HttpInput::Str(HttpVariableSource::Get, 'author');
$collection = HttpInput::Str(HttpVariableSource::Get, 'collection');
$name = null;
$target = null;
$feedTypes = ['opds', 'atom', 'rss'];

View file

@ -4,7 +4,7 @@ use Safe\DateTimeImmutable;
$ebooks = [];
try{
$query = HttpInput::Str(GET, 'query') ?? '';
$query = HttpInput::Str(HttpVariableSource::Get, 'query') ?? '';
if($query !== ''){
$ebooks = Library::Search($query);

View file

@ -4,7 +4,7 @@ use Safe\DateTimeImmutable;
$ebooks = [];
try{
$query = HttpInput::Str(GET, 'query') ?? '';
$query = HttpInput::Str(HttpVariableSource::Get, 'query') ?? '';
if($query !== ''){
$ebooks = Library::Search($query);

View file

@ -7,7 +7,7 @@ use function Safe\sort;
$currentManual = Manual::GetLatestVersion();
$url = HttpInput::Str(GET, 'url') ?? '';
$url = HttpInput::Str(HttpVariableSource::Get, 'url') ?? '';
$url = preg_replace('|^/|ius', '', $url);
$url = preg_replace('|\.php$|ius', '', $url);
$url = preg_replace('|/$|ius', '', $url);

View file

@ -4,7 +4,7 @@ session_start();
$subscription = new NewsletterSubscription();
try{
$subscription = NewsletterSubscription::Get(HttpInput::Str(GET, 'uuid'));
$subscription = NewsletterSubscription::Get(HttpInput::Str(HttpVariableSource::Get, 'uuid'));
if(!$subscription->IsConfirmed){
$subscription->Confirm();

View file

@ -1,27 +1,19 @@
<?
use function Safe\preg_match;
$requestType = HttpInput::RequestType();
try{
// We may use GET if we're called from an unsubscribe link in an email
if(!in_array(HttpInput::RequestMethod(), [HTTP_DELETE, HTTP_GET])){
throw new Exceptions\InvalidRequestException();
}
HttpInput::ValidateRequestMethod([HttpMethod::Get, HttpMethod::Delete]);
$subscription = NewsletterSubscription::Get(HttpInput::Str(GET, 'uuid'));
$requestType = HttpInput::RequestType();
$subscription = NewsletterSubscription::Get(HttpInput::Str(HttpVariableSource::Get, 'uuid'));
$subscription->Delete();
if($requestType == REST){
if($requestType == HttpRequestType::Rest){
exit();
}
}
catch(Exceptions\InvalidRequestException){
http_response_code(405);
exit();
}
catch(Exceptions\NewsletterSubscriptionNotFoundException){
if($requestType == WEB){
if($requestType == HttpRequestType::Web){
Template::Emit404();
}
else{

View file

@ -13,7 +13,7 @@ try{
$created = true;
}
else{
$subscription = NewsletterSubscription::Get(HttpInput::Str(GET, 'uuid'));
$subscription = NewsletterSubscription::Get(HttpInput::Str(HttpVariableSource::Get, 'uuid'));
if(isset($_SESSION['subscription-created']) && $_SESSION['subscription-created'] == $subscription->UserId){
$created = true;

View file

@ -2,20 +2,18 @@
use Ramsey\Uuid\Uuid;
use function Safe\session_unset;
if(HttpInput::RequestMethod() != HTTP_POST){
http_response_code(405);
exit();
}
try{
HttpInput::ValidateRequestMethod([HttpMethod::Post]);
session_start();
session_start();
$requestType = HttpInput::RequestType();
$requestType = HttpInput::RequestType();
$subscription = new NewsletterSubscription();
$subscription = new NewsletterSubscription();
if(HttpInput::Str(POST, 'automationtest')){
if(HttpInput::Str(HttpVariableSource::Post, 'automationtest')){
// A bot filled out this form field, which should always be empty. Pretend like we succeeded.
if($requestType == WEB){
if($requestType == HttpRequestType::Web){
http_response_code(303);
$uuid = Uuid::uuid4();
$subscription->User = new User();
@ -24,41 +22,41 @@ if(HttpInput::Str(POST, 'automationtest')){
header('Location: /newsletter/subscriptions/success');
}
else{
// Access via REST api; 201 CREATED with location
// Access via HttpRequestType::Rest api; 201 CREATED with location
http_response_code(201);
header('Location: /newsletter/subscriptions/success');
}
exit();
}
}
try{
$subscription->User = new User();
$subscription->User->Email = HttpInput::Str(POST, 'email');
$subscription->IsSubscribedToNewsletter = HttpInput::Bool(POST, 'issubscribedtonewsletter') ?? false;
$subscription->IsSubscribedToSummary = HttpInput::Bool(POST, 'issubscribedtosummary') ?? false;
$subscription->User->Email = HttpInput::Str(HttpVariableSource::Post, 'email');
$subscription->IsSubscribedToNewsletter = HttpInput::Bool(HttpVariableSource::Post, 'issubscribedtonewsletter') ?? false;
$subscription->IsSubscribedToSummary = HttpInput::Bool(HttpVariableSource::Post, 'issubscribedtosummary') ?? false;
$expectedCaptcha = HttpInput::Str(SESSION, 'captcha') ?? '';
$receivedCaptcha = HttpInput::Str(POST, 'captcha');
$expectedCaptcha = HttpInput::Str(HttpVariableSource::Session, 'captcha') ?? '';
$receivedCaptcha = HttpInput::Str(HttpVariableSource::Post, 'captcha');
$subscription->Create($expectedCaptcha, $receivedCaptcha);
session_unset();
if($requestType == WEB){
if($requestType == HttpRequestType::Web){
http_response_code(303);
$_SESSION['subscription-created'] = $subscription->UserId;
header('Location: /newsletter/subscriptions/success');
}
else{
// Access via REST api; 201 CREATED with location
// Access via HttpRequestType::Rest api; 201 CREATED with location
http_response_code(201);
header('Location: /newsletter/subscriptions/success');
}
}
catch(Exceptions\NewsletterSubscriptionExistsException){
// Subscription exists.
if($requestType == WEB){
if($requestType == HttpRequestType::Web){
// If we're accessing from the web, update the subscription,
// re-sending the confirmation email if the user isn't yet confirmed
$existingSubscription = NewsletterSubscription::Get($subscription->User->Uuid);
@ -79,12 +77,12 @@ catch(Exceptions\NewsletterSubscriptionExistsException){
}
}
else{
// Access via REST api; 409 CONFLICT
// Access via HttpRequestType::Rest api; 409 CONFLICT
http_response_code(409);
}
}
catch(Exceptions\InvalidNewsletterSubscription $ex){
if($requestType == WEB){
if($requestType == HttpRequestType::Web){
$_SESSION['subscription'] = $subscription;
$_SESSION['exception'] = $ex;
@ -93,7 +91,7 @@ catch(Exceptions\InvalidNewsletterSubscription $ex){
header('Location: /newsletter/subscriptions/new');
}
else{
// Access via REST api; 422 Unprocessable Entity
// Access via HttpRequestType::Rest api; 422 Unprocessable Entity
http_response_code(422);
}
}

View file

@ -5,7 +5,7 @@ $poll = new Poll();
$canVote = true; // Allow non-logged-in users to see the 'vote' button
try{
$poll = Poll::GetByUrlName(HttpInput::Str(GET, 'pollurlname'));
$poll = Poll::GetByUrlName(HttpInput::Str(HttpVariableSource::Get, 'pollurlname'));
if(!$poll->IsActive() && $poll->End !== null && $poll->End < new DateTimeImmutable()){
// If the poll ended, redirect to the results

View file

@ -7,7 +7,7 @@ $vote = new PollVote();
$created = false;
try{
$vote = PollVote::Get(HttpInput::Str(GET, 'pollurlname'), HttpInput::Int(GET, 'userid'));
$vote = PollVote::Get(HttpInput::Str(HttpVariableSource::Get, 'pollurlname'), HttpInput::Int(HttpVariableSource::Get, 'userid'));
if(isset($_SESSION['vote-created']) && $_SESSION['vote-created'] == $vote->UserId){
$created = true;

View file

@ -2,7 +2,7 @@
$poll = new Poll();
try{
$poll = Poll::GetByUrlName(HttpInput::Str(GET, 'pollurlname'));
$poll = Poll::GetByUrlName(HttpInput::Str(HttpVariableSource::Get, 'pollurlname'));
}
catch(Exceptions\AppException){
Template::Emit404();

View file

@ -19,7 +19,7 @@ try{
$vote->User = $GLOBALS['User'];
}
$poll = Poll::GetByUrlName(HttpInput::Str(GET, 'pollurlname'));
$poll = Poll::GetByUrlName(HttpInput::Str(HttpVariableSource::Get, 'pollurlname'));
try{
$vote = PollVote::Get($poll->UrlName, $GLOBALS['User']->UserId);

View file

@ -1,46 +1,43 @@
<?
use function Safe\session_unset;
if(HttpInput::RequestMethod() != HTTP_POST){
http_response_code(405);
exit();
}
session_start();
$requestType = HttpInput::RequestType();
$vote = new PollVote();
try{
$vote->PollItemId = HttpInput::Int(POST, 'pollitemid');
HttpInput::ValidateRequestMethod([HttpMethod::Post]);
$vote->Create(HttpInput::Str(POST, 'email'));
session_start();
$requestType = HttpInput::RequestType();
$vote = new PollVote();
$vote->PollItemId = HttpInput::Int(HttpVariableSource::Post, 'pollitemid');
$vote->Create(HttpInput::Str(HttpVariableSource::Post, 'email'));
session_unset();
if($requestType == WEB){
if($requestType == HttpRequestType::Web){
$_SESSION['vote-created'] = $vote->UserId;
http_response_code(303);
header('Location: ' . $vote->Url);
}
else{
// Access via REST api; 201 CREATED with location
// Access via HttpRequestType::Rest api; 201 CREATED with location
http_response_code(201);
header('Location: ' . $vote->Url);
}
}
catch(Exceptions\InvalidPollVoteException $ex){
if($requestType == WEB){
if($requestType == HttpRequestType::Web){
$_SESSION['vote'] = $vote;
$_SESSION['exception'] = $ex;
// Access via form; 303 redirect to the form, which will emit a 422 Unprocessable Entity
http_response_code(303);
header('Location: /polls/' . (HttpInput::Str(GET, 'pollurlname') ?? '') . '/votes/new');
header('Location: /polls/' . (HttpInput::Str(HttpVariableSource::Get, 'pollurlname') ?? '') . '/votes/new');
}
else{
// Access via REST api; 422 Unprocessable Entity
// Access via HttpRequestType::Rest api; 422 Unprocessable Entity
http_response_code(422);
}
}

View file

@ -8,8 +8,8 @@ if($GLOBALS['User'] !== null){
exit();
}
$email = HttpInput::Str(SESSION, 'email');
$redirect = HttpInput::Str(SESSION, 'redirect') ?? HttpInput::Str(GET, 'redirect');
$email = HttpInput::Str(HttpVariableSource::Session, 'email');
$redirect = HttpInput::Str(HttpVariableSource::Session, 'redirect') ?? HttpInput::Str(HttpVariableSource::Get, 'redirect');
$exception = $_SESSION['exception'] ?? null;
$passwordRequired = false;

View file

@ -1,40 +1,38 @@
<?
use function Safe\preg_match;
use function Safe\session_unset;
if(HttpInput::RequestMethod() != HTTP_POST){
http_response_code(405);
exit();
}
session_start();
$requestType = HttpInput::RequestType();
$session = new Session();
$email = HttpInput::Str(POST, 'email');
$password = HttpInput::Str(POST, 'password');
$redirect = HttpInput::Str(POST, 'redirect');
try{
HttpInput::ValidateRequestMethod([HttpMethod::Post]);
session_start();
$requestType = HttpInput::RequestType();
$session = new Session();
$email = HttpInput::Str(HttpVariableSource::Post, 'email');
$password = HttpInput::Str(HttpVariableSource::Post, 'password');
$redirect = HttpInput::Str(HttpVariableSource::Post, 'redirect');
if($redirect === null){
$redirect = '/';
}
$session->Create($email, $password);
if($requestType == WEB){
session_unset();
if($requestType == HttpRequestType::Web){
http_response_code(303);
header('Location: ' . $redirect);
}
else{
// Access via REST api; 201 CREATED with location
// Access via HttpRequestType::Rest api; 201 CREATED with location
http_response_code(201);
header('Location: ' . $session->Url);
}
}
catch(Exceptions\AppException $ex){
if($requestType == WEB){
catch(Exceptions\InvalidLoginException | Exceptions\PasswordRequiredException $ex){
if($requestType == HttpRequestType::Web){
$_SESSION['email'] = $email;
$_SESSION['redirect'] = $redirect;
$_SESSION['exception'] = $ex;
@ -44,7 +42,7 @@ catch(Exceptions\AppException $ex){
header('Location: /sessions/new');
}
else{
// Access via REST api; 422 Unprocessable Entity
// Access via HttpRequestType::Rest api; 422 Unprocessable Entity
http_response_code(422);
}
}

View file

@ -1,8 +1,8 @@
<?
use function Safe\strtotime;
$hideDonationAlert = HttpInput::Bool(POST, 'hide-donation-alert');
$colorScheme = HttpInput::Str(POST, 'color-scheme');
$hideDonationAlert = HttpInput::Bool(HttpVariableSource::Post, 'hide-donation-alert');
$colorScheme = HttpInput::Str(HttpVariableSource::Post, 'color-scheme');
if($hideDonationAlert !== null){
setcookie('hide-donation-alert', $hideDonationAlert ? 'true' : 'false', ['expires' => strtotime('+1 month'), 'path' => '/', 'domain' => SITE_DOMAIN, 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);

View file

@ -8,16 +8,13 @@ use function Safe\shell_exec;
// This script makes various calls to external scripts using exec() (and when called via Apache, as the www-data user).
// These scripts are allowed using the /etc/sudoers.d/www-data file. Only the specific scripts
// in that file may be executed by this script.
$log = new Log(GITHUB_WEBHOOK_LOG_FILE_PATH);
$lastPushHashFlag = '';
try{
$log->Write('Received GitHub webhook.');
$log = new Log(GITHUB_WEBHOOK_LOG_FILE_PATH);
$lastPushHashFlag = '';
if(HttpInput::RequestMethod() != HTTP_POST){
throw new Exceptions\WebhookException('Expected HTTP POST.');
}
HttpInput::ValidateRequestMethod([HttpMethod::Post]);
$log->Write('Received GitHub webhook.');
$post = file_get_contents('php://input');

View file

@ -5,17 +5,14 @@ use function Safe\curl_setopt;
use function Safe\file_get_contents;
use function Safe\json_decode;
$log = new Log(POSTMARK_WEBHOOK_LOG_FILE_PATH);
try{
$log = new Log(POSTMARK_WEBHOOK_LOG_FILE_PATH);
/** @var string $smtpUsername */
$smtpUsername = get_cfg_var('se.secrets.postmark.username');
$log->Write('Received Postmark webhook.');
if(HttpInput::RequestMethod() != HTTP_POST){
throw new Exceptions\WebhookException('Expected HTTP POST.');
}
HttpInput::ValidateRequestMethod([HttpMethod::Post]);
$apiKey = get_cfg_var('se.secrets.postmark.api_key');

View file

@ -1,22 +1,17 @@
<?
use Safe\DateTimeImmutable;
use function Safe\file_get_contents;
use function Safe\preg_match;
use function Safe\preg_replace;
use function Safe\json_decode;
// This webhook receives POSTs when email from a Fractured Atlas donation is received
// at the SE Zoho email account. This script processes the email, and inserts the donation ID
// into the database for later processing by ~se/web/scripts/process-pending-payments
$log = new Log(ZOHO_WEBHOOK_LOG_FILE_PATH);
try{
$log->Write('Received Zoho webhook.');
$log = new Log(ZOHO_WEBHOOK_LOG_FILE_PATH);
if(HttpInput::RequestMethod() != HTTP_POST){
throw new Exceptions\WebhookException('Expected HTTP POST.');
}
HttpInput::ValidateRequestMethod([HttpMethod::Post]);
$log->Write('Received Zoho webhook.');
$post = file_get_contents('php://input');
@ -39,11 +34,11 @@ try{
$transactionId = $matches[1];
Db::Query('
INSERT into PendingPayments (Created, ChannelId, TransactionId)
INSERT into PendingPayments (Created, Processor, TransactionId)
values (utc_timestamp(),
?,
?)
', [PAYMENT_CHANNEL_FA, $transactionId]);
', [PaymentProcessor::FracturedAtlas, $transactionId]);
$log->Write('Donation ID: ' . $transactionId);
}