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