Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 205
0.00% covered (danger)
0.00%
0 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
SubPageList3
0.00% covered (danger)
0.00%
0 / 205
0.00% covered (danger)
0.00%
0 / 10
6972
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 renderSubpageList3
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 error
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 geterrors
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 options
0.00% covered (danger)
0.00%
0 / 73
0.00% covered (danger)
0.00%
0 / 1
1722
 render
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
30
 getTitles
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
110
 makeListItem
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
 makeList
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
210
 parse
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3namespace MediaWiki\Extension\SubPageList3;
4
5use LogicException;
6use MediaWiki\Config\Config;
7use MediaWiki\Html\Html;
8use MediaWiki\MediaWikiServices;
9use MediaWiki\Parser\Parser;
10use MediaWiki\Parser\PPFrame;
11use MediaWiki\Title\Title;
12use Wikimedia\Parsoid\DOM\DocumentFragment;
13use Wikimedia\Parsoid\Ext\DOMUtils;
14use Wikimedia\Parsoid\Ext\ParsoidExtensionAPI;
15use Wikimedia\Rdbms\IExpression;
16use Wikimedia\Rdbms\LikeValue;
17
18/**
19 * SubPageList3 class
20 */
21class SubPageList3 {
22    /**
23     * Default limit of descendants
24     */
25    private const DESCENDANTS_LIMIT_DEFAULT = 200;
26
27    /** Is this being processed with Parsoid? */
28    private bool $withParsoid = false;
29    private Parser|ParsoidExtensionAPI $parser;
30    private PPFrame|bool $frame;
31    private Title $title;
32    private Title $ptitle;
33    /**
34     * token object
35     */
36    private string $token = '*';
37    private int $debug = 0;
38    private array $errors = [];
39    /**
40     * order type
41     * Can be:
42     * - asc
43     * - desc
44     */
45    private string $order = 'asc';
46
47    /**
48     * column that's used as order method
49     * Can be:
50     *  - title: alphabetic order of a page title
51     *  - lastedit: Timestamp numeric order of the last edit of a page
52     * @private
53     */
54    private string $ordermethod = 'title';
55
56    /**
57     * mode of the output
58     * Can be:
59     *  - unordered: UL list as output
60     *  - ordered: OL list as output
61     *  - bar: uses ยท as a delimiter producing a horizontal bar menu
62     */
63    private string $mode = 'unordered';
64
65    /**
66     * parent of the listed pages
67     * Can be:
68     *  - -1: the current page title
69     *  - string: title of the specific title
70     * e.g. if you are in Mainpage/ it will list all subpages of Mainpage/
71     * @var mixed parent of listed pages
72     */
73    private $parent = -1;
74
75    /**
76     * style of the path (title)
77     * Can be:
78     *  - full: normal, e.g. Mainpage/Entry/Sub
79     *  - notparent: the path without the $parent item, e.g. Entry/Sub
80     *  - no: no path, only the page title, e.g. Sub
81     * @var string style of the path (title)
82     * @see $parent
83     */
84    private $showpath = 'no';
85
86    /**
87     * whether to show next sublevel only, or all sublevels
88     * Can be:
89     *  - 0 / no / false
90     *  - 1 / yes / true
91     * @var mixed show one sublevel only
92     * @see $parent
93     */
94    private $kidsonly = 0;
95
96    /**
97     * whether to show parent as the top item
98     * Can be:
99     *  - 0 / no / false
100     *  - 1 / yes / true
101     * @var mixed show one sublevel only
102     * @see $parent
103     */
104    private $showparent = 0;
105
106    /**
107     * Text to show when parent has no subpages to list
108     * when null (by default) shows default message
109     */
110    private ?string $nosubpages = null;
111    private Config $config;
112
113    /**
114     * Constructor function of the class
115     * @param Parser|ParsoidExtensionAPI $parser the parser object
116     * @param Config $config
117     * @param PPFrame|bool $frame
118     * @see SubpageList
119     */
120    private function __construct(
121        Parser|ParsoidExtensionAPI $parser, Config $config, PPFrame|bool $frame = false
122    ) {
123        $this->parser = $parser;
124        $this->frame = $frame;
125        $this->config = $config;
126        if ( $parser instanceof ParsoidExtensionAPI ) {
127            $this->withParsoid = true;
128            $this->title = Title::newFromLinkTarget( $parser->getPageConfig()->getLinkTarget() );
129        } else {
130            $this->withParsoid = false;
131            $this->title = $parser->getTitle();
132        }
133    }
134
135    /**
136     * Function called by the Hook, returns the wiki text
137     *
138     * @param string $input
139     * @param array $args
140     * @param Parser|ParsoidExtensionAPI $parser
141     * @param ?PPFrame $frame
142     * @return string|DocumentFragment
143     */
144    public static function renderSubpageList3(
145        $input, array $args, Parser|ParsoidExtensionAPI $parser, ?PPFrame $frame = null
146    ) {
147        $config = MediaWikiServices::getInstance()->getConfigFactory()->makeConfig( 'SubPageList3' );
148        $list = new SubpageList3( $parser, $config, $frame ?? false );
149        $list->options( $args );
150
151        # $parser->disableCache();
152        return $list->render();
153    }
154
155    /**
156     * adds error to the $errors container
157     * but only if $debug is true or 1
158     * @param string $message the errors message
159     * @see $errors
160     * @see $debug
161     */
162    private function error( $message ) {
163        if ( $this->debug ) {
164            $this->errors[] = "<strong>Error [Subpage List 3]:</strong> $message";
165        }
166    }
167
168    /**
169     * returns all errors as a string
170     * @return string all errors separated by a newline
171     */
172    private function geterrors() {
173        return implode( "\n", $this->errors );
174    }
175
176    /**
177     * parse the options that the user has entered
178     * a bit long way, but because that it's easy to add alias
179     * @param array $options the options inserts by the user as array
180     * @see $debug
181     * @see $order
182     * @see $ordermethod
183     * @see $mode
184     * @see $parent
185     * @see $showpath
186     * @see $kidsonly
187     * @see $showparent
188     */
189    private function options( $options ) {
190        if ( isset( $options['debug'] ) ) {
191            if ( in_array( $options['debug'], [ 'true', 1, '1' ], true ) ) {
192                $this->debug = 1;
193            } elseif ( in_array( $options['debug'], [ 'false', 0, '0' ], true ) ) {
194                $this->debug = 0;
195            } else {
196                $this->error( wfMessage( 'spl3_debug', 'debug' )->escaped() );
197            }
198        }
199        if ( isset( $options['sort'] ) ) {
200            switch ( strtolower( $options['sort'] ) ) {
201                case 'asc':
202                    $this->order = 'asc';
203                    break;
204                case 'desc':
205                    $this->order = 'desc';
206                    break;
207                default:
208                    $this->error( wfMessage( 'spl3_debug', 'sort' )->escaped() );
209            }
210        }
211        if ( isset( $options['sortby'] ) ) {
212            switch ( strtolower( $options['sortby'] ) ) {
213                case 'title':
214                    $this->ordermethod = 'title';
215                    break;
216                case 'lastedit':
217                    $this->ordermethod = 'lastedit';
218                    break;
219                default:
220                    $this->error( wfMessage( 'spl3_debug', 'sortby' )->escaped() );
221            }
222        }
223        if ( isset( $options['liststyle'] ) ) {
224            switch ( strtolower( $options['liststyle'] ) ) {
225                case 'ordered':
226                    $this->mode = 'ordered';
227                    $this->token = '#';
228                    break;
229                case 'unordered':
230                    $this->mode = 'unordered';
231                    $this->token = '*';
232                    break;
233                case 'bar':
234                    $this->mode = 'bar';
235                    $this->token = '&#160;ยท ';
236                    break;
237                default:
238                    $this->error( wfMessage( 'spl3_debug', 'liststyle' )->escaped() );
239            }
240        }
241        if ( isset( $options['parent'] ) ) {
242            if ( intval( $options['parent'] ) == -1 ) {
243                $this->parent = -1;
244            } elseif ( is_string( $options['parent'] ) ) {
245                $this->parent = $this->parse( $options['parent'] );
246                if ( $this->withParsoid ) {
247                    // a41be6b added the ability to use wikitext like {{{1}}}
248                    // or {{ROOTPAGENAME}} to set parent title string.
249                    // So, convert the fragment to a text string.
250                    $this->parent = $this->parent->textContent;
251                }
252            } else {
253                $this->error( wfMessage( 'spl3_debug', 'parent' )->escaped() );
254            }
255        }
256        if ( isset( $options['showpath'] ) ) {
257            $showPath = strtolower( $options['showpath'] );
258            if ( $showPath === 'no' || $showPath === '0' || $showPath === 'false' ) {
259                $this->showpath = 'no';
260            } elseif ( $showPath === 'notparent' ) {
261                $this->showpath = 'notparent';
262            } elseif ( in_array( $showPath, [ 'full', 'yes', '1', 'true' ], true ) ) {
263                $this->showpath = 'full';
264            } else {
265                $this->error( wfMessage( 'spl3_debug', 'showpath' )->escaped() );
266            }
267        }
268        if ( isset( $options['kidsonly'] ) ) {
269            if ( $options['kidsonly'] == 'true' || $options['kidsonly'] == 'yes'
270                || intval( $options['kidsonly'] ) == 1
271            ) {
272                $this->kidsonly = 1;
273            } elseif ( $options['kidsonly'] == 'false' || $options['kidsonly'] == 'no'
274                || intval( $options['kidsonly'] ) == 0
275            ) {
276                $this->kidsonly = 0;
277            } else {
278                $this->error( wfMessage( 'spl3_debug', 'kidsonly' )->escaped() );
279            }
280        }
281        if ( isset( $options['showparent'] ) ) {
282            if ( $options['showparent'] == 'true' || $options['showparent'] == 'yes'
283                || intval( $options['showparent'] ) == 1
284            ) {
285                $this->showparent = 1;
286            } elseif ( $options['showparent'] == 'false' || $options['showparent'] == 'no'
287                || intval( $options['showparent'] ) == 0
288            ) {
289                $this->showparent = 0;
290            } else {
291                $this->error( wfMessage( 'spl3_debug', 'showparent' )->escaped() );
292            }
293        }
294
295        $this->nosubpages = $options['nosubpages'] ?? null;
296    }
297
298    /**
299     * produce output using this class
300     * @return string html output
301     */
302    private function render() {
303        $pages = $this->getTitles();
304        $class = 'subpagelist';
305        if ( $pages != null && count( $pages ) > 0 ) {
306            $list = $this->makeList( $pages );
307            $htmlOrDom = $this->parse( $list );
308        } else {
309            if ( $this->nosubpages !== null ) {
310                $out = $this->nosubpages;
311            } else {
312                $plink = "[[" . $this->parent . "]]";
313                $out = "''" . wfMessage( 'spl3_nosubpages', $plink )->text() . "''\n";
314            }
315            $htmlOrDom = $this->parse( $out );
316            $class .= ' subpagelist-empty';
317        }
318        $errorHTML = $this->geterrors();
319        if ( $this->withParsoid ) {
320            $frag = $htmlOrDom;
321            $div = $frag->ownerDocument->createElement( 'div' );
322            $div->setAttribute( 'class', $class );
323            DOMUtils::migrateChildren( $this->parser->htmlToDOM( $errorHTML ), $div );
324            DOMUtils::migrateChildren( $frag, $div );
325            $frag->insertBefore( $div, $frag->firstChild );
326            return $frag;
327        } else {
328            return Html::rawElement( 'div', [ 'class' => $class ], $errorHTML . $htmlOrDom );
329        }
330    }
331
332    /**
333     * return the page titles of the subpages in an array
334     * @return array|null all titles, null on failure
335     */
336    private function getTitles() {
337        if ( $this->parent !== -1 ) {
338            $this->ptitle = Title::newFromText( $this->parent );
339            $userFactory = MediaWikiServices::getInstance()->getUserFactory();
340            // FIXME: Parsoid will excessively restrict access to some pages even if the user
341            // has the rights. Parsoid currently doesn't have a mechanism to unredact
342            // information during read view rendering in the OutputTransformPipeline.
343            // Once implemented, this code here will likely change.
344            $user = $this->withParsoid ? $userFactory->newAnonymous() :
345                    $userFactory->newFromUserIdentity( $this->parser->getUserIdentity() );
346            // note that non-existent pages may nevertheless have valid subpages
347            // on the other hand, not checking that the page exists can let input
348            // through which causes database errors
349            if (
350                $this->ptitle instanceof Title &&
351                $this->ptitle->exists() &&
352                $user->definitelyCan( 'read', $this->ptitle )
353            ) {
354                $parent = $this->ptitle->getDBkey();
355                $this->parent = $parent;
356                $nsi = $this->ptitle->getNamespace();
357            } else {
358                $this->error( wfMessage( 'spl3_debug', 'parent' )->escaped() );
359                return null;
360            }
361        } else {
362            $this->ptitle = $this->title;
363            $parent = $this->title->getDBkey();
364            $this->parent = $parent;
365            $nsi = $this->title->getNamespace();
366        }
367
368        $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
369        $queryBuilder = $dbr->newSelectQueryBuilder()
370            ->select( [ 'page_namespace', 'page_title' ] )
371            ->from( 'page' )
372            // don't let lists cross namespaces or include redirects
373            ->where( [
374                'page_namespace' => $nsi,
375                'page_is_redirect' => 0,
376                $dbr->expr( 'page_title', IExpression::LIKE, new LikeValue( $parent . '/', $dbr->anyString() ) ),
377            ] )
378            ->caller( __METHOD__ );
379
380        $order = strtoupper( $this->order );
381        if ( $this->ordermethod == 'title' ) {
382            $queryBuilder->orderBy( 'page_title', $order );
383        } elseif ( $this->ordermethod == 'lastedit' ) {
384            $queryBuilder->orderBy( 'page_touched', $order );
385        }
386
387        $res = $queryBuilder->fetchResultSet();
388
389        $titles = [];
390        foreach ( $res as $row ) {
391            $title = Title::makeTitleSafe( $row->page_namespace, $row->page_title );
392            if ( $title ) {
393                $titles[] = $title;
394            }
395        }
396
397        return $titles;
398    }
399
400    /**
401     * create one list item
402     * cases:
403     *  - full: full, e.g. Mainpage/Entry/Sub
404     *  - notparent: the path without the $parent item, e.g. Entry/Sub
405     *  - no: no path, only the page title, e.g. Sub
406     * @param Title $title the title of a page
407     * @return string the prepared string
408     * @see $showpath
409     */
410    private function makeListItem( $title ) {
411        switch ( $this->showpath ) {
412            case 'no':
413                $linktitle = substr( strrchr( $title->getText(), "/" ), 1 );
414                break;
415            case 'notparent':
416                $linktitle = substr( strstr( $title->getText(), "/" ), 1 );
417                break;
418            case 'full':
419                $linktitle = $title->getText();
420                break;
421            default:
422                throw new LogicException( "Can not happen" );
423        }
424        return ' [[' . $title->getPrefixedText() . '|' . $linktitle . ']]';
425    }
426
427    /**
428     * create whole list using makeListItem
429     * @param array $titles Array all page titles
430     * @return string the whole list
431     * @see SubPageList::makeListItem
432     */
433    private function makeList( $titles ) {
434        $descendantsLimitRaw = $this->config->get( 'SubPageListDescendantsLimit' );
435        $descendantsLimit = is_int( $descendantsLimitRaw ) ? $descendantsLimitRaw : self::DESCENDANTS_LIMIT_DEFAULT;
436        $c = 0;
437        $list = [];
438        # add parent item
439        if ( $this->showparent ) {
440            $pn = '[[' . $this->ptitle->getPrefixedText() . '|' . $this->ptitle->getText() . ']]';
441            if ( $this->mode != 'bar' ) {
442                $pn = $this->token . $pn;
443            }
444            $ss = trim( $pn );
445            $list[] = $ss;
446            // flag for bar token to be added on next item
447            $c++;
448        }
449        # add descendants
450        $parlv = substr_count( $this->ptitle->getPrefixedText(), '/' );
451        foreach ( $titles as $title ) {
452            $lv = substr_count( $title, '/' ) - $parlv;
453            if ( $this->kidsonly != 1 || $lv < 2 ) {
454                if ( $this->showparent ) {
455                    $lv++;
456                }
457                $ss = "";
458                if ( $this->mode == 'bar' ) {
459                    if ( $c > 0 ) {
460                        $ss .= $this->token;
461                    }
462                } else {
463                    for ( $i = 0; $i < $lv; $i++ ) {
464                        $ss .= $this->token;
465                    }
466                }
467                $ss .= $this->makeListItem( $title );
468                // make sure we don't get any <pre></pre> tags
469                $ss = trim( $ss );
470                $list[] = $ss;
471            }
472            $c++;
473            if ( $c > $descendantsLimit ) {
474                break;
475            }
476        }
477        $retval = '';
478        if ( count( $list ) > 0 ) {
479            $retval = implode( "\n", $list );
480            if ( $this->mode == 'bar' ) {
481                $retval = implode( "", $list );
482            }
483            // Workaround for bug where the first items */# in a list would remain unparsed
484            $retval = "\n" . $retval;
485        }
486
487        return $retval;
488    }
489
490    /**
491     * Wrapper function parse, call the other functions
492     * @return string|DocumentFragment the parsed output
493     */
494    private function parse( string $text ) {
495        if ( $this->withParsoid ) {
496            $opts = [
497                'processInNewFrame' => true,
498                'clearDSROffets' => true,
499                'parseOpts' => [ 'context' => 'inline' ]
500            ];
501            return $this->parser->wikitextToDOM( $text, $opts, true );
502        } else {
503            return $this->parser->recursiveTagParse( $text, $this->frame );
504        }
505    }
506}