Debian Codegraph @

extensions/VisualEditor/includes/ApiParsoidTrait.php

raw symbols SCIP
1 <?php
2 /**
3 * Helper functions for contacting Parsoid/RESTBase from the action API.
4 *
5 * @file
6 * @ingroup Extensions
7 * @copyright 2011-2020 VisualEditor Team and others; see AUTHORS.txt
8 * @license MIT
9 */
10
11 namespace MediaWiki\Extension\VisualEditor;
12
13 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
14 use MediaWiki\Api\ApiUsageException;
15 use MediaWiki\Language\Language;
16 use MediaWiki\MediaWikiServices;
17 use MediaWiki\Message\Message;
18 use MediaWiki\Request\WebRequest;
19 use MediaWiki\Rest\HttpException;
20 use MediaWiki\Rest\LocalizedHttpException;
21 use MediaWiki\Revision\RevisionRecord;
22 use MediaWiki\Title\Title;
23 use Psr\Log\LoggerInterface;
24 use Psr\Log\NullLogger;
25 use Throwable;
26 use Wikimedia\Stats\NullStatsdDataFactory;
27 use Wikimedia\Stats\PrefixingStatsdDataFactoryProxy;
28
29 trait ApiParsoidTrait {
30
31 private ?LoggerInterface $logger = null;
32 private ?StatsdDataFactoryInterface $stats = null;
33
34 protected function getLogger(): LoggerInterface {
35 return $this->logger ?: new NullLogger();
36 }
37
38 protected function setLogger( LoggerInterface $logger ): void {
39 $this->logger = $logger;
40 }
41
42 protected function getStats(): StatsdDataFactoryInterface {
43 return $this->stats ?: new NullStatsdDataFactory();
44 }
45
46 protected function setStats( StatsdDataFactoryInterface $stats ): void {
47 $this->stats = new PrefixingStatsdDataFactoryProxy( $stats, 'VE' );
48 }
49
50 /**
51 * @return float Return a start time for use with statsRecordTiming()
52 */
53 private function statsGetStartTime(): float {
54 return microtime( true );
55 }
56
57 /**
58 * @param string $key
59 * @param float $startTime from statsGetStartTime()
60 */
61 private function statsRecordTiming( string $key, float $startTime ): void {
62 $duration = ( microtime( true ) - $startTime ) * 1000;
63 $this->getStats()->timing( $key, $duration );
64 }
65
66 /**
67 * @return never
68 * @throws ApiUsageException
69 */
70 private function dieWithRestHttpException( HttpException $ex ): void {
71 if ( $ex instanceof LocalizedHttpException ) {
72 $converter = new \MediaWiki\Message\Converter();
73 $msg = $converter->convertMessageValue( $ex->getMessageValue() );
74 $this->dieWithError( $msg, null, $ex->getErrorData() );
75 } else {
76 $this->dieWithException( $ex, [ 'data' => $ex->getErrorData() ] );
77 }
78 }
79
80 /**
81 * Request page HTML from Parsoid.
82 *
83 * @param RevisionRecord $revision Page revision
84 * @return array An array mimicking a RESTbase server's response, with keys: 'headers' and 'body'
85 * @phan-return array{body:string,headers:array<string,string>}
86 * @throws ApiUsageException
87 */
88 protected function requestRestbasePageHtml( RevisionRecord $revision ): array {
89 $title = Title::newFromLinkTarget( $revision->getPageAsLinkTarget() );
90 $lang = self::getPageLanguage( $title );
91
92 $startTime = $this->statsGetStartTime();
93 try {
94 $response = $this->getParsoidClient()->getPageHtml( $revision, $lang );
95 } catch ( HttpException $ex ) {
96 $this->dieWithRestHttpException( $ex );
97 }
98 $this->statsRecordTiming( 'ApiVisualEditor.ParsoidClient.getPageHtml', $startTime );
99
100 return $response;
101 }
102
103 /**
104 * Transform HTML to wikitext with Parsoid.
105 *
106 * @param Title $title The title of the page
107 * @param string $html The HTML of the page to be transformed
108 * @param int|null $oldid What oldid revision, if any, to base the request from (default: `null`)
109 * @param string|null $etag The ETag to set in the HTTP request header
110 * @return array An array mimicking a RESTbase server's response, with keys: 'headers' and 'body'
111 * @phan-return array{body:string,headers:array<string,string>}
112 * @throws ApiUsageException
113 */
114 protected function transformHTML(
115 Title $title, string $html, ?int $oldid = null, ?string $etag = null
116 ): array {
117 $lang = self::getPageLanguage( $title );
118
119 $startTime = $this->statsGetStartTime();
120 try {
121 $response = $this->getParsoidClient()->transformHTML( $title, $lang, $html, $oldid, $etag );
122 } catch ( HttpException $ex ) {
123 $this->dieWithRestHttpException( $ex );
124 }
125 $this->statsRecordTiming( 'ApiVisualEditor.ParsoidClient.transformHTML', $startTime );
126
127 return $response;
128 }
129
130 /**
131 * Transform wikitext to HTML with Parsoid.
132 *
133 * @param Title $title The title of the page to use as the parsing context
134 * @param string $wikitext The wikitext fragment to parse
135 * @param bool $bodyOnly Whether to provide only the contents of the `<body>` tag
136 * @param int|null $oldid What oldid revision, if any, to base the request from (default: `null`)
137 * @param bool $stash Whether to stash the result in the server-side cache (default: `false`)
138 * @return array An array mimicking a RESTbase server's response, with keys: 'headers' and 'body'
139 * @phan-return array{body:string,headers:array<string,string>}
140 * @throws ApiUsageException
141 */
142 protected function transformWikitext(
143 Title $title, string $wikitext, bool $bodyOnly, ?int $oldid = null, bool $stash = false
144 ): array {
145 $lang = self::getPageLanguage( $title );
146
147 $startTime = $this->statsGetStartTime();
148 try {
149 $response = $this->getParsoidClient()->transformWikitext(
150 $title,
151 $lang,
152 $wikitext,
153 $bodyOnly,
154 $oldid,
155 $stash
156 );
157 } catch ( HttpException $ex ) {
158 $this->dieWithRestHttpException( $ex );
159 }
160 $this->statsRecordTiming( 'ApiVisualEditor.ParsoidClient.transformWikitext', $startTime );
161
162 return $response;
163 }
164
165 /**
166 * Get the page language from a title, using the content language as fallback on special pages
167 *
168 * @param Title $title
169 * @return Language Content language
170 */
171 public static function getPageLanguage( Title $title ): Language {
172 if ( $title->isSpecial( 'CollabPad' ) ) {
173 // Use the site language for CollabPad, as getPageLanguage just
174 // returns the interface language for special pages.
175 // TODO: Let the user change the document language on multi-lingual sites.
176 return MediaWikiServices::getInstance()->getContentLanguage();
177 } else {
178 return $title->getPageLanguage();
179 }
180 }
181
182 /**
183 * @see VisualEditorParsoidClientFactory
184 */
185 abstract protected function getParsoidClient(): ParsoidClient;
186
187 /**
188 * @see ApiBase
189 * @param string|array|Message $msg See ApiErrorFormatter::addError()
190 * @param string|null $code See ApiErrorFormatter::addError()
191 * @param array|null $data See ApiErrorFormatter::addError()
192 * @param int|null $httpCode HTTP error code to use
193 * @return never
194 * @throws ApiUsageException
195 */
196 abstract public function dieWithError( $msg, $code = null, $data = null, $httpCode = null );
197
198 /**
199 * @see ApiBase
200 * @param Throwable $exception See ApiErrorFormatter::getMessageFromException()
201 * @param array $options See ApiErrorFormatter::getMessageFromException()
202 * @return never
203 */
204 abstract public function dieWithException( Throwable $exception, array $options = [] );
205
206 /**
207 * @see ContextSource
208 * @return WebRequest
209 */
210 abstract public function getRequest();
211 }