Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Skip malformed page tokens consistently in parsePageList (#8127)

Hariomlokhande-coder3947e94c60bf
diff --git a/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java b/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java
index 5ee0d17895..b153ee1391 100644
--- a/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java
@@ -642,11 +642,7 @@ public class GeneralUtils {
if (pages == null) {
return List.of(1); // Default to first page if input is null
}
- try {
- return parsePageList(pages.split(","), totalPages, oneBased);
- } catch (NumberFormatException e) {
- return List.of(1); // Default to first page if input is invalid
- }
+ return parsePageList(pages.split(","), totalPages, oneBased);
}
public List<Integer> parsePageList(String[] pages, int totalPages) {
@@ -702,11 +698,7 @@ public class GeneralUtils {
List<Integer> results = new ArrayList<>();
DoubleEvaluator evaluator = new DoubleEvaluator();
- // Validate the expression format
- if (!RegexPatternUtils.getInstance()
- .getMathExpressionPattern()
- .matcher(expression.trim())
- .matches()) {
+ if (!isMathExpression(expression)) {
throw new IllegalArgumentException("Invalid expression format: " + expression);
}
@@ -738,6 +730,28 @@ public class GeneralUtils {
return results;
}
+ private boolean isMathExpression(String expression) {
+ return patternCache.getMathExpressionPattern().matcher(expression.trim()).matches();
+ }
+
+ /*
+ * Whether a token is a well-formed n-function. getMathExpressionPattern only restricts the
+ * characters, so "n+" passes it; the expression is parsed once to reject tokens the evaluator
+ * cannot read. Parsing succeeds or fails on structure alone, so a single n is enough.
+ */
+ private boolean isNFunction(String expression) {
+ if (!isMathExpression(expression)) {
+ return false;
+ }
+ try {
+ new DoubleEvaluator().evaluate(sanitizeNFunction(expression.trim(), 1));
+ return true;
+ } catch (Exception e) {
+ log.debug("Not an n-function: '{}': {}", expression, e.getMessage());
+ return false;
+ }
+ }
+
private String sanitizeNFunction(String expression, int nValue) {
// Remove all spaces using a specialized character removal
StringBuilder sb = new StringBuilder(expression.length());
@@ -807,8 +821,11 @@ public class GeneralUtils {
return partResult;
}
- // First check for n-syntax because it should not be processed as a range
- if (trimmedPart.contains("n")) {
+ // First check for n-syntax because it should not be processed as a range. A token that
+ // only contains an "n" ("no", "and") or is not a well-formed expression ("n+") must not
+ // reach evaluateNFunc, which throws and would fail the whole list; it falls through and
+ // is dropped like any other bad token.
+ if (trimmedPart.contains("n") && isNFunction(trimmedPart)) {
partResult = evaluateNFunc(trimmedPart, totalPages);
// Adjust the results according to the offset
for (int i = 0; i < partResult.size(); i++) {
@@ -817,7 +834,8 @@ public class GeneralUtils {
}
} else if (trimmedPart.contains("-")) {
// Process ranges only if it's not n-syntax
- String[] rangeParts = trimmedPart.split("-");
+ // Limit -1 keeps empty parts, so a bare "-" is an invalid range, not an empty array.
+ String[] rangeParts = trimmedPart.split("-", -1);
try {
int start = Integer.parseInt(rangeParts[0].trim());
int end =
diff --git a/app/common/src/test/java/stirling/software/common/util/GeneralUtilsMoreTest.java b/app/common/src/test/java/stirling/software/common/util/GeneralUtilsMoreTest.java
index 497f9f8746..6e71d008bd 100644
--- a/app/common/src/test/java/stirling/software/common/util/GeneralUtilsMoreTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/GeneralUtilsMoreTest.java
@@ -206,6 +206,45 @@ class GeneralUtilsMoreTest {
void rangePartlyOutOfBounds() {
assertEquals(List.of(4, 5), GeneralUtils.parsePageList(new String[] {"4-99"}, 5, true));
}
+
+ @ParameterizedTest(name = "\"{0}\" is dropped")
+ @ValueSource(strings = {"-", "--"})
+ @DisplayName("range without any bounds is dropped")
+ void rangeWithoutBoundsDropped(String token) {
+ assertTrue(GeneralUtils.parsePageList(new String[] {token}, 5, true).isEmpty());
+ }
+ }
+
+ @Nested
+ @DisplayName("tokens containing n that are not n-functions")
+ class NonFunctionTokenTests {
+
+ @ParameterizedTest(name = "\"{0}\" is dropped")
+ @ValueSource(strings = {"no", "and", "none", "xn", "2n+x", "n+", "n*", "n("})
+ @DisplayName("token is dropped like any other non-numeric token")
+ void droppedLikeOtherInvalidTokens(String token) {
+ assertTrue(GeneralUtils.parsePageList(new String[] {token}, 5, true).isEmpty());
+ }
+
+ @Test
+ @DisplayName("valid tokens around it are still returned")
+ void validTokensKept() {
+ assertEquals(List.of(1, 3), GeneralUtils.parsePageList("1,no,3", 5, true));
+ }
+
+ @Test
+ @DisplayName("a real n-function past the evaluation limit still throws")
+ void nFunctionLimitStillEnforced() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> GeneralUtils.parsePageList("2n", 10001, true));
+ }
+
+ @Test
+ @DisplayName("a malformed n-token is dropped even past the evaluation limit")
+ void malformedNTokenPastLimitIsDropped() {
+ assertEquals(List.of(1, 3), GeneralUtils.parsePageList("1,n+,3", 10001, true));
+ }
}
@Nested
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/PDFWithPageNumsTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/PDFWithPageNumsTest.java
index 50489567c1..6ef1a650f1 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/PDFWithPageNumsTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/PDFWithPageNumsTest.java
@@ -75,10 +75,8 @@ class PDFWithPageNumsTest {
pdfWithPageNums.setPageNumbers("invalid");
when(mockDocument.getNumberOfPages()).thenReturn(10);
- assertThrows(
- IllegalArgumentException.class,
- () -> {
- pdfWithPageNums.getPageNumbersList(mockDocument, true);
- });
+ List<Integer> result = pdfWithPageNums.getPageNumbersList(mockDocument, true);
+
+ assertTrue(result.isEmpty());
}
}