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