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