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