mediawiki-extensions-TextEx.../ExtractFormatter.php
Max Semenik 8ef89a82ea Initial conversion of prop=extracts from MobileFrontend
Change-Id: I8a02f38554f6f06a00e6229889f7545f8ee8976a
2013-12-18 03:40:03 +04:00

75 lines
2.2 KiB
PHP

<?php
/**
* Provides text-only or limited-HTML extracts of page HTML
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
class ExtractFormatter extends HtmlFormatter {
const SECTION_MARKER_START = "\1\2";
const SECTION_MARKER_END = "\2\1";
private $plainText;
/**
* @param string $text: Text to convert
* @param bool $plainText: Whether extract should be plaintext
*/
public function __construct( $text, $plainText ) {
global $wgExtractsRemoveClasses;
wfProfileIn( __METHOD__ );
parent::__construct( HtmlFormatter::wrapHTML( $text ) );
$this->plainText = $plainText;
$this->setRemoveMedia( true );
$this->remove( $wgExtractsRemoveClasses );
if ( $plainText ) {
$this->flattenAllTags();
} else {
$this->flatten( array( 'span', 'a' ) );
}
wfProfileOut( __METHOD__ );
}
public function getText( $dummy = null ) {
wfProfileIn( __METHOD__ );
$this->filterContent();
$text = parent::getText();
if ( $this->plainText ) {
$text = html_entity_decode( $text );
$text = str_replace( "\xC2\xA0", ' ', $text ); // replace nbsp with space
$text = str_replace( "\r", "\n", $text ); // for Windows
$text = preg_replace( "/\n{3,}/", "\n\n", $text ); // normalise newlines
}
wfProfileOut( __METHOD__ );
return $text;
}
public function onHtmlReady( $html ) {
wfProfileIn( __METHOD__ );
if ( $this->plainText ) {
$html = preg_replace( '/\s*(<h([1-6])\b)/i',
"\n\n" . self::SECTION_MARKER_START . '$2' . self::SECTION_MARKER_END . '$1' ,
$html
);
}
wfProfileOut( __METHOD__ );
return $html;
}
}