HEX
Server: Microsoft-IIS/10.0
System: Windows NT ITPWINWEBSVR22 10.0 build 20348 (Windows Server 2022) AMD64
User: www.conferencesearch.co.uk (0)
PHP: 8.3.30
Disabled: NONE
Upload Files
File: D:/web/castironradiatorcentre/2024-07-02/prev/inc-template-competition.asp
<!-- #include file="uploadhelper.asp" -->
<%
' (SS,23/10/23) new competition page (based on contact page template)
' using uploadhelper "uploadhelper.asp" included above

Const PU_UPLOADS_FOLDER = "/uploads"
Const PU_DEBUG_MODE = False

Sub ShowCompetitionHeader
  ' no need to page heading/title just wasting space because we have panels in the two sections which are headings
  ShowPageTitle "Competition", "#MyRadRocks Competition", ""
%>
<div id="other-pages2">
<%
End Sub

Sub ShowCompetitionForm(AErrorMessage, AName, AEmail, AMarketingOptIn)

  Dim LMarketingOptInChecked
  If AMarketingOptIn = "checked" Then
    LMarketingOptInChecked = " checked"
  Else
    LMarketingOptInChecked = "" 
  End If

%>


<div class="row">

<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">  

<%=GetTokenText("Competition Header")%>

</div> <!--cols-->

</div> <!--row-->

<div class="row">

<div class="col-lg-6 col-md-6 col-sm-8 col-xs-12">  
<a id="entry"></a>
  <div class="panel panel-default">
  
    <div class="panel-heading">Competition Entry Form</div>
    <div class="panel-body">

<form action="products.asp?page=competition&cmd=upload" method="post" name="Competition Entry Form" role="form" enctype="multipart/form-data">
    
    
<%If AErrorMessage <> "" Then
  ShowAlertMesssage "danger", AErrorMessage
End If%>
  
  <div class="form-group">
    <label for="Name">Name</label>
    <input type="text" class="form-control" name="Name" id="Name" placeholder="Enter name" value="<%=AName%>" maxlength="100" required="true">
  </div>
  
  <div class="form-group">
    <label for="Email">Email</label>
    <input type="email" class="form-control" name="Email" id="Email" placeholder="Enter email address" value="<%=AEmail%>" maxlength="100" required="true">
  </div>

  <div class="form-group">
    <div class="checkbox">
      <label>
        <input type="checkbox" name="MarketingOptIn" id="MarketingOptIn" value="checked"<%=LMarketingOptInChecked%>>Opt in for marketing (optional)
      </label>
    </div>
  </div>
    
  <div class="form-group">
    <label for="files">Upload photos</label>
    <input type="file" class="form-control" name="files" id="files" multiple accept="image/*" maxlength="100" required="true">
    <p class="help-block">Choose photos and press upload (maximum 50 MB)</p>    
  </div>    

  <div class="form-group">
    <button type="submit" class="btn btn-success">Upload</button>
  </div>

</form>

  </div>

  </div> <!--panel-->

</div> <!--cols-->

</div> <!--row-->

<div class="row">

<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">  

<%=GetTokenText("Competition Footer")%>

</div> <!--cols-->

</div> <!--row-->



<%

  AddScript "ScriptUploadFiles"
End Sub

' (SS,26/10/23) for jquery script at the end, after jquery library downloaded
Sub ScriptUploadFiles
%>
<script>
$('#files').change(function() {
  var totalfilesize = 0;
  $.each(this.files, function(i, file) {
    totalfilesize += file.size;
  });
  if (totalfilesize > 52428800) {
    var totalfilesizeMB = (totalfilesize / 1024 / 1024).toFixed(2);
    alert("File(s) are too big\nYou have selected " + totalfilesizeMB.toString() + " MB \nMaximum allowed is 50 MB\nPlease reselect");
    this.value = "";
  }
});
</script>
<%
End Sub


Sub ShowUploadMaxFileSizeScript
  ' from https://uploadcare.com/blog/how-to-upload-files-using-js/
