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