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