|
| 1 | +<?php |
| 2 | + |
| 3 | +class ExecFilter extends StoreFilter implements SocketEvent |
| 4 | +{ |
| 5 | + |
| 6 | + /** @var bool delete file after process exits? */ |
| 7 | + private $delete; |
| 8 | + /** @var string[] command to execute */ |
| 9 | + private $cmd; |
| 10 | + |
| 11 | + public function __construct($action, \MailData $data) |
| 12 | + { |
| 13 | + $this->delete = $action['delete'] ?? true; |
| 14 | + $this->cmd = $action['cmd'] ?? false; |
| 15 | + if ($this->cmd === false) |
| 16 | + return; |
| 17 | + if (strpos(implode(' ', $action['cmd']), '%TEMPFILE%') !== false) { |
| 18 | + $this->filePath = tempnam('/tmp', 'm2f-'); |
| 19 | + if ($this->filePath !== false) { |
| 20 | + $this->fh = fopen($this->filePath, 'wb'); |
| 21 | + } |
| 22 | + foreach ($this->cmd as &$item) { |
| 23 | + $item = str_replace('%TEMPFILE%', $this->filePath, $item); |
| 24 | + } |
| 25 | + } |
| 26 | + $rep = ['%DATE%' => date('Y-m-d')]; |
| 27 | + foreach (get_object_vars($data) as $k => $v) { |
| 28 | + $rep['%' . strtoupper($k) . '%'] = $v; |
| 29 | + } |
| 30 | + foreach ($this->cmd as &$item) { |
| 31 | + $item = str_replace(array_keys($rep), array_values($rep), $item); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + public function finished() |
| 36 | + { |
| 37 | + parent::finished(); |
| 38 | + if ($this->cmd !== false) { |
| 39 | + new Process($this, $this->cmd); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + public function connected(\AbstractSocket $sock) { } |
| 44 | + |
| 45 | + public function dataArrival(\AbstractSocket $sock, string $data) |
| 46 | + { |
| 47 | + Log::info("EXEC({$this->tag()}): " . substr(str_replace(["\r", "\n"], ' ', $data), 0, 60)); |
| 48 | + } |
| 49 | + |
| 50 | + public function incomingConnection(\Socket $sock, \Socket $new) { } |
| 51 | + |
| 52 | + public function sendProgress(\AbstractSocket $sock, int $sent, int $remaining) { } |
| 53 | + |
| 54 | + public function socketClosed(\AbstractSocket $sock) |
| 55 | + { |
| 56 | + Log::info("ExecFilter process finished successfully"); |
| 57 | + if ($this->delete && !empty($this->filePath)) { |
| 58 | + unlink($this->filePath); |
| 59 | + $this->filePath = false; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + public function socketError(\AbstractSocket $sock, $error) |
| 64 | + { |
| 65 | + Log::info("ExecFilter process exited with error $error"); |
| 66 | + if ($this->delete && !empty($this->filePath)) { |
| 67 | + unlink($this->filePath); |
| 68 | + $this->filePath = false; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments