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