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