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