%>

  
  <p>
    <strong>Uploading status:</strong>
    <span id="statusMessage">Nothing's uploaded</span>
  </p>

<script>

const statusMessage = document.getElementById('statusMessage');
const submitButton = document.querySelector('button');
const fileInput = document.querySelector('input');

function updateStatusMessage(text) {
  statusMessage.textContent = text;
}

function assertFilesValid(fileList) {
  const allowedTypes = ['image/webp', 'image/jpeg', 'image/png'];
  // const sizeLimit = 50 * 1024 * 1024; // 50 megabytes
  const sizeLimit = 1 * 1024 * 1024; // 1 megabyte

  for (const file of fileList) {
    const { name: fileName, size: fileSize } = file;

    if (!allowedTypes.includes(file.type)) {
      throw new Error('❌ File "${fileName}" could not be uploaded. Only images with the following types are allowed: WEBP, JPEG, PNG.');
    }

    // ↓ the new condition ↓
    if (fileSize > sizeLimit) {
      throw new Error('❌ File "${fileName}" could not be uploaded. Only images up to 1 MB are allowed.');
    }
  }
}

function handleInputChange() {
  try {
    assertFilesValid(fileInput.files);
  } catch (err) {
    updateStatusMessage(err.message);
    return;
  }

  submitButton.disabled = false;
}

fileInput.addEventListener('change', handleInputChange);

function resetFormState() {
  submitButton.disabled = true;
  updateStatusMessage("Nothing's uploaded")
}

function handleInputChange(event) {
  resetFormState();

  // the rest of the code goes here
}

</script>
<%
End Sub

Sub ShowCompetitionThankYou
  ' (SS,25/10/23) removed following for now
  ' oGTM.EventContactForm "Competition"
  Dim LTokenText, LSuccessMessage
  LTokenText = GetTokenText("Competition Thank You")
  ' add upload success status
  LSuccessMessage = GetUploadSuccessMessage
  If LSuccessMessage = "" Then
    LSuccessMessage = "No photos uploaded"
  End If
  LTokenText = ReplaceStr(LTokenText, "[Upload Status]", LSuccessMessage)
%>
  
  <div class="panel panel-default">  
    <div class="panel-heading">Competition Entry Submitted</b></div>
    <div class="panel-body">
    <%=LTokenText%>
    </div>
  </div>
<%
End Sub

Sub ShowCompetitionFooter
%>
</div> <!-- end #other-pages2 -->
<%
End Sub

Sub DoCompetitionForm
  ShowCompetitionHeader

  Dim LErrorMessage, LShowForm
  LErrorMessage = ""
  LShowForm = True

  Dim LCmd, LName, LEmail, LMarketingOptIn
  ' need to ensure that we don't access the Form collection otherwise we'll get the following error:
  ' Cannot call BinaryRead after using Request.Form collection.
  
  LCmd = CleanRequestQueryString("cmd") 
  
  If LCmd = "upload" Then      
    If ProcessUploads(LErrorMessage, LName, LEmail, LMarketingOptIn) Then
      ' in debug mode don't redirect
      If PU_DEBUG_MODE Then
        ShowCompetitionThankYou  
      Else
        SetPageRedirection "products.asp?page=competition&cmd=thankyou"
      End If
      LShowForm = False
    Else
      LErrorMessage = "Upload failed: " & LErrorMessage
    End If
  ElseIf LCmd = "thankyou" Then
    ShowCompetitionThankYou
    LShowForm = False
  End If
  If LShowForm Then
    ShowCompetitionForm LErrorMessage, LName, LEmail, LMarketingOptIn          
  End If
  
  ShowCompetitionFooter  
End Sub

