Back out r93533, r93531, r93530
[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 }
1032 }
1033 $userid = $wgUser->getId();
1034
1035 # Suppress edit conflict with self, except for section edits where merging is required.
1036 if ( $this->isConflict && $this->section == '' && $this->userWasLastToEdit( $userid, $this->edittime ) ) {
1037 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1038 $this->isConflict = false;
1039 }
1040
1041 if ( $this->isConflict ) {
1042 wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
1043 $this->mArticle->getTimestamp() . "')\n" );
1044 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime );
1045 } else {
1046 wfDebug( __METHOD__ . ": getting section '$this->section'\n" );
1047 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary );
1048 }
1049 if ( is_null( $text ) ) {
1050 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1051 $this->isConflict = true;
1052 $text = $this->textbox1; // do not try to merge here!
1053 } elseif ( $this->isConflict ) {
1054 # Attempt merge
1055 if ( $this->mergeChangesInto( $text ) ) {
1056 // Successful merge! Maybe we should tell the user the good news?
1057 $this->isConflict = false;
1058 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1059 } else {
1060 $this->section = '';
1061 $this->textbox1 = $text;
1062 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1063 }
1064 }
1065
1066 if ( $this->isConflict ) {
1067 wfProfileOut( __METHOD__ );
1068 return self::AS_CONFLICT_DETECTED;
1069 }
1070
1071 $oldtext = $this->mArticle->getContent();
1072
1073 // Run post-section-merge edit filter
1074 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError, $this->summary ) ) ) {
1075 # Error messages etc. could be handled within the hook...
1076 wfProfileOut( __METHOD__ );
1077 return self::AS_HOOK_ERROR;
1078 } elseif ( $this->hookError != '' ) {
1079 # ...or the hook could be expecting us to produce an error
1080 wfProfileOut( __METHOD__ );
1081 return self::AS_HOOK_ERROR_EXPECTED;
1082 }
1083
1084 # Handle the user preference to force summaries here, but not for null edits
1085 if ( $this->section != 'new' && !$this->allowBlankSummary && 0 != strcmp( $oldtext, $text )
1086 && !Title::newFromRedirect( $text ) ) # check if it's not a redirect
1087 {
1088 if ( md5( $this->summary ) == $this->autoSumm ) {
1089 $this->missingSummary = true;
1090 wfProfileOut( __METHOD__ );
1091 return self::AS_SUMMARY_NEEDED;
1092 }
1093 }
1094
1095 # And a similar thing for new sections
1096 if ( $this->section == 'new' && !$this->allowBlankSummary ) {
1097 if ( trim( $this->summary ) == '' ) {
1098 $this->missingSummary = true;
1099 wfProfileOut( __METHOD__ );
1100 return self::AS_SUMMARY_NEEDED;
1101 }
1102 }
1103
1104 # All's well
1105 wfProfileIn( __METHOD__ . '-sectionanchor' );
1106 $sectionanchor = '';
1107 if ( $this->section == 'new' ) {
1108 if ( $this->textbox1 == '' ) {
1109 $this->missingComment = true;
1110 wfProfileOut( __METHOD__ . '-sectionanchor' );
1111 wfProfileOut( __METHOD__ );
1112 return self::AS_TEXTBOX_EMPTY;
1113 }
1114 if ( $this->summary != '' ) {
1115 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1116 # This is a new section, so create a link to the new section
1117 # in the revision summary.
1118 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1119 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
1120 }
1121 } elseif ( $this->section != '' ) {
1122 # Try to get a section anchor from the section source, redirect to edited section if header found
1123 # XXX: might be better to integrate this into Article::replaceSection
1124 # for duplicate heading checking and maybe parsing
1125 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1126 # we can't deal with anchors, includes, html etc in the header for now,
1127 # headline would need to be parsed to improve this
1128 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1129 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1130 }
1131 }
1132 $result['sectionanchor'] = $sectionanchor;
1133 wfProfileOut( __METHOD__ . '-sectionanchor' );
1134
1135 // Save errors may fall down to the edit form, but we've now
1136 // merged the section into full text. Clear the section field
1137 // so that later submission of conflict forms won't try to
1138 // replace that into a duplicated mess.
1139 $this->textbox1 = $text;
1140 $this->section = '';
1141
1142 $retval = self::AS_SUCCESS_UPDATE;
1143 }
1144
1145 // Check for length errors again now that the section is merged in
1146 $this->kblength = (int)( strlen( $text ) / 1024 );
1147 if ( $this->kblength > $wgMaxArticleSize ) {
1148 $this->tooBig = true;
1149 wfProfileOut( __METHOD__ );
1150 return self::AS_MAX_ARTICLE_SIZE_EXCEEDED;
1151 }
1152
1153 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1154 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1155 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1156 ( $bot ? EDIT_FORCE_BOT : 0 );
1157
1158 $status = $this->mArticle->doEdit( $text, $this->summary, $flags );
1159
1160 if ( $status->isOK() ) {
1161 $result['redirect'] = Title::newFromRedirect( $text ) !== null;
1162 $this->commitWatch();
1163 wfProfileOut( __METHOD__ );
1164 return $retval;
1165 } else {
1166 $this->isConflict = true;
1167 wfProfileOut( __METHOD__ );
1168 return self::AS_END;
1169 }
1170 }
1171
1172 /**
1173 * Commit the change of watch status
1174 */
1175 protected function commitWatch() {
1176 global $wgUser;
1177 if ( $this->watchthis xor $this->mTitle->userIsWatching() ) {
1178 $dbw = wfGetDB( DB_MASTER );
1179 $dbw->begin();
1180 if ( $this->watchthis ) {
1181 WatchAction::doWatch( $this->mTitle, $wgUser );
1182 } else {
1183 WatchAction::doUnwatch( $this->mTitle, $wgUser );
1184 }
1185 $dbw->commit();
1186 }
1187 }
1188
1189 /**
1190 * Check if no edits were made by other users since
1191 * the time a user started editing the page. Limit to
1192 * 50 revisions for the sake of performance.
1193 *
1194 * @param $id int
1195 * @param $edittime string
1196 *
1197 * @return bool
1198 */
1199 protected function userWasLastToEdit( $id, $edittime ) {
1200 if( !$id ) return false;
1201 $dbw = wfGetDB( DB_MASTER );
1202 $res = $dbw->select( 'revision',
1203 'rev_user',
1204 array(
1205 'rev_page' => $this->mArticle->getId(),
1206 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1207 ),
1208 __METHOD__,
1209 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1210 foreach ( $res as $row ) {
1211 if( $row->rev_user != $id ) {
1212 return false;
1213 }
1214 }
1215 return true;
1216 }
1217
1218 /**
1219 * Check given input text against $wgSpamRegex, and return the text of the first match.
1220 *
1221 * @param $text string
1222 *
1223 * @return string|false matching string or false
1224 */
1225 public static function matchSpamRegex( $text ) {
1226 global $wgSpamRegex;
1227 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1228 $regexes = (array)$wgSpamRegex;
1229 return self::matchSpamRegexInternal( $text, $regexes );
1230 }
1231
1232 /**
1233 * Check given input text against $wgSpamRegex, and return the text of the first match.
1234 *
1235 * @parma $text string
1236 *
1237 * @return string|false matching string or false
1238 */
1239 public static function matchSummarySpamRegex( $text ) {
1240 global $wgSummarySpamRegex;
1241 $regexes = (array)$wgSummarySpamRegex;
1242 return self::matchSpamRegexInternal( $text, $regexes );
1243 }
1244
1245 /**
1246 * @param $text string
1247 * @param $regexes array
1248 * @return bool|string
1249 */
1250 protected static function matchSpamRegexInternal( $text, $regexes ) {
1251 foreach( $regexes as $regex ) {
1252 $matches = array();
1253 if( preg_match( $regex, $text, $matches ) ) {
1254 return $matches[0];
1255 }
1256 }
1257 return false;
1258 }
1259
1260 /**
1261 * Initialise form fields in the object
1262 * Called on the first invocation, e.g. when a user clicks an edit link
1263 * @return bool -- if the requested section is valid
1264 */
1265 function initialiseForm() {
1266 global $wgUser;
1267 $this->edittime = $this->mArticle->getTimestamp();
1268 $this->textbox1 = $this->getContent( false );
1269 // activate checkboxes if user wants them to be always active
1270 # Sort out the "watch" checkbox
1271 if ( $wgUser->getOption( 'watchdefault' ) ) {
1272 # Watch all edits
1273 $this->watchthis = true;
1274 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1275 # Watch creations
1276 $this->watchthis = true;
1277 } elseif ( $this->mTitle->userIsWatching() ) {
1278 # Already watched
1279 $this->watchthis = true;
1280 }
1281 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
1282 $this->minoredit = true;
1283 }
1284 if ( $this->textbox1 === false ) {
1285 return false;
1286 }
1287 wfProxyCheck();
1288 return true;
1289 }
1290
1291 function setHeaders() {
1292 global $wgOut;
1293 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1294 if ( $this->formtype == 'preview' ) {
1295 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1296 }
1297 if ( $this->isConflict ) {
1298 $wgOut->setPageTitle( wfMsg( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1299 } elseif ( $this->section != '' ) {
1300 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
1301 $wgOut->setPageTitle( wfMsg( $msg, $this->getContextTitle()->getPrefixedText() ) );
1302 } else {
1303 # Use the title defined by DISPLAYTITLE magic word when present
1304 if ( isset( $this->mParserOutput )
1305 && ( $dt = $this->mParserOutput->getDisplayTitle() ) !== false ) {
1306 $title = $dt;
1307 } else {
1308 $title = $this->getContextTitle()->getPrefixedText();
1309 }
1310 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1311 }
1312 }
1313
1314 /**
1315 * Send the edit form and related headers to $wgOut
1316 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1317 * during form output near the top, for captchas and the like.
1318 */
1319 function showEditForm( $formCallback = null ) {
1320 global $wgOut, $wgUser;
1321
1322 wfProfileIn( __METHOD__ );
1323
1324 #need to parse the preview early so that we know which templates are used,
1325 #otherwise users with "show preview after edit box" will get a blank list
1326 #we parse this near the beginning so that setHeaders can do the title
1327 #setting work instead of leaving it in getPreviewText
1328 $previewOutput = '';
1329 if ( $this->formtype == 'preview' ) {
1330 $previewOutput = $this->getPreviewText();
1331 }
1332
1333 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$formCallback ) );
1334
1335 $this->setHeaders();
1336
1337 # Enabled article-related sidebar, toplinks, etc.
1338 $wgOut->setArticleRelated( true );
1339
1340 if ( $this->showHeader() === false ) {
1341 wfProfileOut( __METHOD__ );
1342 return;
1343 }
1344
1345 $action = htmlspecialchars( $this->getActionURL( $this->getContextTitle() ) );
1346
1347 if ( $wgUser->getOption( 'showtoolbar' ) and !$this->isCssJsSubpage ) {
1348 # prepare toolbar for edit buttons
1349 $toolbar = EditPage::getEditToolbar();
1350 } else {
1351 $toolbar = '';
1352 }
1353
1354
1355 $wgOut->addHTML( $this->editFormPageTop );
1356
1357 if ( $wgUser->getOption( 'previewontop' ) ) {
1358 $this->displayPreviewArea( $previewOutput, true );
1359 }
1360
1361 $wgOut->addHTML( $this->editFormTextTop );
1362
1363 $templates = $this->getTemplates();
1364 $formattedtemplates = Linker::formatTemplates( $templates, $this->preview, $this->section != '');
1365
1366 $hiddencats = $this->mArticle->getHiddenCategories();
1367 $formattedhiddencats = Linker::formatHiddenCategories( $hiddencats );
1368
1369 if ( $this->wasDeletedSinceLastEdit() && 'save' != $this->formtype ) {
1370 $wgOut->wrapWikiMsg(
1371 "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1372 'deletedwhileediting' );
1373 } elseif ( $this->wasDeletedSinceLastEdit() ) {
1374 // Hide the toolbar and edit area, user can click preview to get it back
1375 // Add an confirmation checkbox and explanation.
1376 $toolbar = '';
1377 // @todo move this to a cleaner conditional instead of blanking a variable
1378 }
1379 $wgOut->addHTML( <<<HTML
1380 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1381 HTML
1382 );
1383
1384 if ( is_callable( $formCallback ) ) {
1385 call_user_func_array( $formCallback, array( &$wgOut ) );
1386 }
1387
1388 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1389
1390 // Put these up at the top to ensure they aren't lost on early form submission
1391 $this->showFormBeforeText();
1392
1393 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
1394 $username = $this->lastDelete->user_name;
1395 $comment = $this->lastDelete->log_comment;
1396
1397 // It is better to not parse the comment at all than to have templates expanded in the middle
1398 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1399 $key = $comment === ''
1400 ? 'confirmrecreate-noreason'
1401 : 'confirmrecreate';
1402 $wgOut->addHTML(
1403 '<div class="mw-confirm-recreate">' .
1404 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1405 Xml::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1406 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1407 ) .
1408 '</div>'
1409 );
1410 }
1411
1412 # If a blank edit summary was previously provided, and the appropriate
1413 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1414 # user being bounced back more than once in the event that a summary
1415 # is not required.
1416 #####
1417 # For a bit more sophisticated detection of blank summaries, hash the
1418 # automatic one and pass that in the hidden field wpAutoSummary.
1419 if ( $this->missingSummary ||
1420 ( $this->section == 'new' && $this->nosummary ) )
1421 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
1422 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1423 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
1424
1425 $wgOut->addHTML( Html::hidden( 'oldid', $this->mArticle->getOldID() ) );
1426
1427 if ( $this->section == 'new' ) {
1428 $this->showSummaryInput( true, $this->summary );
1429 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
1430 }
1431
1432 $wgOut->addHTML( $this->editFormTextBeforeContent );
1433
1434 $wgOut->addHTML( $toolbar );
1435
1436 if ( $this->isConflict ) {
1437 // In an edit conflict bypass the overrideable content form method
1438 // and fallback to the raw wpTextbox1 since editconflicts can't be
1439 // resolved between page source edits and custom ui edits using the
1440 // custom edit ui.
1441 $this->showTextbox1( null, $this->getContent() );
1442 } else {
1443 $this->showContentForm();
1444 }
1445
1446 $wgOut->addHTML( $this->editFormTextAfterContent );
1447
1448 $wgOut->addWikiText( $this->getCopywarn() );
1449 if ( isset($this->editFormTextAfterWarn) && $this->editFormTextAfterWarn !== '' )
1450 $wgOut->addHTML( $this->editFormTextAfterWarn );
1451
1452 $this->showStandardInputs();
1453
1454 $this->showFormAfterText();
1455
1456 $this->showTosSummary();
1457 $this->showEditTools();
1458
1459 $wgOut->addHTML( <<<HTML
1460 {$this->editFormTextAfterTools}
1461 <div class='templatesUsed'>
1462 {$formattedtemplates}
1463 </div>
1464 <div class='hiddencats'>
1465 {$formattedhiddencats}
1466 </div>
1467 HTML
1468 );
1469
1470 if ( $this->isConflict )
1471 $this->showConflict();
1472
1473 $wgOut->addHTML( $this->editFormTextBottom );
1474 $wgOut->addHTML( "</form>\n" );
1475 if ( !$wgUser->getOption( 'previewontop' ) ) {
1476 $this->displayPreviewArea( $previewOutput, false );
1477 }
1478
1479 wfProfileOut( __METHOD__ );
1480 }
1481
1482 protected function showHeader() {
1483 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1484 if ( $this->isConflict ) {
1485 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1486 $this->edittime = $this->mArticle->getTimestamp();
1487 } else {
1488 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
1489 // We use $this->section to much before this and getVal('wgSection') directly in other places
1490 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1491 // Someone is welcome to try refactoring though
1492 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1493 return false;
1494 }
1495
1496 if ( $this->section != '' && $this->section != 'new' ) {
1497 $matches = array();
1498 if ( !$this->summary && !$this->preview && !$this->diff ) {
1499 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1, $matches );
1500 if ( !empty( $matches[2] ) ) {
1501 global $wgParser;
1502 $this->summary = "/* " .
1503 $wgParser->stripSectionName(trim($matches[2])) .
1504 " */ ";
1505 }
1506 }
1507 }
1508
1509 if ( $this->missingComment ) {
1510 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1511 }
1512
1513 if ( $this->missingSummary && $this->section != 'new' ) {
1514 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1515 }
1516
1517 if ( $this->missingSummary && $this->section == 'new' ) {
1518 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1519 }
1520
1521 if ( $this->hookError !== '' ) {
1522 $wgOut->addWikiText( $this->hookError );
1523 }
1524
1525 if ( !$this->checkUnicodeCompliantBrowser() ) {
1526 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1527 }
1528
1529 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
1530 // Let sysop know that this will make private content public if saved
1531
1532 if ( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1533 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1534 } elseif ( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1535 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1536 }
1537
1538 if ( !$this->mArticle->mRevision->isCurrent() ) {
1539 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
1540 $wgOut->addWikiMsg( 'editingold' );
1541 }
1542 }
1543 }
1544
1545 if ( wfReadOnly() ) {
1546 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1547 } elseif ( $wgUser->isAnon() ) {
1548 if ( $this->formtype != 'preview' ) {
1549 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1550 } else {
1551 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
1552 }
1553 } else {
1554 if ( $this->isCssJsSubpage ) {
1555 # Check the skin exists
1556 if ( $this->isWrongCaseCssJsPage ) {
1557 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->getContextTitle()->getSkinFromCssJsSubpage() ) );
1558 }
1559 if ( $this->formtype !== 'preview' ) {
1560 if ( $this->isCssSubpage )
1561 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
1562 if ( $this->isJsSubpage )
1563 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
1564 }
1565 }
1566 }
1567
1568 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
1569 # Is the title semi-protected?
1570 if ( $this->mTitle->isSemiProtected() ) {
1571 $noticeMsg = 'semiprotectedpagewarning';
1572 } else {
1573 # Then it must be protected based on static groups (regular)
1574 $noticeMsg = 'protectedpagewarning';
1575 }
1576 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle->getPrefixedText(), '',
1577 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1578 }
1579 if ( $this->mTitle->isCascadeProtected() ) {
1580 # Is this page under cascading protection from some source pages?
1581 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1582 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
1583 $cascadeSourcesCount = count( $cascadeSources );
1584 if ( $cascadeSourcesCount > 0 ) {
1585 # Explain, and list the titles responsible
1586 foreach( $cascadeSources as $page ) {
1587 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1588 }
1589 }
1590 $notice .= '</div>';
1591 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1592 }
1593 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
1594 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle->getPrefixedText(), '',
1595 array( 'lim' => 1,
1596 'showIfEmpty' => false,
1597 'msgKey' => array( 'titleprotectedwarning' ),
1598 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
1599 }
1600
1601 if ( $this->kblength === false ) {
1602 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1603 }
1604
1605 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1606 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
1607 array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
1608 } else {
1609 if( !wfMessage('longpage-hint')->isDisabled() ) {
1610 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
1611 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
1612 );
1613 }
1614 }
1615 }
1616
1617 /**
1618 * Standard summary input and label (wgSummary), abstracted so EditPage
1619 * subclasses may reorganize the form.
1620 * Note that you do not need to worry about the label's for=, it will be
1621 * inferred by the id given to the input. You can remove them both by
1622 * passing array( 'id' => false ) to $userInputAttrs.
1623 *
1624 * @param $summary string The value of the summary input
1625 * @param $labelText string The html to place inside the label
1626 * @param $inputAttrs array of attrs to use on the input
1627 * @param $spanLabelAttrs array of attrs to use on the span inside the label
1628 *
1629 * @return array An array in the format array( $label, $input )
1630 */
1631 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
1632 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
1633 $inputAttrs = ( is_array($inputAttrs) ? $inputAttrs : array() ) + array(
1634 'id' => 'wpSummary',
1635 'maxlength' => '200',
1636 'tabindex' => '1',
1637 'size' => 60,
1638 'spellcheck' => 'true',
1639 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
1640
1641 $spanLabelAttrs = ( is_array($spanLabelAttrs) ? $spanLabelAttrs : array() ) + array(
1642 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
1643 'id' => "wpSummaryLabel"
1644 );
1645
1646 $label = null;
1647 if ( $labelText ) {
1648 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1649 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
1650 }
1651
1652 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
1653
1654 return array( $label, $input );
1655 }
1656
1657 /**
1658 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1659 * up top, or false if this is the comment summary
1660 * down below the textarea
1661 * @param $summary String: The text of the summary to display
1662 * @return String
1663 */
1664 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1665 global $wgOut, $wgContLang;
1666 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1667 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
1668 if ( $isSubjectPreview ) {
1669 if ( $this->nosummary ) {
1670 return;
1671 }
1672 } else {
1673 if ( !$this->mShowSummaryField ) {
1674 return;
1675 }
1676 }
1677 $summary = $wgContLang->recodeForEdit( $summary );
1678 $labelText = wfMsgExt( $isSubjectPreview ? 'subject' : 'summary', 'parseinline' );
1679 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
1680 $wgOut->addHTML("{$label} {$input}");
1681 }
1682
1683 /**
1684 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1685 * up top, or false if this is the comment summary
1686 * down below the textarea
1687 * @param $summary String: the text of the summary to display
1688 * @return String
1689 */
1690 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
1691 if ( !$summary || ( !$this->preview && !$this->diff ) )
1692 return "";
1693
1694 global $wgParser;
1695
1696 if ( $isSubjectPreview )
1697 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
1698
1699 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
1700
1701 $summary = wfMsgExt( $message, 'parseinline' ) . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
1702 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
1703 }
1704
1705 protected function showFormBeforeText() {
1706 global $wgOut;
1707 $section = htmlspecialchars( $this->section );
1708 $wgOut->addHTML( <<<HTML
1709 <input type='hidden' value="{$section}" name="wpSection" />
1710 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
1711 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
1712 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
1713
1714 HTML
1715 );
1716 if ( !$this->checkUnicodeCompliantBrowser() )
1717 $wgOut->addHTML(Html::hidden( 'safemode', '1' ));
1718 }
1719
1720 protected function showFormAfterText() {
1721 global $wgOut, $wgUser;
1722 /**
1723 * To make it harder for someone to slip a user a page
1724 * which submits an edit form to the wiki without their
1725 * knowledge, a random token is associated with the login
1726 * session. If it's not passed back with the submission,
1727 * we won't save the page, or render user JavaScript and
1728 * CSS previews.
1729 *
1730 * For anon editors, who may not have a session, we just
1731 * include the constant suffix to prevent editing from
1732 * broken text-mangling proxies.
1733 */
1734 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->editToken() ) . "\n" );
1735 }
1736
1737 /**
1738 * Subpage overridable method for printing the form for page content editing
1739 * By default this simply outputs wpTextbox1
1740 * Subclasses can override this to provide a custom UI for editing;
1741 * be it a form, or simply wpTextbox1 with a modified content that will be
1742 * reverse modified when extracted from the post data.
1743 * Note that this is basically the inverse for importContentFormData
1744 */
1745 protected function showContentForm() {
1746 $this->showTextbox1();
1747 }
1748
1749 /**
1750 * Method to output wpTextbox1
1751 * The $textoverride method can be used by subclasses overriding showContentForm
1752 * to pass back to this method.
1753 *
1754 * @param $customAttribs An array of html attributes to use in the textarea
1755 * @param $textoverride String: optional text to override $this->textarea1 with
1756 */
1757 protected function showTextbox1($customAttribs = null, $textoverride = null) {
1758 $classes = array(); // Textarea CSS
1759 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
1760 # Is the title semi-protected?
1761 if ( $this->mTitle->isSemiProtected() ) {
1762 $classes[] = 'mw-textarea-sprotected';
1763 } else {
1764 # Then it must be protected based on static groups (regular)
1765 $classes[] = 'mw-textarea-protected';
1766 }
1767 # Is the title cascade-protected?
1768 if ( $this->mTitle->isCascadeProtected() ) {
1769 $classes[] = 'mw-textarea-cprotected';
1770 }
1771 }
1772 $attribs = array( 'tabindex' => 1 );
1773 if ( is_array($customAttribs) )
1774 $attribs += $customAttribs;
1775
1776 if ( $this->wasDeletedSinceLastEdit() )
1777 $attribs['type'] = 'hidden';
1778 if ( !empty( $classes ) ) {
1779 if ( isset($attribs['class']) )
1780 $classes[] = $attribs['class'];
1781 $attribs['class'] = implode( ' ', $classes );
1782 }
1783
1784 $this->showTextbox( isset($textoverride) ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
1785 }
1786
1787 protected function showTextbox2() {
1788 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
1789 }
1790
1791 protected function showTextbox( $content, $name, $customAttribs = array() ) {
1792 global $wgOut, $wgUser;
1793
1794 $wikitext = $this->safeUnicodeOutput( $content );
1795 if ( $wikitext !== '' ) {
1796 // Ensure there's a newline at the end, otherwise adding lines
1797 // is awkward.
1798 // But don't add a newline if the ext is empty, or Firefox in XHTML
1799 // mode will show an extra newline. A bit annoying.
1800 $wikitext .= "\n";
1801 }
1802
1803 $attribs = $customAttribs + array(
1804 'accesskey' => ',',
1805 'id' => $name,
1806 'cols' => $wgUser->getIntOption( 'cols' ),
1807 'rows' => $wgUser->getIntOption( 'rows' ),
1808 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
1809 );
1810
1811 $pageLang = $this->mTitle->getPageLanguage();
1812 $attribs['lang'] = $pageLang->getCode();
1813 $attribs['dir'] = $pageLang->getDir();
1814
1815 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
1816 }
1817
1818 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1819 global $wgOut;
1820 $classes = array();
1821 if ( $isOnTop )
1822 $classes[] = 'ontop';
1823
1824 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1825
1826 if ( $this->formtype != 'preview' )
1827 $attribs['style'] = 'display: none;';
1828
1829 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
1830
1831 if ( $this->formtype == 'preview' ) {
1832 $this->showPreview( $previewOutput );
1833 }
1834
1835 $wgOut->addHTML( '</div>' );
1836
1837 if ( $this->formtype == 'diff') {
1838 $this->showDiff();
1839 }
1840 }
1841
1842 /**
1843 * Append preview output to $wgOut.
1844 * Includes category rendering if this is a category page.
1845 *
1846 * @param $text String: the HTML to be output for the preview.
1847 */
1848 protected function showPreview( $text ) {
1849 global $wgOut;
1850 if ( $this->mTitle->getNamespace() == NS_CATEGORY) {
1851 $this->mArticle->openShowCategory();
1852 }
1853 # This hook seems slightly odd here, but makes things more
1854 # consistent for extensions.
1855 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1856 $wgOut->addHTML( $text );
1857 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1858 $this->mArticle->closeShowCategory();
1859 }
1860 }
1861
1862 /**
1863 * Give a chance for site and per-namespace customizations of
1864 * terms of service summary link that might exist separately
1865 * from the copyright notice.
1866 *
1867 * This will display between the save button and the edit tools,
1868 * so should remain short!
1869 */
1870 protected function showTosSummary() {
1871 $msg = 'editpage-tos-summary';
1872 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
1873 if( !wfMessage( $msg )->isDisabled() ) {
1874 global $wgOut;
1875 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1876 $wgOut->addWikiMsg( $msg );
1877 $wgOut->addHTML( '</div>' );
1878 }
1879 }
1880
1881 protected function showEditTools() {
1882 global $wgOut;
1883 $wgOut->addHTML( '<div class="mw-editTools">' .
1884 wfMessage( 'edittools' )->inContentLanguage()->parse() .
1885 '</div>' );
1886 }
1887
1888 protected function getCopywarn() {
1889 global $wgRightsText;
1890 if ( $wgRightsText ) {
1891 $copywarnMsg = array( 'copyrightwarning',
1892 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1893 $wgRightsText );
1894 } else {
1895 $copywarnMsg = array( 'copyrightwarning2',
1896 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1897 }
1898 // Allow for site and per-namespace customization of contribution/copyright notice.
1899 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
1900
1901 return "<div id=\"editpage-copywarn\">\n" .
1902 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
1903 }
1904
1905 protected function showStandardInputs( &$tabindex = 2 ) {
1906 global $wgOut;
1907 $wgOut->addHTML( "<div class='editOptions'>\n" );
1908
1909 if ( $this->section != 'new' ) {
1910 $this->showSummaryInput( false, $this->summary );
1911 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
1912 }
1913
1914 $checkboxes = $this->getCheckboxes( $tabindex,
1915 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1916 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
1917 $wgOut->addHTML( "<div class='editButtons'>\n" );
1918 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
1919
1920 $cancel = $this->getCancelLink();
1921 if ( $cancel !== '' ) {
1922 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1923 }
1924 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
1925 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1926 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1927 htmlspecialchars( wfMsg( 'newwindow' ) );
1928 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
1929 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
1930 }
1931
1932 /**
1933 * Show an edit conflict. textbox1 is already shown in showEditForm().
1934 * If you want to use another entry point to this function, be careful.
1935 */
1936 protected function showConflict() {
1937 global $wgOut;
1938 $this->textbox2 = $this->textbox1;
1939 $this->textbox1 = $this->getContent();
1940 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1941 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
1942
1943 $de = new DifferenceEngine( $this->mTitle );
1944 $de->setText( $this->textbox2, $this->textbox1 );
1945 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1946
1947 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
1948 $this->showTextbox2();
1949 }
1950 }
1951
1952 protected function getLastDelete() {
1953 $dbr = wfGetDB( DB_SLAVE );
1954 $data = $dbr->selectRow(
1955 array( 'logging', 'user' ),
1956 array( 'log_type',
1957 'log_action',
1958 'log_timestamp',
1959 'log_user',
1960 'log_namespace',
1961 'log_title',
1962 'log_comment',
1963 'log_params',
1964 'log_deleted',
1965 'user_name' ),
1966 array( 'log_namespace' => $this->mTitle->getNamespace(),
1967 'log_title' => $this->mTitle->getDBkey(),
1968 'log_type' => 'delete',
1969 'log_action' => 'delete',
1970 'user_id=log_user' ),
1971 __METHOD__,
1972 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1973 );
1974 // Quick paranoid permission checks...
1975 if( is_object( $data ) ) {
1976 if( $data->log_deleted & LogPage::DELETED_USER )
1977 $data->user_name = wfMsgHtml( 'rev-deleted-user' );
1978 if( $data->log_deleted & LogPage::DELETED_COMMENT )
1979 $data->log_comment = wfMsgHtml( 'rev-deleted-comment' );
1980 }
1981 return $data;
1982 }
1983
1984 /**
1985 * Get the rendered text for previewing.
1986 * @return string
1987 */
1988 function getPreviewText() {
1989 global $wgOut, $wgUser, $wgParser;
1990
1991 wfProfileIn( __METHOD__ );
1992
1993 if ( $this->mTriedSave && !$this->mTokenOk ) {
1994 if ( $this->mTokenOkExceptSuffix ) {
1995 $note = wfMsg( 'token_suffix_mismatch' );
1996 } else {
1997 $note = wfMsg( 'session_fail_preview' );
1998 }
1999 } elseif ( $this->incompleteForm ) {
2000 $note = wfMsg( 'edit_form_incomplete' );
2001 } else {
2002 $note = wfMsg( 'previewnote' );
2003 }
2004
2005 $parserOptions = ParserOptions::newFromUser( $wgUser );
2006 $parserOptions->setEditSection( false );
2007 $parserOptions->setIsPreview( true );
2008 $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
2009
2010 global $wgRawHtml;
2011 if ( $wgRawHtml && !$this->mTokenOk ) {
2012 // Could be an offsite preview attempt. This is very unsafe if
2013 // HTML is enabled, as it could be an attack.
2014 $parsedNote = '';
2015 if ( $this->textbox1 !== '' ) {
2016 // Do not put big scary notice, if previewing the empty
2017 // string, which happens when you initially edit
2018 // a category page, due to automatic preview-on-open.
2019 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2020 wfMsg( 'session_fail_preview_html' ) . "</div>" );
2021 }
2022 wfProfileOut( __METHOD__ );
2023 return $parsedNote;
2024 }
2025
2026 # don't parse user css/js, show message about preview
2027 # 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?
2028
2029 if ( $this->isCssJsSubpage || $this->mTitle->isCssOrJsPage() ) {
2030 $level = 'user';
2031 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2032 $level = 'site';
2033 }
2034
2035 # Used messages to make sure grep find them:
2036 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
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 $parserOptions->setTidy( true );
2048 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
2049 $previewHTML = $parserOutput->mText;
2050 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1 ) . "\n</pre>\n";
2051 } else {
2052 $rt = Title::newFromRedirectArray( $this->textbox1 );
2053 if ( $rt ) {
2054 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
2055 } else {
2056 $toparse = $this->textbox1;
2057
2058 # If we're adding a comment, we need to show the
2059 # summary as the headline
2060 if ( $this->section == "new" && $this->summary != "" ) {
2061 $toparse = "== {$this->summary} ==\n\n" . $toparse;
2062 }
2063
2064 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2065
2066 $parserOptions->setTidy( true );
2067 $parserOptions->enableLimitReport();
2068 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ),
2069 $this->mTitle, $parserOptions );
2070
2071 $previewHTML = $parserOutput->getText();
2072 $this->mParserOutput = $parserOutput;
2073 $wgOut->addParserOutputNoText( $parserOutput );
2074
2075 if ( count( $parserOutput->getWarnings() ) ) {
2076 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2077 }
2078 }
2079 }
2080
2081 if( $this->isConflict ) {
2082 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2083 } else {
2084 $conflict = '<hr />';
2085 }
2086
2087 $previewhead = "<div class='previewnote'>\n" .
2088 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2089 $wgOut->parse( $note ) . $conflict . "</div>\n";
2090
2091 $pageLang = $this->mTitle->getPageLanguage();
2092 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2093 'class' => 'mw-content-'.$pageLang->getDir() );
2094 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
2095
2096 wfProfileOut( __METHOD__ );
2097 return $previewhead . $previewHTML . $this->previewTextAfterContent;
2098 }
2099
2100 /**
2101 * @return Array
2102 */
2103 function getTemplates() {
2104 if ( $this->preview || $this->section != '' ) {
2105 $templates = array();
2106 if ( !isset( $this->mParserOutput ) ) {
2107 return $templates;
2108 }
2109 foreach( $this->mParserOutput->getTemplates() as $ns => $template) {
2110 foreach( array_keys( $template ) as $dbk ) {
2111 $templates[] = Title::makeTitle($ns, $dbk);
2112 }
2113 }
2114 return $templates;
2115 } else {
2116 return $this->mArticle->getUsedTemplates();
2117 }
2118 }
2119
2120 /**
2121 * Call the stock "user is blocked" page
2122 */
2123 function blockedPage() {
2124 global $wgOut;
2125 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
2126
2127 # If the user made changes, preserve them when showing the markup
2128 # (This happens when a user is blocked during edit, for instance)
2129 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
2130 if ( $first ) {
2131 $source = $this->mTitle->exists() ? $this->getContent() : false;
2132 } else {
2133 $source = $this->textbox1;
2134 }
2135
2136 # Spit out the source or the user's modified version
2137 if ( $source !== false ) {
2138 $wgOut->addHTML( '<hr />' );
2139 $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() );
2140 $this->showTextbox1( array( 'readonly' ), $source );
2141 }
2142 }
2143
2144 /**
2145 * Produce the stock "please login to edit pages" page
2146 */
2147 function userNotLoggedInPage() {
2148 global $wgOut;
2149
2150 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
2151 $loginLink = Linker::linkKnown(
2152 $loginTitle,
2153 wfMsgHtml( 'loginreqlink' ),
2154 array(),
2155 array( 'returnto' => $this->getContextTitle()->getPrefixedText() )
2156 );
2157
2158 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
2159 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2160 $wgOut->setArticleRelated( false );
2161
2162 $wgOut->addHTML( wfMessage( 'whitelistedittext' )->rawParams( $loginLink )->parse() );
2163 $wgOut->returnToMain( false, $this->getContextTitle() );
2164 }
2165
2166 /**
2167 * Creates a basic error page which informs the user that
2168 * they have attempted to edit a nonexistent section.
2169 */
2170 function noSuchSectionPage() {
2171 global $wgOut;
2172
2173 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
2174 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2175 $wgOut->setArticleRelated( false );
2176
2177 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section );
2178 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2179 $wgOut->addHTML( $res );
2180
2181 $wgOut->returnToMain( false, $this->mTitle );
2182 }
2183
2184 /**
2185 * Produce the stock "your edit contains spam" page
2186 *
2187 * @param $match Text which triggered one or more filters
2188 * @deprecated since 1.17 Use method spamPageWithContent() instead
2189 */
2190 static function spamPage( $match = false ) {
2191 global $wgOut, $wgTitle;
2192
2193 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
2194 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2195 $wgOut->setArticleRelated( false );
2196
2197 $wgOut->addHTML( '<div id="spamprotected">' );
2198 $wgOut->addWikiMsg( 'spamprotectiontext' );
2199 if ( $match ) {
2200 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2201 }
2202 $wgOut->addHTML( '</div>' );
2203
2204 $wgOut->returnToMain( false, $wgTitle );
2205 }
2206
2207 /**
2208 * Show "your edit contains spam" page with your diff and text
2209 *
2210 * @param $match Text which triggered one or more filters
2211 */
2212 public function spamPageWithContent( $match = false ) {
2213 global $wgOut;
2214 $this->textbox2 = $this->textbox1;
2215
2216 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
2217 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2218 $wgOut->setArticleRelated( false );
2219
2220 $wgOut->addHTML( '<div id="spamprotected">' );
2221 $wgOut->addWikiMsg( 'spamprotectiontext' );
2222 if ( $match ) {
2223 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2224 }
2225 $wgOut->addHTML( '</div>' );
2226
2227 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2228 $de = new DifferenceEngine( $this->mTitle );
2229 $de->setText( $this->getContent(), $this->textbox2 );
2230 $de->showDiff( wfMsg( "storedversion" ), wfMsg( "yourtext" ) );
2231
2232 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2233 $this->showTextbox2();
2234
2235 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
2236 }
2237
2238
2239 /**
2240 * @private
2241 * @todo document
2242 *
2243 * @parma $editText string
2244 *
2245 * @return bool
2246 */
2247 function mergeChangesInto( &$editText ){
2248 wfProfileIn( __METHOD__ );
2249
2250 $db = wfGetDB( DB_MASTER );
2251
2252 // This is the revision the editor started from
2253 $baseRevision = $this->getBaseRevision();
2254 if ( is_null( $baseRevision ) ) {
2255 wfProfileOut( __METHOD__ );
2256 return false;
2257 }
2258 $baseText = $baseRevision->getText();
2259
2260 // The current state, we want to merge updates into it
2261 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2262 if ( is_null( $currentRevision ) ) {
2263 wfProfileOut( __METHOD__ );
2264 return false;
2265 }
2266 $currentText = $currentRevision->getText();
2267
2268 $result = '';
2269 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
2270 $editText = $result;
2271 wfProfileOut( __METHOD__ );
2272 return true;
2273 } else {
2274 wfProfileOut( __METHOD__ );
2275 return false;
2276 }
2277 }
2278
2279 /**
2280 * Check if the browser is on a blacklist of user-agents known to
2281 * mangle UTF-8 data on form submission. Returns true if Unicode
2282 * should make it through, false if it's known to be a problem.
2283 * @return bool
2284 * @private
2285 */
2286 function checkUnicodeCompliantBrowser() {
2287 global $wgBrowserBlackList;
2288 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2289 // No User-Agent header sent? Trust it by default...
2290 return true;
2291 }
2292 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2293 foreach ( $wgBrowserBlackList as $browser ) {
2294 if ( preg_match($browser, $currentbrowser) ) {
2295 return false;
2296 }
2297 }
2298 return true;
2299 }
2300
2301 /**
2302 * Format an anchor fragment as it would appear for a given section name
2303 * @param $text String
2304 * @return String
2305 * @private
2306 */
2307 function sectionAnchor( $text ) {
2308 global $wgParser;
2309 return $wgParser->guessSectionNameFromWikiText( $text );
2310 }
2311
2312 /**
2313 * Shows a bulletin board style toolbar for common editing functions.
2314 * It can be disabled in the user preferences.
2315 * The necessary JavaScript code can be found in skins/common/edit.js.
2316 *
2317 * @return string
2318 */
2319 static function getEditToolbar() {
2320 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2321 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2322
2323 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
2324
2325 /**
2326 * $toolarray is an array of arrays each of which includes the
2327 * filename of the button image (without path), the opening
2328 * tag, the closing tag, optionally a sample text that is
2329 * inserted between the two when no selection is highlighted
2330 * and. The tip text is shown when the user moves the mouse
2331 * over the button.
2332 *
2333 * Also here: accesskeys (key), which are not used yet until
2334 * someone can figure out a way to make them work in
2335 * IE. However, we should make sure these keys are not defined
2336 * on the edit page.
2337 */
2338 $toolarray = array(
2339 array(
2340 'image' => $wgLang->getImageFile( 'button-bold' ),
2341 'id' => 'mw-editbutton-bold',
2342 'open' => '\'\'\'',
2343 'close' => '\'\'\'',
2344 'sample' => wfMsg( 'bold_sample' ),
2345 'tip' => wfMsg( 'bold_tip' ),
2346 'key' => 'B'
2347 ),
2348 array(
2349 'image' => $wgLang->getImageFile( 'button-italic' ),
2350 'id' => 'mw-editbutton-italic',
2351 'open' => '\'\'',
2352 'close' => '\'\'',
2353 'sample' => wfMsg( 'italic_sample' ),
2354 'tip' => wfMsg( 'italic_tip' ),
2355 'key' => 'I'
2356 ),
2357 array(
2358 'image' => $wgLang->getImageFile( 'button-link' ),
2359 'id' => 'mw-editbutton-link',
2360 'open' => '[[',
2361 'close' => ']]',
2362 'sample' => wfMsg( 'link_sample' ),
2363 'tip' => wfMsg( 'link_tip' ),
2364 'key' => 'L'
2365 ),
2366 array(
2367 'image' => $wgLang->getImageFile( 'button-extlink' ),
2368 'id' => 'mw-editbutton-extlink',
2369 'open' => '[',
2370 'close' => ']',
2371 'sample' => wfMsg( 'extlink_sample' ),
2372 'tip' => wfMsg( 'extlink_tip' ),
2373 'key' => 'X'
2374 ),
2375 array(
2376 'image' => $wgLang->getImageFile( 'button-headline' ),
2377 'id' => 'mw-editbutton-headline',
2378 'open' => "\n== ",
2379 'close' => " ==\n",
2380 'sample' => wfMsg( 'headline_sample' ),
2381 'tip' => wfMsg( 'headline_tip' ),
2382 'key' => 'H'
2383 ),
2384 $imagesAvailable ? array(
2385 'image' => $wgLang->getImageFile( 'button-image' ),
2386 'id' => 'mw-editbutton-image',
2387 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
2388 'close' => ']]',
2389 'sample' => wfMsg( 'image_sample' ),
2390 'tip' => wfMsg( 'image_tip' ),
2391 'key' => 'D',
2392 ) : false,
2393 $imagesAvailable ? array(
2394 'image' => $wgLang->getImageFile( 'button-media' ),
2395 'id' => 'mw-editbutton-media',
2396 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
2397 'close' => ']]',
2398 'sample' => wfMsg( 'media_sample' ),
2399 'tip' => wfMsg( 'media_tip' ),
2400 'key' => 'M'
2401 ) : false,
2402 $wgUseTeX ? array(
2403 'image' => $wgLang->getImageFile( 'button-math' ),
2404 'id' => 'mw-editbutton-math',
2405 'open' => "<math>",
2406 'close' => "</math>",
2407 'sample' => wfMsg( 'math_sample' ),
2408 'tip' => wfMsg( 'math_tip' ),
2409 'key' => 'C'
2410 ) : false,
2411 array(
2412 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2413 'id' => 'mw-editbutton-nowiki',
2414 'open' => "<nowiki>",
2415 'close' => "</nowiki>",
2416 'sample' => wfMsg( 'nowiki_sample' ),
2417 'tip' => wfMsg( 'nowiki_tip' ),
2418 'key' => 'N'
2419 ),
2420 array(
2421 'image' => $wgLang->getImageFile( 'button-sig' ),
2422 'id' => 'mw-editbutton-signature',
2423 'open' => '--~~~~',
2424 'close' => '',
2425 'sample' => '',
2426 'tip' => wfMsg( 'sig_tip' ),
2427 'key' => 'Y'
2428 ),
2429 array(
2430 'image' => $wgLang->getImageFile( 'button-hr' ),
2431 'id' => 'mw-editbutton-hr',
2432 'open' => "\n----\n",
2433 'close' => '',
2434 'sample' => '',
2435 'tip' => wfMsg( 'hr_tip' ),
2436 'key' => 'R'
2437 )
2438 );
2439 $toolbar = "<div id='toolbar'>\n";
2440
2441 $script = '';
2442 foreach ( $toolarray as $tool ) {
2443 if ( !$tool ) {
2444 continue;
2445 }
2446
2447 $params = array(
2448 $image = $wgStylePath . '/common/images/' . $tool['image'],
2449 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2450 // Older browsers show a "speedtip" type message only for ALT.
2451 // Ideally these should be different, realistically they
2452 // probably don't need to be.
2453 $tip = $tool['tip'],
2454 $open = $tool['open'],
2455 $close = $tool['close'],
2456 $sample = $tool['sample'],
2457 $cssId = $tool['id'],
2458 );
2459
2460 $paramList = implode( ',',
2461 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2462 $script .= "mw.toolbar.addButton($paramList);\n";
2463 }
2464 $wgOut->addScript( Html::inlineScript(
2465 "if ( window.mediaWiki ) {{$script}}"
2466 ) );
2467
2468 $toolbar .= "\n</div>";
2469
2470 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2471
2472 return $toolbar;
2473 }
2474
2475 /**
2476 * Returns an array of html code of the following checkboxes:
2477 * minor and watch
2478 *
2479 * @param $tabindex Current tabindex
2480 * @param $checked Array of checkbox => bool, where bool indicates the checked
2481 * status of the checkbox
2482 *
2483 * @return array
2484 */
2485 public function getCheckboxes( &$tabindex, $checked ) {
2486 global $wgUser;
2487
2488 $checkboxes = array();
2489
2490 // don't show the minor edit checkbox if it's a new page or section
2491 if ( !$this->isNew ) {
2492 $checkboxes['minor'] = '';
2493 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2494 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2495 $attribs = array(
2496 'tabindex' => ++$tabindex,
2497 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2498 'id' => 'wpMinoredit',
2499 );
2500 $checkboxes['minor'] =
2501 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2502 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
2503 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2504 ">{$minorLabel}</label>";
2505 }
2506 }
2507
2508 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2509 $checkboxes['watch'] = '';
2510 if ( $wgUser->isLoggedIn() ) {
2511 $attribs = array(
2512 'tabindex' => ++$tabindex,
2513 'accesskey' => wfMsg( 'accesskey-watch' ),
2514 'id' => 'wpWatchthis',
2515 );
2516 $checkboxes['watch'] =
2517 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2518 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
2519 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
2520 ">{$watchLabel}</label>";
2521 }
2522 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2523 return $checkboxes;
2524 }
2525
2526 /**
2527 * Returns an array of html code of the following buttons:
2528 * save, diff, preview and live
2529 *
2530 * @param $tabindex Current tabindex
2531 *
2532 * @return array
2533 */
2534 public function getEditButtons( &$tabindex ) {
2535 $buttons = array();
2536
2537 $temp = array(
2538 'id' => 'wpSave',
2539 'name' => 'wpSave',
2540 'type' => 'submit',
2541 'tabindex' => ++$tabindex,
2542 'value' => wfMsg( 'savearticle' ),
2543 'accesskey' => wfMsg( 'accesskey-save' ),
2544 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2545 );
2546 $buttons['save'] = Xml::element('input', $temp, '');
2547
2548 ++$tabindex; // use the same for preview and live preview
2549 $temp = array(
2550 'id' => 'wpPreview',
2551 'name' => 'wpPreview',
2552 'type' => 'submit',
2553 'tabindex' => $tabindex,
2554 'value' => wfMsg( 'showpreview' ),
2555 'accesskey' => wfMsg( 'accesskey-preview' ),
2556 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2557 );
2558 $buttons['preview'] = Xml::element( 'input', $temp, '' );
2559 $buttons['live'] = '';
2560
2561 $temp = array(
2562 'id' => 'wpDiff',
2563 'name' => 'wpDiff',
2564 'type' => 'submit',
2565 'tabindex' => ++$tabindex,
2566 'value' => wfMsg( 'showdiff' ),
2567 'accesskey' => wfMsg( 'accesskey-diff' ),
2568 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2569 );
2570 $buttons['diff'] = Xml::element( 'input', $temp, '' );
2571
2572 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2573 return $buttons;
2574 }
2575
2576 /**
2577 * Output preview text only. This can be sucked into the edit page
2578 * via JavaScript, and saves the server time rendering the skin as
2579 * well as theoretically being more robust on the client (doesn't
2580 * disturb the edit box's undo history, won't eat your text on
2581 * failure, etc).
2582 *
2583 * @todo This doesn't include category or interlanguage links.
2584 * Would need to enhance it a bit, <s>maybe wrap them in XML
2585 * or something...</s> that might also require more skin
2586 * initialization, so check whether that's a problem.
2587 */
2588 function livePreview() {
2589 global $wgOut;
2590 $wgOut->disable();
2591 header( 'Content-type: text/xml; charset=utf-8' );
2592 header( 'Cache-control: no-cache' );
2593
2594 $previewText = $this->getPreviewText();
2595 #$categories = $skin->getCategoryLinks();
2596
2597 $s =
2598 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2599 Xml::tags( 'livepreview', null,
2600 Xml::element( 'preview', null, $previewText )
2601 #. Xml::element( 'category', null, $categories )
2602 );
2603 echo $s;
2604 }
2605
2606 /**
2607 * @return string
2608 */
2609 public function getCancelLink() {
2610 $cancelParams = array();
2611 if ( !$this->isConflict && $this->mArticle->getOldID() > 0 ) {
2612 $cancelParams['oldid'] = $this->mArticle->getOldID();
2613 }
2614
2615 return Linker::linkKnown(
2616 $this->getContextTitle(),
2617 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2618 array( 'id' => 'mw-editform-cancel' ),
2619 $cancelParams
2620 );
2621 }
2622
2623 /**
2624 * Get a diff between the current contents of the edit box and the
2625 * version of the page we're editing from.
2626 *
2627 * If this is a section edit, we'll replace the section as for final
2628 * save and then make a comparison.
2629 */
2630 function showDiff() {
2631 $oldtext = $this->mArticle->fetchContent();
2632 $newtext = $this->mArticle->replaceSection(
2633 $this->section, $this->textbox1, $this->summary, $this->edittime );
2634
2635 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2636
2637 $newtext = $this->mArticle->preSaveTransform( $newtext );
2638 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2639 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2640 if ( $oldtext !== false || $newtext != '' ) {
2641 $de = new DifferenceEngine( $this->mTitle );
2642 $de->setText( $oldtext, $newtext );
2643 $difftext = $de->getDiff( $oldtitle, $newtitle );
2644 $de->showDiffStyle();
2645 } else {
2646 $difftext = '';
2647 }
2648
2649 global $wgOut;
2650 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2651 }
2652
2653 /**
2654 * Filter an input field through a Unicode de-armoring process if it
2655 * came from an old browser with known broken Unicode editing issues.
2656 *
2657 * @param $request WebRequest
2658 * @param $field String
2659 * @return String
2660 * @private
2661 */
2662 function safeUnicodeInput( $request, $field ) {
2663 $text = rtrim( $request->getText( $field ) );
2664 return $request->getBool( 'safemode' )
2665 ? $this->unmakesafe( $text )
2666 : $text;
2667 }
2668
2669 /**
2670 * @param $request WebRequest
2671 * @param $text string
2672 * @return string
2673 */
2674 function safeUnicodeText( $request, $text ) {
2675 $text = rtrim( $text );
2676 return $request->getBool( 'safemode' )
2677 ? $this->unmakesafe( $text )
2678 : $text;
2679 }
2680
2681 /**
2682 * Filter an output field through a Unicode armoring process if it is
2683 * going to an old browser with known broken Unicode editing issues.
2684 *
2685 * @param $text String
2686 * @return String
2687 * @private
2688 */
2689 function safeUnicodeOutput( $text ) {
2690 global $wgContLang;
2691 $codedText = $wgContLang->recodeForEdit( $text );
2692 return $this->checkUnicodeCompliantBrowser()
2693 ? $codedText
2694 : $this->makesafe( $codedText );
2695 }
2696
2697 /**
2698 * A number of web browsers are known to corrupt non-ASCII characters
2699 * in a UTF-8 text editing environment. To protect against this,
2700 * detected browsers will be served an armored version of the text,
2701 * with non-ASCII chars converted to numeric HTML character references.
2702 *
2703 * Preexisting such character references will have a 0 added to them
2704 * to ensure that round-trips do not alter the original data.
2705 *
2706 * @param $invalue String
2707 * @return String
2708 * @private
2709 */
2710 function makesafe( $invalue ) {
2711 // Armor existing references for reversability.
2712 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2713
2714 $bytesleft = 0;
2715 $result = "";
2716 $working = 0;
2717 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2718 $bytevalue = ord( $invalue[$i] );
2719 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2720 $result .= chr( $bytevalue );
2721 $bytesleft = 0;
2722 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2723 $working = $working << 6;
2724 $working += ($bytevalue & 0x3F);
2725 $bytesleft--;
2726 if ( $bytesleft <= 0 ) {
2727 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2728 }
2729 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2730 $working = $bytevalue & 0x1F;
2731 $bytesleft = 1;
2732 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2733 $working = $bytevalue & 0x0F;
2734 $bytesleft = 2;
2735 } else { //1111 0xxx
2736 $working = $bytevalue & 0x07;
2737 $bytesleft = 3;
2738 }
2739 }
2740 return $result;
2741 }
2742
2743 /**
2744 * Reverse the previously applied transliteration of non-ASCII characters
2745 * back to UTF-8. Used to protect data from corruption by broken web browsers
2746 * as listed in $wgBrowserBlackList.
2747 *
2748 * @param $invalue String
2749 * @return String
2750 * @private
2751 */
2752 function unmakesafe( $invalue ) {
2753 $result = "";
2754 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2755 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+3] != '0' ) ) {
2756 $i += 3;
2757 $hexstring = "";
2758 do {
2759 $hexstring .= $invalue[$i];
2760 $i++;
2761 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
2762
2763 // Do some sanity checks. These aren't needed for reversability,
2764 // but should help keep the breakage down if the editor
2765 // breaks one of the entities whilst editing.
2766 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2767 $codepoint = hexdec($hexstring);
2768 $result .= codepointToUtf8( $codepoint );
2769 } else {
2770 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2771 }
2772 } else {
2773 $result .= substr( $invalue, $i, 1 );
2774 }
2775 }
2776 // reverse the transform that we made for reversability reasons.
2777 return strtr( $result, array( "&#x0" => "&#x" ) );
2778 }
2779
2780 function noCreatePermission() {
2781 global $wgOut;
2782 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2783 $wgOut->addWikiMsg( 'nocreatetext' );
2784 }
2785
2786 /**
2787 * Attempt submission
2788 * @return bool false if output is done, true if the rest of the form should be displayed
2789 */
2790 function attemptSave() {
2791 global $wgUser, $wgOut;
2792
2793 $resultDetails = false;
2794 # Allow bots to exempt some edits from bot flagging
2795 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
2796 $value = $this->internalAttemptSave( $resultDetails, $bot );
2797
2798 if ( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2799 $this->didSave = true;
2800 }
2801
2802 switch ( $value ) {
2803 case self::AS_HOOK_ERROR_EXPECTED:
2804 case self::AS_CONTENT_TOO_BIG:
2805 case self::AS_ARTICLE_WAS_DELETED:
2806 case self::AS_CONFLICT_DETECTED:
2807 case self::AS_SUMMARY_NEEDED:
2808 case self::AS_TEXTBOX_EMPTY:
2809 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
2810 case self::AS_END:
2811 return true;
2812
2813 case self::AS_HOOK_ERROR:
2814 case self::AS_FILTERING:
2815 return false;
2816
2817 case self::AS_SUCCESS_NEW_ARTICLE:
2818 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
2819 $wgOut->redirect( $this->mTitle->getFullURL( $query ) );
2820 return false;
2821
2822 case self::AS_SUCCESS_UPDATE:
2823 $extraQuery = '';
2824 $sectionanchor = $resultDetails['sectionanchor'];
2825
2826 // Give extensions a chance to modify URL query on update
2827 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle, &$sectionanchor, &$extraQuery ) );
2828
2829 if ( $resultDetails['redirect'] ) {
2830 if ( $extraQuery == '' ) {
2831 $extraQuery = 'redirect=no';
2832 } else {
2833 $extraQuery = 'redirect=no&' . $extraQuery;
2834 }
2835 }
2836 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
2837 return false;
2838
2839 case self::AS_SPAM_ERROR:
2840 $this->spamPageWithContent( $resultDetails['spam'] );
2841 return false;
2842
2843 case self::AS_BLOCKED_PAGE_FOR_USER:
2844 $this->blockedPage();
2845 return false;
2846
2847 case self::AS_IMAGE_REDIRECT_ANON:
2848 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2849 return false;
2850
2851 case self::AS_READ_ONLY_PAGE_ANON:
2852 $this->userNotLoggedInPage();
2853 return false;
2854
2855 case self::AS_READ_ONLY_PAGE_LOGGED:
2856 case self::AS_READ_ONLY_PAGE:
2857 $wgOut->readOnlyPage();
2858 return false;
2859
2860 case self::AS_RATE_LIMITED:
2861 $wgOut->rateLimited();
2862 return false;
2863
2864 case self::AS_NO_CREATE_PERMISSION:
2865 $this->noCreatePermission();
2866 return false;
2867
2868 case self::AS_BLANK_ARTICLE:
2869 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
2870 return false;
2871
2872 case self::AS_IMAGE_REDIRECT_LOGGED:
2873 $wgOut->permissionRequired( 'upload' );
2874 return false;
2875 }
2876 }
2877
2878 /**
2879 * @return Revision
2880 */
2881 function getBaseRevision() {
2882 if ( !$this->mBaseRevision ) {
2883 $db = wfGetDB( DB_MASTER );
2884 $baseRevision = Revision::loadFromTimestamp(
2885 $db, $this->mTitle, $this->edittime );
2886 return $this->mBaseRevision = $baseRevision;
2887 } else {
2888 return $this->mBaseRevision;
2889 }
2890 }
2891 }