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