' (SS,24/10/23) need to make sure max size is increased in IIS to about 30MB
' files are saved to public folder
' Upload works from "Files" or similar field I think?
Function ProcessUploads(ByRef AErrorMessage, ByRef AName, ByRef AEmail, ByRef AMarketingOptIn)
  Dim objUpload, LResult
  LResult = False
  Set objUpload = New UploadHelper
  If objUpload.GetError <> "" Then
    AErrorMessage = "Warning: " & objUpload.GetError
    ' Response.Write("Warning: "  & objUpload.GetError)
  Else  
    If PU_DEBUG_MODE Then 
      Response.Write("found "&objUpload.FileCount&" files...<br />")
    End If
    
    ' get the Name, Email and MarketingOptIn values
    Dim i, LFormFieldName, LImageCount
    LImageCount = 0
    For i = 0 To objUpload.FileCount - 1
      LFormFieldName = objUpload.File(i).FormFieldName
      If LFormFieldName = "Name" Then
        AName = EscapeHTMLAngleBrackets(objUpload.File(i).ContentAsStr)
      ElseIf LFormFieldName = "Email" Then
        AEmail = EscapeHTMLAngleBrackets(objUpload.File(i).ContentAsStr)
      ElseIf LFormFieldName = "MarketingOptIn" Then
        AMarketingOptIn = EscapeHTMLAngleBrackets(objUpload.File(i).ContentAsStr)
      ElseIf LFormFieldName = "files" Then
        If ContentTypeIsImage(objUpload.File(i).ContentType) Then LImageCount = LImageCount + 1: End If
      End If        
    Next
    ' check that Name and Email are entered
    If AName = "" Then
      AErrorMessage = "Please enter either your name"
    ElseIf AEmail = "" Then
      AErrorMessage = "Please enter either your email address"
    ElseIf LImageCount = 0 Then
      AErrorMessage = "No images sent"
    Else
      AErrorMessage = ""
    End If
    
    If AErrorMessage = "" Then
      ' reaches here when there is ar least one image
      Dim LFileCount, LTotalFileSize    
      LFileCount = 0
      LTotalFileSize = 0
    
      Dim LUploadID, LUploadedFileID, LOriginalFileName, LSavedFileName, LFileExtension, LFileType, LFileSize, LImageWidth, LImageHeight
      
      ' create header record
      LUploadID = GetNewUploadID("MyRadRocks", AName, AEmail, AMarketingOptIn)
    
      Dim x
      For x = 0 To objUpload.FileCount - 1
        If PU_DEBUG_MODE Then
          Response.Write "form field name: " & objUpload.File(x).FormFieldName & BR
          Response.Write "content disposition: "&objUpload.File(x).ContentDisposition & BR
          Response.Write "file name: " & objUpload.File(x).FileName & BR
          Response.Write "file type: " & objUpload.File(x).ContentType & BR
          Response.Write "file size: " & objUpload.File(x).Size & BR
          Response.Write "image width: " & objUpload.File(x).ImageWidth & BR
          Response.Write "image height: " & objUpload.File(x).ImageHeight & BR
        End If
        'If (objUpload.File(x).ImageWidth > 10000) Or (objUpload.File(x).ImageHeight > 10000) Then
        '  Response.Write("the image is too big, file not saved!")
        'Else
        
        If objUpload.File(x).FormFieldName = "files" And ContentTypeIsImage(objUpload.File(x).ContentType) Then
          LFileCount = LFileCount + 1
          LOriginalFileName = objUpload.File(x).FileName
          LFileExtension = objUpload.File(x).Extension
          LFileType = objUpload.File(x).ContentType
          LFileSize = objUpload.File(x).Size
          LTotalFileSize = LTotalFileSize + LFileSize
          LImageWidth = objUpload.File(x).ImageWidth
          LImageHeight = objUpload.File(x).ImageHeight
          ' Response.Write "file ext: " & LFileExtension & BR
          
          ' create detail record
           ' ASavedFileName is composed of AUploadID + "123_1.jpg" "123-1.jpg"
          ' Make sure extension is digits or numbers only
          LUploadedFileID = GetNewUploadedFileID(LUploadID, LOriginalFileName, "", LFileType, LFileSize, LImageWidth, LImageHeight)
          
          ' set the saved file name and update the record with it, file extension is check to ensure its alphanumeric and not longer than 30 chars max
          LFileExtension = Left(GetAlphaNumericStr(LFileExtension), 30)
          LSavedFileName = LUploadID & "-" & LUploadedFileID & "." & LFileExtension
          UpdateUploadedFileSavedFileName LUploadedFileID, LSavedFileName
          
          ' save the file        
          Call objUpload.File(x).SaveToDisk(Server.MapPath(PU_UPLOADS_FOLDER), LSavedFileName)
          LResult = True
          If PU_DEBUG_MODE Then Response.Write("file saved successfully!"): End If
        Else
          If PU_DEBUG_MODE Then Response.Write("not saved"): End If
        End If
        If PU_DEBUG_MODE Then Response.Write "<hr>": End If
      Next
      
      SetUploadSuccessMessage "Successfully uploaded " & PluralString(LFileCount, "photo", "photos") & " totalling " & Round2dp(LTotalFileSize / 1024 / 1024) & " MB"
    End If
  End If
  ProcessUploads = LResult

