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