PdftotextExtractor.php in Search API attachments 9.0.x
File
src/Plugin/search_api_attachments/PdftotextExtractor.php
View source
<?php
namespace Drupal\search_api_attachments\Plugin\search_api_attachments;
use Drupal\Core\Form\FormStateInterface;
use Drupal\search_api_attachments\TextExtractorPluginBase;
use Drupal\file\Entity\File;
class PdftotextExtractor extends TextExtractorPluginBase {
public function extract(File $file) {
if (in_array($file
->getMimeType(), $this
->getPdfMimeTypes())) {
$output = '';
$pdftotext_path = $this->configuration['pdftotext_path'];
$filepath = $this
->getRealpath($file
->getFileUri());
$backup_locale = setlocale(LC_CTYPE, '0');
setlocale(LC_CTYPE, 'en_US.UTF-8');
$cmd = escapeshellcmd($pdftotext_path) . ' ' . escapeshellarg($filepath) . ' -';
setlocale(LC_CTYPE, $backup_locale);
shell_exec("LANG=en_US.utf-8");
$output = shell_exec($cmd);
if (is_null($output)) {
throw new \Exception('Pdftotext Exctractor is not available.');
}
return $output;
}
else {
return NULL;
}
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['pdftotext_path'] = [
'#type' => 'textfield',
'#title' => $this
->t('Pdftotext binary'),
'#description' => $this
->t('Enter the name of pdftotext executable or the full path to the pdftotext binary. Example: "pdftotext" or "/usr/bin/pdftotext".'),
'#default_value' => $this->configuration['pdftotext_path'],
'#required' => TRUE,
];
return $form;
}
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
$values = $form_state
->getValue([
'text_extractor_config',
]);
$pdftotext_path = $values['pdftotext_path'];
$is_name = strpos($pdftotext_path, '/') === FALSE && strpos($pdftotext_path, '\\') === FALSE;
if (!$is_name && !file_exists($pdftotext_path)) {
$form_state
->setError($form['text_extractor_config']['pdftotext_path'], $this
->t('The file %path does not exist.', [
'%path' => $pdftotext_path,
]));
}
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['pdftotext_path'] = $form_state
->getValue([
'text_extractor_config',
'pdftotext_path',
]);
parent::submitConfigurationForm($form, $form_state);
}
}