00f68147bfb4dadb3f6bcf9990b870716c500925
[lhc/web/wiklou.git] / includes / api / ApiStashEdit.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Aaron Schulz
20 */
21
22 /**
23 * Prepare and edit in shared cache so that it can be reused on edit
24 *
25 * This endpoint can be called via AJAX as the user focuses on the edit
26 * summary box. By the time of submission, the parse may have already
27 * finished, and can be immediately used on page save. Certain parser
28 * functions like {{REVISIONID}} or {{CURRENTTIME}} may cause the cache
29 * to not be used on edit. Template and files used are check for changes
30 * since the output was generated. The cache TTL is also kept low for sanity.
31 *
32 * @ingroup API
33 * @since 1.25
34 */
35 class ApiStashEdit extends ApiBase {
36 public function execute() {
37 global $wgMemc;
38
39 $user = $this->getUser();
40 $params = $this->extractRequestParams();
41
42 $page = $this->getTitleOrPageId( $params );
43 $title = $page->getTitle();
44
45 if ( !ContentHandler::getForModelID( $params['contentmodel'] )
46 ->isSupportedFormat( $params['contentformat'] )
47 ) {
48 $this->dieUsage( "Unsupported content model/format", 'badmodelformat' );
49 }
50
51 $text = trim( $params['text'] ); // needed so the key SHA1's match
52 $textContent = ContentHandler::makeContent(
53 $text, $title, $params['contentmodel'], $params['contentformat'] );
54
55 $page = WikiPage::factory( $title );
56 if ( $page->exists() ) {
57 // Page exists: get the merged content with the proposed change
58 $baseRev = Revision::newFromPageId( $page->getId(), $params['baserevid'] );
59 if ( !$baseRev ) {
60 $this->dieUsage( "No revision ID {$params['baserevid']}", 'missingrev' );
61 }
62 $currentRev = $page->getRevision();
63 if ( !$currentRev ) {
64 $this->dieUsage( "No current revision of page ID {$page->getId()}", 'missingrev' );
65 }
66 // Merge in the new version of the section to get the proposed version
67 $editContent = $page->replaceSectionAtRev(
68 $params['section'],
69 $textContent,
70 $params['sectiontitle'],
71 $baseRev->getId()
72 );
73 if ( !$editContent ) {
74 $this->dieUsage( "Could not merge updated section.", 'replacefailed' );
75 }
76 if ( $currentRev->getId() == $baseRev->getId() ) {
77 // Base revision was still the latest; nothing to merge
78 $content = $editContent;
79 } else {
80 // Merge the edit into the current version
81 $baseContent = $baseRev->getContent();
82 $currentContent = $currentRev->getContent();
83 if ( !$baseContent || !$currentContent ) {
84 $this->dieUsage( "Missing content for page ID {$page->getId()}", 'missingrev' );
85 }
86 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
87 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
88 }
89 } else {
90 // New pages: use the user-provided content model
91 $content = $textContent;
92 }
93
94 if ( !$content ) { // merge3() failed
95 $this->getResult()->addValue( null,
96 $this->getModuleName(), array( 'status' => 'editconflict' ) );
97 return;
98 }
99
100 // The user will abort the AJAX request by pressing "save", so ignore that
101 ignore_user_abort( true );
102
103 // Get a key based on the source text, format, and user preferences
104 $key = self::getStashKey( $title, $content, $user );
105 // De-duplicate requests on the same key
106 if ( $user->pingLimiter( 'stashedit' ) ) {
107 $editInfo = false;
108 $status = 'ratelimited';
109 } elseif ( $wgMemc->lock( $key, 0, 30 ) ) {
110 $contentFormat = $content->getDefaultFormat();
111 $editInfo = $page->prepareContentForEdit( $content, null, $user, $contentFormat );
112 $wgMemc->unlock( $key );
113 $status = 'error'; // default
114 } else {
115 $editInfo = false;
116 $status = 'busy';
117 }
118
119 if ( $editInfo && $editInfo->output ) {
120 $parserOutput = $editInfo->output;
121 // If an item is renewed, mind the cache TTL determined by config and parser functions
122 $since = time() - wfTimestamp( TS_UNIX, $parserOutput->getTimestamp() );
123 $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
124 if ( $ttl > 0 && !$parserOutput->getFlag( 'vary-revision' ) ) {
125 // Only store what is actually needed
126 $stashInfo = (object)array(
127 'pstContent' => $editInfo->pstContent,
128 'output' => $editInfo->output,
129 'timestamp' => $editInfo->timestamp
130 );
131 $ok = $wgMemc->set( $key, $stashInfo, $ttl );
132 if ( $ok ) {
133 $status = 'stashed';
134 wfDebugLog( 'StashEdit', "Cached parser output for key '$key'." );
135 } else {
136 $status = 'error';
137 wfDebugLog( 'StashEdit', "Failed to cache parser output for key '$key'." );
138 }
139 } else {
140 $status = 'uncacheable';
141 wfDebugLog( 'StashEdit', "Uncacheable parser output for key '$key'." );
142 }
143 }
144
145 $this->getResult()->addValue( null, $this->getModuleName(), array( 'status' => $status ) );
146 }
147
148 /**
149 * Get the temporary prepared edit stash key for a user
150 *
151 * @param Title $title
152 * @param Content $content
153 * @param User $user User to get parser options from
154 * @return string
155 */
156 protected static function getStashKey(
157 Title $title, Content $content, User $user
158 ) {
159 return wfMemcKey( 'prepared-edit',
160 md5( $title->getPrefixedDBkey() ), // handle rename races
161 $content->getModel(),
162 $content->getDefaultFormat(),
163 sha1( $content->serialize( $content->getDefaultFormat() ) ),
164 $user->getId() ?: md5( $user->getName() ), // account for user parser options
165 $user->getId() ? $user->getTouched() : '-' // handle preference change races
166 );
167 }
168
169 /**
170 * Check that a prepared edit is in cache and still up-to-date
171 *
172 * This method blocks if the prepared edit is already being rendered,
173 * waiting until rendering finishes before doing final validity checks.
174 *
175 * The cache is rejected if template or file changes are detected.
176 * Note that foreign template or file transclusions are not checked.
177 *
178 * The result is a map (pstContent,output,timestamp) with fields
179 * extracted directly from WikiPage::prepareContentForEdit().
180 *
181 * @param Title $title
182 * @param Content $content
183 * @param User $user User to get parser options from
184 * @return stdClass|bool Returns false on cache miss
185 */
186 public static function checkCache( Title $title, Content $content, User $user ) {
187 global $wgMemc;
188
189 $key = self::getStashKey( $title, $content, $user );
190 $editInfo = $wgMemc->get( $key );
191 if ( !is_object( $editInfo ) ) {
192 $start = microtime( true );
193 // We ignore user aborts and keep parsing. Block on any prior parsing
194 // so as to use it's results and make use of the time spent parsing.
195 if ( $wgMemc->lock( $key, 30, 30 ) ) {
196 $editInfo = $wgMemc->get( $key );
197 $wgMemc->unlock( $key );
198 $sec = microtime( true ) - $start;
199 wfDebugLog( 'StashEdit', "Waited $sec seconds on '$key'." );
200 }
201 }
202
203 if ( !is_object( $editInfo ) || !$editInfo->output ) {
204 return false;
205 }
206
207 $time = wfTimestamp( TS_UNIX, $editInfo->output->getTimestamp() );
208 if ( ( time() - $time ) <= 3 ) {
209 wfDebugLog( 'StashEdit', "Timestamp-based cache hit for key '$key'." );
210 return $editInfo; // assume nothing changed
211 }
212
213 $dbr = wfGetDB( DB_SLAVE );
214 // Check that no templates used in the output changed...
215 $cWhr = array(); // conditions to find changes/creations
216 $dWhr = array(); // conditions to find deletions
217 foreach ( $editInfo->output->getTemplateIds() as $ns => $stuff ) {
218 foreach ( $stuff as $dbkey => $revId ) {
219 $cWhr[] = array( 'page_namespace' => $ns, 'page_title' => $dbkey,
220 'page_latest != ' . intval( $revId ) );
221 $dWhr[] = array( 'page_namespace' => $ns, 'page_title' => $dbkey );
222 }
223 }
224 $change = $dbr->selectField( 'page', '1', $dbr->makeList( $cWhr, LIST_OR ), __METHOD__ );
225 $n = $dbr->selectField( 'page', 'COUNT(*)', $dbr->makeList( $dWhr, LIST_OR ), __METHOD__ );
226 if ( $change || $n != count( $dWhr ) ) {
227 wfDebugLog( 'StashEdit', "Stale cache for key '$key'; template changed." );
228 return false;
229 }
230
231 // Check that no files used in the output changed...
232 $cWhr = array(); // conditions to find changes/creations
233 $dWhr = array(); // conditions to find deletions
234 foreach ( $editInfo->output->getFileSearchOptions() as $name => $options ) {
235 $cWhr[] = array( 'img_name' => $dbkey,
236 'img_sha1 != ' . $dbr->addQuotes( strval( $options['sha1'] ) ) );
237 $dWhr[] = array( 'img_name' => $dbkey );
238 }
239 $change = $dbr->selectField( 'image', '1', $dbr->makeList( $cWhr, LIST_OR ), __METHOD__ );
240 $n = $dbr->selectField( 'image', 'COUNT(*)', $dbr->makeList( $dWhr, LIST_OR ), __METHOD__ );
241 if ( $change || $n != count( $dWhr ) ) {
242 wfDebugLog( 'StashEdit', "Stale cache for key '$key'; file changed." );
243 return false;
244 }
245
246 wfDebugLog( 'StashEdit', "Cache hit for key '$key'." );
247
248 return $editInfo;
249 }
250
251 public function getAllowedParams() {
252 return array(
253 'title' => array(
254 ApiBase::PARAM_TYPE => 'string',
255 ApiBase::PARAM_REQUIRED => true
256 ),
257 'section' => array(
258 ApiBase::PARAM_TYPE => 'string',
259 ),
260 'sectiontitle' => array(
261 ApiBase::PARAM_TYPE => 'string'
262 ),
263 'text' => array(
264 ApiBase::PARAM_TYPE => 'string',
265 ApiBase::PARAM_REQUIRED => true
266 ),
267 'contentmodel' => array(
268 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
269 ApiBase::PARAM_REQUIRED => true
270 ),
271 'contentformat' => array(
272 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
273 ApiBase::PARAM_REQUIRED => true
274 ),
275 'baserevid' => array(
276 ApiBase::PARAM_TYPE => 'integer',
277 ApiBase::PARAM_REQUIRED => true
278 )
279 );
280 }
281
282 function needsToken() {
283 return 'csrf';
284 }
285
286 function mustBePosted() {
287 return true;
288 }
289
290 function isInternal() {
291 return true;
292 }
293 }