1#!/usr/bin/env php
2<?php
3
4use splitbrain\phpcli\CLI;
5use splitbrain\phpcli\Options;
6
7if (!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
8define('NOSESSION', 1);
9require_once(DOKU_INC . 'inc/init.php');
10
11/**
12 * Update the Search Index from command line
13 */
14class IndexerCLI extends CLI
15{
16    private $quiet = false;
17    private $clear = false;
18
19    /**
20     * Register options and arguments on the given $options object
21     *
22     * @param Options $options
23     * @return void
24     */
25    protected function setup(Options $options)
26    {
27        $options->setHelp(
28            'Updates the searchindex by indexing all new or changed pages. When the -c option is ' .
29            'given the index is cleared first.'
30        );
31
32        $options->registerOption(
33            'clear',
34            'clear the index before updating',
35            'c'
36        );
37        $options->registerOption(
38            'quiet',
39            'don\'t produce any output',
40            'q'
41        );
42    }
43
44    /**
45     * Your main program
46     *
47     * Arguments and options have been parsed when this is run
48     *
49     * @param Options $options
50     * @return void
51     */
52    protected function main(Options $options)
53    {
54        $this->clear = $options->getOpt('clear');
55        $this->quiet = $options->getOpt('quiet');
56
57        if ($this->clear) $this->clearindex();
58
59        $this->update();
60    }
61
62    /**
63     * Update the index
64     */
65    protected function update()
66    {
67        global $conf;
68        $data = [];
69        $this->quietecho("Searching pages... ");
70        search($data, $conf['datadir'], 'search_allpages', ['skipacl' => true]);
71        $this->quietecho(count($data) . " pages found.\n");
72
73        foreach ($data as $val) {
74            $this->index($val['id']);
75        }
76    }
77
78    /**
79     * Index the given page
80     *
81     * @param string $id
82     */
83    protected function index($id)
84    {
85        $this->quietecho("$id... ");
86        idx_addPage($id, !$this->quiet, $this->clear);
87        $this->quietecho("done.\n");
88    }
89
90    /**
91     * Clear all index files
92     */
93    protected function clearindex()
94    {
95        $this->quietecho("Clearing index... ");
96        idx_get_indexer()->clear();
97        $this->quietecho("done.\n");
98    }
99
100    /**
101     * Print message if not supressed
102     *
103     * @param string $msg
104     */
105    protected function quietecho($msg)
106    {
107        if (!$this->quiet) echo $msg;
108    }
109}
110
111// Main
112$cli = new IndexerCLI();
113$cli->run();
114