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