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