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