1<?php
2/**
3 * DokuWiki Plugin pagestats (Action Component)
4 * Counts the number of pages and media files and calculates their total size.
5 */
6
7if (!defined('DOKU_INC')) die();
8
9class action_plugin_pagestats extends DokuWiki_Action_Plugin {
10
11    public function register(Doku_Event_Handler $controller) {
12        $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'add_stats_to_page');
13    }
14
15    public function add_stats_to_page(Doku_Event $event, $param) {
16        $dataPathPages = DOKU_INC . 'data/pages';
17        $dataPathMedia = DOKU_INC . 'data/media';
18
19        $stats = [
20            'pagestatspage' => $this->countFiles($dataPathPages, 'txt'),
21            'pagestatsmb' => $this->calculateSize($dataPathPages, 'txt'),
22            'mediastatspage' => $this->countFiles($dataPathMedia, ''),
23            'mediastatsmb' => $this->calculateSize($dataPathMedia, '')
24        ];
25
26        foreach ($stats as $name => $value) {
27            $event->data['meta'][] = ['name' => $name, 'content' => $value];
28        }
29    }
30
31    private function countFiles($path, $extension) {
32        if (!is_dir($path)) return 0;
33
34        $count = 0;
35        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
36        foreach ($iterator as $file) {
37            if ($file->isFile() && ($extension === '' || $file->getExtension() === $extension)) {
38                $count++;
39            }
40        }
41
42        return $count;
43    }
44
45    private function calculateSize($path, $extension) {
46        if (!is_dir($path)) return 0;
47
48        $totalSize = 0;
49        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
50        foreach ($iterator as $file) {
51            if ($file->isFile() && ($extension === '' || $file->getExtension() === $extension)) {
52                $totalSize += $file->getSize();
53            }
54        }
55
56        return round($totalSize / (1024 * 1024), 2); // In MB
57    }
58}
59