MediaWiki  master
SpecialBooksources.php
Go to the documentation of this file.
1 <?php
35  private $isbn = '';
36 
37  public function __construct() {
38  parent::__construct( 'Booksources' );
39  }
40 
46  public function execute( $isbn ) {
47  $this->setHeaders();
48  $this->outputHeader();
49  $this->isbn = self::cleanIsbn( $isbn ?: $this->getRequest()->getText( 'isbn' ) );
50  $this->getOutput()->addHTML( $this->makeForm() );
51  if ( $this->isbn !== '' ) {
52  if ( !self::isValidISBN( $this->isbn ) ) {
53  $this->getOutput()->wrapWikiMsg(
54  "<div class=\"error\">\n$1\n</div>",
55  'booksources-invalid-isbn'
56  );
57  }
58  $this->showList();
59  }
60  }
61 
68  public static function isValidISBN( $isbn ) {
69  $isbn = self::cleanIsbn( $isbn );
70  $sum = 0;
71  if ( strlen( $isbn ) == 13 ) {
72  for ( $i = 0; $i < 12; $i++ ) {
73  if ( $isbn[$i] === 'X' ) {
74  return false;
75  } elseif ( $i % 2 == 0 ) {
76  $sum += $isbn[$i];
77  } else {
78  $sum += 3 * $isbn[$i];
79  }
80  }
81 
82  $check = ( 10 - ( $sum % 10 ) ) % 10;
83  if ( (string)$check === $isbn[12] ) {
84  return true;
85  }
86  } elseif ( strlen( $isbn ) == 10 ) {
87  for ( $i = 0; $i < 9; $i++ ) {
88  if ( $isbn[$i] === 'X' ) {
89  return false;
90  }
91  $sum += $isbn[$i] * ( $i + 1 );
92  }
93 
94  $check = $sum % 11;
95  if ( $check == 10 ) {
96  $check = "X";
97  }
98  if ( (string)$check === $isbn[9] ) {
99  return true;
100  }
101  }
102 
103  return false;
104  }
105 
112  private static function cleanIsbn( $isbn ) {
113  return trim( preg_replace( '![^0-9X]!', '', $isbn ) );
114  }
115 
121  private function makeForm() {
122  $form = Html::openElement( 'fieldset' ) . "\n";
123  $form .= Html::element(
124  'legend',
125  [],
126  $this->msg( 'booksources-search-legend' )->text()
127  ) . "\n";
128  $form .= Html::openElement( 'form', [ 'method' => 'get', 'action' => wfScript() ] ) . "\n";
129  $form .= Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) . "\n";
130  $form .= '<p>' . Xml::inputLabel(
131  $this->msg( 'booksources-isbn' )->text(),
132  'isbn',
133  'isbn',
134  20,
135  $this->isbn,
136  [ 'autofocus' => '', 'class' => 'mw-ui-input-inline' ]
137  );
138 
139  $form .= '&#160;' . Html::submitButton(
140  $this->msg( 'booksources-search' )->text(),
141  [], [ 'mw-ui-progressive' ]
142  ) . "</p>\n";
143 
144  $form .= Html::closeElement( 'form' ) . "\n";
145  $form .= Html::closeElement( 'fieldset' ) . "\n";
146 
147  return $form;
148  }
149 
157  private function showList() {
159 
160  # Hook to allow extensions to insert additional HTML,
161  # e.g. for API-interacting plugins and so on
162  Hooks::run( 'BookInformation', [ $this->isbn, $this->getOutput() ] );
163 
164  # Check for a local page such as Project:Book_sources and use that if available
165  $page = $this->msg( 'booksources' )->inContentLanguage()->text();
166  $title = Title::makeTitleSafe( NS_PROJECT, $page ); # Show list in content language
167  if ( is_object( $title ) && $title->exists() ) {
169  $content = $rev->getContent();
170 
171  if ( $content instanceof TextContent ) {
172  // XXX: in the future, this could be stored as structured data, defining a list of book sources
173 
174  $text = $content->getNativeData();
175  $this->getOutput()->addWikiText( str_replace( 'MAGICNUMBER', $this->isbn, $text ) );
176 
177  return true;
178  } else {
179  throw new MWException( "Unexpected content type for book sources: " . $content->getModel() );
180  }
181  }
182 
183  # Fall back to the defaults given in the language file
184  $this->getOutput()->addWikiMsg( 'booksources-text' );
185  $this->getOutput()->addHTML( '<ul>' );
186  $items = $wgContLang->getBookstoreList();
187  foreach ( $items as $label => $url ) {
188  $this->getOutput()->addHTML( $this->makeListItem( $label, $url ) );
189  }
190  $this->getOutput()->addHTML( '</ul>' );
191 
192  return true;
193  }
194 
202  private function makeListItem( $label, $url ) {
203  $url = str_replace( '$1', $this->isbn, $url );
204 
205  return Html::rawElement( 'li', [],
206  Html::element( 'a', [ 'href' => $url, 'class' => 'external' ], $label )
207  );
208  }
209 
210  protected function getGroupName() {
211  return 'wiki';
212  }
213 }
static closeElement($element)
Returns "</$element>".
Definition: Html.php:313
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
wfScript($script= 'index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
per default it will return the text for text based content
static rawElement($element, $attribs=[], $contents= '')
Returns an HTML element in a string.
Definition: Html.php:213
static hidden($name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:789
null for the local wiki Added in
Definition: hooks.txt:1391
static inputLabel($label, $name, $id, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field with a label.
Definition: Xml.php:381
msg()
Wrapper around wfMessage that sets the current context.
getOutput()
Get the OutputPage being used for this instance.
static isValidISBN($isbn)
Return whether a given ISBN (10 or 13) is valid.
makeForm()
Generate a form to allow users to enter an ISBN.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target...
Definition: Revision.php:117
outputHeader($summaryMessageKey= '')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
Parent class for all special pages.
Definition: SpecialPage.php:34
static openElement($element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:255
const NS_PROJECT
Definition: Defines.php:73
Content object implementation for representing flat text.
Definition: TextContent.php:35
MediaWiki exception.
Definition: MWException.php:26
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes! ...
static makeTitleSafe($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:548
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead.&$feedLinks conditions will AND in the final query as a Content object as a Content object $title
Definition: hooks.txt:314
execute($isbn)
Show the special page.
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1557
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
namespace and then decline to actually register it file or subcat img or subcat RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition: hooks.txt:977
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static submitButton($contents, array $attrs, array $modifiers=[])
Returns an HTML link element in a string styled as a button (when $wgUseMediaWikiUIEverywhere is enab...
Definition: Html.php:188
$isbn
ISBN passed to the page, if any.
static cleanIsbn($isbn)
Trim ISBN and remove characters which aren't required.
showList()
Determine where to get the list of book sources from, format and output them.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
getRequest()
Get the WebRequest being used for this instance.
makeListItem($label, $url)
Format a book source list item.
static element($element, $attribs=[], $contents= '')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:237
Special page outputs information on sourcing a book with a particular ISBN The parser creates links t...
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2317
getPageTitle($subpage=false)
Get a self-referential title object.