From adb11945e9932c87c7a761caebd0c0c3eaad74c6 Mon Sep 17 00:00:00 2001 From: Brian Huisman Date: Fri, 15 Mar 2024 13:37:06 -0400 Subject: [PATCH 1/6] Account for inline image data in formatContent() `formatContent()` now accounts for inline image `BI ... ID ... EI` commands in document streams. --- src/Smalot/PdfParser/PDFObject.php | 24 +++++++++++++++++++++ tests/PHPUnit/Integration/PDFObjectTest.php | 13 +++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/Smalot/PdfParser/PDFObject.php b/src/Smalot/PdfParser/PDFObject.php index 69e2120b..f3165ca0 100644 --- a/src/Smalot/PdfParser/PDFObject.php +++ b/src/Smalot/PdfParser/PDFObject.php @@ -214,6 +214,20 @@ private function formatContent(?string $content): string return ''; } + // Find all inline image content and replace them so they aren't + // affected by the next steps + $pdfInlineImages = []; + while (preg_match('/\sID\s(.+?)\sEI(?=\s|$)/', $content, $text)) { + $id = uniqid('IMAGE_', true); + $pdfInlineImages[$id] = $text[1]; + $content = preg_replace( + '/'.preg_quote($text[0], '/').'/', + '^^^'.$id.'^^^', + $content, + 1 + ); + } + // Outside of (String) content in PDF document streams, all // text should conform to UTF-8. Test for binary content by // deleting everything after the first open-parenthesis ( which @@ -319,6 +333,16 @@ private function formatContent(?string $content): string $content = str_replace('@@@'.$id.'@@@', $text, $content); } + // Restore the original content of any inline images + $pdfInlineImages = array_reverse($pdfInlineImages, true); + foreach ($pdfInlineImages as $id => $image) { + $content = str_replace( + '^^^'.$id.'^^^', + "\r\nID\r\n".$image."\r\nEI\r\n", + $content + ); + } + $content = trim(preg_replace(['/(\r\n){2,}/', '/\r\n +/'], "\r\n", $content)); return $content; diff --git a/tests/PHPUnit/Integration/PDFObjectTest.php b/tests/PHPUnit/Integration/PDFObjectTest.php index 025c11b1..39079a2c 100644 --- a/tests/PHPUnit/Integration/PDFObjectTest.php +++ b/tests/PHPUnit/Integration/PDFObjectTest.php @@ -284,6 +284,19 @@ public function testFormatContent(): void // Binary check is done before a regexp that causes an error $this->assertStringContainsString('Marko Nestorović PR', $pages[0]->getText()); + + // Check that inline image data does not corrupt the stream + // See: https://github.com/smalot/pdfparser/issues/691 + $cleaned = $formatContent->invoke( + $this->getPdfObjectInstance(new Document()), + 'q 65.30 0 0 18.00 412 707 cm BI /W 544 /H 150 /BPC 1 /IM true /F [/A85 /Fl] ID Gb"0F_$L6!$j/a\$:ma&h\'JnJJ9S?O_EA-W+%D^ClCH=FP3s5M-gStQm\'5/hc`C?CqL(^pV$_-er6Ik`"-1]Q ;~> EI Q /F002 10.00 Tf 0.00 Tw 0 g' + ); + + // PdfParser should not be fooled by Q's in inline image data; + // Only one 'Q' command should be found + $commandQ = preg_match_all('/Q\r\n/', $cleaned); + + $this->assertEquals(1, $commandQ); } public function testGetSectionsText(): void From 4ae52e79f4666a965ff300f92dc5efb18c9b0a82 Mon Sep 17 00:00:00 2001 From: Brian Huisman Date: Fri, 15 Mar 2024 13:56:32 -0400 Subject: [PATCH 2/6] Include BI command in the regexp Include the `BI` command in the regexp, and move inline image detection after string replacement to prevent false-positives. --- src/Smalot/PdfParser/PDFObject.php | 48 +++++++++++++++--------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/src/Smalot/PdfParser/PDFObject.php b/src/Smalot/PdfParser/PDFObject.php index f3165ca0..b9ac62d1 100644 --- a/src/Smalot/PdfParser/PDFObject.php +++ b/src/Smalot/PdfParser/PDFObject.php @@ -214,20 +214,6 @@ private function formatContent(?string $content): string return ''; } - // Find all inline image content and replace them so they aren't - // affected by the next steps - $pdfInlineImages = []; - while (preg_match('/\sID\s(.+?)\sEI(?=\s|$)/', $content, $text)) { - $id = uniqid('IMAGE_', true); - $pdfInlineImages[$id] = $text[1]; - $content = preg_replace( - '/'.preg_quote($text[0], '/').'/', - '^^^'.$id.'^^^', - $content, - 1 - ); - } - // Outside of (String) content in PDF document streams, all // text should conform to UTF-8. Test for binary content by // deleting everything after the first open-parenthesis ( which @@ -268,6 +254,20 @@ private function formatContent(?string $content): string } } + // Find all inline image content and replace them so they aren't + // affected by the next steps + $pdfInlineImages = []; + while (preg_match('/\sBI(.+?)\sID\s(.+?)\sEI(?=\s|$)/', $content, $text)) { + $id = uniqid('IMAGE_', true); + $pdfInlineImages[$id] = [$text[1], $text[2]]; + $content = preg_replace( + '/'.preg_quote($text[0], '/').'/', + '^^^'.$id.'^^^', + $content, + 1 + ); + } + // Remove all carriage returns and line-feeds from the document stream $content = str_replace(["\r", "\n"], ' ', trim($content)); @@ -317,6 +317,16 @@ private function formatContent(?string $content): string $content = str_replace('###'.$id.'###', $dict, $content); } + // Restore the original content of any inline images + $pdfInlineImages = array_reverse($pdfInlineImages, true); + foreach ($pdfInlineImages as $id => $image) { + $content = str_replace( + '^^^'.$id.'^^^', + "\r\nBI\r\n".$image[0]."\r\nID\r\n".$image[1]."\r\nEI\r\n", + $content + ); + } + // Restore the original string content $pdfstrings = array_reverse($pdfstrings, true); foreach ($pdfstrings as $id => $text) { @@ -333,16 +343,6 @@ private function formatContent(?string $content): string $content = str_replace('@@@'.$id.'@@@', $text, $content); } - // Restore the original content of any inline images - $pdfInlineImages = array_reverse($pdfInlineImages, true); - foreach ($pdfInlineImages as $id => $image) { - $content = str_replace( - '^^^'.$id.'^^^', - "\r\nID\r\n".$image."\r\nEI\r\n", - $content - ); - } - $content = trim(preg_replace(['/(\r\n){2,}/', '/\r\n +/'], "\r\n", $content)); return $content; From 6f0ef9c309b3a9789d5fdf498a4d4b83e50bcd54 Mon Sep 17 00:00:00 2001 From: Brian Huisman Date: Mon, 25 Mar 2024 11:40:13 -0400 Subject: [PATCH 3/6] Add PCRE dotall modifier Add the /s modifier so the `.` token matches newlines as well. Thanks to @iGrog for supplying another PDF that demonstrated this issue. Add the same modifier for dictionaries as well, fixing this oversight. Move the inline image replacement before string replacement. Parentheses in binary image data may be interpreted as the start of a string. Move the inline images test to its own function and add a newline to the sample data to test for the dotall modifier change. --- src/Smalot/PdfParser/PDFObject.php | 50 ++++++++++----------- tests/PHPUnit/Integration/PDFObjectTest.php | 16 +++++-- 2 files changed, 38 insertions(+), 28 deletions(-) diff --git a/src/Smalot/PdfParser/PDFObject.php b/src/Smalot/PdfParser/PDFObject.php index b9ac62d1..20e92334 100644 --- a/src/Smalot/PdfParser/PDFObject.php +++ b/src/Smalot/PdfParser/PDFObject.php @@ -224,6 +224,20 @@ private function formatContent(?string $content): string return ''; } + // Find all inline image content and replace them so they aren't + // affected by the next steps + $pdfInlineImages = []; + while (preg_match('/\sBI\s(.+?)\sID\s(.+?)\sEI(?=\s|$)/s', $content, $text)) { + $id = uniqid('IMAGE_', true); + $pdfInlineImages[$id] = [$text[1], $text[2]]; + $content = preg_replace( + '/'.preg_quote($text[0], '/').'/', + '^^^'.$id.'^^^', + $content, + 1 + ); + } + // Find all strings () and replace them so they aren't affected // by the next steps $pdfstrings = []; @@ -254,27 +268,13 @@ private function formatContent(?string $content): string } } - // Find all inline image content and replace them so they aren't - // affected by the next steps - $pdfInlineImages = []; - while (preg_match('/\sBI(.+?)\sID\s(.+?)\sEI(?=\s|$)/', $content, $text)) { - $id = uniqid('IMAGE_', true); - $pdfInlineImages[$id] = [$text[1], $text[2]]; - $content = preg_replace( - '/'.preg_quote($text[0], '/').'/', - '^^^'.$id.'^^^', - $content, - 1 - ); - } - // Remove all carriage returns and line-feeds from the document stream $content = str_replace(["\r", "\n"], ' ', trim($content)); // Find all dictionary << >> commands and replace them so they // aren't affected by the next steps $dictstore = []; - while (preg_match('/(<<.*?>> *)(BDC|BMC|DP|MP)/', $content, $dicttext)) { + while (preg_match('/(<<.*?>> *)(BDC|BMC|DP|MP)/s', $content, $dicttext)) { $dictid = uniqid('DICT_', true); $dictstore[$dictid] = $dicttext[1]; $content = preg_replace( @@ -317,16 +317,6 @@ private function formatContent(?string $content): string $content = str_replace('###'.$id.'###', $dict, $content); } - // Restore the original content of any inline images - $pdfInlineImages = array_reverse($pdfInlineImages, true); - foreach ($pdfInlineImages as $id => $image) { - $content = str_replace( - '^^^'.$id.'^^^', - "\r\nBI\r\n".$image[0]."\r\nID\r\n".$image[1]."\r\nEI\r\n", - $content - ); - } - // Restore the original string content $pdfstrings = array_reverse($pdfstrings, true); foreach ($pdfstrings as $id => $text) { @@ -343,6 +333,16 @@ private function formatContent(?string $content): string $content = str_replace('@@@'.$id.'@@@', $text, $content); } + // Restore the original content of any inline images + $pdfInlineImages = array_reverse($pdfInlineImages, true); + foreach ($pdfInlineImages as $id => $image) { + $content = str_replace( + '^^^'.$id.'^^^', + "\r\nBI\r\n".$image[0]."\r\nID\r\n".$image[1]."\r\nEI\r\n", + $content + ); + } + $content = trim(preg_replace(['/(\r\n){2,}/', '/\r\n +/'], "\r\n", $content)); return $content; diff --git a/tests/PHPUnit/Integration/PDFObjectTest.php b/tests/PHPUnit/Integration/PDFObjectTest.php index 39079a2c..a2ee699f 100644 --- a/tests/PHPUnit/Integration/PDFObjectTest.php +++ b/tests/PHPUnit/Integration/PDFObjectTest.php @@ -284,12 +284,22 @@ public function testFormatContent(): void // Binary check is done before a regexp that causes an error $this->assertStringContainsString('Marko Nestorović PR', $pages[0]->getText()); + } + + /** + * Check that inline image data does not corrupt the stream + * + * @see: https://github.com/smalot/pdfparser/issues/691 + */ + public function testFormatContentInlineImages(): void + { + $formatContent = new \ReflectionMethod('Smalot\PdfParser\PDFObject', 'formatContent'); + $formatContent->setAccessible(true); - // Check that inline image data does not corrupt the stream - // See: https://github.com/smalot/pdfparser/issues/691 $cleaned = $formatContent->invoke( $this->getPdfObjectInstance(new Document()), - 'q 65.30 0 0 18.00 412 707 cm BI /W 544 /H 150 /BPC 1 /IM true /F [/A85 /Fl] ID Gb"0F_$L6!$j/a\$:ma&h\'JnJJ9S?O_EA-W+%D^ClCH=FP3s5M-gStQm\'5/hc`C?CqL(^pV$_-er6Ik`"-1]Q ;~> EI Q /F002 10.00 Tf 0.00 Tw 0 g' + 'q 65.30 0 0 18.00 412 707 cm BI /W 544 /H 150 +/BPC 1 /IM true /F [/A85 /Fl] ID Gb"0F_$L6!$j/a\$:ma&h\'JnJJ9S?O_EA-W+%D^ClCH=FP3s5M-gStQm\'5/hc`C?CqL(^pV$_-er6Ik`"-1]Q ;~> EI Q /F002 10.00 Tf 0.00 Tw 0 g' ); // PdfParser should not be fooled by Q's in inline image data; From 8d005080cc21dc1e476260f31b6e85681a307379 Mon Sep 17 00:00:00 2001 From: Brian Huisman Date: Mon, 25 Mar 2024 16:10:21 -0400 Subject: [PATCH 4/6] More robust check for BI within strings `BI` "commands" within strings should not be parsed as the beginning of inline image blocks. Detect if the `BI` we found is inside a (string) and if it is, note the offset and move past it for the next match. --- src/Smalot/PdfParser/PDFObject.php | 59 +++++++++++++++++---- tests/PHPUnit/Integration/PDFObjectTest.php | 18 ++++++- 2 files changed, 65 insertions(+), 12 deletions(-) diff --git a/src/Smalot/PdfParser/PDFObject.php b/src/Smalot/PdfParser/PDFObject.php index 20e92334..ab3b66e8 100644 --- a/src/Smalot/PdfParser/PDFObject.php +++ b/src/Smalot/PdfParser/PDFObject.php @@ -227,15 +227,54 @@ private function formatContent(?string $content): string // Find all inline image content and replace them so they aren't // affected by the next steps $pdfInlineImages = []; - while (preg_match('/\sBI\s(.+?)\sID\s(.+?)\sEI(?=\s|$)/s', $content, $text)) { - $id = uniqid('IMAGE_', true); - $pdfInlineImages[$id] = [$text[1], $text[2]]; - $content = preg_replace( - '/'.preg_quote($text[0], '/').'/', - '^^^'.$id.'^^^', - $content, - 1 - ); + $offsetBI = 0; + while (preg_match('/\sBI\s(\/.+?)\sID\s(.+?)\sEI(?=\s|$)/s', $content, $text, \PREG_OFFSET_CAPTURE, $offsetBI)) { + // Attempt to detemine if this instance of the 'BI' command + // actually occured within a (string) using the following + // steps: + + // Remove any escaped parentheses from the alleged image + // characteristics data + $para = str_replace(['\\(', '\\)'], '', $text[1][0]); + + // Remove all correctly ordered and balanced parentheses + // from (strings) + do { + $paraTest = $para; + $para = preg_replace('/\(([^)]*)\)/', '$1', $paraTest); + } while ($para != $paraTest); + + $paraOpen = strpos($para, '('); + $paraClose = strpos($para, ')'); + + // If the remaining text contains a close parenthesis ')' + // AND it occurs before any open parenthesis, then we are + // almost certain to be inside a (string) + if (0 < $paraClose && (false === $paraOpen || $paraClose < $paraOpen)) { + // Bump the search offset forward and match again + $offsetBI = (int) $text[1][1]; + continue; + } + + // Double check that this is actually inline image data by + // parsing the alleged image characteristics as a dictionary + $dict = $this->parseDictionary('<<'.$text[1][0].'>>'); + + // Check if an image Width and Height are set in the dict + if ((isset($dict['W']) || isset($dict['Width'])) + && (isset($dict['H']) || isset($dict['Height']))) { + $id = uniqid('IMAGE_', true); + $pdfInlineImages[$id] = [ + preg_replace(['/\r\n/', '/\r/', '/\n/'], ' ', $text[1][0]), + preg_replace(['/\r\n/', '/\r/', '/\n/'], '', $text[2][0]), + ]; + $content = preg_replace( + '/'.preg_quote($text[0][0], '/').'/', + '^^^'.$id.'^^^', + $content, + 1 + ); + } } // Find all strings () and replace them so they aren't affected @@ -338,7 +377,7 @@ private function formatContent(?string $content): string foreach ($pdfInlineImages as $id => $image) { $content = str_replace( '^^^'.$id.'^^^', - "\r\nBI\r\n".$image[0]."\r\nID\r\n".$image[1]."\r\nEI\r\n", + "\r\nBI\r\n".$image[0]." ID\r\n".$image[1]." EI\r\n", $content ); } diff --git a/tests/PHPUnit/Integration/PDFObjectTest.php b/tests/PHPUnit/Integration/PDFObjectTest.php index a2ee699f..947a6944 100644 --- a/tests/PHPUnit/Integration/PDFObjectTest.php +++ b/tests/PHPUnit/Integration/PDFObjectTest.php @@ -298,15 +298,29 @@ public function testFormatContentInlineImages(): void $cleaned = $formatContent->invoke( $this->getPdfObjectInstance(new Document()), - 'q 65.30 0 0 18.00 412 707 cm BI /W 544 /H 150 + 'BT (This BI /W 258 /H 51 /should not trigger /as a /PDF command) TD ET q 65.30 0 0 18.00 412 707 cm BI /W 544 /H 150 /BPC 1 /IM true /F [/A85 /Fl] ID Gb"0F_$L6!$j/a\$:ma&h\'JnJJ9S?O_EA-W+%D^ClCH=FP3s5M-gStQm\'5/hc`C?CqL(^pV$_-er6Ik`"-1]Q ;~> EI Q /F002 10.00 Tf 0.00 Tw 0 g' ); // PdfParser should not be fooled by Q's in inline image data; // Only one 'Q' command should be found $commandQ = preg_match_all('/Q\r\n/', $cleaned); - $this->assertEquals(1, $commandQ); + + // The 'BI' inside a string should not be interpreted as the + // beginning of an inline image command + $this->assertStringContainsString('(This BI /W 258 /H 51 /should not trigger /as a /PDF command) TD', $cleaned); + + $cleaned = $formatContent->invoke( + $this->getPdfObjectInstance(new Document()), + 'BT (This BI /W 258 /H 51 /should not () \) trigger /as a /PDF command) TD (There is no ID inline image in this data) TD (Nothing but text EI should be found) TD ET' + ); + + $this->assertEquals('BT'."\r\n". +'(This BI /W 258 /H 51 /should not () \) trigger /as a /PDF command) TD'."\r\n". +'(There is no ID inline image in this data) TD'."\r\n". +'(Nothing but text EI should be found) TD'."\r\n". +'ET', $cleaned); } public function testGetSectionsText(): void From 5322e77a05a073745b9c548f0af8c3314002a42a Mon Sep 17 00:00:00 2001 From: Brian Huisman Date: Mon, 29 Apr 2024 13:23:36 -0400 Subject: [PATCH 5/6] Bump search offset if no Height or Width found In the case where a valid inline image dictionary isn't found, or if the dictionary doesn't include the required parameters Height and Width, also bump the search offset forward by the current match position so we don't fall into a loop here. --- src/Smalot/PdfParser/PDFObject.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Smalot/PdfParser/PDFObject.php b/src/Smalot/PdfParser/PDFObject.php index d2ded2d7..d17a2f76 100644 --- a/src/Smalot/PdfParser/PDFObject.php +++ b/src/Smalot/PdfParser/PDFObject.php @@ -274,6 +274,12 @@ private function formatContent(?string $content): string $content, 1 ); + } else { + // If there was no valid dictionary, or a height and width + // weren't specified, then we don't know what this is, so + // just leave it alone; bump the search offset forward and + // match again + $offsetBI = (int) $text[1][1]; } } From a827236c63f161e60405d51465a1038997c8ea77 Mon Sep 17 00:00:00 2001 From: Brian Huisman Date: Fri, 10 May 2024 10:59:40 -0400 Subject: [PATCH 6/6] Add "Step X:" to comments in formatContent() Add "Step X:" to the comments to better define what the inline image replacement code is doing. Small adjustment to the balanced parentheses regexp to also exclude open parenthesis '(' from the matching. This will ensure replacing balanced parentheses from the innermost to the outermost. --- src/Smalot/PdfParser/PDFObject.php | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/Smalot/PdfParser/PDFObject.php b/src/Smalot/PdfParser/PDFObject.php index d17a2f76..d1b8846f 100644 --- a/src/Smalot/PdfParser/PDFObject.php +++ b/src/Smalot/PdfParser/PDFObject.php @@ -233,31 +233,32 @@ private function formatContent(?string $content): string // actually occured within a (string) using the following // steps: - // Remove any escaped parentheses from the alleged image - // characteristics data + // Step 1: Remove any escaped parentheses from the alleged + // image characteristics data $para = str_replace(['\\(', '\\)'], '', $text[1][0]); - // Remove all correctly ordered and balanced parentheses - // from (strings) + // Step 2: Remove all correctly ordered and balanced + // parentheses from (strings) do { $paraTest = $para; - $para = preg_replace('/\(([^)]*)\)/', '$1', $paraTest); + $para = preg_replace('/\(([^()]*)\)/', '$1', $paraTest); } while ($para != $paraTest); $paraOpen = strpos($para, '('); $paraClose = strpos($para, ')'); - // If the remaining text contains a close parenthesis ')' - // AND it occurs before any open parenthesis, then we are - // almost certain to be inside a (string) + // Check: If the remaining text contains a close parenthesis + // ')' AND it occurs before any open parenthesis, then we + // are almost certain to be inside a (string) if (0 < $paraClose && (false === $paraOpen || $paraClose < $paraOpen)) { // Bump the search offset forward and match again $offsetBI = (int) $text[1][1]; continue; } - // Double check that this is actually inline image data by - // parsing the alleged image characteristics as a dictionary + // Step 3: Double check that this is actually inline image + // data by parsing the alleged image characteristics as a + // dictionary $dict = $this->parseDictionary('<<'.$text[1][0].'>>'); // Check if an image Width and Height are set in the dict