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