End Function

Function ContentTypeIsImage(AContentType)
  ContentTypeIsImage = LCase(Mid(AContentType, 1, 6)) = "image/"  
End Function

Function GetNewUploadID(AType, AName, AEmail, AMarketingOptIn)
  Dim LSQL, LLastInsertID
  LSQL = "INSERT INTO uploads SET Type = '" & AType & "'" &_   
    ", Name = '" & CleanSQLStrMax(AName, 100) & "'" &_
    ", Email = '" & CleanSQLStrMax(AEmail, 100) & "'" &_
    ", MarketingOptIn = '" & iif(AMarketingOptIn = "", 0, 1) & "'" &_
    ", DateTimeCreated = NOW()"    
  ExecuteQuery LSQL
  GetNewUploadID = GetSQLLastInsertID  
End Function

Function GetNewUploadedFileID(AUploadID, AOriginalFileName, ASavedFileName, AFileType, AFileSize, AImageWidth, AImageHeight) 
  Dim LSQL, LLastInsertID
  LSQL = "INSERT INTO uploaded_files SET UploadID = " & AUploadID & _   
    ", OriginalFileName = '" & CleanSQLStrMax(AOriginalFileName, 255) & "'" &_
    ", SavedFileName = '" & CleanSQLStrMax(ASavedFileName, 50) & "'" &_
    ", FileType = '" & CleanSQLStrMax(AFileType, 50) & "'" &_
    ", FileSize = " & AFileSize &_
    ", ImageWidth = " & AImageWidth &_
    ", ImageHeight = " & AImageHeight &_
    ", DateTimeUploaded = NOW()"     
  ExecuteQuery LSQL
  GetNewUploadedFileID = GetSQLLastInsertID  
End Function

Sub UpdateUploadedFileSavedFileName(AUploadedFileID, ASavedFileName)
  Dim LSQL
  ExecuteQuery "UPDATE uploaded_files SET SavedFileName = '" & CleanSQLStrMax(ASavedFileName, 50) & "' WHERE UploadedFileID = " & AUploadedFileID
End Sub

' remove non alpha numeric characters from given string
' !!! to be placed in dbfunctions.asp
Function GetAlphaNumericStr(AString)
  Dim LLen, LString, LChar, LResult, i
  LLen = Len(AString)
  LString = NB(AString)
  LResult = ""
  If LString <> "" Then
    For i = 1 To LLen
      LChar = Mid(LString, i, 1)
      If IsCharAlpha(LChar) Or IsCharNumeric(LChar) Then
        LResult = LResult + LChar
      End If
    Next
  End If
  GetAlphaNumericStr = LString
End Function

Sub SetUploadSuccessMessage(AMessage)
  Session("UploadSuccessMessage") = AMessage
End Sub

Function GetUploadSuccessMessage
  GetUploadSuccessMessage = Session("UploadSuccessMessage")
End Function


%>