Repository navigation
Expand file tree
/
Copy pathProcessVotee.module.php
More file actions
319 lines (289 loc) · 14.6 KB
/
Copy pathProcessVotee.module.php
File metadata and controls
319 lines (289 loc) · 14.6 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
<?php
namespace ProcessWire;
/**
* Admin page "Polls": overview, results, CSV export, reset votes, regenerate hash,
* moderation of "Other" answers.
*/
class ProcessVotee extends Process
{
public static function getModuleInfo()
{
return [
'title' => 'Votee: Polls',
'summary' => 'Results and management of Votee polls.',
'version' => '0.1.0',
'icon' => 'bar-chart',
'requires' => 'Votee',
'permission' => 'votee-admin',
'permissions' => ['votee-admin' => 'View and manage Votee polls'],
'page' => ['name' => 'votee', 'parent' => '', 'title' => 'Polls'],
];
}
protected function votee(): Votee
{
return $this->wire()->modules->get('Votee');
}
protected function poll(): Page
{
$id = (int) $this->wire()->input->get('id') ?: (int) $this->wire()->input->post('id');
$poll = $this->wire()->pages->get("id=$id, template=" . Votee::TPL_POLL . ', include=all');
if (!$poll->id) throw new Wire404Exception($this->_('Poll not found'));
return $poll;
}
/* ------------------------------------------------------------------ Overview */
public function ___execute()
{
$votee = $this->votee();
$sanitizer = $this->wire()->sanitizer;
$config = $this->wire()->config;
$parent = $votee->getParent();
$counts = $this->participantCounts();
$labels = $this->statusLabels();
$table = $this->wire()->modules->get('MarkupAdminDataTable');
$table->setEncodeEntities(false);
$table->headerRow([
$this->_('Poll'), $this->_('Status'), $this->_('Period'), $this->_('Targets'),
$this->_('Participants'), '',
]);
foreach ($votee->getAllPolls() as $poll) {
$poll->of(false);
$edit = $config->urls->admin . 'page/edit/?id=' . $poll->id;
$status = $votee->status($poll);
$table->row([
'<a href="' . $edit . '"><strong>' . $sanitizer->entities($poll->title) . '</strong></a><br><small>'
. $sanitizer->entities((string) $poll->votee_question) . '</small>',
'<span class="votee-status votee-status--' . $status . '">' . $labels[$status] . '</span>',
$this->period($poll),
$this->targetSummary($poll),
(int) ($counts[$poll->id] ?? 0),
'<a class="ui-button ui-state-default" href="./view/?id=' . $poll->id . '">' . $this->_('Results') . '</a>',
]);
}
$out = '';
if ($parent->id) {
$btn = $this->wire()->modules->get('InputfieldButton');
$btn->href = $config->urls->admin . 'page/add/?parent_id=' . $parent->id;
$btn->value = $this->_('New poll');
$btn->icon = 'plus';
$out .= '<p>' . $btn->render() . '</p>';
}
$out .= $votee->getAllPolls()->count()
? $table->render()
: '<p>' . $this->_('No polls yet.') . '</p>';
return $out;
}
protected function statusLabels(): array
{
return [
'draft' => $this->_('draft'),
'scheduled' => $this->_('scheduled'),
'active' => $this->_('active'),
'ended' => $this->_('ended'),
];
}
protected function participantCounts(): array
{
$rows = $this->wire()->database->query('SELECT poll_id, COUNT(DISTINCT submission) c FROM '
. Votee::TABLE_VOTES . ' GROUP BY poll_id')->fetchAll(\PDO::FETCH_KEY_PAIR);
return array_map('intval', $rows);
}
protected function period(Page $poll): string
{
$s = (int) $poll->getUnformatted('votee_start');
$e = (int) $poll->getUnformatted('votee_end');
if (!$s && !$e) return $this->_('unlimited');
return ($s ? date('Y-m-d H:i', $s) : '…') . ' – ' . ($e ? date('Y-m-d H:i', $e) : '…');
}
protected function targetSummary(Page $poll): string
{
$sanitizer = $this->wire()->sanitizer;
$out = [];
$pages = $poll->getUnformatted('votee_target_pages');
if ($pages instanceof PageArray && $pages->count()) {
$out[] = sprintf($this->_n('%d page', '%d pages', $pages->count()), $pages->count())
. ($poll->getUnformatted('votee_target_children') ? ' + ' . $this->_('children') : '');
}
if ($tpls = $this->votee()->targetTemplates($poll)) {
$out[] = $this->_('Templates:') . ' ' . $sanitizer->entities(implode(', ', $tpls));
}
$sel = trim((string) $poll->getUnformatted('votee_target_selector'));
if ($sel !== '') $out[] = '<code>' . $sanitizer->entities($sel) . '</code>';
return $out ? implode('<br>', $out) : '<em>' . $this->_('no target') . '</em>';
}
/* ------------------------------------------------------------------ Results */
public function ___executeView()
{
$poll = $this->poll();
$poll->of(false);
$votee = $this->votee();
$sanitizer = $this->wire()->sanitizer;
$db = $this->wire()->database;
$t = Votee::TABLE_VOTES;
$this->headline($poll->title);
$this->breadcrumb('../', $this->_('Polls'));
$r = $votee->getResults($poll);
$labels = $this->statusLabels();
$out = '<h2>' . $sanitizer->entities((string) $poll->votee_question) . '</h2>';
$out .= '<p>' . sprintf(
$this->_('Status: %1$s · Period: %2$s · %3$d participants · %4$d votes · Hash %5$s'),
$labels[$votee->status($poll)], $this->period($poll), $r['participants'], $r['votes'],
'<code>' . $sanitizer->entities((string) $poll->votee_hash) . '</code>'
) . ($poll->votee_multi ? ' · ' . $this->_('multiple choice') : '') . '</p>';
// Result bars
$out .= '<table class="votee-admin-results">';
foreach ($r['options'] as $o) {
$out .= '<tr><th>' . $sanitizer->entities($o['label']) . '</th><td><div class="votee-admin-bar">'
. '<span style="width:' . (int) $o['percent'] . '%"></span></div></td><td>'
. (int) $o['percent'] . ' %</td><td>' . (int) $o['count'] . '</td></tr>';
}
$out .= '</table>';
$out .= '<style>.votee-admin-results{border-collapse:collapse;margin:1em 0;width:100%;max-width:56rem}'
. '.votee-admin-results th{text-align:left;font-weight:normal;padding:.35em 1em .35em 0;width:35%}'
. '.votee-admin-results td{padding:.35em .5em;white-space:nowrap}.votee-admin-results td:nth-child(2){width:100%}'
. '.votee-admin-bar{background:#e5e7eb;border-radius:3px;height:1.1em;overflow:hidden}'
. '.votee-admin-bar span{display:block;height:100%;background:#3eb998}</style>';
// Per day
$q = $db->prepare("SELECT DATE(created) d, COUNT(DISTINCT submission) c FROM $t WHERE poll_id=:p GROUP BY d ORDER BY d DESC LIMIT 60");
$q->execute([':p' => $poll->id]);
$days = $q->fetchAll(\PDO::FETCH_KEY_PAIR);
if ($days) {
$table = $this->wire()->modules->get('MarkupAdminDataTable');
$table->headerRow([$this->_('Day'), $this->_('Participants')]);
foreach ($days as $d => $c) $table->row([date('Y-m-d', strtotime($d)), (int) $c]);
$out .= '<h3>' . $this->_('Participants per day') . '</h3>' . $table->render();
}
// Per page
$q = $db->prepare("SELECT page_id, COUNT(DISTINCT submission) c FROM $t WHERE poll_id=:p GROUP BY page_id ORDER BY c DESC");
$q->execute([':p' => $poll->id]);
$byPage = $q->fetchAll(\PDO::FETCH_KEY_PAIR);
if ($byPage) {
$table = $this->wire()->modules->get('MarkupAdminDataTable');
$table->setEncodeEntities(false);
$table->headerRow([$this->_('Page'), $this->_('Participants')]);
$i = 0;
$rest = 0;
foreach ($byPage as $pid => $c) {
if (++$i > 20) {
$rest += (int) $c;
continue;
}
$p = $this->wire()->pages->get((int) $pid);
$label = $p->id ? '<a href="' . $p->url . '" target="_blank">' . $sanitizer->entities($p->path) . '</a>' : '#' . (int) $pid;
$table->row([$label, (int) $c]);
}
if ($rest) $table->row([$this->_('other pages'), $rest]);
$out .= '<h3>' . $this->_('By page') . '</h3>' . $table->render();
}
// "Other" answers
$q = $db->prepare("SELECT id, other_text, created FROM $t WHERE poll_id=:p AND option_id=0 AND other_text <> '' ORDER BY created DESC");
$q->execute([':p' => $poll->id]);
$others = $q->fetchAll(\PDO::FETCH_ASSOC);
if ($others) {
$table = $this->wire()->modules->get('MarkupAdminDataTable');
$table->setEncodeEntities(false);
$table->headerRow([$this->_('Date'), $this->_('Answer'), '']);
foreach ($others as $o) {
$table->row([
date('Y-m-d H:i', strtotime($o['created'])),
$sanitizer->entities($o['other_text']),
$this->postButton('deleteOther', $poll, $this->_('Delete text'), ['vote' => (int) $o['id']],
$this->_('Delete this text? The vote still counts as "Other".')),
]);
}
$out .= '<h3>' . sprintf($this->_('Answers "%s"'), $sanitizer->entities($votee->otherLabel($poll))) . '</h3>' . $table->render();
}
// Actions
$out .= '<h3>' . $this->_('Actions') . '</h3><p>'
. '<a class="ui-button ui-state-default" href="./export/?id=' . $poll->id . '&type=agg">' . $this->_('CSV: results') . '</a> '
. '<a class="ui-button ui-state-default" href="./export/?id=' . $poll->id . '&type=raw">' . $this->_('CSV: raw data') . '</a> '
. '<a class="ui-button ui-state-default" href="' . $this->wire()->config->urls->admin . 'page/edit/?id=' . $poll->id . '">' . $this->_('Edit') . '</a>'
. '</p><p>'
. $this->postButton('reset', $poll, $this->_('Reset votes'), [],
$this->_('Permanently delete all votes of this poll?'))
. ' '
. $this->postButton('rehash', $poll, $this->_('Regenerate hash'), [],
$this->_('Regenerate the hash? All visitors may then vote again. Existing votes are kept.'))
. '</p>';
return $out;
}
protected function postButton(string $action, Page $poll, string $label, array $extra, string $confirm): string
{
$token = $this->wire()->session->CSRF;
$fields = '<input type="hidden" name="' . $token->getTokenName() . '" value="' . $token->getTokenValue() . '">'
. '<input type="hidden" name="id" value="' . $poll->id . '">';
foreach ($extra as $k => $v) $fields .= '<input type="hidden" name="' . $k . '" value="' . (int) $v . '">';
$confirm = htmlspecialchars(json_encode($confirm, JSON_UNESCAPED_UNICODE), ENT_QUOTES);
return '<form method="post" action="./' . $action . '/" style="display:inline" onsubmit="return confirm(' . $confirm . ')">'
. $fields . '<button type="submit" class="ui-button ui-state-default">' . $label . '</button></form>';
}
protected function requirePost(): Page
{
$input = $this->wire()->input;
if ($input->requestMethod() !== 'POST') throw new WireException('POST required');
$this->wire()->session->CSRF->validate();
return $this->poll();
}
public function ___executeReset()
{
$poll = $this->requirePost();
$q = $this->wire()->database->prepare('DELETE FROM ' . Votee::TABLE_VOTES . ' WHERE poll_id=:p');
$q->execute([':p' => $poll->id]);
$this->message(sprintf($this->_('%d votes deleted.'), $q->rowCount()));
$this->wire()->session->redirect('../view/?id=' . $poll->id);
}
public function ___executeRehash()
{
$poll = $this->requirePost();
$poll->of(false);
$poll->votee_hash = Votee::newHash();
$poll->save('votee_hash');
$this->votee()->clearCache();
$this->message($this->_('New hash generated.'));
$this->wire()->session->redirect('../view/?id=' . $poll->id);
}
public function ___executeDeleteOther()
{
$poll = $this->requirePost();
$q = $this->wire()->database->prepare('UPDATE ' . Votee::TABLE_VOTES . ' SET other_text=NULL WHERE id=:id AND poll_id=:p');
$q->execute([':id' => (int) $this->wire()->input->post('vote'), ':p' => $poll->id]);
$this->message($this->_('Text deleted.'));
$this->wire()->session->redirect('../view/?id=' . $poll->id);
}
/* ------------------------------------------------------------------ Export */
public function ___executeExport()
{
$poll = $this->poll();
$poll->of(false);
$type = $this->wire()->input->get('type') === 'raw' ? 'raw' : 'agg';
$votee = $this->votee();
$name = $this->wire()->sanitizer->pageName($poll->name) . "-$type-" . date('Ymd') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $name . '"');
$fh = fopen('php://output', 'w');
fwrite($fh, "\xEF\xBB\xBF"); // BOM for Excel
if ($type === 'agg') {
$r = $votee->getResults($poll);
fputcsv($fh, ['option_id', 'answer', 'votes', 'percent_of_participants'], ';');
foreach ($r['options'] as $o) fputcsv($fh, [$o['id'], $o['label'], $o['count'], $o['percent']], ';');
fputcsv($fh, ['', 'participants', $r['participants'], ''], ';');
} else {
$labels = [0 => $votee->otherLabel($poll)];
foreach ($votee->getOptions($poll) as $o) $labels[$o['id']] = $o['label'];
$q = $this->wire()->database->prepare('SELECT submission, created, page_id, option_id, other_text FROM '
. Votee::TABLE_VOTES . ' WHERE poll_id=:p ORDER BY created, submission');
$q->execute([':p' => $poll->id]);
fputcsv($fh, ['submission', 'created', 'page', 'option_id', 'answer', 'other_text'], ';');
$paths = [];
while ($row = $q->fetch(\PDO::FETCH_ASSOC)) {
$pid = (int) $row['page_id'];
$paths[$pid] ??= $this->wire()->pages->get($pid)->path ?: "#$pid";
fputcsv($fh, [
$row['submission'], $row['created'], $paths[$pid], $row['option_id'],
$labels[(int) $row['option_id']] ?? '(deleted option)', (string) $row['other_text'],
], ';');
}
}
fclose($fh);
exit;
}
}