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