3ae829acf7cf8ca85059f24a5fed00502195c791
[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, $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 = wfGetIP();
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 }
1032 }
1033 $userid = $wgUser->getId();
1034
1035 # Suppress edit conflict with self, except for section edits where merging is required.
1036 if ( $this->isConflict && $this->section == '' && $this->userWasLastToEdit( $userid, $this->edittime ) ) {
1037 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1038 $this->isConflict = false;
1039 }
1040
1041 if ( $this->isConflict ) {
1042 wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
1043 $this->mArticle->getTimestamp() . "')\n" );
1044 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime );
1045 } else {
1046 wfDebug( __METHOD__ . ": getting section '$this->section'\n" );
1047 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary );
1048 }
1049 if ( is_null( $text ) ) {
1050 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1051 $this->isConflict = true;
1052 $text = $this->textbox1; // do not try to merge here!
1053 } elseif ( $this->isConflict ) {
1054 # Attempt merge
1055 if ( $this->mergeChangesInto( $text ) ) {
1056 // Successful merge! Maybe we should tell the user the good news?
1057 $this->isConflict = false;
1058 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1059 } else {
1060 $this->section = '';
1061 $this->textbox1 = $text;
1062 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1063 }
1064 }
1065
1066 if ( $this->isConflict ) {
1067 wfProfileOut( __METHOD__ );
1068 return self::AS_CONFLICT_DETECTED;
1069 }
1070
1071 $oldtext = $this->mArticle->getContent();
1072
1073 // Run post-section-merge edit filter
1074 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError, $this->summary ) ) ) {
1075 # Error messages etc. could be handled within the hook...
1076 wfProfileOut( __METHOD__ );
1077 return self::AS_HOOK_ERROR;
1078 } elseif ( $this->hookError != '' ) {
1079 # ...or the hook could be expecting us to produce an error
1080 wfProfileOut( __METHOD__ );
1081 return self::AS_HOOK_ERROR_EXPECTED;
1082 }
1083
1084 # Handle the user preference to force summaries here, but not for null edits
1085 if ( $this->section != 'new' && !$this->allowBlankSummary && 0 != strcmp( $oldtext, $text )
1086 && !Title::newFromRedirect( $text ) ) # check if it's not a redirect
1087 {
1088 if ( md5( $this->summary ) == $this->autoSumm ) {
1089 $this->missingSummary = true;
1090 wfProfileOut( __METHOD__ );
1091 return self::AS_SUMMARY_NEEDED;
1092 }
1093 }
1094
1095 # And a similar thing for new sections
1096 if ( $this->section == 'new' && !$this->allowBlankSummary ) {
1097 if ( trim( $this->summary ) == '' ) {
1098 $this->missingSummary = true;
1099 wfProfileOut( __METHOD__ );
1100 return self::AS_SUMMARY_NEEDED;
1101 }
1102 }
1103
1104 # All's well
1105 wfProfileIn( __METHOD__ . '-sectionanchor' );
1106 $sectionanchor = '';
1107 if ( $this->section == 'new' ) {
1108 if ( $this->textbox1 == '' ) {
1109 $this->missingComment = true;
1110 wfProfileOut( __METHOD__ . '-sectionanchor' );
1111 wfProfileOut( __METHOD__ );
1112 return self::AS_TEXTBOX_EMPTY;
1113 }
1114 if ( $this->summary != '' ) {
1115 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1116 # This is a new section, so create a link to the new section
1117 # in the revision summary.
1118 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1119 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
1120 }
1121 } elseif ( $this->section != '' ) {
1122 # Try to get a section anchor from the section source, redirect to edited section if header found
1123 # XXX: might be better to integrate this into Article::replaceSection
1124 # for duplicate heading checking and maybe parsing
1125 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1126 # we can't deal with anchors, includes, html etc in the header for now,
1127 # headline would need to be parsed to improve this
1128 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1129 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1130 }
1131 }
1132 $result['sectionanchor'] = $sectionanchor;
1133 wfProfileOut( __METHOD__ . '-sectionanchor' );
1134
1135 // Save errors may fall down to the edit form, but we've now
1136 // merged the section into full text. Clear the section field
1137 // so that later submission of conflict forms won't try to
1138 // replace that into a duplicated mess.
1139 $this->textbox1 = $text;
1140 $this->section = '';
1141
1142 $retval = self::AS_SUCCESS_UPDATE;
1143 }
1144
1145 // Check for length errors again now that the section is merged in
1146 $this->kblength = (int)( strlen( $text ) / 1024 );
1147 if ( $this->kblength > $wgMaxArticleSize ) {
1148 $this->tooBig = true;
1149 wfProfileOut( __METHOD__ );
1150 return self::AS_MAX_ARTICLE_SIZE_EXCEEDED;
1151 }
1152
1153 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1154 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1155 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1156 ( $bot ? EDIT_FORCE_BOT : 0 );
1157
1158 $status = $this->mArticle->doEdit( $text, $this->summary, $flags );
1159
1160 if ( $status->isOK() ) {
1161 $result['redirect'] = Title::newFromRedirect( $text ) !== null;
1162 $this->commitWatch();
1163 wfProfileOut( __METHOD__ );
1164 return $retval;
1165 } else {
1166 $this->isConflict = true;
1167 wfProfileOut( __METHOD__ );
1168 return self::AS_END;
1169 }
1170 }
1171
1172 /**
1173 * Commit the change of watch status
1174 */
1175 protected function commitWatch() {
1176 global $wgUser;
1177 if ( $this->watchthis xor $this->mTitle->userIsWatching() ) {
1178 $dbw = wfGetDB( DB_MASTER );
1179 $dbw->begin();
1180 if ( $this->watchthis ) {
1181 WatchAction::doWatch( $this->mTitle, $wgUser );
1182 } else {
1183 WatchAction::doUnwatch( $this->mTitle, $wgUser );
1184 }
1185 $dbw->commit();
1186 }
1187 }
1188
1189 /**
1190 * Check if no edits were made by other users since
1191 * the time a user started editing the page. Limit to
1192 * 50 revisions for the sake of performance.
1193 *
1194 * @param $id int
1195 * @param $edittime string
1196 *
1197 * @return bool
1198 */
1199 protected function userWasLastToEdit( $id, $edittime ) {
1200 if( !$id ) return false;
1201 $dbw = wfGetDB( DB_MASTER );
1202 $res = $dbw->select( 'revision',
1203 'rev_user',
1204 array(
1205 'rev_page' => $this->mArticle->getId(),
1206 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1207 ),
1208 __METHOD__,
1209 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1210 foreach ( $res as $row ) {
1211 if( $row->rev_user != $id ) {
1212 return false;
1213 }
1214 }
1215 return true;
1216 }
1217
1218 /**
1219 * Check given input text against $wgSpamRegex, and return the text of the first match.
1220 *
1221 * @param $text string
1222 *
1223 * @return string|false matching string or false
1224 */
1225 public static function matchSpamRegex( $text ) {
1226 global $wgSpamRegex;
1227 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1228 $regexes = (array)$wgSpamRegex;
1229 return self::matchSpamRegexInternal( $text, $regexes );
1230 }
1231
1232 /**
1233 * Check given input text against $wgSpamRegex, and return the text of the first match.
1234 *
1235 * @parma $text string
1236 *
1237 * @return string|false matching string or false
1238 */
1239 public static function matchSummarySpamRegex( $text ) {
1240 global $wgSummarySpamRegex;
1241 $regexes = (array)$wgSummarySpamRegex;
1242 return self::matchSpamRegexInternal( $text, $regexes );
1243 }
1244
1245 /**
1246 * @param $text string
1247 * @param $regexes array
1248 * @return bool|string
1249 */
1250 protected static function matchSpamRegexInternal( $text, $regexes ) {
1251 foreach( $regexes as $regex ) {
1252 $matches = array();
1253 if( preg_match( $regex, $text, $matches ) ) {
1254 return $matches[0];
1255 }
1256 }
1257 return false;
1258 }
1259
1260 /**
1261 * Initialise form fields in the object
1262 * Called on the first invocation, e.g. when a user clicks an edit link
1263 * @return bool -- if the requested section is valid
1264 */
1265 function initialiseForm() {
1266 global $wgUser;
1267 $this->edittime = $this->mArticle->getTimestamp();
1268 $this->textbox1 = $this->getContent( false );
1269 // activate checkboxes if user wants them to be always active
1270 # Sort out the "watch" checkbox
1271 if ( $wgUser->getOption( 'watchdefault' ) ) {
1272 # Watch all edits
1273 $this->watchthis = true;
1274 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1275 # Watch creations
1276 $this->watchthis = true;
1277 } elseif ( $this->mTitle->userIsWatching() ) {
1278 # Already watched
1279 $this->watchthis = true;
1280 }
1281 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
1282 $this->minoredit = true;
1283 }
1284 if ( $this->textbox1 === false ) {
1285 return false;
1286 }
1287 wfProxyCheck();
1288 return true;
1289 }
1290
1291 function setHeaders() {
1292 global $wgOut;
1293 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1294 if ( $this->formtype == 'preview' ) {
1295 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1296 }
1297 if ( $this->isConflict ) {
1298 $wgOut->setPageTitle( wfMsg( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1299 } elseif ( $this->section != '' ) {
1300 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
1301 $wgOut->setPageTitle( wfMsg( $msg, $this->getContextTitle()->getPrefixedText() ) );
1302 } else {
1303 # Use the title defined by DISPLAYTITLE magic word when present
1304 if ( isset( $this->mParserOutput )
1305 && ( $dt = $this->mParserOutput->getDisplayTitle() ) !== false ) {
1306 $title = $dt;
1307 } else {
1308 $title = $this->getContextTitle()->getPrefixedText();
1309 }
1310 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1311 }
1312 }
1313
1314 /**
1315 * Send the edit form and related headers to $wgOut
1316 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1317 * during form output near the top, for captchas and the like.
1318 */
1319 function showEditForm( $formCallback=null ) {
1320 global $wgOut, $wgUser, $wgEnableInterwikiTranscluding, $wgEnableInterwikiTemplatesTracking;
1321
1322 wfProfileIn( __METHOD__ );
1323
1324 #need to parse the preview early so that we know which templates are used,
1325 #otherwise users with "show preview after edit box" will get a blank list
1326 #we parse this near the beginning so that setHeaders can do the title
1327 #setting work instead of leaving it in getPreviewText
1328 $previewOutput = '';
1329 if ( $this->formtype == 'preview' ) {
1330 $previewOutput = $this->getPreviewText();
1331 }
1332
1333 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$formCallback ) );
1334
1335 $this->setHeaders();
1336
1337 # Enabled article-related sidebar, toplinks, etc.
1338 $wgOut->setArticleRelated( true );
1339
1340 if ( $this->showHeader() === false ) {
1341 wfProfileOut( __METHOD__ );
1342 return;
1343 }
1344
1345 $action = htmlspecialchars( $this->getActionURL( $this->getContextTitle() ) );
1346
1347 if ( $wgUser->getOption( 'showtoolbar' ) and !$this->isCssJsSubpage ) {
1348 # prepare toolbar for edit buttons
1349 $toolbar = EditPage::getEditToolbar();
1350 } else {
1351 $toolbar = '';
1352 }
1353
1354 $wgOut->addHTML( $this->editFormPageTop );
1355
1356 if ( $wgUser->getOption( 'previewontop' ) ) {
1357 $this->displayPreviewArea( $previewOutput, true );
1358 }
1359
1360 $wgOut->addHTML( $this->editFormTextTop );
1361
1362 $templates = $this->getTemplates();
1363 $formattedtemplates = Linker::formatTemplates( $templates, $this->preview, $this->section != '');
1364
1365 $distantTemplates = $this->getDistantTemplates();
1366 $formattedDistantTemplates = Linker::formatDistantTemplates( $distantTemplates, $this->preview, $this->section != '' );
1367
1368 $hiddencats = $this->mArticle->getHiddenCategories();
1369 $formattedhiddencats = Linker::formatHiddenCategories( $hiddencats );
1370
1371 if ( $this->wasDeletedSinceLastEdit() && 'save' != $this->formtype ) {
1372 $wgOut->wrapWikiMsg(
1373 "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1374 'deletedwhileediting' );
1375 } elseif ( $this->wasDeletedSinceLastEdit() ) {
1376 // Hide the toolbar and edit area, user can click preview to get it back
1377 // Add an confirmation checkbox and explanation.
1378 $toolbar = '';
1379 // @todo move this to a cleaner conditional instead of blanking a variable
1380 }
1381 $wgOut->addHTML( <<<HTML
1382 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1383 HTML
1384 );
1385
1386 if ( is_callable( $formCallback ) ) {
1387 call_user_func_array( $formCallback, array( &$wgOut ) );
1388 }
1389
1390 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1391
1392 // Put these up at the top to ensure they aren't lost on early form submission
1393 $this->showFormBeforeText();
1394
1395 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
1396 $username = $this->lastDelete->user_name;
1397 $comment = $this->lastDelete->log_comment;
1398
1399 // It is better to not parse the comment at all than to have templates expanded in the middle
1400 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1401 $key = $comment === ''
1402 ? 'confirmrecreate-noreason'
1403 : 'confirmrecreate';
1404 $wgOut->addHTML(
1405 '<div class="mw-confirm-recreate">' .
1406 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1407 Xml::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1408 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1409 ) .
1410 '</div>'
1411 );
1412 }
1413
1414 # If a blank edit summary was previously provided, and the appropriate
1415 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1416 # user being bounced back more than once in the event that a summary
1417 # is not required.
1418 #####
1419 # For a bit more sophisticated detection of blank summaries, hash the
1420 # automatic one and pass that in the hidden field wpAutoSummary.
1421 if ( $this->missingSummary ||
1422 ( $this->section == 'new' && $this->nosummary ) )
1423 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
1424 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1425 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
1426
1427 $wgOut->addHTML( Html::hidden( 'oldid', $this->mArticle->getOldID() ) );
1428
1429 if ( $this->section == 'new' ) {
1430 $this->showSummaryInput( true, $this->summary );
1431 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
1432 }
1433
1434 $wgOut->addHTML( $this->editFormTextBeforeContent );
1435
1436 $wgOut->addHTML( $toolbar );
1437
1438 if ( $this->isConflict ) {
1439 // In an edit conflict bypass the overrideable content form method
1440 // and fallback to the raw wpTextbox1 since editconflicts can't be
1441 // resolved between page source edits and custom ui edits using the
1442 // custom edit ui.
1443 $this->showTextbox1( null, $this->getContent() );
1444 } else {
1445 $this->showContentForm();
1446 }
1447
1448 $wgOut->addHTML( $this->editFormTextAfterContent );
1449
1450 $wgOut->addWikiText( $this->getCopywarn() );
1451 if ( isset($this->editFormTextAfterWarn) && $this->editFormTextAfterWarn !== '' )
1452 $wgOut->addHTML( $this->editFormTextAfterWarn );
1453
1454 $this->showStandardInputs();
1455
1456 $this->showFormAfterText();
1457
1458 $this->showTosSummary();
1459 $this->showEditTools();
1460
1461 $wgOut->addHTML( <<<HTML
1462 {$this->editFormTextAfterTools}
1463 <div class='templatesUsed'>
1464 {$formattedtemplates}
1465 </div>
1466 HTML
1467 );
1468
1469 if ( $wgEnableInterwikiTranscluding && $wgEnableInterwikiTemplatesTracking ) {
1470 $wgOut->addHTML( <<<HTML
1471 {$this->editFormTextAfterTools}
1472 <div class='distantTemplatesUsed'>
1473 {$formattedDistantTemplates}
1474 </div>
1475 HTML
1476 );
1477 }
1478
1479 $wgOut->addHTML( <<<HTML
1480 {$this->editFormTextAfterTools}
1481 <div class='hiddencats'>
1482 {$formattedhiddencats}
1483 </div>
1484 HTML
1485 );
1486
1487 if ( $this->isConflict )
1488 $this->showConflict();
1489
1490 $wgOut->addHTML( $this->editFormTextBottom );
1491 $wgOut->addHTML( "</form>\n" );
1492 if ( !$wgUser->getOption( 'previewontop' ) ) {
1493 $this->displayPreviewArea( $previewOutput, false );
1494 }
1495
1496 wfProfileOut( __METHOD__ );
1497 }
1498
1499 protected function showHeader() {
1500 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1501 if ( $this->isConflict ) {
1502 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1503 $this->edittime = $this->mArticle->getTimestamp();
1504 } else {
1505 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
1506 // We use $this->section to much before this and getVal('wgSection') directly in other places
1507 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1508 // Someone is welcome to try refactoring though
1509 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1510 return false;
1511 }
1512
1513 if ( $this->section != '' && $this->section != 'new' ) {
1514 $matches = array();
1515 if ( !$this->summary && !$this->preview && !$this->diff ) {
1516 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1, $matches );
1517 if ( !empty( $matches[2] ) ) {
1518 global $wgParser;
1519 $this->summary = "/* " .
1520 $wgParser->stripSectionName(trim($matches[2])) .
1521 " */ ";
1522 }
1523 }
1524 }
1525
1526 if ( $this->missingComment ) {
1527 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1528 }
1529
1530 if ( $this->missingSummary && $this->section != 'new' ) {
1531 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1532 }
1533
1534 if ( $this->missingSummary && $this->section == 'new' ) {
1535 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1536 }
1537
1538 if ( $this->hookError !== '' ) {
1539 $wgOut->addWikiText( $this->hookError );
1540 }
1541
1542 if ( !$this->checkUnicodeCompliantBrowser() ) {
1543 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1544 }
1545
1546 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
1547 // Let sysop know that this will make private content public if saved
1548
1549 if ( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1550 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1551 } elseif ( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1552 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1553 }
1554
1555 if ( !$this->mArticle->mRevision->isCurrent() ) {
1556 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
1557 $wgOut->addWikiMsg( 'editingold' );
1558 }
1559 }
1560 }
1561
1562 if ( wfReadOnly() ) {
1563 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1564 } elseif ( $wgUser->isAnon() ) {
1565 if ( $this->formtype != 'preview' ) {
1566 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1567 } else {
1568 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
1569 }
1570 } else {
1571 if ( $this->isCssJsSubpage ) {
1572 # Check the skin exists
1573 if ( $this->isWrongCaseCssJsPage ) {
1574 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->getContextTitle()->getSkinFromCssJsSubpage() ) );
1575 }
1576 if ( $this->formtype !== 'preview' ) {
1577 if ( $this->isCssSubpage )
1578 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
1579 if ( $this->isJsSubpage )
1580 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
1581 }
1582 }
1583 }
1584
1585 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
1586 # Is the title semi-protected?
1587 if ( $this->mTitle->isSemiProtected() ) {
1588 $noticeMsg = 'semiprotectedpagewarning';
1589 } else {
1590 # Then it must be protected based on static groups (regular)
1591 $noticeMsg = 'protectedpagewarning';
1592 }
1593 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle->getPrefixedText(), '',
1594 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1595 }
1596 if ( $this->mTitle->isCascadeProtected() ) {
1597 # Is this page under cascading protection from some source pages?
1598 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1599 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
1600 $cascadeSourcesCount = count( $cascadeSources );
1601 if ( $cascadeSourcesCount > 0 ) {
1602 # Explain, and list the titles responsible
1603 foreach( $cascadeSources as $page ) {
1604 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1605 }
1606 }
1607 $notice .= '</div>';
1608 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1609 }
1610 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
1611 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle->getPrefixedText(), '',
1612 array( 'lim' => 1,
1613 'showIfEmpty' => false,
1614 'msgKey' => array( 'titleprotectedwarning' ),
1615 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
1616 }
1617
1618 if ( $this->kblength === false ) {
1619 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1620 }
1621
1622 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1623 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
1624 array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
1625 } else {
1626 if( !wfMessage('longpage-hint')->isDisabled() ) {
1627 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
1628 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
1629 );
1630 }
1631 }
1632 }
1633
1634 /**
1635 * Standard summary input and label (wgSummary), abstracted so EditPage
1636 * subclasses may reorganize the form.
1637 * Note that you do not need to worry about the label's for=, it will be
1638 * inferred by the id given to the input. You can remove them both by
1639 * passing array( 'id' => false ) to $userInputAttrs.
1640 *
1641 * @param $summary string The value of the summary input
1642 * @param $labelText string The html to place inside the label
1643 * @param $inputAttrs array of attrs to use on the input
1644 * @param $spanLabelAttrs array of attrs to use on the span inside the label
1645 *
1646 * @return array An array in the format array( $label, $input )
1647 */
1648 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
1649 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
1650 $inputAttrs = ( is_array($inputAttrs) ? $inputAttrs : array() ) + array(
1651 'id' => 'wpSummary',
1652 'maxlength' => '200',
1653 'tabindex' => '1',
1654 'size' => 60,
1655 'spellcheck' => 'true',
1656 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
1657
1658 $spanLabelAttrs = ( is_array($spanLabelAttrs) ? $spanLabelAttrs : array() ) + array(
1659 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
1660 'id' => "wpSummaryLabel"
1661 );
1662
1663 $label = null;
1664 if ( $labelText ) {
1665 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1666 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
1667 }
1668
1669 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
1670
1671 return array( $label, $input );
1672 }
1673
1674 /**
1675 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1676 * up top, or false if this is the comment summary
1677 * down below the textarea
1678 * @param $summary String: The text of the summary to display
1679 * @return String
1680 */
1681 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1682 global $wgOut, $wgContLang;
1683 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1684 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
1685 if ( $isSubjectPreview ) {
1686 if ( $this->nosummary ) {
1687 return;
1688 }
1689 } else {
1690 if ( !$this->mShowSummaryField ) {
1691 return;
1692 }
1693 }
1694 $summary = $wgContLang->recodeForEdit( $summary );
1695 $labelText = wfMsgExt( $isSubjectPreview ? 'subject' : 'summary', 'parseinline' );
1696 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
1697 $wgOut->addHTML("{$label} {$input}");
1698 }
1699
1700 /**
1701 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1702 * up top, or false if this is the comment summary
1703 * down below the textarea
1704 * @param $summary String: the text of the summary to display
1705 * @return String
1706 */
1707 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
1708 if ( !$summary || ( !$this->preview && !$this->diff ) )
1709 return "";
1710
1711 global $wgParser;
1712
1713 if ( $isSubjectPreview )
1714 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
1715
1716 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
1717
1718 $summary = wfMsgExt( $message, 'parseinline' ) . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
1719 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
1720 }
1721
1722 protected function showFormBeforeText() {
1723 global $wgOut;
1724 $section = htmlspecialchars( $this->section );
1725 $wgOut->addHTML( <<<HTML
1726 <input type='hidden' value="{$section}" name="wpSection" />
1727 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
1728 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
1729 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
1730
1731 HTML
1732 );
1733 if ( !$this->checkUnicodeCompliantBrowser() )
1734 $wgOut->addHTML(Html::hidden( 'safemode', '1' ));
1735 }
1736
1737 protected function showFormAfterText() {
1738 global $wgOut, $wgUser;
1739 /**
1740 * To make it harder for someone to slip a user a page
1741 * which submits an edit form to the wiki without their
1742 * knowledge, a random token is associated with the login
1743 * session. If it's not passed back with the submission,
1744 * we won't save the page, or render user JavaScript and
1745 * CSS previews.
1746 *
1747 * For anon editors, who may not have a session, we just
1748 * include the constant suffix to prevent editing from
1749 * broken text-mangling proxies.
1750 */
1751 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->editToken() ) . "\n" );
1752 }
1753
1754 /**
1755 * Subpage overridable method for printing the form for page content editing
1756 * By default this simply outputs wpTextbox1
1757 * Subclasses can override this to provide a custom UI for editing;
1758 * be it a form, or simply wpTextbox1 with a modified content that will be
1759 * reverse modified when extracted from the post data.
1760 * Note that this is basically the inverse for importContentFormData
1761 */
1762 protected function showContentForm() {
1763 $this->showTextbox1();
1764 }
1765
1766 /**
1767 * Method to output wpTextbox1
1768 * The $textoverride method can be used by subclasses overriding showContentForm
1769 * to pass back to this method.
1770 *
1771 * @param $customAttribs An array of html attributes to use in the textarea
1772 * @param $textoverride String: optional text to override $this->textarea1 with
1773 */
1774 protected function showTextbox1($customAttribs = null, $textoverride = null) {
1775 $classes = array(); // Textarea CSS
1776 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
1777 # Is the title semi-protected?
1778 if ( $this->mTitle->isSemiProtected() ) {
1779 $classes[] = 'mw-textarea-sprotected';
1780 } else {
1781 # Then it must be protected based on static groups (regular)
1782 $classes[] = 'mw-textarea-protected';
1783 }
1784 # Is the title cascade-protected?
1785 if ( $this->mTitle->isCascadeProtected() ) {
1786 $classes[] = 'mw-textarea-cprotected';
1787 }
1788 }
1789 $attribs = array( 'tabindex' => 1 );
1790 if ( is_array($customAttribs) )
1791 $attribs += $customAttribs;
1792
1793 if ( $this->wasDeletedSinceLastEdit() )
1794 $attribs['type'] = 'hidden';
1795 if ( !empty( $classes ) ) {
1796 if ( isset($attribs['class']) )
1797 $classes[] = $attribs['class'];
1798 $attribs['class'] = implode( ' ', $classes );
1799 }
1800
1801 $this->showTextbox( isset($textoverride) ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
1802 }
1803
1804 protected function showTextbox2() {
1805 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
1806 }
1807
1808 protected function showTextbox( $content, $name, $customAttribs = array() ) {
1809 global $wgOut, $wgUser;
1810
1811 $wikitext = $this->safeUnicodeOutput( $content );
1812 if ( $wikitext !== '' ) {
1813 // Ensure there's a newline at the end, otherwise adding lines
1814 // is awkward.
1815 // But don't add a newline if the ext is empty, or Firefox in XHTML
1816 // mode will show an extra newline. A bit annoying.
1817 $wikitext .= "\n";
1818 }
1819
1820 $attribs = $customAttribs + array(
1821 'accesskey' => ',',
1822 'id' => $name,
1823 'cols' => $wgUser->getIntOption( 'cols' ),
1824 'rows' => $wgUser->getIntOption( 'rows' ),
1825 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
1826 );
1827
1828 $pageLang = $this->mTitle->getPageLanguage();
1829 $attribs['lang'] = $pageLang->getCode();
1830 $attribs['dir'] = $pageLang->getDir();
1831
1832 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
1833 }
1834
1835 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1836 global $wgOut;
1837 $classes = array();
1838 if ( $isOnTop )
1839 $classes[] = 'ontop';
1840
1841 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1842
1843 if ( $this->formtype != 'preview' )
1844 $attribs['style'] = 'display: none;';
1845
1846 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
1847
1848 if ( $this->formtype == 'preview' ) {
1849 $this->showPreview( $previewOutput );
1850 }
1851
1852 $wgOut->addHTML( '</div>' );
1853
1854 if ( $this->formtype == 'diff') {
1855 $this->showDiff();
1856 }
1857 }
1858
1859 /**
1860 * Append preview output to $wgOut.
1861 * Includes category rendering if this is a category page.
1862 *
1863 * @param $text String: the HTML to be output for the preview.
1864 */
1865 protected function showPreview( $text ) {
1866 global $wgOut;
1867 if ( $this->mTitle->getNamespace() == NS_CATEGORY) {
1868 $this->mArticle->openShowCategory();
1869 }
1870 # This hook seems slightly odd here, but makes things more
1871 # consistent for extensions.
1872 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1873 $wgOut->addHTML( $text );
1874 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1875 $this->mArticle->closeShowCategory();
1876 }
1877 }
1878
1879 /**
1880 * Give a chance for site and per-namespace customizations of
1881 * terms of service summary link that might exist separately
1882 * from the copyright notice.
1883 *
1884 * This will display between the save button and the edit tools,
1885 * so should remain short!
1886 */
1887 protected function showTosSummary() {
1888 $msg = 'editpage-tos-summary';
1889 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
1890 if( !wfMessage( $msg )->isDisabled() ) {
1891 global $wgOut;
1892 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1893 $wgOut->addWikiMsg( $msg );
1894 $wgOut->addHTML( '</div>' );
1895 }
1896 }
1897
1898 protected function showEditTools() {
1899 global $wgOut;
1900 $wgOut->addHTML( '<div class="mw-editTools">' .
1901 wfMessage( 'edittools' )->inContentLanguage()->parse() .
1902 '</div>' );
1903 }
1904
1905 protected function getCopywarn() {
1906 global $wgRightsText;
1907 if ( $wgRightsText ) {
1908 $copywarnMsg = array( 'copyrightwarning',
1909 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1910 $wgRightsText );
1911 } else {
1912 $copywarnMsg = array( 'copyrightwarning2',
1913 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1914 }
1915 // Allow for site and per-namespace customization of contribution/copyright notice.
1916 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
1917
1918 return "<div id=\"editpage-copywarn\">\n" .
1919 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
1920 }
1921
1922 protected function showStandardInputs( &$tabindex = 2 ) {
1923 global $wgOut;
1924 $wgOut->addHTML( "<div class='editOptions'>\n" );
1925
1926 if ( $this->section != 'new' ) {
1927 $this->showSummaryInput( false, $this->summary );
1928 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
1929 }
1930
1931 $checkboxes = $this->getCheckboxes( $tabindex,
1932 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1933 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
1934 $wgOut->addHTML( "<div class='editButtons'>\n" );
1935 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
1936
1937 $cancel = $this->getCancelLink();
1938 if ( $cancel !== '' ) {
1939 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1940 }
1941 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
1942 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1943 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1944 htmlspecialchars( wfMsg( 'newwindow' ) );
1945 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
1946 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
1947 }
1948
1949 /**
1950 * Show an edit conflict. textbox1 is already shown in showEditForm().
1951 * If you want to use another entry point to this function, be careful.
1952 */
1953 protected function showConflict() {
1954 global $wgOut;
1955 $this->textbox2 = $this->textbox1;
1956 $this->textbox1 = $this->getContent();
1957 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1958 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
1959
1960 $de = new DifferenceEngine( $this->mTitle );
1961 $de->setText( $this->textbox2, $this->textbox1 );
1962 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1963
1964 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
1965 $this->showTextbox2();
1966 }
1967 }
1968
1969 protected function getLastDelete() {
1970 $dbr = wfGetDB( DB_SLAVE );
1971 $data = $dbr->selectRow(
1972 array( 'logging', 'user' ),
1973 array( 'log_type',
1974 'log_action',
1975 'log_timestamp',
1976 'log_user',
1977 'log_namespace',
1978 'log_title',
1979 'log_comment',
1980 'log_params',
1981 'log_deleted',
1982 'user_name' ),
1983 array( 'log_namespace' => $this->mTitle->getNamespace(),
1984 'log_title' => $this->mTitle->getDBkey(),
1985 'log_type' => 'delete',
1986 'log_action' => 'delete',
1987 'user_id=log_user' ),
1988 __METHOD__,
1989 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1990 );
1991 // Quick paranoid permission checks...
1992 if( is_object( $data ) ) {
1993 if( $data->log_deleted & LogPage::DELETED_USER )
1994 $data->user_name = wfMsgHtml( 'rev-deleted-user' );
1995 if( $data->log_deleted & LogPage::DELETED_COMMENT )
1996 $data->log_comment = wfMsgHtml( 'rev-deleted-comment' );
1997 }
1998 return $data;
1999 }
2000
2001 /**
2002 * Get the rendered text for previewing.
2003 * @return string
2004 */
2005 function getPreviewText() {
2006 global $wgOut, $wgUser, $wgParser;
2007
2008 wfProfileIn( __METHOD__ );
2009
2010 if ( $this->mTriedSave && !$this->mTokenOk ) {
2011 if ( $this->mTokenOkExceptSuffix ) {
2012 $note = wfMsg( 'token_suffix_mismatch' );
2013 } else {
2014 $note = wfMsg( 'session_fail_preview' );
2015 }
2016 } elseif ( $this->incompleteForm ) {
2017 $note = wfMsg( 'edit_form_incomplete' );
2018 } else {
2019 $note = wfMsg( 'previewnote' );
2020 }
2021
2022 $parserOptions = ParserOptions::newFromUser( $wgUser );
2023 $parserOptions->setEditSection( false );
2024 $parserOptions->setIsPreview( true );
2025 $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
2026
2027 global $wgRawHtml;
2028 if ( $wgRawHtml && !$this->mTokenOk ) {
2029 // Could be an offsite preview attempt. This is very unsafe if
2030 // HTML is enabled, as it could be an attack.
2031 $parsedNote = '';
2032 if ( $this->textbox1 !== '' ) {
2033 // Do not put big scary notice, if previewing the empty
2034 // string, which happens when you initially edit
2035 // a category page, due to automatic preview-on-open.
2036 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2037 wfMsg( 'session_fail_preview_html' ) . "</div>" );
2038 }
2039 wfProfileOut( __METHOD__ );
2040 return $parsedNote;
2041 }
2042
2043 # don't parse user css/js, show message about preview
2044 # 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?
2045
2046 if ( $this->isCssJsSubpage || $this->mTitle->isCssOrJsPage() ) {
2047 $level = 'user';
2048 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2049 $level = 'site';
2050 }
2051
2052 # Used messages to make sure grep find them:
2053 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
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 $parserOptions->setTidy( true );
2065 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
2066 $previewHTML = $parserOutput->mText;
2067 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1 ) . "\n</pre>\n";
2068 } else {
2069 $rt = Title::newFromRedirectArray( $this->textbox1 );
2070 if ( $rt ) {
2071 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
2072 } else {
2073 $toparse = $this->textbox1;
2074
2075 # If we're adding a comment, we need to show the
2076 # summary as the headline
2077 if ( $this->section == "new" && $this->summary != "" ) {
2078 $toparse = "== {$this->summary} ==\n\n" . $toparse;
2079 }
2080
2081 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2082
2083 $parserOptions->setTidy( true );
2084 $parserOptions->enableLimitReport();
2085 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ),
2086 $this->mTitle, $parserOptions );
2087
2088 $previewHTML = $parserOutput->getText();
2089 $this->mParserOutput = $parserOutput;
2090 $wgOut->addParserOutputNoText( $parserOutput );
2091
2092 if ( count( $parserOutput->getWarnings() ) ) {
2093 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2094 }
2095 }
2096 }
2097
2098 if( $this->isConflict ) {
2099 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2100 } else {
2101 $conflict = '<hr />';
2102 }
2103
2104 $previewhead = "<div class='previewnote'>\n" .
2105 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2106 $wgOut->parse( $note ) . $conflict . "</div>\n";
2107
2108 $pageLang = $this->mTitle->getPageLanguage();
2109 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2110 'class' => 'mw-content-'.$pageLang->getDir() );
2111 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
2112
2113 wfProfileOut( __METHOD__ );
2114 return $previewhead . $previewHTML . $this->previewTextAfterContent;
2115 }
2116
2117 /**
2118 * @return Array
2119 */
2120 function getTemplates() {
2121 if ( $this->preview || $this->section != '' ) {
2122 $templates = array();
2123 if ( !isset( $this->mParserOutput ) ) {
2124 return $templates;
2125 }
2126 foreach( $this->mParserOutput->getTemplates() as $ns => $template) {
2127 foreach( array_keys( $template ) as $dbk ) {
2128 $templates[] = Title::makeTitle($ns, $dbk);
2129 }
2130 }
2131 return $templates;
2132 } else {
2133 return $this->mArticle->getUsedTemplates();
2134 }
2135 }
2136
2137 function getDistantTemplates() {
2138 global $wgEnableInterwikiTemplatesTracking;
2139 if ( !$wgEnableInterwikiTemplatesTracking ) {
2140 return array( );
2141 }
2142 if ( $this->preview || $this->section != '' ) {
2143 $templates = array();
2144 if ( !isset( $this->mParserOutput ) ) return $templates;
2145 $templatesList = $this->mParserOutput->getDistantTemplates();
2146 foreach( $templatesList as $prefix => $templatesbyns ) {
2147 foreach( $templatesbyns as $ns => $template ) {
2148 foreach( array_keys( $template ) as $dbk ) {
2149 $templates[] = Title::makeTitle( $ns, $dbk, null, $prefix );
2150 }
2151 }
2152 }
2153 return $templates;
2154 } else {
2155 return $this->mArticle->getUsedDistantTemplates();
2156 }
2157 }
2158
2159 /**
2160 * Call the stock "user is blocked" page
2161 */
2162 function blockedPage() {
2163 global $wgOut;
2164 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
2165
2166 # If the user made changes, preserve them when showing the markup
2167 # (This happens when a user is blocked during edit, for instance)
2168 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
2169 if ( $first ) {
2170 $source = $this->mTitle->exists() ? $this->getContent() : false;
2171 } else {
2172 $source = $this->textbox1;
2173 }
2174
2175 # Spit out the source or the user's modified version
2176 if ( $source !== false ) {
2177 $wgOut->addHTML( '<hr />' );
2178 $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() );
2179 $this->showTextbox1( array( 'readonly' ), $source );
2180 }
2181 }
2182
2183 /**
2184 * Produce the stock "please login to edit pages" page
2185 */
2186 function userNotLoggedInPage() {
2187 global $wgOut;
2188
2189 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
2190 $loginLink = Linker::linkKnown(
2191 $loginTitle,
2192 wfMsgHtml( 'loginreqlink' ),
2193 array(),
2194 array( 'returnto' => $this->getContextTitle()->getPrefixedText() )
2195 );
2196
2197 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
2198 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2199 $wgOut->setArticleRelated( false );
2200
2201 $wgOut->addHTML( wfMessage( 'whitelistedittext' )->rawParams( $loginLink )->parse() );
2202 $wgOut->returnToMain( false, $this->getContextTitle() );
2203 }
2204
2205 /**
2206 * Creates a basic error page which informs the user that
2207 * they have attempted to edit a nonexistent section.
2208 */
2209 function noSuchSectionPage() {
2210 global $wgOut;
2211
2212 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
2213 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2214 $wgOut->setArticleRelated( false );
2215
2216 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section );
2217 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2218 $wgOut->addHTML( $res );
2219
2220 $wgOut->returnToMain( false, $this->mTitle );
2221 }
2222
2223 /**
2224 * Produce the stock "your edit contains spam" page
2225 *
2226 * @param $match Text which triggered one or more filters
2227 * @deprecated since 1.17 Use method spamPageWithContent() instead
2228 */
2229 static function spamPage( $match = false ) {
2230 global $wgOut, $wgTitle;
2231
2232 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
2233 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2234 $wgOut->setArticleRelated( false );
2235
2236 $wgOut->addHTML( '<div id="spamprotected">' );
2237 $wgOut->addWikiMsg( 'spamprotectiontext' );
2238 if ( $match ) {
2239 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2240 }
2241 $wgOut->addHTML( '</div>' );
2242
2243 $wgOut->returnToMain( false, $wgTitle );
2244 }
2245
2246 /**
2247 * Show "your edit contains spam" page with your diff and text
2248 *
2249 * @param $match Text which triggered one or more filters
2250 */
2251 public function spamPageWithContent( $match = false ) {
2252 global $wgOut;
2253 $this->textbox2 = $this->textbox1;
2254
2255 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
2256 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2257 $wgOut->setArticleRelated( false );
2258
2259 $wgOut->addHTML( '<div id="spamprotected">' );
2260 $wgOut->addWikiMsg( 'spamprotectiontext' );
2261 if ( $match ) {
2262 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2263 }
2264 $wgOut->addHTML( '</div>' );
2265
2266 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2267 $de = new DifferenceEngine( $this->mTitle );
2268 $de->setText( $this->getContent(), $this->textbox2 );
2269 $de->showDiff( wfMsg( "storedversion" ), wfMsg( "yourtext" ) );
2270
2271 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2272 $this->showTextbox2();
2273
2274 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
2275 }
2276
2277
2278 /**
2279 * @private
2280 * @todo document
2281 *
2282 * @parma $editText string
2283 *
2284 * @return bool
2285 */
2286 function mergeChangesInto( &$editText ){
2287 wfProfileIn( __METHOD__ );
2288
2289 $db = wfGetDB( DB_MASTER );
2290
2291 // This is the revision the editor started from
2292 $baseRevision = $this->getBaseRevision();
2293 if ( is_null( $baseRevision ) ) {
2294 wfProfileOut( __METHOD__ );
2295 return false;
2296 }
2297 $baseText = $baseRevision->getText();
2298
2299 // The current state, we want to merge updates into it
2300 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2301 if ( is_null( $currentRevision ) ) {
2302 wfProfileOut( __METHOD__ );
2303 return false;
2304 }
2305 $currentText = $currentRevision->getText();
2306
2307 $result = '';
2308 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
2309 $editText = $result;
2310 wfProfileOut( __METHOD__ );
2311 return true;
2312 } else {
2313 wfProfileOut( __METHOD__ );
2314 return false;
2315 }
2316 }
2317
2318 /**
2319 * Check if the browser is on a blacklist of user-agents known to
2320 * mangle UTF-8 data on form submission. Returns true if Unicode
2321 * should make it through, false if it's known to be a problem.
2322 * @return bool
2323 * @private
2324 */
2325 function checkUnicodeCompliantBrowser() {
2326 global $wgBrowserBlackList;
2327 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2328 // No User-Agent header sent? Trust it by default...
2329 return true;
2330 }
2331 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2332 foreach ( $wgBrowserBlackList as $browser ) {
2333 if ( preg_match($browser, $currentbrowser) ) {
2334 return false;
2335 }
2336 }
2337 return true;
2338 }
2339
2340 /**
2341 * Format an anchor fragment as it would appear for a given section name
2342 * @param $text String
2343 * @return String
2344 * @private
2345 */
2346 function sectionAnchor( $text ) {
2347 global $wgParser;
2348 return $wgParser->guessSectionNameFromWikiText( $text );
2349 }
2350
2351 /**
2352 * Shows a bulletin board style toolbar for common editing functions.
2353 * It can be disabled in the user preferences.
2354 * The necessary JavaScript code can be found in skins/common/edit.js.
2355 *
2356 * @return string
2357 */
2358 static function getEditToolbar() {
2359 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2360 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2361
2362 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
2363
2364 /**
2365 * $toolarray is an array of arrays each of which includes the
2366 * filename of the button image (without path), the opening
2367 * tag, the closing tag, optionally a sample text that is
2368 * inserted between the two when no selection is highlighted
2369 * and. The tip text is shown when the user moves the mouse
2370 * over the button.
2371 *
2372 * Also here: accesskeys (key), which are not used yet until
2373 * someone can figure out a way to make them work in
2374 * IE. However, we should make sure these keys are not defined
2375 * on the edit page.
2376 */
2377 $toolarray = array(
2378 array(
2379 'image' => $wgLang->getImageFile( 'button-bold' ),
2380 'id' => 'mw-editbutton-bold',
2381 'open' => '\'\'\'',
2382 'close' => '\'\'\'',
2383 'sample' => wfMsg( 'bold_sample' ),
2384 'tip' => wfMsg( 'bold_tip' ),
2385 'key' => 'B'
2386 ),
2387 array(
2388 'image' => $wgLang->getImageFile( 'button-italic' ),
2389 'id' => 'mw-editbutton-italic',
2390 'open' => '\'\'',
2391 'close' => '\'\'',
2392 'sample' => wfMsg( 'italic_sample' ),
2393 'tip' => wfMsg( 'italic_tip' ),
2394 'key' => 'I'
2395 ),
2396 array(
2397 'image' => $wgLang->getImageFile( 'button-link' ),
2398 'id' => 'mw-editbutton-link',
2399 'open' => '[[',
2400 'close' => ']]',
2401 'sample' => wfMsg( 'link_sample' ),
2402 'tip' => wfMsg( 'link_tip' ),
2403 'key' => 'L'
2404 ),
2405 array(
2406 'image' => $wgLang->getImageFile( 'button-extlink' ),
2407 'id' => 'mw-editbutton-extlink',
2408 'open' => '[',
2409 'close' => ']',
2410 'sample' => wfMsg( 'extlink_sample' ),
2411 'tip' => wfMsg( 'extlink_tip' ),
2412 'key' => 'X'
2413 ),
2414 array(
2415 'image' => $wgLang->getImageFile( 'button-headline' ),
2416 'id' => 'mw-editbutton-headline',
2417 'open' => "\n== ",
2418 'close' => " ==\n",
2419 'sample' => wfMsg( 'headline_sample' ),
2420 'tip' => wfMsg( 'headline_tip' ),
2421 'key' => 'H'
2422 ),
2423 $imagesAvailable ? array(
2424 'image' => $wgLang->getImageFile( 'button-image' ),
2425 'id' => 'mw-editbutton-image',
2426 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
2427 'close' => ']]',
2428 'sample' => wfMsg( 'image_sample' ),
2429 'tip' => wfMsg( 'image_tip' ),
2430 'key' => 'D',
2431 ) : false,
2432 $imagesAvailable ? array(
2433 'image' => $wgLang->getImageFile( 'button-media' ),
2434 'id' => 'mw-editbutton-media',
2435 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
2436 'close' => ']]',
2437 'sample' => wfMsg( 'media_sample' ),
2438 'tip' => wfMsg( 'media_tip' ),
2439 'key' => 'M'
2440 ) : false,
2441 $wgUseTeX ? array(
2442 'image' => $wgLang->getImageFile( 'button-math' ),
2443 'id' => 'mw-editbutton-math',
2444 'open' => "<math>",
2445 'close' => "</math>",
2446 'sample' => wfMsg( 'math_sample' ),
2447 'tip' => wfMsg( 'math_tip' ),
2448 'key' => 'C'
2449 ) : false,
2450 array(
2451 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2452 'id' => 'mw-editbutton-nowiki',
2453 'open' => "<nowiki>",
2454 'close' => "</nowiki>",
2455 'sample' => wfMsg( 'nowiki_sample' ),
2456 'tip' => wfMsg( 'nowiki_tip' ),
2457 'key' => 'N'
2458 ),
2459 array(
2460 'image' => $wgLang->getImageFile( 'button-sig' ),
2461 'id' => 'mw-editbutton-signature',
2462 'open' => '--~~~~',
2463 'close' => '',
2464 'sample' => '',
2465 'tip' => wfMsg( 'sig_tip' ),
2466 'key' => 'Y'
2467 ),
2468 array(
2469 'image' => $wgLang->getImageFile( 'button-hr' ),
2470 'id' => 'mw-editbutton-hr',
2471 'open' => "\n----\n",
2472 'close' => '',
2473 'sample' => '',
2474 'tip' => wfMsg( 'hr_tip' ),
2475 'key' => 'R'
2476 )
2477 );
2478 $toolbar = "<div id='toolbar'>\n";
2479
2480 $script = '';
2481 foreach ( $toolarray as $tool ) {
2482 if ( !$tool ) {
2483 continue;
2484 }
2485
2486 $params = array(
2487 $image = $wgStylePath . '/common/images/' . $tool['image'],
2488 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2489 // Older browsers show a "speedtip" type message only for ALT.
2490 // Ideally these should be different, realistically they
2491 // probably don't need to be.
2492 $tip = $tool['tip'],
2493 $open = $tool['open'],
2494 $close = $tool['close'],
2495 $sample = $tool['sample'],
2496 $cssId = $tool['id'],
2497 );
2498
2499 $paramList = implode( ',',
2500 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2501 $script .= "mw.toolbar.addButton($paramList);\n";
2502 }
2503 $wgOut->addScript( Html::inlineScript(
2504 "if ( window.mediaWiki ) {{$script}}"
2505 ) );
2506
2507 $toolbar .= "\n</div>";
2508
2509 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2510
2511 return $toolbar;
2512 }
2513
2514 /**
2515 * Returns an array of html code of the following checkboxes:
2516 * minor and watch
2517 *
2518 * @param $tabindex Current tabindex
2519 * @param $checked Array of checkbox => bool, where bool indicates the checked
2520 * status of the checkbox
2521 *
2522 * @return array
2523 */
2524 public function getCheckboxes( &$tabindex, $checked ) {
2525 global $wgUser;
2526
2527 $checkboxes = array();
2528
2529 // don't show the minor edit checkbox if it's a new page or section
2530 if ( !$this->isNew ) {
2531 $checkboxes['minor'] = '';
2532 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2533 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2534 $attribs = array(
2535 'tabindex' => ++$tabindex,
2536 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2537 'id' => 'wpMinoredit',
2538 );
2539 $checkboxes['minor'] =
2540 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2541 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
2542 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2543 ">{$minorLabel}</label>";
2544 }
2545 }
2546
2547 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2548 $checkboxes['watch'] = '';
2549 if ( $wgUser->isLoggedIn() ) {
2550 $attribs = array(
2551 'tabindex' => ++$tabindex,
2552 'accesskey' => wfMsg( 'accesskey-watch' ),
2553 'id' => 'wpWatchthis',
2554 );
2555 $checkboxes['watch'] =
2556 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2557 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
2558 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
2559 ">{$watchLabel}</label>";
2560 }
2561 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2562 return $checkboxes;
2563 }
2564
2565 /**
2566 * Returns an array of html code of the following buttons:
2567 * save, diff, preview and live
2568 *
2569 * @param $tabindex Current tabindex
2570 *
2571 * @return array
2572 */
2573 public function getEditButtons( &$tabindex ) {
2574 $buttons = array();
2575
2576 $temp = array(
2577 'id' => 'wpSave',
2578 'name' => 'wpSave',
2579 'type' => 'submit',
2580 'tabindex' => ++$tabindex,
2581 'value' => wfMsg( 'savearticle' ),
2582 'accesskey' => wfMsg( 'accesskey-save' ),
2583 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2584 );
2585 $buttons['save'] = Xml::element('input', $temp, '');
2586
2587 ++$tabindex; // use the same for preview and live preview
2588 $temp = array(
2589 'id' => 'wpPreview',
2590 'name' => 'wpPreview',
2591 'type' => 'submit',
2592 'tabindex' => $tabindex,
2593 'value' => wfMsg( 'showpreview' ),
2594 'accesskey' => wfMsg( 'accesskey-preview' ),
2595 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2596 );
2597 $buttons['preview'] = Xml::element( 'input', $temp, '' );
2598 $buttons['live'] = '';
2599
2600 $temp = array(
2601 'id' => 'wpDiff',
2602 'name' => 'wpDiff',
2603 'type' => 'submit',
2604 'tabindex' => ++$tabindex,
2605 'value' => wfMsg( 'showdiff' ),
2606 'accesskey' => wfMsg( 'accesskey-diff' ),
2607 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2608 );
2609 $buttons['diff'] = Xml::element( 'input', $temp, '' );
2610
2611 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2612 return $buttons;
2613 }
2614
2615 /**
2616 * Output preview text only. This can be sucked into the edit page
2617 * via JavaScript, and saves the server time rendering the skin as
2618 * well as theoretically being more robust on the client (doesn't
2619 * disturb the edit box's undo history, won't eat your text on
2620 * failure, etc).
2621 *
2622 * @todo This doesn't include category or interlanguage links.
2623 * Would need to enhance it a bit, <s>maybe wrap them in XML
2624 * or something...</s> that might also require more skin
2625 * initialization, so check whether that's a problem.
2626 */
2627 function livePreview() {
2628 global $wgOut;
2629 $wgOut->disable();
2630 header( 'Content-type: text/xml; charset=utf-8' );
2631 header( 'Cache-control: no-cache' );
2632
2633 $previewText = $this->getPreviewText();
2634 #$categories = $skin->getCategoryLinks();
2635
2636 $s =
2637 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2638 Xml::tags( 'livepreview', null,
2639 Xml::element( 'preview', null, $previewText )
2640 #. Xml::element( 'category', null, $categories )
2641 );
2642 echo $s;
2643 }
2644
2645 /**
2646 * @return string
2647 */
2648 public function getCancelLink() {
2649 $cancelParams = array();
2650 if ( !$this->isConflict && $this->mArticle->getOldID() > 0 ) {
2651 $cancelParams['oldid'] = $this->mArticle->getOldID();
2652 }
2653
2654 return Linker::linkKnown(
2655 $this->getContextTitle(),
2656 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2657 array( 'id' => 'mw-editform-cancel' ),
2658 $cancelParams
2659 );
2660 }
2661
2662 /**
2663 * Get a diff between the current contents of the edit box and the
2664 * version of the page we're editing from.
2665 *
2666 * If this is a section edit, we'll replace the section as for final
2667 * save and then make a comparison.
2668 */
2669 function showDiff() {
2670 $oldtext = $this->mArticle->fetchContent();
2671 $newtext = $this->mArticle->replaceSection(
2672 $this->section, $this->textbox1, $this->summary, $this->edittime );
2673
2674 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2675
2676 $newtext = $this->mArticle->preSaveTransform( $newtext );
2677 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2678 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2679 if ( $oldtext !== false || $newtext != '' ) {
2680 $de = new DifferenceEngine( $this->mTitle );
2681 $de->setText( $oldtext, $newtext );
2682 $difftext = $de->getDiff( $oldtitle, $newtitle );
2683 $de->showDiffStyle();
2684 } else {
2685 $difftext = '';
2686 }
2687
2688 global $wgOut;
2689 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2690 }
2691
2692 /**
2693 * Filter an input field through a Unicode de-armoring process if it
2694 * came from an old browser with known broken Unicode editing issues.
2695 *
2696 * @param $request WebRequest
2697 * @param $field String
2698 * @return String
2699 * @private
2700 */
2701 function safeUnicodeInput( $request, $field ) {
2702 $text = rtrim( $request->getText( $field ) );
2703 return $request->getBool( 'safemode' )
2704 ? $this->unmakesafe( $text )
2705 : $text;
2706 }
2707
2708 /**
2709 * @param $request WebRequest
2710 * @param $text string
2711 * @return string
2712 */
2713 function safeUnicodeText( $request, $text ) {
2714 $text = rtrim( $text );
2715 return $request->getBool( 'safemode' )
2716 ? $this->unmakesafe( $text )
2717 : $text;
2718 }
2719
2720 /**
2721 * Filter an output field through a Unicode armoring process if it is
2722 * going to an old browser with known broken Unicode editing issues.
2723 *
2724 * @param $text String
2725 * @return String
2726 * @private
2727 */
2728 function safeUnicodeOutput( $text ) {
2729 global $wgContLang;
2730 $codedText = $wgContLang->recodeForEdit( $text );
2731 return $this->checkUnicodeCompliantBrowser()
2732 ? $codedText
2733 : $this->makesafe( $codedText );
2734 }
2735
2736 /**
2737 * A number of web browsers are known to corrupt non-ASCII characters
2738 * in a UTF-8 text editing environment. To protect against this,
2739 * detected browsers will be served an armored version of the text,
2740 * with non-ASCII chars converted to numeric HTML character references.
2741 *
2742 * Preexisting such character references will have a 0 added to them
2743 * to ensure that round-trips do not alter the original data.
2744 *
2745 * @param $invalue String
2746 * @return String
2747 * @private
2748 */
2749 function makesafe( $invalue ) {
2750 // Armor existing references for reversability.
2751 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2752
2753 $bytesleft = 0;
2754 $result = "";
2755 $working = 0;
2756 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2757 $bytevalue = ord( $invalue[$i] );
2758 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2759 $result .= chr( $bytevalue );
2760 $bytesleft = 0;
2761 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2762 $working = $working << 6;
2763 $working += ($bytevalue & 0x3F);
2764 $bytesleft--;
2765 if ( $bytesleft <= 0 ) {
2766 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2767 }
2768 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2769 $working = $bytevalue & 0x1F;
2770 $bytesleft = 1;
2771 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2772 $working = $bytevalue & 0x0F;
2773 $bytesleft = 2;
2774 } else { //1111 0xxx
2775 $working = $bytevalue & 0x07;
2776 $bytesleft = 3;
2777 }
2778 }
2779 return $result;
2780 }
2781
2782 /**
2783 * Reverse the previously applied transliteration of non-ASCII characters
2784 * back to UTF-8. Used to protect data from corruption by broken web browsers
2785 * as listed in $wgBrowserBlackList.
2786 *
2787 * @param $invalue String
2788 * @return String
2789 * @private
2790 */
2791 function unmakesafe( $invalue ) {
2792 $result = "";
2793 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2794 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+3] != '0' ) ) {
2795 $i += 3;
2796 $hexstring = "";
2797 do {
2798 $hexstring .= $invalue[$i];
2799 $i++;
2800 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
2801
2802 // Do some sanity checks. These aren't needed for reversability,
2803 // but should help keep the breakage down if the editor
2804 // breaks one of the entities whilst editing.
2805 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2806 $codepoint = hexdec($hexstring);
2807 $result .= codepointToUtf8( $codepoint );
2808 } else {
2809 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2810 }
2811 } else {
2812 $result .= substr( $invalue, $i, 1 );
2813 }
2814 }
2815 // reverse the transform that we made for reversability reasons.
2816 return strtr( $result, array( "&#x0" => "&#x" ) );
2817 }
2818
2819 function noCreatePermission() {
2820 global $wgOut;
2821 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2822 $wgOut->addWikiMsg( 'nocreatetext' );
2823 }
2824
2825 /**
2826 * Attempt submission
2827 * @return bool false if output is done, true if the rest of the form should be displayed
2828 */
2829 function attemptSave() {
2830 global $wgUser, $wgOut;
2831
2832 $resultDetails = false;
2833 # Allow bots to exempt some edits from bot flagging
2834 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
2835 $value = $this->internalAttemptSave( $resultDetails, $bot );
2836
2837 if ( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2838 $this->didSave = true;
2839 }
2840
2841 switch ( $value ) {
2842 case self::AS_HOOK_ERROR_EXPECTED:
2843 case self::AS_CONTENT_TOO_BIG:
2844 case self::AS_ARTICLE_WAS_DELETED:
2845 case self::AS_CONFLICT_DETECTED:
2846 case self::AS_SUMMARY_NEEDED:
2847 case self::AS_TEXTBOX_EMPTY:
2848 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
2849 case self::AS_END:
2850 return true;
2851
2852 case self::AS_HOOK_ERROR:
2853 case self::AS_FILTERING:
2854 return false;
2855
2856 case self::AS_SUCCESS_NEW_ARTICLE:
2857 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
2858 $wgOut->redirect( $this->mTitle->getFullURL( $query ) );
2859 return false;
2860
2861 case self::AS_SUCCESS_UPDATE:
2862 $extraQuery = '';
2863 $sectionanchor = $resultDetails['sectionanchor'];
2864
2865 // Give extensions a chance to modify URL query on update
2866 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle, &$sectionanchor, &$extraQuery ) );
2867
2868 if ( $resultDetails['redirect'] ) {
2869 if ( $extraQuery == '' ) {
2870 $extraQuery = 'redirect=no';
2871 } else {
2872 $extraQuery = 'redirect=no&' . $extraQuery;
2873 }
2874 }
2875 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
2876 return false;
2877
2878 case self::AS_SPAM_ERROR:
2879 $this->spamPageWithContent( $resultDetails['spam'] );
2880 return false;
2881
2882 case self::AS_BLOCKED_PAGE_FOR_USER:
2883 $this->blockedPage();
2884 return false;
2885
2886 case self::AS_IMAGE_REDIRECT_ANON:
2887 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2888 return false;
2889
2890 case self::AS_READ_ONLY_PAGE_ANON:
2891 $this->userNotLoggedInPage();
2892 return false;
2893
2894 case self::AS_READ_ONLY_PAGE_LOGGED:
2895 case self::AS_READ_ONLY_PAGE:
2896 $wgOut->readOnlyPage();
2897 return false;
2898
2899 case self::AS_RATE_LIMITED:
2900 $wgOut->rateLimited();
2901 return false;
2902
2903 case self::AS_NO_CREATE_PERMISSION:
2904 $this->noCreatePermission();
2905 return false;
2906
2907 case self::AS_BLANK_ARTICLE:
2908 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
2909 return false;
2910
2911 case self::AS_IMAGE_REDIRECT_LOGGED:
2912 $wgOut->permissionRequired( 'upload' );
2913 return false;
2914 }
2915 }
2916
2917 /**
2918 * @return Revision
2919 */
2920 function getBaseRevision() {
2921 if ( !$this->mBaseRevision ) {
2922 $db = wfGetDB( DB_MASTER );
2923 $baseRevision = Revision::loadFromTimestamp(
2924 $db, $this->mTitle, $this->edittime );
2925 return $this->mBaseRevision = $baseRevision;
2926 } else {
2927 return $this->mBaseRevision;
2928 }
2929 }
2930 }