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