Reverse removal of Live Preview in r59446, with the following changes:
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Contains the EditPage class
4 * @file
5 */
6
7 /**
8 * The edit page/HTML interface (split from Article)
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
11 * interfaces.
12 *
13 * EditPage cares about two distinct titles:
14 * $wgTitle is the page that forms submit to, links point to,
15 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
16 * page in the database that is actually being edited. These are
17 * usually the same, but they are now allowed to be different.
18 */
19 class EditPage {
20 const AS_SUCCESS_UPDATE = 200;
21 const AS_SUCCESS_NEW_ARTICLE = 201;
22 const AS_HOOK_ERROR = 210;
23 const AS_FILTERING = 211;
24 const AS_HOOK_ERROR_EXPECTED = 212;
25 const AS_BLOCKED_PAGE_FOR_USER = 215;
26 const AS_CONTENT_TOO_BIG = 216;
27 const AS_USER_CANNOT_EDIT = 217;
28 const AS_READ_ONLY_PAGE_ANON = 218;
29 const AS_READ_ONLY_PAGE_LOGGED = 219;
30 const AS_READ_ONLY_PAGE = 220;
31 const AS_RATE_LIMITED = 221;
32 const AS_ARTICLE_WAS_DELETED = 222;
33 const AS_NO_CREATE_PERMISSION = 223;
34 const AS_BLANK_ARTICLE = 224;
35 const AS_CONFLICT_DETECTED = 225;
36 const AS_SUMMARY_NEEDED = 226;
37 const AS_TEXTBOX_EMPTY = 228;
38 const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
39 const AS_OK = 230;
40 const AS_END = 231;
41 const AS_SPAM_ERROR = 232;
42 const AS_IMAGE_REDIRECT_ANON = 233;
43 const AS_IMAGE_REDIRECT_LOGGED = 234;
44
45 var $mArticle;
46 var $mTitle;
47 var $action;
48 var $mMetaData = '';
49 var $isConflict = false;
50 var $isCssJsSubpage = false;
51 var $isCssSubpage = false;
52 var $isJsSubpage = false;
53 var $deletedSinceEdit = false;
54 var $formtype;
55 var $firsttime;
56 var $lastDelete;
57 var $mTokenOk = false;
58 var $mTokenOkExceptSuffix = false;
59 var $mTriedSave = false;
60 var $tooBig = false;
61 var $kblength = false;
62 var $missingComment = false;
63 var $missingSummary = false;
64 var $allowBlankSummary = false;
65 var $autoSumm = '';
66 var $hookError = '';
67 #var $mPreviewTemplates;
68 var $mParserOutput;
69 var $mBaseRevision = false;
70 var $mShowSummaryField = true;
71
72 # Form values
73 var $save = false, $preview = false, $diff = false;
74 var $minoredit = false, $watchthis = false, $recreate = false;
75 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
76 var $edittime = '', $section = '', $starttime = '';
77 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
78
79 # Placeholders for text injection by hooks (must be HTML)
80 # extensions should take care to _append_ to the present value
81 public $editFormPageTop; // Before even the preview
82 public $editFormTextTop;
83 public $editFormTextBeforeContent;
84 public $editFormTextAfterWarn;
85 public $editFormTextAfterTools;
86 public $editFormTextBottom;
87 public $editFormTextAfterContent;
88 public $previewTextAfterContent;
89
90 /* $didSave should be set to true whenever an article was succesfully altered. */
91 public $didSave = false;
92 public $undidRev = 0;
93
94 public $suppressIntro = false;
95
96 /**
97 * @todo document
98 * @param $article
99 */
100 function EditPage( $article ) {
101 $this->mArticle =& $article;
102 $this->mTitle = $article->getTitle();
103 $this->action = 'submit';
104
105 # Placeholders for text injection by hooks (empty per default)
106 $this->editFormPageTop =
107 $this->editFormTextTop =
108 $this->editFormTextBeforeContent =
109 $this->editFormTextAfterWarn =
110 $this->editFormTextAfterTools =
111 $this->editFormTextBottom =
112 $this->editFormTextAfterContent =
113 $this->previewTextAfterContent =
114 $this->mPreloadText = "";
115 }
116
117 function getArticle() {
118 return $this->mArticle;
119 }
120
121
122 /**
123 * Fetch initial editing page content.
124 * @returns mixed string on success, $def_text for invalid sections
125 * @private
126 */
127 function getContent( $def_text = '' ) {
128 global $wgOut, $wgRequest, $wgParser, $wgContLang, $wgMessageCache;
129
130 wfProfileIn( __METHOD__ );
131 # Get variables from query string :P
132 $section = $wgRequest->getVal( 'section' );
133
134 $preload = $wgRequest->getVal( 'preload',
135 // Custom preload text for new sections
136 $section === 'new' ? 'MediaWiki:addsection-preload' : '' );
137 $undoafter = $wgRequest->getVal( 'undoafter' );
138 $undo = $wgRequest->getVal( 'undo' );
139
140 $text = '';
141 // For message page not locally set, use the i18n message.
142 // For other non-existent articles, use preload text if any.
143 if ( !$this->mTitle->exists() ) {
144 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
145 # If this is a system message, get the default text.
146 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
147 $wgMessageCache->loadAllMessages( $lang );
148 $text = wfMsgGetKey( $message, false, $lang, false );
149 if( wfEmptyMsg( $message, $text ) )
150 $text = $this->getPreloadedText( $preload );
151 } else {
152 # If requested, preload some text.
153 $text = $this->getPreloadedText( $preload );
154 }
155 // For existing pages, get text based on "undo" or section parameters.
156 } else {
157 $text = $this->mArticle->getContent();
158 if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
159 # If they got undoafter and undo round the wrong way, switch them
160 list( $undo, $undoafter ) = array( $undoafter, $undo );
161 }
162 if ( $undo > 0 && $undo > $undoafter ) {
163 # Undoing a specific edit overrides section editing; section-editing
164 # doesn't work with undoing.
165 if ( $undoafter ) {
166 $undorev = Revision::newFromId( $undo );
167 $oldrev = Revision::newFromId( $undoafter );
168 } else {
169 $undorev = Revision::newFromId( $undo );
170 $oldrev = $undorev ? $undorev->getPrevious() : null;
171 }
172
173 # Sanity check, make sure it's the right page,
174 # the revisions exist and they were not deleted.
175 # Otherwise, $text will be left as-is.
176 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
177 $undorev->getPage() == $oldrev->getPage() &&
178 $undorev->getPage() == $this->mArticle->getID() &&
179 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
180 !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
181
182 $undotext = $this->mArticle->getUndoText( $undorev, $oldrev );
183 if ( $undotext === false ) {
184 # Warn the user that something went wrong
185 $this->editFormPageTop .= $wgOut->parse( '<div class="error mw-undo-failure">' . wfMsgNoTrans( 'undo-failure' ) . '</div>' );
186 } else {
187 $text = $undotext;
188 # Inform the user of our success and set an automatic edit summary
189 $this->editFormPageTop .= $wgOut->parse( '<div class="mw-undo-success">' . wfMsgNoTrans( 'undo-success' ) . '</div>' );
190 $firstrev = $oldrev->getNext();
191 # If we just undid one rev, use an autosummary
192 if ( $firstrev->mId == $undo ) {
193 $this->summary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
194 $this->undidRev = $undo;
195 }
196 $this->formtype = 'diff';
197 }
198 } else {
199 // Failed basic sanity checks.
200 // Older revisions may have been removed since the link
201 // was created, or we may simply have got bogus input.
202 $this->editFormPageTop .= $wgOut->parse( '<div class="error mw-undo-norev">' . wfMsgNoTrans( 'undo-norev' ) . '</div>' );
203 }
204 } else if ( $section != '' ) {
205 if ( $section == 'new' ) {
206 $text = $this->getPreloadedText( $preload );
207 } else {
208 // Get section edit text (returns $def_text for invalid sections)
209 $text = $wgParser->getSection( $text, $section, $def_text );
210 }
211 }
212 }
213
214 wfProfileOut( __METHOD__ );
215 return $text;
216 }
217
218 /** Use this method before edit() to preload some text into the edit box */
219 public function setPreloadedText( $text ) {
220 $this->mPreloadText = $text;
221 }
222
223 /**
224 * Get the contents of a page from its title and remove includeonly tags
225 *
226 * @param $preload String: the title of the page.
227 * @return string The contents of the page.
228 */
229 protected function getPreloadedText( $preload ) {
230 global $wgParser, $wgUser;
231 if ( !empty( $this->mPreloadText ) ) {
232 return $this->mPreloadText;
233 } else {
234 $preloadTitle = Title::newFromText( $preload );
235 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
236 return $wgParser->getTransclusionText( $preloadTitle, ParserOptions::newFromUser( $wgUser ) );
237 }
238 }
239 }
240
241 /**
242 * This is the function that extracts metadata from the article body on the first view.
243 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
244 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
245 */
246 function extractMetaDataFromArticle () {
247 global $wgUseMetadataEdit, $wgMetadataWhitelist, $wgContLang;
248 $this->mMetaData = '';
249 if ( !$wgUseMetadataEdit ) return;
250 if ( $wgMetadataWhitelist == '' ) return;
251 $s = '';
252 $t = $this->getContent();
253
254 # MISSING : <nowiki> filtering
255
256 # Categories and language links
257 $t = explode( "\n" , $t );
258 $catlow = strtolower( $wgContLang->getNsText( NS_CATEGORY ) );
259 $cat = $ll = array();
260 foreach ( $t as $key => $x ) {
261 $y = trim( strtolower ( $x ) );
262 while ( substr( $y , 0 , 2 ) == '[[' ) {
263 $y = explode( ']]' , trim ( $x ) );
264 $first = array_shift( $y );
265 $first = explode( ':' , $first );
266 $ns = array_shift( $first );
267 $ns = trim( str_replace( '[' , '' , $ns ) );
268 if ( $wgContLang->getLanguageName( $ns ) || strtolower( $ns ) == $catlow ) {
269 $add = '[[' . $ns . ':' . implode( ':' , $first ) . ']]';
270 if ( strtolower( $ns ) == $catlow ) $cat[] = $add;
271 else $ll[] = $add;
272 $x = implode( ']]', $y );
273 $t[$key] = $x;
274 $y = trim( strtolower( $x ) );
275 } else {
276 $x = implode( ']]' , $y );
277 $y = trim( strtolower( $x ) );
278 }
279 }
280 }
281 if ( count( $cat ) ) $s .= implode( ' ' , $cat ) . "\n";
282 if ( count( $ll ) ) $s .= implode( ' ' , $ll ) . "\n";
283 $t = implode( "\n" , $t );
284
285 # Load whitelist
286 $sat = array () ; # stand-alone-templates; must be lowercase
287 $wl_title = Title::newFromText( $wgMetadataWhitelist );
288 $wl_article = new Article ( $wl_title );
289 $wl = explode ( "\n" , $wl_article->getContent() );
290 foreach ( $wl AS $x ) {
291 $isentry = false;
292 $x = trim ( $x );
293 while ( substr ( $x , 0 , 1 ) == '*' ) {
294 $isentry = true;
295 $x = trim ( substr ( $x , 1 ) );
296 }
297 if ( $isentry ) {
298 $sat[] = strtolower ( $x );
299 }
300
301 }
302
303 # Templates, but only some
304 $t = explode( '{{' , $t );
305 $tl = array() ;
306 foreach ( $t as $key => $x ) {
307 $y = explode( '}}' , $x , 2 );
308 if ( count( $y ) == 2 ) {
309 $z = $y[0];
310 $z = explode( '|' , $z );
311 $tn = array_shift( $z );
312 if ( in_array( strtolower( $tn ) , $sat ) ) {
313 $tl[] = '{{' . $y[0] . '}}';
314 $t[$key] = $y[1];
315 $y = explode( '}}' , $y[1] , 2 );
316 }
317 else $t[$key] = '{{' . $x;
318 }
319 else if ( $key != 0 ) $t[$key] = '{{' . $x;
320 else $t[$key] = $x;
321 }
322 if ( count( $tl ) ) $s .= implode( ' ' , $tl );
323 $t = implode( '' , $t );
324
325 $t = str_replace( "\n\n\n", "\n", $t );
326 $this->mArticle->mContent = $t;
327 $this->mMetaData = $s;
328 }
329
330 /*
331 * Check if a page was deleted while the user was editing it, before submit.
332 * Note that we rely on the logging table, which hasn't been always there,
333 * but that doesn't matter, because this only applies to brand new
334 * deletes.
335 */
336 protected function wasDeletedSinceLastEdit() {
337 if ( $this->deletedSinceEdit )
338 return true;
339 if ( $this->mTitle->isDeletedQuick() ) {
340 $this->lastDelete = $this->getLastDelete();
341 if ( $this->lastDelete ) {
342 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
343 if ( $deleteTime > $this->starttime ) {
344 $this->deletedSinceEdit = true;
345 }
346 }
347 }
348 return $this->deletedSinceEdit;
349 }
350
351 function submit() {
352 $this->edit();
353 }
354
355 /**
356 * This is the function that gets called for "action=edit". It
357 * sets up various member variables, then passes execution to
358 * another function, usually showEditForm()
359 *
360 * The edit form is self-submitting, so that when things like
361 * preview and edit conflicts occur, we get the same form back
362 * with the extra stuff added. Only when the final submission
363 * is made and all is well do we actually save and redirect to
364 * the newly-edited page.
365 */
366 function edit() {
367 global $wgOut, $wgRequest, $wgUser;
368 // Allow extensions to modify/prevent this form or submission
369 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
370 return;
371 }
372
373 wfProfileIn( __METHOD__ );
374 wfDebug( __METHOD__.": enter\n" );
375
376 // This is not an article
377 $wgOut->setArticleFlag( false );
378
379 $this->importFormData( $wgRequest );
380 $this->firsttime = false;
381
382 if ( $this->live ) {
383 $this->livePreview();
384 wfProfileOut( __METHOD__ );
385 return;
386 }
387
388 if ( wfReadOnly() && $this->save ) {
389 // Force preview
390 $this->save = false;
391 $this->preview = true;
392 }
393
394 $wgOut->addScriptFile( 'edit.js' );
395
396 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
397 $wgOut->includeJQuery();
398 $wgOut->addScriptFile( 'preview.js' );
399 }
400
401 $permErrors = $this->getEditPermissionErrors();
402 if ( $permErrors ) {
403 wfDebug( __METHOD__ . ": User can't edit\n" );
404 $this->readOnlyPage( $this->getContent( false ), true, $permErrors, 'edit' );
405 wfProfileOut( __METHOD__ );
406 return;
407 } else {
408 if ( $this->save ) {
409 $this->formtype = 'save';
410 } else if ( $this->preview ) {
411 $this->formtype = 'preview';
412 } else if ( $this->diff ) {
413 $this->formtype = 'diff';
414 } else { # First time through
415 $this->firsttime = true;
416 if ( $this->previewOnOpen() ) {
417 $this->formtype = 'preview';
418 } else {
419 $this->extractMetaDataFromArticle () ;
420 $this->formtype = 'initial';
421 }
422 }
423 }
424
425 // If they used redlink=1 and the page exists, redirect to the main article
426 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
427 $wgOut->redirect( $this->mTitle->getFullURL() );
428 }
429
430 wfProfileIn( __METHOD__."-business-end" );
431
432 $this->isConflict = false;
433 // css / js subpages of user pages get a special treatment
434 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
435 $this->isCssSubpage = $this->mTitle->isCssSubpage();
436 $this->isJsSubpage = $this->mTitle->isJsSubpage();
437 $this->isValidCssJsSubpage = $this->mTitle->isValidCssJsSubpage();
438
439 # Show applicable editing introductions
440 if ( $this->formtype == 'initial' || $this->firsttime )
441 $this->showIntro();
442
443 if ( $this->mTitle->isTalkPage() ) {
444 $wgOut->addWikiMsg( 'talkpagetext' );
445 }
446
447 # Optional notices on a per-namespace and per-page basis
448 $editnotice_ns = 'editnotice-'.$this->mTitle->getNamespace();
449 if ( !wfEmptyMsg( $editnotice_ns, wfMsgForContent( $editnotice_ns ) ) ) {
450 $wgOut->addWikiText( wfMsgForContent( $editnotice_ns ) );
451 }
452 if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
453 $parts = explode( '/', $this->mTitle->getDBkey() );
454 $editnotice_base = $editnotice_ns;
455 while ( count( $parts ) > 0 ) {
456 $editnotice_base .= '-'.array_shift( $parts );
457 if ( !wfEmptyMsg( $editnotice_base, wfMsgForContent( $editnotice_base ) ) ) {
458 $wgOut->addWikiText( wfMsgForContent( $editnotice_base ) );
459 }
460 }
461 }
462
463 # Attempt submission here. This will check for edit conflicts,
464 # and redundantly check for locked database, blocked IPs, etc.
465 # that edit() already checked just in case someone tries to sneak
466 # in the back door with a hand-edited submission URL.
467
468 if ( 'save' == $this->formtype ) {
469 if ( !$this->attemptSave() ) {
470 wfProfileOut( __METHOD__."-business-end" );
471 wfProfileOut( __METHOD__ );
472 return;
473 }
474 }
475
476 # First time through: get contents, set time for conflict
477 # checking, etc.
478 if ( 'initial' == $this->formtype || $this->firsttime ) {
479 if ( $this->initialiseForm() === false ) {
480 $this->noSuchSectionPage();
481 wfProfileOut( __METHOD__."-business-end" );
482 wfProfileOut( __METHOD__ );
483 return;
484 }
485 if ( !$this->mTitle->getArticleId() )
486 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
487 }
488
489 $this->showEditForm();
490 wfProfileOut( __METHOD__."-business-end" );
491 wfProfileOut( __METHOD__ );
492 }
493
494 protected function getEditPermissionErrors() {
495 global $wgUser;
496 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
497 # Can this title be created?
498 if ( !$this->mTitle->exists() ) {
499 $permErrors = array_merge( $permErrors,
500 wfArrayDiff2( $this->mTitle->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
501 }
502 # Ignore some permissions errors when a user is just previewing/viewing diffs
503 $remove = array();
504 foreach( $permErrors as $error ) {
505 if ( ( $this->preview || $this->diff ) &&
506 ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' ) )
507 {
508 $remove[] = $error;
509 }
510 }
511 $permErrors = wfArrayDiff2( $permErrors, $remove );
512 return $permErrors;
513 }
514
515 /**
516 * Show a read-only error
517 * Parameters are the same as OutputPage:readOnlyPage()
518 * Redirect to the article page if redlink=1
519 */
520 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
521 global $wgRequest, $wgOut;
522 if ( $wgRequest->getBool( 'redlink' ) ) {
523 // The edit page was reached via a red link.
524 // Redirect to the article page and let them click the edit tab if
525 // they really want a permission error.
526 $wgOut->redirect( $this->mTitle->getFullUrl() );
527 } else {
528 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
529 }
530 }
531
532 /**
533 * Should we show a preview when the edit form is first shown?
534 *
535 * @return bool
536 */
537 protected function previewOnOpen() {
538 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
539 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
540 // Explicit override from request
541 return true;
542 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
543 // Explicit override from request
544 return false;
545 } elseif ( $this->section == 'new' ) {
546 // Nothing *to* preview for new sections
547 return false;
548 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
549 // Standard preference behaviour
550 return true;
551 } elseif ( !$this->mTitle->exists() &&
552 isset($wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]) &&
553 $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
554 {
555 // Categories are special
556 return true;
557 } else {
558 return false;
559 }
560 }
561
562 /**
563 * Does this EditPage class support section editing?
564 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
565 *
566 * @return bool
567 */
568 protected function isSectionEditSupported() {
569 return true;
570 }
571
572 /**
573 * Returns the URL to use in the form's action attribute.
574 * This is used by EditPage subclasses when simply customizing the action
575 * variable in the constructor is not enough. This can be used when the
576 * EditPage lives inside of a Special page rather than a custom page action.
577 *
578 * @param Title $title The title for which is being edited (where we go to for &action= links)
579 * @return string
580 */
581 protected function getActionURL( Title $title ) {
582 return $title->getLocalURL( array( 'action' => $this->action ) );
583 }
584
585 /**
586 * @todo document
587 * @param $request
588 */
589 function importFormData( &$request ) {
590 global $wgLang, $wgUser;
591
592 wfProfileIn( __METHOD__ );
593
594 # Section edit can come from either the form or a link
595 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
596
597 if ( $request->wasPosted() ) {
598 # These fields need to be checked for encoding.
599 # Also remove trailing whitespace, but don't remove _initial_
600 # whitespace from the text boxes. This may be significant formatting.
601 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
602 if ( !$request->getCheck('wpTextbox2') ) {
603 // Skip this if wpTextbox2 has input, it indicates that we came
604 // from a conflict page with raw page text, not a custom form
605 // modified by subclasses
606 wfProfileIn( get_class($this)."::importContentFormData" );
607 $textbox1 = $this->importContentFormData( $request );
608 if ( isset($textbox1) )
609 $this->textbox1 = $textbox1;
610 wfProfileOut( get_class($this)."::importContentFormData" );
611 }
612 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
613 # Truncate for whole multibyte characters. +5 bytes for ellipsis
614 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250, '' );
615
616 # Remove extra headings from summaries and new sections.
617 $this->summary = preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary);
618
619 $this->edittime = $request->getVal( 'wpEdittime' );
620 $this->starttime = $request->getVal( 'wpStarttime' );
621
622 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
623
624 if ( is_null( $this->edittime ) ) {
625 # If the form is incomplete, force to preview.
626 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
627 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
628 $this->preview = true;
629 } else {
630 /* Fallback for live preview */
631 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
632 $this->diff = $request->getCheck( 'wpDiff' );
633
634 // Remember whether a save was requested, so we can indicate
635 // if we forced preview due to session failure.
636 $this->mTriedSave = !$this->preview;
637
638 if ( $this->tokenOk( $request ) ) {
639 # Some browsers will not report any submit button
640 # if the user hits enter in the comment box.
641 # The unmarked state will be assumed to be a save,
642 # if the form seems otherwise complete.
643 wfDebug( __METHOD__ . ": Passed token check.\n" );
644 } else if ( $this->diff ) {
645 # Failed token check, but only requested "Show Changes".
646 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
647 } else {
648 # Page might be a hack attempt posted from
649 # an external site. Preview instead of saving.
650 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
651 $this->preview = true;
652 }
653 }
654 $this->save = !$this->preview && !$this->diff;
655 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
656 $this->edittime = null;
657 }
658
659 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
660 $this->starttime = null;
661 }
662
663 $this->recreate = $request->getCheck( 'wpRecreate' );
664
665 $this->minoredit = $request->getCheck( 'wpMinoredit' );
666 $this->watchthis = $request->getCheck( 'wpWatchthis' );
667
668 # Don't force edit summaries when a user is editing their own user or talk page
669 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) &&
670 $this->mTitle->getText() == $wgUser->getName() )
671 {
672 $this->allowBlankSummary = true;
673 } else {
674 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' ) || !$wgUser->getOption( 'forceeditsummary');
675 }
676
677 $this->autoSumm = $request->getText( 'wpAutoSummary' );
678 } else {
679 # Not a posted form? Start with nothing.
680 wfDebug( __METHOD__ . ": Not a posted form.\n" );
681 $this->textbox1 = '';
682 $this->mMetaData = '';
683 $this->summary = '';
684 $this->edittime = '';
685 $this->starttime = wfTimestampNow();
686 $this->edit = false;
687 $this->preview = false;
688 $this->save = false;
689 $this->diff = false;
690 $this->minoredit = false;
691 $this->watchthis = $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
692 $this->recreate = false;
693
694 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
695 $this->summary = $request->getVal( 'preloadtitle' );
696 }
697 elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
698 $this->summary = $request->getText( 'summary' );
699 }
700
701 if ( $request->getVal( 'minor' ) ) {
702 $this->minoredit = true;
703 }
704 }
705
706 $this->bot = $request->getBool( 'bot', true );
707 $this->nosummary = $request->getBool( 'nosummary' );
708
709 // FIXME: unused variable?
710 $this->oldid = $request->getInt( 'oldid' );
711
712 $this->live = $request->getCheck( 'live' );
713 $this->editintro = $request->getText( 'editintro',
714 // Custom edit intro for new sections
715 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
716
717 wfProfileOut( __METHOD__ );
718
719 // Allow extensions to modify form data
720 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
721 }
722
723 /**
724 * Subpage overridable method for extracting the page content data from the
725 * posted form to be placed in $this->textbox1, if using customized input
726 * this method should be overrided and return the page text that will be used
727 * for saving, preview parsing and so on...
728 *
729 * @praram WebRequest $request
730 */
731 protected function importContentFormData( &$request ) {
732 return; // Don't do anything, EditPage already extracted wpTextbox1
733 }
734
735 /**
736 * Make sure the form isn't faking a user's credentials.
737 *
738 * @param $request WebRequest
739 * @return bool
740 * @private
741 */
742 function tokenOk( &$request ) {
743 global $wgUser;
744 $token = $request->getVal( 'wpEditToken' );
745 $this->mTokenOk = $wgUser->matchEditToken( $token );
746 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
747 return $this->mTokenOk;
748 }
749
750 /**
751 * Show all applicable editing introductions
752 */
753 protected function showIntro() {
754 global $wgOut, $wgUser;
755 if ( $this->suppressIntro ) {
756 return;
757 }
758
759 $namespace = $this->mTitle->getNamespace();
760
761 if ( $namespace == NS_MEDIAWIKI ) {
762 # Show a warning if editing an interface message
763 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1</div>", 'editinginterface' );
764 }
765
766 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
767 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
768 $parts = explode( '/', $this->mTitle->getText(), 2 );
769 $username = $parts[0];
770 $id = User::idFromName( $username );
771 $ip = User::isIP( $username );
772 if ( $id == 0 && !$ip ) {
773 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1</div>",
774 array( 'userpage-userdoesnotexist', $username ) );
775 }
776 }
777 # Try to add a custom edit intro, or use the standard one if this is not possible.
778 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
779 if ( $wgUser->isLoggedIn() ) {
780 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1</div>", 'newarticletext' );
781 } else {
782 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1</div>", 'newarticletextanon' );
783 }
784 }
785 # Give a notice if the user is editing a deleted/moved page...
786 if ( !$this->mTitle->exists() ) {
787 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle->getPrefixedText(),
788 '', array( 'lim' => 10,
789 'conds' => array( "log_action != 'revision'" ),
790 'showIfEmpty' => false,
791 'msgKey' => array( 'recreate-moveddeleted-warn') )
792 );
793 }
794 }
795
796 /**
797 * Attempt to show a custom editing introduction, if supplied
798 *
799 * @return bool
800 */
801 protected function showCustomIntro() {
802 if ( $this->editintro ) {
803 $title = Title::newFromText( $this->editintro );
804 if ( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
805 global $wgOut;
806 $revision = Revision::newFromTitle( $title );
807 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle );
808 return true;
809 } else {
810 return false;
811 }
812 } else {
813 return false;
814 }
815 }
816
817 /**
818 * Attempt submission (no UI)
819 * @return one of the constants describing the result
820 */
821 function internalAttemptSave( &$result, $bot = false ) {
822 global $wgFilterCallback, $wgUser, $wgOut, $wgParser;
823 global $wgMaxArticleSize;
824
825 wfProfileIn( __METHOD__ );
826 wfProfileIn( __METHOD__ . '-checks' );
827
828 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) )
829 {
830 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
831 return self::AS_HOOK_ERROR;
832 }
833
834 # Check image redirect
835 if ( $this->mTitle->getNamespace() == NS_FILE &&
836 Title::newFromRedirect( $this->textbox1 ) instanceof Title &&
837 !$wgUser->isAllowed( 'upload' ) ) {
838 if ( $wgUser->isAnon() ) {
839 return self::AS_IMAGE_REDIRECT_ANON;
840 } else {
841 return self::AS_IMAGE_REDIRECT_LOGGED;
842 }
843 }
844
845 # Reintegrate metadata
846 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
847 $this->mMetaData = '' ;
848
849 # Check for spam
850 $match = self::matchSummarySpamRegex( $this->summary );
851 if ( $match === false ) {
852 $match = self::matchSpamRegex( $this->textbox1 );
853 }
854 if ( $match !== false ) {
855 $result['spam'] = $match;
856 $ip = wfGetIP();
857 $pdbk = $this->mTitle->getPrefixedDBkey();
858 $match = str_replace( "\n", '', $match );
859 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
860 wfProfileOut( __METHOD__ . '-checks' );
861 wfProfileOut( __METHOD__ );
862 return self::AS_SPAM_ERROR;
863 }
864 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section, $this->hookError, $this->summary ) ) {
865 # Error messages or other handling should be performed by the filter function
866 wfProfileOut( __METHOD__ . '-checks' );
867 wfProfileOut( __METHOD__ );
868 return self::AS_FILTERING;
869 }
870 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
871 # Error messages etc. could be handled within the hook...
872 wfProfileOut( __METHOD__ . '-checks' );
873 wfProfileOut( __METHOD__ );
874 return self::AS_HOOK_ERROR;
875 } elseif ( $this->hookError != '' ) {
876 # ...or the hook could be expecting us to produce an error
877 wfProfileOut( __METHOD__ . '-checks' );
878 wfProfileOut( __METHOD__ );
879 return self::AS_HOOK_ERROR_EXPECTED;
880 }
881 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
882 # Check block state against master, thus 'false'.
883 wfProfileOut( __METHOD__ . '-checks' );
884 wfProfileOut( __METHOD__ );
885 return self::AS_BLOCKED_PAGE_FOR_USER;
886 }
887 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
888 if ( $this->kblength > $wgMaxArticleSize ) {
889 // Error will be displayed by showEditForm()
890 $this->tooBig = true;
891 wfProfileOut( __METHOD__ . '-checks' );
892 wfProfileOut( __METHOD__ );
893 return self::AS_CONTENT_TOO_BIG;
894 }
895
896 if ( !$wgUser->isAllowed( 'edit' ) ) {
897 if ( $wgUser->isAnon() ) {
898 wfProfileOut( __METHOD__ . '-checks' );
899 wfProfileOut( __METHOD__ );
900 return self::AS_READ_ONLY_PAGE_ANON;
901 } else {
902 wfProfileOut( __METHOD__ . '-checks' );
903 wfProfileOut( __METHOD__ );
904 return self::AS_READ_ONLY_PAGE_LOGGED;
905 }
906 }
907
908 if ( wfReadOnly() ) {
909 wfProfileOut( __METHOD__ . '-checks' );
910 wfProfileOut( __METHOD__ );
911 return self::AS_READ_ONLY_PAGE;
912 }
913 if ( $wgUser->pingLimiter() ) {
914 wfProfileOut( __METHOD__ . '-checks' );
915 wfProfileOut( __METHOD__ );
916 return self::AS_RATE_LIMITED;
917 }
918
919 # If the article has been deleted while editing, don't save it without
920 # confirmation
921 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
922 wfProfileOut( __METHOD__ . '-checks' );
923 wfProfileOut( __METHOD__ );
924 return self::AS_ARTICLE_WAS_DELETED;
925 }
926
927 wfProfileOut( __METHOD__ . '-checks' );
928
929 # If article is new, insert it.
930 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
931 if ( 0 == $aid ) {
932 // Late check for create permission, just in case *PARANOIA*
933 if ( !$this->mTitle->userCan( 'create' ) ) {
934 wfDebug( __METHOD__ . ": no create permission\n" );
935 wfProfileOut( __METHOD__ );
936 return self::AS_NO_CREATE_PERMISSION;
937 }
938
939 # Don't save a new article if it's blank.
940 if ( $this->textbox1 == '' ) {
941 wfProfileOut( __METHOD__ );
942 return self::AS_BLANK_ARTICLE;
943 }
944
945 // Run post-section-merge edit filter
946 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError, $this->summary ) ) ) {
947 # Error messages etc. could be handled within the hook...
948 wfProfileOut( __METHOD__ );
949 return self::AS_HOOK_ERROR;
950 } elseif ( $this->hookError != '' ) {
951 # ...or the hook could be expecting us to produce an error
952 wfProfileOut( __METHOD__ );
953 return self::AS_HOOK_ERROR_EXPECTED;
954 }
955
956 # Handle the user preference to force summaries here. Check if it's not a redirect.
957 if ( !$this->allowBlankSummary && !Title::newFromRedirect( $this->textbox1 ) ) {
958 if ( md5( $this->summary ) == $this->autoSumm ) {
959 $this->missingSummary = true;
960 wfProfileOut( __METHOD__ );
961 return self::AS_SUMMARY_NEEDED;
962 }
963 }
964
965 $isComment = ( $this->section == 'new' );
966
967 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
968 $this->minoredit, $this->watchthis, false, $isComment, $bot );
969
970 wfProfileOut( __METHOD__ );
971 return self::AS_SUCCESS_NEW_ARTICLE;
972 }
973
974 # Article exists. Check for edit conflict.
975
976 $this->mArticle->clear(); # Force reload of dates, etc.
977 $this->mArticle->forUpdate( true ); # Lock the article
978
979 wfDebug( "timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n" );
980
981 if ( $this->mArticle->getTimestamp() != $this->edittime ) {
982 $this->isConflict = true;
983 if ( $this->section == 'new' ) {
984 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
985 $this->mArticle->getComment() == $this->summary ) {
986 // Probably a duplicate submission of a new comment.
987 // This can happen when squid resends a request after
988 // a timeout but the first one actually went through.
989 wfDebug( __METHOD__ . ": duplicate new section submission; trigger edit conflict!\n" );
990 } else {
991 // New comment; suppress conflict.
992 $this->isConflict = false;
993 wfDebug( __METHOD__ .": conflict suppressed; new section\n" );
994 }
995 }
996 }
997 $userid = $wgUser->getId();
998
999 # Suppress edit conflict with self, except for section edits where merging is required.
1000 if ( $this->isConflict && $this->section == '' && $this->userWasLastToEdit( $userid, $this->edittime ) ) {
1001 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1002 $this->isConflict = false;
1003 }
1004
1005 if ( $this->isConflict ) {
1006 wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
1007 $this->mArticle->getTimestamp() . "')\n" );
1008 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime );
1009 } else {
1010 wfDebug( __METHOD__ . ": getting section '$this->section'\n" );
1011 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary );
1012 }
1013 if ( is_null( $text ) ) {
1014 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1015 $this->isConflict = true;
1016 $text = $this->textbox1; // do not try to merge here!
1017 } else if ( $this->isConflict ) {
1018 # Attempt merge
1019 if ( $this->mergeChangesInto( $text ) ) {
1020 // Successful merge! Maybe we should tell the user the good news?
1021 $this->isConflict = false;
1022 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1023 } else {
1024 $this->section = '';
1025 $this->textbox1 = $text;
1026 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1027 }
1028 }
1029
1030 if ( $this->isConflict ) {
1031 wfProfileOut( __METHOD__ );
1032 return self::AS_CONFLICT_DETECTED;
1033 }
1034
1035 $oldtext = $this->mArticle->getContent();
1036
1037 // Run post-section-merge edit filter
1038 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError, $this->summary ) ) ) {
1039 # Error messages etc. could be handled within the hook...
1040 wfProfileOut( __METHOD__ );
1041 return self::AS_HOOK_ERROR;
1042 } elseif ( $this->hookError != '' ) {
1043 # ...or the hook could be expecting us to produce an error
1044 wfProfileOut( __METHOD__ );
1045 return self::AS_HOOK_ERROR_EXPECTED;
1046 }
1047
1048 # Handle the user preference to force summaries here, but not for null edits
1049 if ( $this->section != 'new' && !$this->allowBlankSummary && 0 != strcmp( $oldtext, $text )
1050 && !Title::newFromRedirect( $text ) ) # check if it's not a redirect
1051 {
1052 if ( md5( $this->summary ) == $this->autoSumm ) {
1053 $this->missingSummary = true;
1054 wfProfileOut( __METHOD__ );
1055 return self::AS_SUMMARY_NEEDED;
1056 }
1057 }
1058
1059 # And a similar thing for new sections
1060 if ( $this->section == 'new' && !$this->allowBlankSummary ) {
1061 if ( trim( $this->summary ) == '' ) {
1062 $this->missingSummary = true;
1063 wfProfileOut( __METHOD__ );
1064 return self::AS_SUMMARY_NEEDED;
1065 }
1066 }
1067
1068 # All's well
1069 wfProfileIn( __METHOD__ . '-sectionanchor' );
1070 $sectionanchor = '';
1071 if ( $this->section == 'new' ) {
1072 if ( $this->textbox1 == '' ) {
1073 $this->missingComment = true;
1074 wfProfileOut( __METHOD__ . '-sectionanchor' );
1075 wfProfileOut( __METHOD__ );
1076 return self::AS_TEXTBOX_EMPTY;
1077 }
1078 if ( $this->summary != '' ) {
1079 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary );
1080 # This is a new section, so create a link to the new section
1081 # in the revision summary.
1082 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1083 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
1084 }
1085 } elseif ( $this->section != '' ) {
1086 # Try to get a section anchor from the section source, redirect to edited section if header found
1087 # XXX: might be better to integrate this into Article::replaceSection
1088 # for duplicate heading checking and maybe parsing
1089 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1090 # we can't deal with anchors, includes, html etc in the header for now,
1091 # headline would need to be parsed to improve this
1092 if ( $hasmatch and strlen( $matches[2] ) > 0 ) {
1093 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
1094 }
1095 }
1096 wfProfileOut( __METHOD__ . '-sectionanchor' );
1097
1098 // Save errors may fall down to the edit form, but we've now
1099 // merged the section into full text. Clear the section field
1100 // so that later submission of conflict forms won't try to
1101 // replace that into a duplicated mess.
1102 $this->textbox1 = $text;
1103 $this->section = '';
1104
1105 // Check for length errors again now that the section is merged in
1106 $this->kblength = (int)( strlen( $text ) / 1024 );
1107 if ( $this->kblength > $wgMaxArticleSize ) {
1108 $this->tooBig = true;
1109 wfProfileOut( __METHOD__ );
1110 return self::AS_MAX_ARTICLE_SIZE_EXCEEDED;
1111 }
1112
1113 # update the article here
1114 if ( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
1115 $this->watchthis, $bot, $sectionanchor ) )
1116 {
1117 wfProfileOut( __METHOD__ );
1118 return self::AS_SUCCESS_UPDATE;
1119 } else {
1120 $this->isConflict = true;
1121 }
1122 wfProfileOut( __METHOD__ );
1123 return self::AS_END;
1124 }
1125
1126 /**
1127 * Check if no edits were made by other users since
1128 * the time a user started editing the page. Limit to
1129 * 50 revisions for the sake of performance.
1130 */
1131 protected function userWasLastToEdit( $id, $edittime ) {
1132 if( !$id ) return false;
1133 $dbw = wfGetDB( DB_MASTER );
1134 $res = $dbw->select( 'revision',
1135 'rev_user',
1136 array(
1137 'rev_page' => $this->mArticle->getId(),
1138 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1139 ),
1140 __METHOD__,
1141 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1142 while( $row = $res->fetchObject() ) {
1143 if( $row->rev_user != $id ) {
1144 return false;
1145 }
1146 }
1147 return true;
1148 }
1149
1150 /**
1151 * Check given input text against $wgSpamRegex, and return the text of the first match.
1152 * @return mixed -- matching string or false
1153 */
1154 public static function matchSpamRegex( $text ) {
1155 global $wgSpamRegex;
1156 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1157 $regexes = (array)$wgSpamRegex;
1158 return self::matchSpamRegexInternal( $text, $regexes );
1159 }
1160
1161 /**
1162 * Check given input text against $wgSpamRegex, and return the text of the first match.
1163 * @return mixed -- matching string or false
1164 */
1165 public static function matchSummarySpamRegex( $text ) {
1166 global $wgSummarySpamRegex;
1167 $regexes = (array)$wgSummarySpamRegex;
1168 return self::matchSpamRegexInternal( $text, $regexes );
1169 }
1170
1171 protected static function matchSpamRegexInternal( $text, $regexes ) {
1172 foreach( $regexes as $regex ) {
1173 $matches = array();
1174 if( preg_match( $regex, $text, $matches ) ) {
1175 return $matches[0];
1176 }
1177 }
1178 return false;
1179 }
1180
1181 /**
1182 * Initialise form fields in the object
1183 * Called on the first invocation, e.g. when a user clicks an edit link
1184 * @returns bool -- if the requested section is valid
1185 */
1186 function initialiseForm() {
1187 global $wgUser;
1188 $this->edittime = $this->mArticle->getTimestamp();
1189 $this->textbox1 = $this->getContent( false );
1190 // activate checkboxes if user wants them to be always active
1191 # Sort out the "watch" checkbox
1192 if ( $wgUser->getOption( 'watchdefault' ) ) {
1193 # Watch all edits
1194 $this->watchthis = true;
1195 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1196 # Watch creations
1197 $this->watchthis = true;
1198 } elseif ( $this->mTitle->userIsWatching() ) {
1199 # Already watched
1200 $this->watchthis = true;
1201 }
1202 if ( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1203 if ( $this->textbox1 === false ) return false;
1204 wfProxyCheck();
1205 return true;
1206 }
1207
1208 function setHeaders() {
1209 global $wgOut, $wgTitle;
1210 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1211 if ( $this->formtype == 'preview' ) {
1212 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1213 }
1214 if ( $this->isConflict ) {
1215 $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) );
1216 } elseif ( $this->section != '' ) {
1217 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
1218 $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->getPrefixedText() ) );
1219 } else {
1220 # Use the title defined by DISPLAYTITLE magic word when present
1221 if ( isset( $this->mParserOutput )
1222 && ( $dt = $this->mParserOutput->getDisplayTitle() ) !== false ) {
1223 $title = $dt;
1224 } else {
1225 $title = $wgTitle->getPrefixedText();
1226 }
1227 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1228 }
1229 }
1230
1231 /**
1232 * Send the edit form and related headers to $wgOut
1233 * @param $formCallback Optional callable that takes an OutputPage
1234 * parameter; will be called during form output
1235 * near the top, for captchas and the like.
1236 */
1237 function showEditForm( $formCallback=null ) {
1238 global $wgOut, $wgUser, $wgTitle;
1239
1240 # If $wgTitle is null, that means we're in API mode.
1241 # Some hook probably called this function without checking
1242 # for is_null($wgTitle) first. Bail out right here so we don't
1243 # do lots of work just to discard it right after.
1244 if ( is_null( $wgTitle ) )
1245 return;
1246
1247 wfProfileIn( __METHOD__ );
1248
1249 $sk = $wgUser->getSkin();
1250
1251 #need to parse the preview early so that we know which templates are used,
1252 #otherwise users with "show preview after edit box" will get a blank list
1253 #we parse this near the beginning so that setHeaders can do the title
1254 #setting work instead of leaving it in getPreviewText
1255 $previewOutput = '';
1256 if ( $this->formtype == 'preview' ) {
1257 $previewOutput = $this->getPreviewText();
1258 }
1259
1260 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1261
1262 $this->setHeaders();
1263
1264 # Enabled article-related sidebar, toplinks, etc.
1265 $wgOut->setArticleRelated( true );
1266
1267 if ( $this->showHeader() === false )
1268 return;
1269
1270 $action = htmlspecialchars($this->getActionURL($wgTitle));
1271
1272 if ( $wgUser->getOption( 'showtoolbar' ) and !$this->isCssJsSubpage ) {
1273 # prepare toolbar for edit buttons
1274 $toolbar = EditPage::getEditToolbar();
1275 } else {
1276 $toolbar = '';
1277 }
1278
1279
1280 $wgOut->addHTML( $this->editFormPageTop );
1281
1282 if ( $wgUser->getOption( 'previewontop' ) ) {
1283 $this->displayPreviewArea( $previewOutput, true );
1284 }
1285
1286 $wgOut->addHTML( $this->editFormTextTop );
1287
1288 $templates = $this->getTemplates();
1289 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1290
1291 $hiddencats = $this->mArticle->getHiddenCategories();
1292 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1293
1294 if ( $this->wasDeletedSinceLastEdit() && 'save' != $this->formtype ) {
1295 $wgOut->wrapWikiMsg(
1296 "<div class='error mw-deleted-while-editing'>\n$1</div>",
1297 'deletedwhileediting' );
1298 } elseif ( $this->wasDeletedSinceLastEdit() ) {
1299 // Hide the toolbar and edit area, user can click preview to get it back
1300 // Add an confirmation checkbox and explanation.
1301 $toolbar = '';
1302 // @todo move this to a cleaner conditional instead of blanking a variable
1303 }
1304 $wgOut->addHTML( <<<HTML
1305 {$toolbar}
1306 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1307 HTML
1308 );
1309
1310 if ( is_callable( $formCallback ) ) {
1311 call_user_func_array( $formCallback, array( &$wgOut ) );
1312 }
1313
1314 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1315
1316 // Put these up at the top to ensure they aren't lost on early form submission
1317 $this->showFormBeforeText();
1318
1319 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
1320 $wgOut->addHTML(
1321 '<div class="mw-confirm-recreate">' .
1322 $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ) ) .
1323 Xml::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1324 array( 'title' => $sk->titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1325 ) .
1326 '</div>'
1327 );
1328 }
1329
1330 # If a blank edit summary was previously provided, and the appropriate
1331 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1332 # user being bounced back more than once in the event that a summary
1333 # is not required.
1334 #####
1335 # For a bit more sophisticated detection of blank summaries, hash the
1336 # automatic one and pass that in the hidden field wpAutoSummary.
1337 if ( $this->missingSummary ||
1338 ( $this->section == 'new' && $this->nosummary ) )
1339 $wgOut->addHTML( Xml::hidden( 'wpIgnoreBlankSummary', true ) );
1340 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1341 $wgOut->addHTML( Xml::hidden( 'wpAutoSummary', $autosumm ) );
1342
1343 $wgOut->addHTML( Xml::hidden( 'oldid', $this->mArticle->getOldID() ) );
1344
1345 if ( $this->section == 'new' ) {
1346 $this->showSummaryInput( true, $this->summary );
1347 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
1348 }
1349
1350 $wgOut->addHTML( $this->editFormTextBeforeContent );
1351
1352 if ( $this->isConflict ) {
1353 // In an edit conflict bypass the overrideable content form method
1354 // and fallback to the raw wpTextbox1 since editconflicts can't be
1355 // resolved between page source edits and custom ui edits using the
1356 // custom edit ui.
1357 $this->showTextbox1();
1358 } else {
1359 $this->showContentForm();
1360 }
1361
1362 $wgOut->addHTML( $this->editFormTextAfterContent );
1363
1364 $wgOut->addWikiText( $this->getCopywarn() );
1365 if ( isset($this->editFormTextAfterWarn) && $this->editFormTextAfterWarn !== '' )
1366 $wgOut->addHTML( $this->editFormTextAfterWarn );
1367
1368 global $wgUseMetadataEdit;
1369 if ( $wgUseMetadataEdit )
1370 $this->showMetaData();
1371
1372 $this->showStandardInputs();
1373
1374 $this->showFormAfterText();
1375
1376 $this->showTosSummary();
1377 $this->showEditTools();
1378
1379 $wgOut->addHTML( <<<HTML
1380 {$this->editFormTextAfterTools}
1381 <div class='templatesUsed'>
1382 {$formattedtemplates}
1383 </div>
1384 <div class='hiddencats'>
1385 {$formattedhiddencats}
1386 </div>
1387 HTML
1388 );
1389
1390 if ( $this->isConflict )
1391 $this->showConflict();
1392
1393 $wgOut->addHTML( $this->editFormTextBottom );
1394 $wgOut->addHTML( "</form>\n" );
1395 if ( !$wgUser->getOption( 'previewontop' ) ) {
1396 $this->displayPreviewArea( $previewOutput, false );
1397 }
1398
1399 wfProfileOut( __METHOD__ );
1400 }
1401
1402 protected function showHeader() {
1403 global $wgOut, $wgUser, $wgTitle, $wgMaxArticleSize, $wgLang;
1404 if ( $this->isConflict ) {
1405 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1</div>", 'explainconflict' );
1406 $this->edittime = $this->mArticle->getTimestamp();
1407 } else {
1408 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
1409 // We use $this->section to much before this and getVal('wgSection') directly in other places
1410 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1411 // Someone is welcome to try refactoring though
1412 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1413 return false;
1414 }
1415
1416 if ( $this->section != '' && $this->section != 'new' ) {
1417 $matches = array();
1418 if ( !$this->summary && !$this->preview && !$this->diff ) {
1419 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1, $matches );
1420 if ( !empty( $matches[2] ) ) {
1421 global $wgParser;
1422 $this->summary = "/* " .
1423 $wgParser->stripSectionName(trim($matches[2])) .
1424 " */ ";
1425 }
1426 }
1427 }
1428
1429 if ( $this->missingComment ) {
1430 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1</div>", 'missingcommenttext' );
1431 }
1432
1433 if ( $this->missingSummary && $this->section != 'new' ) {
1434 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1</div>", 'missingsummary' );
1435 }
1436
1437 if ( $this->missingSummary && $this->section == 'new' ) {
1438 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1</div>", 'missingcommentheader' );
1439 }
1440
1441 if ( $this->hookError !== '' ) {
1442 $wgOut->addWikiText( $this->hookError );
1443 }
1444
1445 if ( !$this->checkUnicodeCompliantBrowser() ) {
1446 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1447 }
1448
1449 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
1450 // Let sysop know that this will make private content public if saved
1451
1452 if ( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1453 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
1454 } else if ( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1455 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
1456 }
1457
1458 if ( !$this->mArticle->mRevision->isCurrent() ) {
1459 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
1460 $wgOut->addWikiMsg( 'editingold' );
1461 }
1462 }
1463 }
1464
1465 if ( wfReadOnly() ) {
1466 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1467 } elseif ( $wgUser->isAnon() && $this->formtype != 'preview' ) {
1468 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1469 } else {
1470 if ( $this->isCssJsSubpage ) {
1471 # Check the skin exists
1472 if ( !$this->isValidCssJsSubpage ) {
1473 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1474 }
1475 if ( $this->formtype !== 'preview' ) {
1476 if ( $this->isCssSubpage )
1477 $wgOut->addWikiMsg( 'usercssyoucanpreview' );
1478 if ( $this->isJsSubpage )
1479 $wgOut->addWikiMsg( 'userjsyoucanpreview' );
1480 }
1481 }
1482 }
1483
1484 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
1485 # Is the title semi-protected?
1486 if ( $this->mTitle->isSemiProtected() ) {
1487 $noticeMsg = 'semiprotectedpagewarning';
1488 } else {
1489 # Then it must be protected based on static groups (regular)
1490 $noticeMsg = 'protectedpagewarning';
1491 }
1492 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle->getPrefixedText(), '',
1493 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1494 }
1495 if ( $this->mTitle->isCascadeProtected() ) {
1496 # Is this page under cascading protection from some source pages?
1497 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1498 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
1499 $cascadeSourcesCount = count( $cascadeSources );
1500 if ( $cascadeSourcesCount > 0 ) {
1501 # Explain, and list the titles responsible
1502 foreach( $cascadeSources as $page ) {
1503 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1504 }
1505 }
1506 $notice .= '</div>';
1507 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1508 }
1509 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
1510 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle->getPrefixedText(), '',
1511 array( 'lim' => 1,
1512 'showIfEmpty' => false,
1513 'msgKey' => array( 'titleprotectedwarning' ),
1514 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
1515 }
1516
1517 if ( $this->kblength === false ) {
1518 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1519 }
1520
1521 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1522 $wgOut->addHTML( "<div class='error' id='mw-edit-longpageerror'>\n" );
1523 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) );
1524 $wgOut->addHTML( "</div>\n" );
1525 } elseif ( $this->kblength > 29 ) {
1526 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1527 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) );
1528 $wgOut->addHTML( "</div>\n" );
1529 }
1530 }
1531
1532 /**
1533 * Standard summary input and label (wgSummary), abstracted so EditPage
1534 * subclasses may reorganize the form.
1535 * Note that you do not need to worry about the label's for=, it will be
1536 * inferred by the id given to the input. You can remove them both by
1537 * passing array( 'id' => false ) to $userInputAttrs.
1538 *
1539 * @param $summary The value of the summary input
1540 * @param $labelText The html to place inside the label
1541 * @param $userInputAttrs An array of attrs to use on the input
1542 * @param $userSpanAttrs An array of attrs to use on the span inside the label
1543 *
1544 * @return array An array in the format array( $label, $input )
1545 */
1546 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
1547 $inputAttrs = ( is_array($inputAttrs) ? $inputAttrs : array() ) + array(
1548 'id' => 'wpSummary',
1549 'maxlength' => '200',
1550 'tabindex' => '2',
1551 'size' => 60,
1552 'spellcheck' => 'true',
1553 );
1554
1555 $spanLabelAttrs = ( is_array($spanLabelAttrs) ? $spanLabelAttrs : array() ) + array(
1556 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
1557 'id' => "wpSummaryLabel"
1558 );
1559
1560 $label = null;
1561 if ( $labelText ) {
1562 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1563 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
1564 }
1565
1566 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
1567
1568 return array( $label, $input );
1569 }
1570
1571 /**
1572 * @param bool $isSubjectPreview true if this is the section subject/title
1573 * up top, or false if this is the comment
1574 * summary down below the textarea
1575 * @param string $summary The text of the summary to display
1576 * @return string
1577 */
1578 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1579 global $wgOut, $wgContLang;
1580 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1581 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
1582 if ( $isSubjectPreview ) {
1583 if ( $this->nosummary )
1584 return;
1585 } else {
1586 if ( !$this->mShowSummaryField )
1587 return;
1588 }
1589 $summary = $wgContLang->recodeForEdit( $summary );
1590 $labelText = wfMsgExt( $isSubjectPreview ? 'subject' : 'summary', 'parseinline' );
1591 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
1592 $wgOut->addHTML("{$label} {$input}");
1593 }
1594
1595 /**
1596 * @param bool $isSubjectPreview true if this is the section subject/title
1597 * up top, or false if this is the comment
1598 * summary down below the textarea
1599 * @param string $summary The text of the summary to display
1600 * @return string
1601 */
1602 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
1603 if ( !$summary || ( !$this->preview && !$this->diff ) )
1604 return "";
1605
1606 global $wgParser, $wgUser;
1607 $sk = $wgUser->getSkin();
1608
1609 if ( $isSubjectPreview )
1610 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
1611
1612 $summary = wfMsgExt( 'subject-preview', 'parseinline' ) . $sk->commentBlock( $summary, $this->mTitle, !!$isSubjectPreview );
1613 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
1614 }
1615
1616 protected function showFormBeforeText() {
1617 global $wgOut;
1618 $section = htmlspecialchars( $this->section );
1619 $wgOut->addHTML( <<<INPUTS
1620 <input type='hidden' value="{$section}" name="wpSection" />
1621 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
1622 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
1623 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
1624
1625 INPUTS
1626 );
1627 if ( !$this->checkUnicodeCompliantBrowser() )
1628 $wgOut->addHTML(Xml::hidden( 'safemode', '1' ));
1629 }
1630
1631 protected function showFormAfterText() {
1632 global $wgOut, $wgUser;
1633 /**
1634 * To make it harder for someone to slip a user a page
1635 * which submits an edit form to the wiki without their
1636 * knowledge, a random token is associated with the login
1637 * session. If it's not passed back with the submission,
1638 * we won't save the page, or render user JavaScript and
1639 * CSS previews.
1640 *
1641 * For anon editors, who may not have a session, we just
1642 * include the constant suffix to prevent editing from
1643 * broken text-mangling proxies.
1644 */
1645 $wgOut->addHTML( "\n" . Xml::hidden( "wpEditToken", $wgUser->editToken() ) . "\n" );
1646 }
1647
1648 /**
1649 * Subpage overridable method for printing the form for page content editing
1650 * By default this simply outputs wpTextbox1
1651 * Subclasses can override this to provide a custom UI for editing;
1652 * be it a form, or simply wpTextbox1 with a modified content that will be
1653 * reverse modified when extracted from the post data.
1654 * Note that this is basically the inverse for importContentFormData
1655 *
1656 * @praram WebRequest $request
1657 */
1658 protected function showContentForm() {
1659 $this->showTextbox1();
1660 }
1661
1662 /**
1663 * Method to output wpTextbox1
1664 * The $textoverride method can be used by subclasses overriding showContentForm
1665 * to pass back to this method.
1666 *
1667 * @param array $customAttribs An array of html attributes to use in the textarea
1668 * @param string $textoverride Optional text to override $this->textarea1 with
1669 */
1670 protected function showTextbox1($customAttribs = null, $textoverride = null) {
1671 $classes = array(); // Textarea CSS
1672 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
1673 # Is the title semi-protected?
1674 if ( $this->mTitle->isSemiProtected() ) {
1675 $classes[] = 'mw-textarea-sprotected';
1676 } else {
1677 # Then it must be protected based on static groups (regular)
1678 $classes[] = 'mw-textarea-protected';
1679 }
1680 }
1681 $attribs = array( 'tabindex' => 1 );
1682 if ( is_array($customAttribs) )
1683 $attribs += $customAttribs;
1684
1685 if ( $this->wasDeletedSinceLastEdit() )
1686 $attribs['type'] = 'hidden';
1687 if ( !empty( $classes ) ) {
1688 if ( isset($attribs['class']) )
1689 $classes[] = $attribs['class'];
1690 $attribs['class'] = implode( ' ', $classes );
1691 }
1692
1693 $this->showTextbox( isset($textoverride) ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
1694 }
1695
1696 protected function showTextbox2() {
1697 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6 ) );
1698 }
1699
1700 protected function showTextbox( $content, $name, $customAttribs = array() ) {
1701 global $wgOut, $wgUser;
1702
1703 $wikitext = $this->safeUnicodeOutput( $content );
1704 if ( $wikitext !== '' ) {
1705 // Ensure there's a newline at the end, otherwise adding lines
1706 // is awkward.
1707 // But don't add a newline if the ext is empty, or Firefox in XHTML
1708 // mode will show an extra newline. A bit annoying.
1709 $wikitext .= "\n";
1710 }
1711
1712 $attribs = $customAttribs + array(
1713 'accesskey' => ',',
1714 'id' => $name,
1715 'cols' => $wgUser->getIntOption( 'cols' ),
1716 'rows' => $wgUser->getIntOption( 'rows' ),
1717 'style' => '' // avoid php notices when appending for editwidth preference (appending allows customAttribs['style'] to still work
1718 );
1719
1720 if ( $wgUser->getOption( 'editwidth' ) )
1721 $attribs['style'] .= 'width: 100%';
1722
1723 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
1724 }
1725
1726 protected function showMetaData() {
1727 global $wgOut, $wgContLang, $wgUser;
1728 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $this->mMetaData ) );
1729 $ew = $wgUser->getOption( 'editwidth' ) ? ' style="width:100%"' : '';
1730 $cols = $wgUser->getIntOption( 'cols' );
1731 $metadata = wfMsgWikiHtml( 'metadata_help' ) . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1732 $wgOut->addHTML( $metadata );
1733 }
1734
1735 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1736 global $wgOut;
1737 $classes = array();
1738 if ( $isOnTop )
1739 $classes[] = 'ontop';
1740
1741 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1742
1743 if ( $this->formtype != 'preview' )
1744 $attribs['style'] = 'display: none;';
1745
1746 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
1747
1748 if ( $this->formtype == 'preview' ) {
1749 $this->showPreview( $previewOutput );
1750 }
1751
1752 $wgOut->addHTML( '</div>' );
1753
1754 if ( $this->formtype == 'diff') {
1755 $this->showDiff();
1756 }
1757 }
1758
1759 /**
1760 * Append preview output to $wgOut.
1761 * Includes category rendering if this is a category page.
1762 *
1763 * @param string $text The HTML to be output for the preview.
1764 */
1765 protected function showPreview( $text ) {
1766 global $wgOut;
1767 if ( $this->mTitle->getNamespace() == NS_CATEGORY) {
1768 $this->mArticle->openShowCategory();
1769 }
1770 # This hook seems slightly odd here, but makes things more
1771 # consistent for extensions.
1772 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1773 $wgOut->addHTML( $text );
1774 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1775 $this->mArticle->closeShowCategory();
1776 }
1777 }
1778
1779 protected function showTosSummary() {
1780 $msg = 'editpage-tos-summary';
1781 // Give a chance for site and per-namespace customizations of
1782 // terms of service summary link that might exist separately
1783 // from the copyright notice.
1784 //
1785 // This will display between the save button and the edit tools,
1786 // so should remain short!
1787 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
1788 $text = wfMsg( $msg );
1789 if( !wfEmptyMsg( $msg, $text ) && $text !== '-' ) {
1790 global $wgOut;
1791 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1792 $wgOut->addWikiMsgArray( $msg, array() );
1793 $wgOut->addHTML( '</div>' );
1794 }
1795 }
1796
1797 protected function showEditTools() {
1798 global $wgOut;
1799 $wgOut->addHTML( '<div class="mw-editTools">' );
1800 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1801 $wgOut->addHTML( '</div>' );
1802 }
1803
1804 protected function getCopywarn() {
1805 global $wgRightsText;
1806 if ( $wgRightsText ) {
1807 $copywarnMsg = array( 'copyrightwarning',
1808 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1809 $wgRightsText );
1810 } else {
1811 $copywarnMsg = array( 'copyrightwarning2',
1812 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1813 }
1814 // Allow for site and per-namespace customization of contribution/copyright notice.
1815 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
1816
1817 return "<div id=\"editpage-copywarn\">\n" . call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
1818 }
1819
1820 protected function showStandardInputs( &$tabindex = 2 ) {
1821 global $wgOut, $wgUser;
1822 $wgOut->addHTML( "<div class='editOptions'>\n" );
1823
1824 if ( $this->section != 'new' ) {
1825 $this->showSummaryInput( false, $this->summary );
1826 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
1827 }
1828
1829 $checkboxes = $this->getCheckboxes( $tabindex, $wgUser->getSkin(),
1830 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1831 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
1832 $wgOut->addHTML( "<div class='editButtons'>\n" );
1833 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
1834
1835 $cancel = $this->getCancelLink();
1836 $separator = wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1837 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
1838 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1839 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1840 htmlspecialchars( wfMsg( 'newwindow' ) );
1841 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span>\n" );
1842 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
1843 }
1844
1845 protected function showConflict() {
1846 global $wgOut;
1847 $this->textbox2 = $this->textbox1;
1848 $this->textbox1 = $this->getContent();
1849 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1850 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
1851
1852 $de = new DifferenceEngine( $this->mTitle );
1853 $de->setText( $this->textbox2, $this->textbox1 );
1854 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1855
1856 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
1857 $this->showTextbox2();
1858 }
1859 }
1860
1861 protected function getLastDelete() {
1862 $dbr = wfGetDB( DB_SLAVE );
1863 $data = $dbr->selectRow(
1864 array( 'logging', 'user' ),
1865 array( 'log_type',
1866 'log_action',
1867 'log_timestamp',
1868 'log_user',
1869 'log_namespace',
1870 'log_title',
1871 'log_comment',
1872 'log_params',
1873 'log_deleted',
1874 'user_name' ),
1875 array( 'log_namespace' => $this->mTitle->getNamespace(),
1876 'log_title' => $this->mTitle->getDBkey(),
1877 'log_type' => 'delete',
1878 'log_action' => 'delete',
1879 'user_id=log_user' ),
1880 __METHOD__,
1881 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1882 );
1883 // Quick paranoid permission checks...
1884 if( is_object( $data ) ) {
1885 if( $data->log_deleted & LogPage::DELETED_USER )
1886 $data->user_name = wfMsgHtml( 'rev-deleted-user' );
1887 if( $data->log_deleted & LogPage::DELETED_COMMENT )
1888 $data->log_comment = wfMsgHtml( 'rev-deleted-comment' );
1889 }
1890 return $data;
1891 }
1892
1893 /**
1894 * Get the rendered text for previewing.
1895 * @return string
1896 */
1897 function getPreviewText() {
1898 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
1899
1900 wfProfileIn( __METHOD__ );
1901
1902 if ( $this->mTriedSave && !$this->mTokenOk ) {
1903 if ( $this->mTokenOkExceptSuffix ) {
1904 $note = wfMsg( 'token_suffix_mismatch' );
1905 } else {
1906 $note = wfMsg( 'session_fail_preview' );
1907 }
1908 } else {
1909 $note = wfMsg( 'previewnote' );
1910 }
1911
1912 $parserOptions = ParserOptions::newFromUser( $wgUser );
1913 $parserOptions->setEditSection( false );
1914 $parserOptions->setIsPreview( true );
1915 $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
1916
1917 global $wgRawHtml;
1918 if ( $wgRawHtml && !$this->mTokenOk ) {
1919 // Could be an offsite preview attempt. This is very unsafe if
1920 // HTML is enabled, as it could be an attack.
1921 return $wgOut->parse( "<div class='previewnote'>" .
1922 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1923 }
1924
1925 # don't parse user css/js, show message about preview
1926 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1927
1928 if ( $this->isCssJsSubpage ) {
1929 if (preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
1930 $previewtext = wfMsg( 'usercsspreview' );
1931 } else if (preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
1932 $previewtext = wfMsg( 'userjspreview' );
1933 }
1934 $parserOptions->setTidy( true );
1935 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
1936 $previewHTML = $parserOutput->mText;
1937 } elseif ( $rt = Title::newFromRedirectArray( $this->textbox1 ) ) {
1938 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
1939 } else {
1940 $toparse = $this->textbox1;
1941
1942 # If we're adding a comment, we need to show the
1943 # summary as the headline
1944 if ( $this->section == "new" && $this->summary != "" ) {
1945 $toparse="== {$this->summary} ==\n\n" . $toparse;
1946 }
1947
1948 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData;
1949
1950 // Parse mediawiki messages with correct target language
1951 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1952 list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle->getText() );
1953 $obj = wfGetLangObj( $lang );
1954 $parserOptions->setTargetLanguage( $obj );
1955 }
1956
1957
1958 $parserOptions->setTidy( true );
1959 $parserOptions->enableLimitReport();
1960 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ),
1961 $this->mTitle, $parserOptions );
1962
1963 $previewHTML = $parserOutput->getText();
1964 $this->mParserOutput = $parserOutput;
1965 $wgOut->addParserOutputNoText( $parserOutput );
1966
1967 if ( count( $parserOutput->getWarnings() ) ) {
1968 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1969 }
1970 }
1971
1972 if( $this->isConflict ) {
1973 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1974 } else {
1975 $conflict = '<hr />';
1976 }
1977
1978 $previewhead = "<div class='previewnote'>\n" .
1979 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
1980 $wgOut->parse( $note ) . $conflict . "</div>\n";
1981
1982 wfProfileOut( __METHOD__ );
1983 return $previewhead . $previewHTML . $this->previewTextAfterContent;
1984 }
1985
1986 function getTemplates() {
1987 if ( $this->preview || $this->section != '' ) {
1988 $templates = array();
1989 if ( !isset( $this->mParserOutput ) ) return $templates;
1990 foreach( $this->mParserOutput->getTemplates() as $ns => $template) {
1991 foreach( array_keys( $template ) as $dbk ) {
1992 $templates[] = Title::makeTitle($ns, $dbk);
1993 }
1994 }
1995 return $templates;
1996 } else {
1997 return $this->mArticle->getUsedTemplates();
1998 }
1999 }
2000
2001 /**
2002 * Call the stock "user is blocked" page
2003 */
2004 function blockedPage() {
2005 global $wgOut;
2006 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
2007
2008 # If the user made changes, preserve them when showing the markup
2009 # (This happens when a user is blocked during edit, for instance)
2010 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
2011 if ( $first ) {
2012 $source = $this->mTitle->exists() ? $this->getContent() : false;
2013 } else {
2014 $source = $this->textbox1;
2015 }
2016
2017 # Spit out the source or the user's modified version
2018 if ( $source !== false ) {
2019 $wgOut->addHTML( '<hr />' );
2020 $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() );
2021 $this->showTextbox1( array( 'readonly' ), $source );
2022 }
2023 }
2024
2025 /**
2026 * Produce the stock "please login to edit pages" page
2027 */
2028 function userNotLoggedInPage() {
2029 global $wgUser, $wgOut, $wgTitle;
2030 $skin = $wgUser->getSkin();
2031
2032 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
2033 $loginLink = $skin->link(
2034 $loginTitle,
2035 wfMsgHtml( 'loginreqlink' ),
2036 array(),
2037 array( 'returnto' => $wgTitle->getPrefixedText() ),
2038 array( 'known', 'noclasses' )
2039 );
2040
2041 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
2042 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2043 $wgOut->setArticleRelated( false );
2044
2045 $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
2046 $wgOut->returnToMain( false, $wgTitle );
2047 }
2048
2049 /**
2050 * Creates a basic error page which informs the user that
2051 * they have attempted to edit a nonexistent section.
2052 */
2053 function noSuchSectionPage() {
2054 global $wgOut;
2055
2056 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
2057 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2058 $wgOut->setArticleRelated( false );
2059
2060 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section );
2061 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2062 $wgOut->addHTML( $res );
2063
2064 $wgOut->returnToMain( false, $this->mTitle );
2065 }
2066
2067 /**
2068 * Produce the stock "your edit contains spam" page
2069 *
2070 * @param $match Text which triggered one or more filters
2071 */
2072 function spamPage( $match = false ) {
2073 global $wgOut, $wgTitle;
2074
2075 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
2076 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2077 $wgOut->setArticleRelated( false );
2078
2079 $wgOut->addHTML( '<div id="spamprotected">' );
2080 $wgOut->addWikiMsg( 'spamprotectiontext' );
2081 if ( $match )
2082 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2083 $wgOut->addHTML( '</div>' );
2084
2085 $wgOut->returnToMain( false, $wgTitle );
2086 }
2087
2088 /**
2089 * @private
2090 * @todo document
2091 */
2092 function mergeChangesInto( &$editText ){
2093 wfProfileIn( __METHOD__ );
2094
2095 $db = wfGetDB( DB_MASTER );
2096
2097 // This is the revision the editor started from
2098 $baseRevision = $this->getBaseRevision();
2099 if ( is_null( $baseRevision ) ) {
2100 wfProfileOut( __METHOD__ );
2101 return false;
2102 }
2103 $baseText = $baseRevision->getText();
2104
2105 // The current state, we want to merge updates into it
2106 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2107 if ( is_null( $currentRevision ) ) {
2108 wfProfileOut( __METHOD__ );
2109 return false;
2110 }
2111 $currentText = $currentRevision->getText();
2112
2113 $result = '';
2114 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
2115 $editText = $result;
2116 wfProfileOut( __METHOD__ );
2117 return true;
2118 } else {
2119 wfProfileOut( __METHOD__ );
2120 return false;
2121 }
2122 }
2123
2124 /**
2125 * Check if the browser is on a blacklist of user-agents known to
2126 * mangle UTF-8 data on form submission. Returns true if Unicode
2127 * should make it through, false if it's known to be a problem.
2128 * @return bool
2129 * @private
2130 */
2131 function checkUnicodeCompliantBrowser() {
2132 global $wgBrowserBlackList;
2133 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2134 // No User-Agent header sent? Trust it by default...
2135 return true;
2136 }
2137 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2138 foreach ( $wgBrowserBlackList as $browser ) {
2139 if ( preg_match($browser, $currentbrowser) ) {
2140 return false;
2141 }
2142 }
2143 return true;
2144 }
2145
2146 /**
2147 * @deprecated use $wgParser->stripSectionName()
2148 */
2149 function pseudoParseSectionAnchor( $text ) {
2150 global $wgParser;
2151 return $wgParser->stripSectionName( $text );
2152 }
2153
2154 /**
2155 * Format an anchor fragment as it would appear for a given section name
2156 * @param string $text
2157 * @return string
2158 * @private
2159 */
2160 function sectionAnchor( $text ) {
2161 global $wgParser;
2162 return $wgParser->guessSectionNameFromWikiText( $text );
2163 }
2164
2165 /**
2166 * Shows a bulletin board style toolbar for common editing functions.
2167 * It can be disabled in the user preferences.
2168 * The necessary JavaScript code can be found in skins/common/edit.js.
2169 *
2170 * @return string
2171 */
2172 static function getEditToolbar() {
2173 global $wgStylePath, $wgContLang, $wgLang;
2174
2175 /**
2176
2177 * toolarray an array of arrays which each include the filename of
2178 * the button image (without path), the opening tag, the closing tag,
2179 * and optionally a sample text that is inserted between the two when no
2180 * selection is highlighted.
2181 * The tip text is shown when the user moves the mouse over the button.
2182 *
2183 * Already here are accesskeys (key), which are not used yet until someone
2184 * can figure out a way to make them work in IE. However, we should make
2185 * sure these keys are not defined on the edit page.
2186 */
2187 $toolarray = array(
2188 array(
2189 'image' => $wgLang->getImageFile( 'button-bold' ),
2190 'id' => 'mw-editbutton-bold',
2191 'open' => '\'\'\'',
2192 'close' => '\'\'\'',
2193 'sample' => wfMsg( 'bold_sample' ),
2194 'tip' => wfMsg( 'bold_tip' ),
2195 'key' => 'B'
2196 ),
2197 array(
2198 'image' => $wgLang->getImageFile( 'button-italic' ),
2199 'id' => 'mw-editbutton-italic',
2200 'open' => '\'\'',
2201 'close' => '\'\'',
2202 'sample' => wfMsg( 'italic_sample' ),
2203 'tip' => wfMsg( 'italic_tip' ),
2204 'key' => 'I'
2205 ),
2206 array(
2207 'image' => $wgLang->getImageFile( 'button-link' ),
2208 'id' => 'mw-editbutton-link',
2209 'open' => '[[',
2210 'close' => ']]',
2211 'sample' => wfMsg( 'link_sample' ),
2212 'tip' => wfMsg( 'link_tip' ),
2213 'key' => 'L'
2214 ),
2215 array(
2216 'image' => $wgLang->getImageFile( 'button-extlink' ),
2217 'id' => 'mw-editbutton-extlink',
2218 'open' => '[',
2219 'close' => ']',
2220 'sample' => wfMsg( 'extlink_sample' ),
2221 'tip' => wfMsg( 'extlink_tip' ),
2222 'key' => 'X'
2223 ),
2224 array(
2225 'image' => $wgLang->getImageFile( 'button-headline' ),
2226 'id' => 'mw-editbutton-headline',
2227 'open' => "\n== ",
2228 'close' => " ==\n",
2229 'sample' => wfMsg( 'headline_sample' ),
2230 'tip' => wfMsg( 'headline_tip' ),
2231 'key' => 'H'
2232 ),
2233 array(
2234 'image' => $wgLang->getImageFile( 'button-image' ),
2235 'id' => 'mw-editbutton-image',
2236 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
2237 'close' => ']]',
2238 'sample' => wfMsg( 'image_sample' ),
2239 'tip' => wfMsg( 'image_tip' ),
2240 'key' => 'D'
2241 ),
2242 array(
2243 'image' => $wgLang->getImageFile( 'button-media' ),
2244 'id' => 'mw-editbutton-media',
2245 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
2246 'close' => ']]',
2247 'sample' => wfMsg( 'media_sample' ),
2248 'tip' => wfMsg( 'media_tip' ),
2249 'key' => 'M'
2250 ),
2251 array(
2252 'image' => $wgLang->getImageFile( 'button-math' ),
2253 'id' => 'mw-editbutton-math',
2254 'open' => "<math>",
2255 'close' => "</math>",
2256 'sample' => wfMsg( 'math_sample' ),
2257 'tip' => wfMsg( 'math_tip' ),
2258 'key' => 'C'
2259 ),
2260 array(
2261 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2262 'id' => 'mw-editbutton-nowiki',
2263 'open' => "<nowiki>",
2264 'close' => "</nowiki>",
2265 'sample' => wfMsg( 'nowiki_sample' ),
2266 'tip' => wfMsg( 'nowiki_tip' ),
2267 'key' => 'N'
2268 ),
2269 array(
2270 'image' => $wgLang->getImageFile( 'button-sig' ),
2271 'id' => 'mw-editbutton-signature',
2272 'open' => '--~~~~',
2273 'close' => '',
2274 'sample' => '',
2275 'tip' => wfMsg( 'sig_tip' ),
2276 'key' => 'Y'
2277 ),
2278 array(
2279 'image' => $wgLang->getImageFile( 'button-hr' ),
2280 'id' => 'mw-editbutton-hr',
2281 'open' => "\n----\n",
2282 'close' => '',
2283 'sample' => '',
2284 'tip' => wfMsg( 'hr_tip' ),
2285 'key' => 'R'
2286 )
2287 );
2288 $toolbar = "<div id='toolbar'>\n";
2289
2290 $script = '';
2291 foreach ( $toolarray as $tool ) {
2292 $params = array(
2293 $image = $wgStylePath . '/common/images/' . $tool['image'],
2294 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2295 // Older browsers show a "speedtip" type message only for ALT.
2296 // Ideally these should be different, realistically they
2297 // probably don't need to be.
2298 $tip = $tool['tip'],
2299 $open = $tool['open'],
2300 $close = $tool['close'],
2301 $sample = $tool['sample'],
2302 $cssId = $tool['id'],
2303 );
2304
2305 $paramList = implode( ',',
2306 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2307 $script .= "addButton($paramList);\n";
2308 }
2309 $toolbar .= Html::inlineScript( "\n$script\n" );
2310
2311 $toolbar .= "\n</div>";
2312
2313 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2314
2315 return $toolbar;
2316 }
2317
2318 /**
2319 * Returns an array of html code of the following checkboxes:
2320 * minor and watch
2321 *
2322 * @param $tabindex Current tabindex
2323 * @param $skin Skin object
2324 * @param $checked Array of checkbox => bool, where bool indicates the checked
2325 * status of the checkbox
2326 *
2327 * @return array
2328 */
2329 public function getCheckboxes( &$tabindex, $skin, $checked ) {
2330 global $wgUser;
2331
2332 $checkboxes = array();
2333
2334 $checkboxes['minor'] = '';
2335 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2336 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2337 $attribs = array(
2338 'tabindex' => ++$tabindex,
2339 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2340 'id' => 'wpMinoredit',
2341 );
2342 $checkboxes['minor'] =
2343 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2344 "&nbsp;<label for='wpMinoredit'" . $skin->tooltip( 'minoredit', 'withaccess' ) . ">{$minorLabel}</label>";
2345 }
2346
2347 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2348 $checkboxes['watch'] = '';
2349 if ( $wgUser->isLoggedIn() ) {
2350 $attribs = array(
2351 'tabindex' => ++$tabindex,
2352 'accesskey' => wfMsg( 'accesskey-watch' ),
2353 'id' => 'wpWatchthis',
2354 );
2355 $checkboxes['watch'] =
2356 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2357 "&nbsp;<label for='wpWatchthis'" . $skin->tooltip( 'watch', 'withaccess' ) . ">{$watchLabel}</label>";
2358 }
2359 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2360 return $checkboxes;
2361 }
2362
2363 /**
2364 * Returns an array of html code of the following buttons:
2365 * save, diff, preview and live
2366 *
2367 * @param $tabindex Current tabindex
2368 *
2369 * @return array
2370 */
2371 public function getEditButtons(&$tabindex) {
2372 $buttons = array();
2373
2374 $temp = array(
2375 'id' => 'wpSave',
2376 'name' => 'wpSave',
2377 'type' => 'submit',
2378 'tabindex' => ++$tabindex,
2379 'value' => wfMsg( 'savearticle' ),
2380 'accesskey' => wfMsg( 'accesskey-save' ),
2381 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2382 );
2383 $buttons['save'] = Xml::element('input', $temp, '');
2384
2385 ++$tabindex; // use the same for preview and live preview
2386 $temp = array(
2387 'id' => 'wpPreview',
2388 'name' => 'wpPreview',
2389 'type' => 'submit',
2390 'tabindex' => $tabindex,
2391 'value' => wfMsg( 'showpreview' ),
2392 'accesskey' => wfMsg( 'accesskey-preview' ),
2393 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2394 );
2395 $buttons['preview'] = Xml::element( 'input', $temp, '' );
2396 $buttons['live'] = '';
2397
2398 $temp = array(
2399 'id' => 'wpDiff',
2400 'name' => 'wpDiff',
2401 'type' => 'submit',
2402 'tabindex' => ++$tabindex,
2403 'value' => wfMsg( 'showdiff' ),
2404 'accesskey' => wfMsg( 'accesskey-diff' ),
2405 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2406 );
2407 $buttons['diff'] = Xml::element( 'input', $temp, '' );
2408
2409 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2410 return $buttons;
2411 }
2412
2413 /**
2414 * Output preview text only. This can be sucked into the edit page
2415 * via JavaScript, and saves the server time rendering the skin as
2416 * well as theoretically being more robust on the client (doesn't
2417 * disturb the edit box's undo history, won't eat your text on
2418 * failure, etc).
2419 *
2420 * @todo This doesn't include category or interlanguage links.
2421 * Would need to enhance it a bit, <s>maybe wrap them in XML
2422 * or something...</s> that might also require more skin
2423 * initialization, so check whether that's a problem.
2424 */
2425 function livePreview() {
2426 global $wgOut;
2427 $wgOut->disable();
2428 header( 'Content-type: text/xml; charset=utf-8' );
2429 header( 'Cache-control: no-cache' );
2430
2431 $previewText = $this->getPreviewText();
2432 #$categories = $skin->getCategoryLinks();
2433
2434 $s =
2435 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2436 Xml::tags( 'livepreview', null,
2437 Xml::element( 'preview', null, $previewText )
2438 #. Xml::element( 'category', null, $categories )
2439 );
2440 echo $s;
2441 }
2442
2443
2444 public function getCancelLink() {
2445 global $wgUser, $wgTitle;
2446
2447 $cancelParams = array();
2448 if ( !$this->isConflict && $this->mArticle->getOldID() > 0 ) {
2449 $cancelParams['oldid'] = $this->mArticle->getOldID();
2450 }
2451
2452 return $wgUser->getSkin()->link(
2453 $wgTitle,
2454 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2455 array( 'id' => 'mw-editform-cancel' ),
2456 $cancelParams,
2457 array( 'known', 'noclasses' )
2458 );
2459 }
2460
2461 /**
2462 * Get a diff between the current contents of the edit box and the
2463 * version of the page we're editing from.
2464 *
2465 * If this is a section edit, we'll replace the section as for final
2466 * save and then make a comparison.
2467 */
2468 function showDiff() {
2469 $oldtext = $this->mArticle->fetchContent();
2470 $newtext = $this->mArticle->replaceSection(
2471 $this->section, $this->textbox1, $this->summary, $this->edittime );
2472 $newtext = $this->mArticle->preSaveTransform( $newtext );
2473 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2474 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2475 if ( $oldtext !== false || $newtext != '' ) {
2476 $de = new DifferenceEngine( $this->mTitle );
2477 $de->setText( $oldtext, $newtext );
2478 $difftext = $de->getDiff( $oldtitle, $newtitle );
2479 $de->showDiffStyle();
2480 } else {
2481 $difftext = '';
2482 }
2483
2484 global $wgOut;
2485 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2486 }
2487
2488 /**
2489 * Filter an input field through a Unicode de-armoring process if it
2490 * came from an old browser with known broken Unicode editing issues.
2491 *
2492 * @param WebRequest $request
2493 * @param string $field
2494 * @return string
2495 * @private
2496 */
2497 function safeUnicodeInput( $request, $field ) {
2498 $text = rtrim( $request->getText( $field ) );
2499 return $request->getBool( 'safemode' )
2500 ? $this->unmakesafe( $text )
2501 : $text;
2502 }
2503
2504 function safeUnicodeText( $request, $text ) {
2505 $text = rtrim( $text );
2506 return $request->getBool( 'safemode' )
2507 ? $this->unmakesafe( $text )
2508 : $text;
2509 }
2510
2511 /**
2512 * Filter an output field through a Unicode armoring process if it is
2513 * going to an old browser with known broken Unicode editing issues.
2514 *
2515 * @param string $text
2516 * @return string
2517 * @private
2518 */
2519 function safeUnicodeOutput( $text ) {
2520 global $wgContLang;
2521 $codedText = $wgContLang->recodeForEdit( $text );
2522 return $this->checkUnicodeCompliantBrowser()
2523 ? $codedText
2524 : $this->makesafe( $codedText );
2525 }
2526
2527 /**
2528 * A number of web browsers are known to corrupt non-ASCII characters
2529 * in a UTF-8 text editing environment. To protect against this,
2530 * detected browsers will be served an armored version of the text,
2531 * with non-ASCII chars converted to numeric HTML character references.
2532 *
2533 * Preexisting such character references will have a 0 added to them
2534 * to ensure that round-trips do not alter the original data.
2535 *
2536 * @param string $invalue
2537 * @return string
2538 * @private
2539 */
2540 function makesafe( $invalue ) {
2541 // Armor existing references for reversability.
2542 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2543
2544 $bytesleft = 0;
2545 $result = "";
2546 $working = 0;
2547 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2548 $bytevalue = ord( $invalue{$i} );
2549 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2550 $result .= chr( $bytevalue );
2551 $bytesleft = 0;
2552 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2553 $working = $working << 6;
2554 $working += ($bytevalue & 0x3F);
2555 $bytesleft--;
2556 if ( $bytesleft <= 0 ) {
2557 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2558 }
2559 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2560 $working = $bytevalue & 0x1F;
2561 $bytesleft = 1;
2562 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2563 $working = $bytevalue & 0x0F;
2564 $bytesleft = 2;
2565 } else { //1111 0xxx
2566 $working = $bytevalue & 0x07;
2567 $bytesleft = 3;
2568 }
2569 }
2570 return $result;
2571 }
2572
2573 /**
2574 * Reverse the previously applied transliteration of non-ASCII characters
2575 * back to UTF-8. Used to protect data from corruption by broken web browsers
2576 * as listed in $wgBrowserBlackList.
2577 *
2578 * @param string $invalue
2579 * @return string
2580 * @private
2581 */
2582 function unmakesafe( $invalue ) {
2583 $result = "";
2584 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2585 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2586 $i += 3;
2587 $hexstring = "";
2588 do {
2589 $hexstring .= $invalue{$i};
2590 $i++;
2591 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2592
2593 // Do some sanity checks. These aren't needed for reversability,
2594 // but should help keep the breakage down if the editor
2595 // breaks one of the entities whilst editing.
2596 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2597 $codepoint = hexdec($hexstring);
2598 $result .= codepointToUtf8( $codepoint );
2599 } else {
2600 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2601 }
2602 } else {
2603 $result .= substr( $invalue, $i, 1 );
2604 }
2605 }
2606 // reverse the transform that we made for reversability reasons.
2607 return strtr( $result, array( "&#x0" => "&#x" ) );
2608 }
2609
2610 function noCreatePermission() {
2611 global $wgOut;
2612 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2613 $wgOut->addWikiMsg( 'nocreatetext' );
2614 }
2615
2616 /**
2617 * Attempt submission
2618 * @return bool false if output is done, true if the rest of the form should be displayed
2619 */
2620 function attemptSave() {
2621 global $wgUser, $wgOut, $wgTitle;
2622
2623 $resultDetails = false;
2624 # Allow bots to exempt some edits from bot flagging
2625 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
2626 $value = $this->internalAttemptSave( $resultDetails, $bot );
2627
2628 if ( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2629 $this->didSave = true;
2630 }
2631
2632 switch ( $value ) {
2633 case self::AS_HOOK_ERROR_EXPECTED:
2634 case self::AS_CONTENT_TOO_BIG:
2635 case self::AS_ARTICLE_WAS_DELETED:
2636 case self::AS_CONFLICT_DETECTED:
2637 case self::AS_SUMMARY_NEEDED:
2638 case self::AS_TEXTBOX_EMPTY:
2639 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
2640 case self::AS_END:
2641 return true;
2642
2643 case self::AS_HOOK_ERROR:
2644 case self::AS_FILTERING:
2645 case self::AS_SUCCESS_NEW_ARTICLE:
2646 case self::AS_SUCCESS_UPDATE:
2647 return false;
2648
2649 case self::AS_SPAM_ERROR:
2650 $this->spamPage( $resultDetails['spam'] );
2651 return false;
2652
2653 case self::AS_BLOCKED_PAGE_FOR_USER:
2654 $this->blockedPage();
2655 return false;
2656
2657 case self::AS_IMAGE_REDIRECT_ANON:
2658 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2659 return false;
2660
2661 case self::AS_READ_ONLY_PAGE_ANON:
2662 $this->userNotLoggedInPage();
2663 return false;
2664
2665 case self::AS_READ_ONLY_PAGE_LOGGED:
2666 case self::AS_READ_ONLY_PAGE:
2667 $wgOut->readOnlyPage();
2668 return false;
2669
2670 case self::AS_RATE_LIMITED:
2671 $wgOut->rateLimited();
2672 return false;
2673
2674 case self::AS_NO_CREATE_PERMISSION:
2675 $this->noCreatePermission();
2676 return;
2677
2678 case self::AS_BLANK_ARTICLE:
2679 $wgOut->redirect( $wgTitle->getFullURL() );
2680 return false;
2681
2682 case self::AS_IMAGE_REDIRECT_LOGGED:
2683 $wgOut->permissionRequired( 'upload' );
2684 return false;
2685 }
2686 }
2687
2688 function getBaseRevision() {
2689 if ( $this->mBaseRevision == false ) {
2690 $db = wfGetDB( DB_MASTER );
2691 $baseRevision = Revision::loadFromTimestamp(
2692 $db, $this->mTitle, $this->edittime );
2693 return $this->mBaseRevision = $baseRevision;
2694 } else {
2695 return $this->mBaseRevision;
2696 }
2697 }
2698 }