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