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