DeToc MediaWiki extension 1.0.0
[DeToc.git] / DeToc.php
blob45f27143dfd5a6fca58c5c58db907c1995c2f3d1
1 <?php
2 /*
3 * Copyright (c) 2015 Marcin Cieślak (saper.info)
4 *
5 * DeToc 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 3 of the License, or
8 * (at your option) any later version.
9 *
10 * DeToc 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.
15 * You should have received a copy of the GNU General Public License
16 * along with DeToc. If not, see <http://www.gnu.org/licenses/>.
19 /**
20 * DeToc extension
22 * @file
23 * @ingroup Extensions
24 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 3.0 or later
27 class DeToc {
28 public static function RemoveToc($body, &$extracted_toc) {
29 $extracted_toc = '';
30 $last_toc_ptr = 0;
31 $new_body = '';
32 while ( preg_match( '/<div id="toc".*?>(.*)/s',
33 $body, $toc_matches,
34 PREG_OFFSET_CAPTURE, $last_toc_ptr ) === 1 ) {
36 $toc_offset = $toc_matches[0][1];
38 $rest = $toc_matches[1][0];
39 $rest_ptr = $toc_matches[1][1];
41 $divlevel = 1;
42 $endtoc_ptr = $rest_ptr;
43 while ( $divlevel > 0 && strlen($rest) > 0) {
44 if ( preg_match(',<(/?)div.*?>(.*),s',
45 $rest, $div_matches,
46 PREG_OFFSET_CAPTURE ) === 1 ) {
48 $rest = $div_matches[2][0];
50 if ( $div_matches[1][0] === '/' ) {
51 $divlevel = $divlevel - 1;
52 if ( $divlevel > 0 ) {
53 $endtoc_ptr += $div_matches[2][1];
54 } else {
55 /* We skip the first <div>, so we need to skip the closing one */
56 $endtoc_ptr += $div_matches[0][1];
58 } else {
59 $divlevel = $divlevel + 1;
60 $endtoc_ptr += $div_matches[2][1];
62 } else {
63 $rest = '';
66 $extracted_toc .= substr( $body,
67 $last_toc_ptr + $rest_ptr, $endtoc_ptr - $rest_ptr );
69 $new_body .= substr( $body, $last_toc_ptr, $toc_offset );
70 $last_toc_ptr += $endtoc_ptr;
72 $new_body .= substr( $body, $last_toc_ptr );
73 return $new_body;