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