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