1<?php 2 3use dokuwiki\plugin\totext\Extractor\ExtractionResult; 4use dokuwiki\plugin\totext\Extractor\ExtractorFactory; 5 6/** 7 * DokuWiki Plugin totext (Helper Component) 8 * 9 * Gives other plugins a simple API to extract plain text and metadata from 10 * documents. 11 * 12 * @license GPL-2.0-only 13 * @author Andreas Gohr <gohr@cosmocode.de> 14 */ 15class helper_plugin_totext extends \dokuwiki\Extension\Plugin 16{ 17 /** 18 * Extract body text and metadata from the given file. 19 * 20 * @param string $path absolute path to the file 21 * @return ExtractionResult the extracted body text and canonical metadata 22 * @throws \dokuwiki\plugin\totext\Exception\ExtractionException on failure 23 * @throws \dokuwiki\plugin\totext\Exception\UnsupportedFormatException on unsupported format 24 */ 25 public function extract($path) 26 { 27 return ExtractorFactory::extract($path); 28 } 29 30 /** 31 * Extract plain text from the given file. 32 * 33 * Unlike extract(), this throws when text extraction itself failed (even if 34 * metadata was salvaged), so callers that want only the text — e.g. the 35 * docsearch plugin, which falls back to its own converters on failure — keep 36 * their throw-on-failure contract. 37 * 38 * @param string $path absolute path to the file 39 * @return string the extracted plain text 40 * @throws \dokuwiki\plugin\totext\Exception\ExtractionException on failure 41 * @throws \dokuwiki\plugin\totext\Exception\UnsupportedFormatException on unsupported format 42 */ 43 public function extractText($path) 44 { 45 $result = $this->extract($path); 46 if ($result->textError !== null) { 47 throw $result->textError; 48 } 49 return $result->text; 50 } 51 52 /** 53 * Extract the canonical metadata map from the given file. 54 * 55 * Throws when metadata extraction itself failed (even if the body text was 56 * extracted), mirroring extractText(). 57 * 58 * @param string $path absolute path to the file 59 * @return array<string, string> canonical key => value map 60 * @throws \dokuwiki\plugin\totext\Exception\ExtractionException on failure 61 * @throws \dokuwiki\plugin\totext\Exception\UnsupportedFormatException on unsupported format 62 */ 63 public function extractMetadata($path) 64 { 65 $result = $this->extract($path); 66 if ($result->metadataError !== null) { 67 throw $result->metadataError; 68 } 69 return $result->metadata; 70 } 71 72 /** 73 * List the file extensions this plugin can handle. 74 * 75 * @return string[] supported extensions (without leading dot) 76 */ 77 public function supportedExtensions() 78 { 79 return ExtractorFactory::supportedExtensions(); 80 } 81 82 /** 83 * Whether the given file is supported, based on its extension. 84 * 85 * @param string $path file name or path 86 * @return bool 87 */ 88 public function isSupported($path) 89 { 90 return in_array( 91 strtolower(pathinfo($path, PATHINFO_EXTENSION)), 92 $this->supportedExtensions(), 93 true 94 ); 95 } 96} 97