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