1<?php
2/**
3 * Plugin nspages : Displays nicely a list of the pages of a namespace
4 *
5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 */
7if(!defined('DOKU_INC')) die();
8require_once 'filePreparer.php';
9
10class namespacePreparer extends filePreparer {
11    function __construct($excludedFiles, $pregOn, $pregOff, $pregTitleOn, $pregTitleOff, $useTitle, $sortPageById, $useIdAndTitle, $sortPageByDate, $sortByCreationDate){
12        parent::__construct($excludedFiles, $pregOn, $pregOff, $pregTitleOn, $pregTitleOff, $useTitle, $sortPageById, $useIdAndTitle, $sortPageByDate, $sortByCreationDate);
13    }
14
15    function isFileWanted($file, $useTitle){
16        return $file['type'] == 'd' && parent::isFileWanted($file, $useTitle);
17    }
18
19    function prepareFileTitle(&$ns){
20        $idMainPage = $this->getMainPageId($ns);
21        if ( !is_null($idMainPage) ){
22            $ns['title'] = p_get_first_heading($idMainPage, true);
23        } else {
24            $ns['title'] = null;
25        }
26    }
27
28    /**
29     * When we display a namespace, we want to:
30     * - link to it's main page (if such a page exists)
31     * - get the id of this main page (if the option is active)
32     *
33     * @param         $ns  A structure which represents a namespace
34     */
35    function prepareFile(&$ns){
36        $ns['nameToDisplay'] = $this->buildNameToDisplay($ns['title'], noNS($ns['id']));
37        $ns['id'] = $this->buildIdToLinkTo($this->getMainPageId($ns), $ns['id']);
38        $ns['sort'] = $this->buildSortAttribute($ns['nameToDisplay'], $ns['id'], $ns['mtime']);
39    }
40
41    private function getMainPageId(&$ns){
42        if (is_null($ns['idMainPage'])){
43            $idMainPage = $ns['id'].':';
44            resolve_pageid('', $idMainPage, $exist); //get the id of the main page of the ns
45            $ns['idMainPage'] = $exist ? $idMainPage : null;
46        }
47        return $ns['idMainPage'];
48    }
49
50    private function buildNameToDisplay($title, $defaultName){
51        if ( ! is_null($title) ){
52            if($this->useIdAndTitle){
53                return $defaultName . " - " . $title;
54            }
55
56            if($this->useTitle) {
57                return $title;
58            }
59        }
60
61        return $defaultName;
62    }
63
64    private function buildIdToLinkTo($idMainPage, $currentNsId){
65        if(is_null($idMainPage)) {
66            return $currentNsId . ':';
67        } else {
68            return $idMainPage;
69        }
70    }
71
72    private function buildSortAttribute($nameToDisplay, $nsId, $mtime){
73        if ( $this->sortPageById ){
74            return curNS($nsId);
75        } else if ( $this->sortPageByDate ){
76            return $mtime;
77        } else {
78            return $nameToDisplay;
79        }
80    }
81}
82