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