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