1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ottosmops\Pdfvalidate; |
4
|
|
|
|
5
|
|
|
use Ottosmops\Pdfvalidate\Exceptions\BinaryNotFound; |
6
|
|
|
use Ottosmops\Pdfvalidate\Exceptions\FileNotFound; |
7
|
|
|
use Ottosmops\Pdfvalidate\Exceptions\MimeTypeIsNotPdf; |
8
|
|
|
use Symfony\Component\Process\Process; |
9
|
|
|
|
10
|
|
|
class Validator |
11
|
|
|
{ |
12
|
|
|
|
13
|
|
|
public $file; |
14
|
|
|
|
15
|
|
|
public $error = ''; |
16
|
|
|
|
17
|
|
|
public $process = ''; |
18
|
|
|
|
19
|
|
|
public $output; |
20
|
|
|
|
21
|
|
|
public $executable; |
22
|
|
|
|
23
|
|
|
public $timeout; |
24
|
|
|
|
25
|
8 |
|
public function __construct($file, $executable = '', $timeout = 60) |
26
|
|
|
{ |
27
|
8 |
|
$this->executable = $executable ? $executable : 'pdftocairo'; |
28
|
8 |
|
$this->checkExecutable(); |
29
|
7 |
|
if (!is_file($file)) { |
30
|
1 |
|
throw new FileNotFound($file); |
31
|
|
|
} |
32
|
6 |
|
if (!self::is_pdf($file)) { |
33
|
1 |
|
throw new MimeTypeIsNotPdf($file); |
34
|
|
|
} |
35
|
5 |
|
$this->file = $file; |
36
|
5 |
|
$this->timeout = $timeout; |
37
|
5 |
|
} |
38
|
|
|
|
39
|
1 |
|
public static function validate($file, $executable = '', $timeout = 60) |
40
|
|
|
{ |
41
|
1 |
|
return (new static($file, $executable, $timeout)); |
42
|
|
|
} |
43
|
|
|
|
44
|
8 |
|
public function checkExecutable() |
45
|
|
|
{ |
46
|
8 |
|
$process = Process::fromShellCommandline('which ' . $this->executable); |
47
|
8 |
|
$process->run(); |
48
|
8 |
|
if (!$process->isSuccessful()) { |
49
|
1 |
|
throw new BinaryNotFound($process); |
50
|
|
|
} |
51
|
7 |
|
return true; |
52
|
|
|
} |
53
|
|
|
|
54
|
6 |
|
public static function is_pdf($file) |
55
|
|
|
{ |
56
|
6 |
|
$finfo = finfo_open(FILEINFO_MIME_TYPE); |
57
|
6 |
|
return finfo_file($finfo, $file) == 'application/pdf'; |
58
|
|
|
} |
59
|
|
|
|
60
|
5 |
|
public function check() |
61
|
|
|
{ |
62
|
5 |
|
$command = $this->executable . ' -pdf "' . $this->file . '" - 2>&1 >/dev/null'; |
63
|
|
|
|
64
|
5 |
|
$process = Process::fromShellCommandline($command); |
65
|
5 |
|
$process->setTimeout($this->timeout); |
66
|
5 |
|
$process->run(); |
67
|
|
|
|
68
|
5 |
|
$output = $process->getOutput(); |
69
|
|
|
|
70
|
5 |
|
if (!$output) { |
71
|
3 |
|
return true; |
72
|
|
|
}; |
73
|
|
|
|
74
|
2 |
|
$this->error = $output; |
75
|
|
|
|
76
|
2 |
|
if (mb_strpos($output, 'Error') !== false) { |
77
|
2 |
|
$this->error = "Could open the PDF, but the PDF seems to be corrupted."; |
78
|
|
|
} |
79
|
|
|
|
80
|
2 |
|
if (mb_strpos($output, 'Error opening') !== false) { |
81
|
1 |
|
$this->error = "Could not open the PDF."; |
82
|
|
|
} |
83
|
|
|
|
84
|
2 |
|
return false; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|