xref: /dokuwiki/lib/exe/indexer.php (revision 38479cbba628ee76a92ff5f3c974cfa8e6ce9e61)
1<?php
2/**
3 * DokuWiki indexer
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../');
9define('DOKU_DISABLE_GZIP_OUTPUT',1);
10require_once(DOKU_INC.'inc/init.php');
11session_write_close();  //close session
12if(!defined('NL')) define('NL',"\n");
13
14// keep running after browser closes connection
15@ignore_user_abort(true);
16
17// check if user abort worked, if yes send output early
18$defer = !@ignore_user_abort() || $conf['broken_iua'];
19if(!$defer){
20    sendGIF(); // send gif
21}
22
23$ID = cleanID($INPUT->str('id'));
24
25// Catch any possible output (e.g. errors)
26$output = $INPUT->has('debug') && $conf['allowdebug'];
27if(!$output) ob_start();
28
29// run one of the jobs
30$tmp = array(); // No event data
31$evt = new Doku_Event('INDEXER_TASKS_RUN', $tmp);
32if ($evt->advise_before()) {
33  runIndexer() or
34  runSitemapper() or
35  sendDigest() or
36  runTrimRecentChanges() or
37  runTrimRecentChanges(true) or
38  $evt->advise_after();
39}
40if($defer) sendGIF();
41
42if(!$output) ob_end_clean();
43exit;
44
45// --------------------------------------------------------------------
46
47/**
48 * Trims the recent changes cache (or imports the old changelog) as needed.
49 *
50 * @param media_changes If the media changelog shall be trimmed instead of
51 * the page changelog
52 *
53 * @author Ben Coburn <btcoburn@silicodon.net>
54 */
55function runTrimRecentChanges($media_changes = false) {
56    global $conf;
57
58    echo "runTrimRecentChanges($media_changes): started".NL;
59
60    $fn = ($media_changes ? $conf['media_changelog'] : $conf['changelog']);
61
62    // Trim the Recent Changes
63    // Trims the recent changes cache to the last $conf['changes_days'] recent
64    // changes or $conf['recent'] items, which ever is larger.
65    // The trimming is only done once a day.
66    if (@file_exists($fn) &&
67        (@filemtime($fn.'.trimmed')+86400)<time() &&
68        !@file_exists($fn.'_tmp')) {
69            @touch($fn.'.trimmed');
70            io_lock($fn);
71            $lines = file($fn);
72            if (count($lines)<=$conf['recent']) {
73                // nothing to trim
74                io_unlock($fn);
75                echo "runTrimRecentChanges($media_changes): finished".NL;
76                return false;
77            }
78
79            io_saveFile($fn.'_tmp', '');          // presave tmp as 2nd lock
80            $trim_time = time() - $conf['recent_days']*86400;
81            $out_lines = array();
82
83            for ($i=0; $i<count($lines); $i++) {
84              $log = parseChangelogLine($lines[$i]);
85              if ($log === false) continue;                      // discard junk
86              if ($log['date'] < $trim_time) {
87                $old_lines[$log['date'].".$i"] = $lines[$i];     // keep old lines for now (append .$i to prevent key collisions)
88              } else {
89                $out_lines[$log['date'].".$i"] = $lines[$i];     // definitely keep these lines
90              }
91            }
92
93            if (count($lines)==count($out_lines)) {
94              // nothing to trim
95              @unlink($fn.'_tmp');
96              io_unlock($fn);
97              echo "runTrimRecentChanges($media_changes): finished".NL;
98              return false;
99            }
100
101            // sort the final result, it shouldn't be necessary,
102            //   however the extra robustness in making the changelog cache self-correcting is worth it
103            ksort($out_lines);
104            $extra = $conf['recent'] - count($out_lines);        // do we need extra lines do bring us up to minimum
105            if ($extra > 0) {
106              ksort($old_lines);
107              $out_lines = array_merge(array_slice($old_lines,-$extra),$out_lines);
108            }
109
110            // save trimmed changelog
111            io_saveFile($fn.'_tmp', implode('', $out_lines));
112            @unlink($fn);
113            if (!rename($fn.'_tmp', $fn)) {
114                // rename failed so try another way...
115                io_unlock($fn);
116                io_saveFile($fn, implode('', $out_lines));
117                @unlink($fn.'_tmp');
118            } else {
119                io_unlock($fn);
120            }
121            echo "runTrimRecentChanges($media_changes): finished".NL;
122            return true;
123    }
124
125    // nothing done
126    echo "runTrimRecentChanges($media_changes): finished".NL;
127    return false;
128}
129
130/**
131 * Runs the indexer for the current page
132 *
133 * @author Andreas Gohr <andi@splitbrain.org>
134 */
135function runIndexer(){
136    global $ID;
137    global $conf;
138    print "runIndexer(): started".NL;
139
140    if(!$ID) return false;
141
142    // do the work
143    return idx_addPage($ID, true);
144}
145
146/**
147 * Builds a Google Sitemap of all public pages known to the indexer
148 *
149 * The map is placed in the root directory named sitemap.xml.gz - This
150 * file needs to be writable!
151 *
152 * @author Andreas Gohr
153 * @link   https://www.google.com/webmasters/sitemaps/docs/en/about.html
154 */
155function runSitemapper(){
156    print "runSitemapper(): started".NL;
157    $result = Sitemapper::generate() && Sitemapper::pingSearchEngines();
158    print 'runSitemapper(): finished'.NL;
159    return $result;
160}
161
162/**
163 * Send digest and list mails for all subscriptions which are in effect for the
164 * current page
165 *
166 * @author Adrian Lang <lang@cosmocode.de>
167 */
168function sendDigest() {
169    echo 'sendDigest(): started'.NL;
170    global $ID;
171    global $conf;
172    if (!$conf['subscribers']) {
173        echo 'sendDigest(): disabled'.NL;
174        return false;
175    }
176    $subscriptions = subscription_find($ID, array('style' => '(digest|list)',
177                                                  'escaped' => true));
178    /** @var auth_basic $auth */
179    global $auth;
180    global $lang;
181    global $conf;
182    global $USERINFO;
183
184    $sent = false;
185
186    // remember current user info
187    $olduinfo = $USERINFO;
188    $olduser  = $_SERVER['REMOTE_USER'];
189
190    foreach($subscriptions as $id => $users) {
191        if (!subscription_lock($id)) {
192            continue;
193        }
194        foreach($users as $data) {
195            list($user, $style, $lastupdate) = $data;
196            $lastupdate = (int) $lastupdate;
197            if ($lastupdate + $conf['subscribe_time'] > time()) {
198                // Less than the configured time period passed since last
199                // update.
200                continue;
201            }
202
203            // Work as the user to make sure ACLs apply correctly
204            $USERINFO = $auth->getUserData($user);
205            $_SERVER['REMOTE_USER'] = $user;
206            if ($USERINFO === false) {
207                continue;
208            }
209
210            if (substr($id, -1, 1) === ':') {
211                // The subscription target is a namespace
212                $changes = getRecentsSince($lastupdate, null, getNS($id));
213            } else {
214                if(auth_quickaclcheck($id) < AUTH_READ) continue;
215
216                $meta = p_get_metadata($id);
217                $changes = array($meta['last_change']);
218            }
219
220            // Filter out pages only changed in small and own edits
221            $change_ids = array();
222            foreach($changes as $rev) {
223                $n = 0;
224                while (!is_null($rev) && $rev['date'] >= $lastupdate &&
225                       ($_SERVER['REMOTE_USER'] === $rev['user'] ||
226                        $rev['type'] === DOKU_CHANGE_TYPE_MINOR_EDIT)) {
227                    $rev = getRevisions($rev['id'], $n++, 1);
228                    $rev = (count($rev) > 0) ? $rev[0] : null;
229                }
230
231                if (!is_null($rev) && $rev['date'] >= $lastupdate) {
232                    // Some change was not a minor one and not by myself
233                    $change_ids[] = $rev['id'];
234                }
235            }
236
237            if ($style === 'digest') {
238                foreach($change_ids as $change_id) {
239                    subscription_send_digest($USERINFO['mail'], $change_id,
240                                             $lastupdate);
241                    $sent = true;
242                }
243            } elseif ($style === 'list') {
244                subscription_send_list($USERINFO['mail'], $change_ids, $id);
245                $sent = true;
246            }
247            // TODO: Handle duplicate subscriptions.
248
249            // Update notification time.
250            subscription_set($user, $id, $style, time(), true);
251        }
252        subscription_unlock($id);
253    }
254
255    // restore current user info
256    $USERINFO = $olduinfo;
257    $_SERVER['REMOTE_USER'] = $olduser;
258    echo 'sendDigest(): finished'.NL;
259    return $sent;
260}
261
262/**
263 * Just send a 1x1 pixel blank gif to the browser
264 *
265 * @author Andreas Gohr <andi@splitbrain.org>
266 * @author Harry Fuecks <fuecks@gmail.com>
267 */
268function sendGIF(){
269    global $INPUT;
270    if($INPUT->has('debug')){
271        header('Content-Type: text/plain');
272        return;
273    }
274    $img = base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAEALAAAAAABAAEAAAIBTAA7');
275    header('Content-Type: image/gif');
276    header('Content-Length: '.strlen($img));
277    header('Connection: Close');
278    print $img;
279    flush();
280    // Browser should drop connection after this
281    // Thinks it's got the whole image
282}
283
284//Setup VIM: ex: et ts=4 :
285// No trailing PHP closing tag - no output please!
286// See Note at http://www.php.net/manual/en/language.basic-syntax.instruction-separation.php
287