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