Failed Conditions
Push — TaskRunner ( b413fb )
by Michael
05:21
created

TaskRunner   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 173
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 173
rs 10
c 0
b 0
f 0
wmc 26
lcom 1
cbo 3

5 Methods

Rating   Name   Duplication   Size   Complexity  
B run() 0 14 7
D runTrimRecentChanges() 0 84 13
A runIndexer() 0 13 2
A runSitemapper() 0 7 2
A sendDigest() 0 17 2
1
<?php
2
3
namespace dokuwiki;
4
5
use Doku_Event;
6
use Sitemapper;
7
use Subscription;
8
9
class TaskRunner
10
{
11
    public function run()
12
    {
13
        // run one of the jobs
14
        $tmp = []; // No event data
15
        $evt = new Doku_Event('INDEXER_TASKS_RUN', $tmp);
16
        if ($evt->advise_before()) {
17
            $this->runIndexer() or
18
            $this->runSitemapper() or
19
            $this->sendDigest() or
20
            $this->runTrimRecentChanges() or
21
            $this->runTrimRecentChanges(true) or
22
            $evt->advise_after();
23
        }
24
    }
25
26
    /**
27
     * Trims the recent changes cache (or imports the old changelog) as needed.
28
     *
29
     * @param bool $media_changes   If the media changelog shall be trimmed instead of
30
     *                              the page changelog
31
     *
32
     * @return bool
33
     *
34
     * @author Ben Coburn <[email protected]>
35
     */
36
    protected function runTrimRecentChanges($media_changes = false)
37
    {
38
        global $conf;
39
40
        echo "runTrimRecentChanges($media_changes): started" . NL;
41
42
        $fn = ($media_changes ? $conf['media_changelog'] : $conf['changelog']);
43
44
        // Trim the Recent Changes
45
        // Trims the recent changes cache to the last $conf['changes_days'] recent
46
        // changes or $conf['recent'] items, which ever is larger.
47
        // The trimming is only done once a day.
48
        if (file_exists($fn) &&
49
            (@filemtime($fn . '.trimmed') + 86400) < time() &&
50
            !file_exists($fn . '_tmp')) {
51
            @touch($fn . '.trimmed');
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
52
            io_lock($fn);
53
            $lines = file($fn);
54
            if (count($lines) <= $conf['recent']) {
55
                // nothing to trim
56
                io_unlock($fn);
57
                echo "runTrimRecentChanges($media_changes): finished" . NL;
58
                return false;
59
            }
60
61
            io_saveFile($fn . '_tmp', '');          // presave tmp as 2nd lock
62
            $trim_time = time() - $conf['recent_days'] * 86400;
63
            $out_lines = [];
64
            $old_lines = [];
65
            for ($i = 0; $i < count($lines); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
66
                $log = parseChangelogLine($lines[$i]);
67
                if ($log === false) {
68
                    continue;
69
                }                      // discard junk
70
                if ($log['date'] < $trim_time) {
71
                    $old_lines[$log['date'] . ".$i"] = $lines[$i];     // keep old lines for now (append .$i to prevent key collisions)
72
                } else {
73
                    $out_lines[$log['date'] . ".$i"] = $lines[$i];     // definitely keep these lines
74
                }
75
            }
76
77
            if (count($lines) == count($out_lines)) {
78
                // nothing to trim
79
                @unlink($fn . '_tmp');
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
80
                io_unlock($fn);
81
                echo "runTrimRecentChanges($media_changes): finished" . NL;
82
                return false;
83
            }
84
85
            // sort the final result, it shouldn't be necessary,
86
            //   however the extra robustness in making the changelog cache self-correcting is worth it
87
            ksort($out_lines);
88
            $extra = $conf['recent'] - count($out_lines);        // do we need extra lines do bring us up to minimum
89
            if ($extra > 0) {
90
                ksort($old_lines);
91
                $out_lines = array_merge(array_slice($old_lines, -$extra), $out_lines);
92
            }
93
94
            $eventData = [
95
                'trimmedChangelogLines' => $out_lines,
96
                'removedChangelogLines' => $extra > 0 ? array_slice($old_lines, 0, -$extra) : $old_lines,
97
            ];
98
            trigger_event('TRIM_RECENT_CHANGES', $eventData);
99
            $out_lines = $eventData['trimmedChangelogLines'];
100
101
            // save trimmed changelog
102
            io_saveFile($fn . '_tmp', implode('', $out_lines));
103
            @unlink($fn);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
104
            if (!rename($fn . '_tmp', $fn)) {
105
                // rename failed so try another way...
106
                io_unlock($fn);
107
                io_saveFile($fn, implode('', $out_lines));
108
                @unlink($fn . '_tmp');
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
109
            } else {
110
                io_unlock($fn);
111
            }
112
            echo "runTrimRecentChanges($media_changes): finished" . NL;
113
            return true;
114
        }
115
116
        // nothing done
117
        echo "runTrimRecentChanges($media_changes): finished" . NL;
118
        return false;
119
    }
120
121
122
    /**
123
     * Runs the indexer for the current page
124
     *
125
     * @author Andreas Gohr <[email protected]>
126
     */
127
    protected function runIndexer()
128
    {
129
        global $ID;
130
        global $conf;
131
        print 'runIndexer(): started' . NL;
132
133
        if (!$ID) {
134
            return false;
135
        }
136
137
        // do the work
138
        return idx_addPage($ID, true);
139
    }
140
141
    /**
142
     * Builds a Google Sitemap of all public pages known to the indexer
143
     *
144
     * The map is placed in the root directory named sitemap.xml.gz - This
145
     * file needs to be writable!
146
     *
147
     * @author Andreas Gohr
148
     * @link   https://www.google.com/webmasters/sitemaps/docs/en/about.html
149
     */
150
    protected function runSitemapper()
151
    {
152
        print 'runSitemapper(): started' . NL;
153
        $result = Sitemapper::generate() && Sitemapper::pingSearchEngines();
154
        print 'runSitemapper(): finished' . NL;
155
        return $result;
156
    }
157
158
    /**
159
     * Send digest and list mails for all subscriptions which are in effect for the
160
     * current page
161
     *
162
     * @author Adrian Lang <[email protected]>
163
     */
164
    protected function sendDigest()
165
    {
166
        global $conf;
167
        global $ID;
168
169
        echo 'sendDigest(): started' . NL;
170
        if (!actionOK('subscribe')) {
171
            echo 'sendDigest(): disabled' . NL;
172
            return false;
173
        }
174
        $sub = new Subscription();
175
        $sent = $sub->send_bulk($ID);
176
177
        echo "sendDigest(): sent $sent mails" . NL;
178
        echo 'sendDigest(): finished' . NL;
179
        return (bool)$sent;
180
    }
181
}
182