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