add getInfo(), getAdditionalParams() and handle output to stdout

This commit is contained in:
Uwe Steinmann 2021-10-08 12:12:00 +02:00
parent 1813ac32a0
commit 306555cd45

View File

@ -98,28 +98,83 @@ class SeedDMS_ConversionServiceExec extends SeedDMS_ConversionServiceBase {
$this->timeout = 5;
}
public function getInfo() {
return "Convert with command '".$this->cmd."'";
}
public function getAdditionalParams() { /* {{{ */
/* output format is an image and the command has a placeholder for the
* width of the converted image, then allow to set the width.
*/
if(substr($this->to, 0, 6) == 'image/' && strpos($this->cmd, '%w') !== false)
return [
['name'=>'width', 'type'=>'number', 'description'=>'Width of converted image'],
];
return [];
} /* }}} */
/**
* Convert by running an external command
*
* The command was set when calling the constructor. The command may
* either write a file or to stdout, depending on the placeholder '%o'
* either exists or not in the command. If $target is null, but the
* command writes to a file, it will create a temporary file, write
* ot it and read the content back to be returned by the method.
*/
public function convert($infile, $target = null, $params = array()) {
/* if no %f placeholder is found, we assume output to stdout */
$tostdout = strpos($this->cmd, '%o') === false;
$start = microtime(true);
if(!$target)
if(!$target && !$tostdout)
$tmpfile = tempnam(sys_get_temp_dir(), 'convert');
else
$tmpfile = $target;
$cmd = str_replace(array('%w', '%f', '%o', '%m'), array(isset($params['width']) ? $params['width'] : '', $infile, $tmpfile, $this->from), $this->cmd);
$format = '';
switch($this->to) {
case 'image/gif':
$format = 'gif';
break;
case 'image/jpg':
case 'image/jpeg':
$format = 'jpg';
break;
case 'image/png':
$format = 'png';
break;
}
/* %s was just added because the commands to convert to text/plain used
* it instead of %f for the input file
* %f = input file
* %o = output file
* %m = mime type
* %w = width
*/
$cmd = str_replace(array('%w', '%f', '%s', '%if', '%o', '%m'), array(isset($params['width']) ? $params['width'] : '150', $infile, $infile, $format, $tmpfile, $this->from), $this->cmd);
try {
self::execWithTimeout($cmd, $this->timeout);
$ret = self::execWithTimeout($cmd, $this->timeout);
} catch(Exception $e) {
return false;
}
$end = microtime(true);
if($this->logger) {
$this->logger->log('Conversion from '.$this->from.' to '.$this->to.' with cmd "'.$this->cmd.'" took '.($end-$start).' sec.', PEAR_LOG_INFO);
$this->logger->log('Conversion from '.$this->from.' to '.$this->to.' with cmd "'.$this->cmd.'" took '.($end-$start).' sec.', PEAR_LOG_DEBUG);
}
if(!$target) {
$content = file_get_contents($tmpfile);
unlink($tmpfile);
return $content;
if($tostdout) {
if(!$target) {
return $ret['stdout'];
} else {
return file_put_contents($tmpfile, $ret['stdout']);
}
} else {
return true;
if(!$target) {
$content = file_get_contents($tmpfile);
unlink($tmpfile);
return $content;
} else {
return true;
}
}
}
}