From e89ec2d9a4f7fede34a75c5fdc4b1bb8d3f8c628 Mon Sep 17 00:00:00 2001
From: lkmorlan <lkmorlan@493050.no-reply.drupal.org>
Date: Fri, 9 Aug 2019 15:32:11 -0400
Subject: [PATCH] Issue #3036845 by Liam Morland: Log pdftk errors using
 proc_open()

---
 fillpdf.module | 42 ++++++++++++++++++++++++++++++------------
 1 file changed, 30 insertions(+), 12 deletions(-)

diff --git a/fillpdf.module b/fillpdf.module
index 2a52ae4..aed28bf 100644
--- a/fillpdf.module
+++ b/fillpdf.module
@@ -1561,21 +1561,39 @@ function fillpdf_execute_merge($method, array $fields, $fillpdf, $mode = 'url',
         $pdftk_command[] = 'flatten';
       }
       $pdftk_command[] = 'drop_xfa';
-      ob_start();
-      passthru(implode(' ', $pdftk_command));
-      $data = ob_get_clean();
+      $pdftk_command = implode(' ', $pdftk_command);
 
-      $error = NULL;
-      if ($data === FALSE) {
-        $error = t('pdftk not properly installed. No PDF generated.');
-      }
-      elseif (!$data) {
-        $error = t('Error with pdftk. No PDF generated.');
+      // Run the pdftk command and read stdout, stderr, and exit status.
+      $descriptorspec = array(
+        1 => array('pipe', 'w'),
+        2 => array('pipe', 'w'),
+      );
+      $proc = proc_open($pdftk_command, $descriptorspec, $pipes);
+      // Read stdout.
+      $data = stream_get_contents($pipes[1]);
+      fclose($pipes[1]);
+      // Read stderr.
+      $stderr = stream_get_contents($pipes[2]);
+      fclose($pipes[2]);
+      // Read exit status.
+      $exit_status = proc_close($proc);
+
+      // Public error message if no data returned by pdftk.
+      if (!$data) {
+        drupal_set_message(t('Error with pdftk. No PDF generated.'), 'error');
       }
-      if ($error) {
-        drupal_set_message($error, 'error');
-        watchdog('fillpdf', $error, array(), WATCHDOG_ERROR);
+
+      // Log errors when no PDF or non-zero exit status.
+      if (!$data || $exit_status !== 0) {
+        $message = 'Error with pdftk: Exit status: !exit_status; data length: !data_length; stderr: @stderr';
+        $variables = array(
+          '!exit_status' => $exit_status,
+          '!data_length' => strlen($data),
+          '@stderr' => $stderr,
+        );
+        watchdog('fillpdf', $message, $variables, WATCHDOG_ERROR);
       }
+
       file_unmanaged_delete($xfdffile);
       break;
 
-- 
GitLab