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