-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.php
More file actions
259 lines (228 loc) · 8.32 KB
/
Copy pathcli.php
File metadata and controls
259 lines (228 loc) · 8.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
<?php
use dokuwiki\Extension\CLIPlugin;
use splitbrain\phpcli\Options;
/**
* DokuWiki Plugin acknowledge (CLI Component)
*
* @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
* @author Anna Dabrowska <dokuwiki@cosmocode.de>
*/
class cli_plugin_acknowledge extends CLIPlugin
{
/** @var helper_plugin_acknowledge */
protected $helper;
/**
* Initialize helper
*/
public function __construct()
{
parent::__construct();
$this->helper = plugin_load('helper', 'acknowledge');
}
/**
* @inheritDoc
*/
protected function setup(Options $options)
{
$options->setHelp('Maintenance and import tools for the acknowledge plugin');
$options->registerCommand(
'import-ireadit',
'Import read records and ~~IREADIT~~ assignments from the ireadit plugin'
);
$options->registerOption(
'dry-run',
'Only report what would be imported, without writing anything',
'd',
false,
'import-ireadit'
);
}
/**
* @inheritDoc
*/
protected function main(Options $options)
{
$cmd = $options->getCmd();
switch ($cmd) {
case 'import-ireadit':
try {
$this->importIreadit((bool)$options->getOpt('dry-run'));
} catch (\Exception $e) {
$this->fatal($e);
}
break;
default:
$this->error('No command provided');
echo $options->help();
exit(1);
}
}
/**
* Import acknowledgements and assignments from the ireadit plugin
*
* @param bool $dryRun whether to only report instead of writing
* @return void
* @throws Exception
*/
protected function importIreadit(bool $dryRun): void
{
/** @var helper_plugin_ireadit_db $ireaditDb */
$ireaditDb = plugin_load('helper', 'ireadit_db');
if ($ireaditDb === null) {
throw new \RuntimeException(
'The ireaditDb plugin is required but could not be loaded.'
);
}
if ($dryRun) {
$this->notice('Running in dry-run mode, no changes will be written');
}
// make sure the pages table is populated
if (!$dryRun) {
$this->helper->updatePageIndex();
}
[$assignmentCount, $patternCount] = $this->importAssignments($dryRun);
$acksCount = $this->importIreaditRecords($ireaditDb, $dryRun);
$this->success(sprintf(
'Done: imported %d ireadit record(s), %d assignment pattern(s) (%d assignee entries)',
$acksCount,
$patternCount,
$assignmentCount
));
}
/**
* Import ireadit records into the acks table, keeping only the latest per page+user
*
* @param helper_plugin_ireadit_db $ireaditDb
* @param bool $dryRun
* @return int number of records imported (or that would be imported if on dry-run)
* @throws Exception
*/
protected function importIreaditRecords(\helper_plugin_ireadit_db $ireaditDb, bool $dryRun): int
{
$sqlite = $ireaditDb->getDB();
$res = $sqlite->query('SELECT page, user, rev, tim§estamp FROM ireadit');
if ($res === false) {
throw new \RuntimeException('Failed to read records from the ireadit database');
}
$rows = $sqlite->res2arr($res);
// keep only the latest acknowledgement per page+user
$latest = [];
foreach ($rows as $row) {
$time = $row['timestamp'] ? strtotime($row['timestamp']) : (int)$row['rev'];
if (!$time) continue;
// index by page+user; the NUL byte is a safe separator because it can never
// appear in a page id or user name, so the two parts can't collide
$key = $row['page'] . "\0" . $row['user'];
if (!isset($latest[$key]) || $time > $latest[$key]['time']) {
$latest[$key] = ['page' => $row['page'], 'user' => $row['user'], 'time' => $time];
}
}
$imported = 0;
$failed = 0;
foreach ($latest as $entry) {
$this->info(sprintf(
'ireadit record: %s by %s at %s',
$entry['page'],
$entry['user'],
dformat($entry['time'])
));
if ($dryRun) {
$imported++;
continue;
}
// a single bad record should not abort the whole import
try {
$this->helper->importAcknowledgement($entry['page'], $entry['user'], $entry['time']);
$imported++;
} catch (\Exception $e) {
$failed++;
$this->error(sprintf(
'Failed to import read record for %s by %s: %s',
$entry['page'],
$entry['user'],
$e->getMessage()
));
}
}
if ($failed) {
$this->warning(sprintf('%d read record(s) could not be imported', $failed));
}
return $imported;
}
/**
* Create assignment patterns for every page containing ~~IREADIT...~~ syntax
*
* @param bool $dryRun
* @return array{0:int,1:int} number of assignee entries and number of patterns created
* @throws RuntimeException if the assignment patterns cannot be saved
*/
protected function importAssignments(bool $dryRun): array
{
// legacy indexer, starting with Mort
$pages = idx_getIndex('page', '');
$newPatterns = [];
foreach ($pages as $page) {
$page = trim($page);
if ($page === '') continue;
$source = rawWiki($page);
if (!preg_match('/~~IREADIT(.*?)~~/', $source, $match)) {
continue;
}
$assignees = $this->parseIreaditAssignees($match[1]);
$newPatterns[$page] = $assignees;
$this->info(sprintf('Pattern: %s -> %s', $page, $assignees));
}
if (!$dryRun && $newPatterns) {
// saveAssignmentPatterns() rewrites the whole assignments_patterns table, so we must merge
$patterns = $this->helper->getAssignmentPatterns();
foreach ($newPatterns as $newPattern => $assignees) {
// when a page already has our pattern, append the imported assignees
if (!empty($patterns[$newPattern])) {
$assignees = $patterns[$newPattern] . ',' . $assignees;
}
// clean up combined assignees
$entries = array_map('trim', explode(',', $assignees));
$entries = array_filter($entries);
$patterns[$newPattern] = implode(',', array_unique($entries));
}
try {
$this->helper->saveAssignmentPatterns($patterns);
} catch (\Exception $e) {
throw new \RuntimeException('Failed to save assignment patterns: ' . $e->getMessage(), 0, $e);
}
}
$assigneeCount = 0;
foreach ($newPatterns as $assignees) {
$assigneeCount += count(array_filter(explode(',', $assignees)));
}
return [$assigneeCount, count($newPatterns)];
}
/**
* Parse the ~~IREADIT...~~ syntax into an acknowledge assignee string
*
* Mirrors the parsing in syntax_plugin_ireadit_ireadit::handle(). Empty syntax means
* "everyone" in ireadit, which is mapped to the global default group.
*
* @param string $inner the text between ~~IREADIT and ~~
* @return string comma-separated list of users and @groups
*/
protected function parseIreaditAssignees(string $inner): string
{
global $conf;
$splits = preg_split('/[\s:]+/', trim($inner), -1, PREG_SPLIT_NO_EMPTY);
$users = [];
$groups = [];
foreach ($splits as $split) {
if ($split[0] === '@') {
$groups[] = $split;
} else {
$users[] = $split;
}
}
// empty ~~IREADIT~~ means everyone, so use default group
if (!$users && !$groups) {
return '@' . $conf['defaultgroup'];
}
return implode(',', array_merge($users, $groups));
}
}