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