c6acd661f22d3761eda2602a6f96db0b9fdf728a
[lhc/web/wiklou.git] / includes / tidy / Html5Depurate.php
1 <?php
2
3 namespace MediaWiki\Tidy;
4
5 use MWHttpRequest;
6 use Exception;
7
8 class Html5Depurate extends TidyDriverBase {
9 public function __construct( array $config ) {
10 parent::__construct( $config + [
11 'url' => 'http://localhost:4339/document',
12 'timeout' => 10,
13 'connectTimeout' => 0.5,
14 ] );
15 }
16
17 public function tidy( $text ) {
18 $wrappedtext = '<!DOCTYPE html><html>' .
19 '<body>' . $text . '</body></html>';
20
21 $req = MWHttpRequest::factory( $this->config['url'],
22 [
23 'method' => 'POST',
24 'timeout' => $this->config['timeout'],
25 'connectTimeout' => $this->config['connectTimeout'],
26 'postData' => [
27 'text' => $wrappedtext
28 ]
29 ] );
30 $status = $req->execute();
31 if ( !$status->isOK() ) {
32 throw new Exception( "Error contacting depurate service: "
33 . $status->getWikiText( false, false, 'en' ) );
34 } elseif ( $req->getStatus() !== 200 ) {
35 throw new Exception( "Depurate returned error: " . $status->getWikiText( false, false, 'en' ) );
36 }
37 $result = $req->getContent();
38 $startBody = strpos( $result, "<body>" );
39 $endBody = strrpos( $result, "</body>" );
40 if ( $startBody !== false && $endBody !== false && $endBody > $startBody ) {
41 $startBody += strlen( "<body>" );
42 return substr( $result, $startBody, $endBody - $startBody );
43 } else {
44 return $text . "\n<!-- Html5Depurate returned an invalid result -->";
45 }
46 }
47 }