Repository navigation
Expand file tree
/
Copy pathEmbargo.module.php
More file actions
496 lines (429 loc) · 16.6 KB
/
Copy pathEmbargo.module.php
File metadata and controls
496 lines (429 loc) · 16.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
<?php
namespace ProcessWire;
/**
* Embargo — keeps pages that carry an `embargo_date` unpublished until that date
* and releases them automatically once it has been reached.
*
* Guard: every save (normal saves and field-only saves) of a page whose template
* has the field is checked. A page with a future date is switched to unpublished
* instead of blocking the save, so the state is always unambiguous. A lazy cron
* job releases pages whose date has been reached.
*
* @property int $enabled Master switch (default on)
* @property string $interval LazyCron interval hook name (default everyHour)
* @property int $clearProCache Clear the full ProCache after a release (default off)
*/
class Embargo extends WireData implements Module, ConfigurableModule, CliModule
{
const FIELD = 'embargo_date';
/** LazyCron interval hooks; must match LazyCron::timeFuncs. */
const INTERVALS = [
'everyMinute',
'every2Minutes',
'every3Minutes',
'every4Minutes',
'every5Minutes',
'every10Minutes',
'every15Minutes',
'every30Minutes',
'every45Minutes',
'everyHour',
'every2Hours',
'every4Hours',
'every6Hours',
'every12Hours',
'everyDay',
'every2Days',
'every4Days',
'everyWeek',
'every2Weeks',
'every4Weeks',
];
const MAX_PER_RUN = 100;
const MAX_RUN_SECONDS = 20;
/** @var bool Skip all guard checks (migrations, imports, emergencies). */
protected $bypass = false;
/** @var array<int,bool> Page IDs whose field-only save needs a status fix. */
protected $pendingFieldSave = [];
public static function getModuleInfo()
{
return [
'title' => 'Embargo',
'version' => '0.1.0',
'summary' => 'Blocks publishing of pages until their embargo_date and releases them automatically.',
'author' => 'webmanufaktur',
'icon' => 'calendar',
'autoload' => true,
'singular' => true,
'requires' => 'ProcessWire>=3.0.260, LazyCron',
'cli' => 'embargo',
];
}
public function __construct()
{
parent::__construct();
$this->setArray(self::defaults());
}
public static function defaults(): array
{
return [
'enabled' => 1,
'interval' => 'everyHour',
'clearProCache' => 0,
];
}
public function init()
{
if (!$this->enabled) {
return;
}
$interval = in_array($this->interval, self::INTERVALS, true) ? $this->interval : 'everyHour';
$this->addHookAfter('LazyCron::' . $interval, $this, 'hookCron');
}
public function ready()
{
if (!$this->enabled) {
return;
}
$this->addHookBefore('Pages::saveReady', $this, 'guardSaveReady');
$this->addHookBefore('Pages::saveFieldReady', $this, 'guardSaveFieldReady');
$this->addHookAfter('Pages::savedField', $this, 'guardSavedField');
$this->addHookAfter('ProcessPageEdit::buildForm', $this, 'hookPageEditForm');
}
/* ------------------------------------------------------------------ Public API */
/** Enable/disable the guard for the current request (migrations, imports). */
public function setBypass(bool $bypass = true): void
{
$this->bypass = $bypass;
}
public function isBypassed(): bool
{
return $this->bypass;
}
/** Release all pages whose embargo date has been reached. Returns the count. */
public function runCron(): int
{
if (!$this->enabled) {
return 0;
}
$pages = $this->wire('pages');
$until = strtotime('today') + 86399;
$selector = self::FIELD . '>0, ' . self::FIELD . '<=' . $until
. ', include=all, status=' . Page::statusUnpublished . ', status!=hidden'
. ', limit=' . self::MAX_PER_RUN;
$released = 0;
$failed = 0;
$started = microtime(true);
foreach ($pages->find($selector) as $page) {
if (microtime(true) - $started > self::MAX_RUN_SECONDS) {
$this->logLine('cron time budget reached, remaining pages deferred to the next run');
break;
}
// Hidden pages stay as they are (deliberately not released), trash is ignored.
if ($page->hasStatus(Page::statusHidden) || $page->hasStatus(Page::statusTrash)) {
continue;
}
// Drafts (ProDrafts) remain out of scope; the page itself is not the draft.
if ($page->hasStatus(Page::statusDraft)) {
continue;
}
try {
$page->of(false);
$page->removeStatus(Page::statusUnpublished);
$pages->save($page);
$released++;
$this->logLine(sprintf(
'released page %d %s (embargo_date %s)',
$page->id,
$page->path,
date('Y-m-d', (int) $page->getUnformatted(self::FIELD))
));
} catch (\Throwable $e) {
$failed++;
$this->logLine(sprintf('release failed for page %d: %s', $page->id, $e->getMessage()));
}
}
if ($released && $this->clearProCache) {
$this->clearProCache();
}
if ($released || $failed) {
$this->logLine(sprintf('cron run: released %d page(s), %d failure(s)', $released, $failed));
}
$this->wire('cache')->save('Embargo.lastRun', time(), WireCache::expireNever);
return $released;
}
/* ------------------------------------------------------------------ Guard */
public function guardSaveReady(HookEvent $event): void
{
if ($this->bypass) {
return;
}
$page = $event->arguments(0);
if ($page instanceof Page) {
$this->enforce($page);
}
}
public function guardSaveFieldReady(HookEvent $event): void
{
if ($this->bypass) {
return;
}
$page = $event->arguments(0);
if (!$page instanceof Page || !$this->isEmbargoed($page)) {
return;
}
// The status cannot be persisted by saveField(), so remember the page and
// correct it right after the field has been saved.
$this->pendingFieldSave[$page->id] = true;
}
public function guardSavedField(HookEvent $event): void
{
$page = $event->arguments(0);
if (!$page instanceof Page || !isset($this->pendingFieldSave[$page->id])) {
return;
}
unset($this->pendingFieldSave[$page->id]);
if (!$this->enforce($page)) {
return;
}
try {
$this->wire('pages')->save($page);
} catch (\Throwable $e) {
$this->logLine(sprintf('status fix after saveField failed for page %d: %s', $page->id, $e->getMessage()));
}
}
/**
* Should this page be locked? Checks field, date and status.
*/
protected function isEmbargoed(Page $page): bool
{
if (!$page->id) {
return false;
}
$template = $page->template;
if (!$template || !$template->hasField(self::FIELD)) {
return false;
}
if ($page->hasStatus(Page::statusTrash) || $page->hasStatus(Page::statusDeleted)) {
return false;
}
if ($page->hasStatus(Page::statusDraft)) {
return false;
}
// Never trust the formatted value: FieldtypeDatetime returns a string there.
$ts = (int) $page->getUnformatted(self::FIELD);
if ($ts <= 0) {
return false;
}
if ($ts <= strtotime('today')) {
return false;
}
if ($page->hasStatus(Page::statusUnpublished)) {
return false;
}
return true;
}
/** Locks the page if needed. Returns true when the status was changed. */
protected function enforce(Page $page): bool
{
if (!$this->isEmbargoed($page)) {
return false;
}
$ts = (int) $page->getUnformatted(self::FIELD);
$page->addStatus(Page::statusUnpublished);
$this->notifyLocked($page, $ts);
return true;
}
protected function notifyLocked(Page $page, int $ts): void
{
$this->logLine(sprintf(
'locked page %d %s until %s',
$page->id,
$page->path,
date('Y-m-d', $ts)
));
$process = $this->wire('process');
if ($process instanceof \ProcessWire\ProcessPageEdit && $this->wire('user')->isLoggedin()) {
// ProcessPageEdit redirects after save, so a normal notice would be lost.
$this->wire('session')->warning(sprintf(
$this->_('Embargo: saved, but the page stays unpublished until %s.'),
date('d.m.Y', $ts)
));
}
}
/** Inline hint in the page edit form, directly below the date field. */
public function hookPageEditForm(HookEvent $event): void
{
$page = $event->object->getPage();
if (!$page instanceof Page || !$page->template || !$page->template->hasField(self::FIELD)) {
return;
}
$form = $event->return;
$anchor = $form->getChildByName(self::FIELD);
if (!$anchor) {
return;
}
$ts = (int) $page->getUnformatted(self::FIELD);
if ($ts <= 0) {
return;
}
if ($ts > strtotime('today')) {
$text = sprintf(
$this->_('🔒 Embargo active: the page stays unpublished until %s. Automatic release on %s.'),
date('d.m.Y', strtotime('-1 day', $ts)),
date('d.m.Y', $ts)
);
} else {
$text = sprintf(
$this->_('✔ Embargo expired since %s — publishing is allowed (the cron may have released it already).'),
date('d.m.Y', $ts)
);
}
/** @var InputfieldMarkup $markup */
$markup = $this->wire('modules')->get('InputfieldMarkup');
$markup->name = 'embargo_hint';
$markup->label = $this->_('Embargo');
$markup->icon = 'lock';
$markup->value = '<p class="detail">' . $this->wire('sanitizer')->entities($text) . '</p>';
$markup->collapsed = Inputfield::collapsedNo;
$parent = $anchor->getParent();
if ($parent) {
$parent->insertAfter($markup, $anchor);
} else {
$form->insertAfter($markup, $anchor);
}
}
/* ------------------------------------------------------------------ LazyCron / CLI */
public function hookCron(HookEvent $event): void
{
$this->runCron();
}
public function executeCli(array $args)
{
$released = $this->runCron();
echo sprintf($this->_('Embargo cron: released %d page(s).'), $released);
}
public function getCliCommands()
{
return [
'run' => 'Release all pages whose embargo date has been reached',
];
}
/* ------------------------------------------------------------------ Field / install */
public function ___install()
{
$this->ensureField();
$config = array_merge(self::defaults(), (array) $this->wire('modules')->getConfig($this));
$this->wire('modules')->saveConfig($this, $config);
$this->logLine('module installed (field ' . (wire('fields')->get(self::FIELD) ? 'present' : 'missing') . ')');
}
public function ___upgrade($fromVersion, $toVersion)
{
$this->ensureField();
}
protected function ensureField(): void
{
$fields = $this->wire('fields');
if ($fields->get(self::FIELD)) {
return;
}
$field = new Field();
$field->type = $this->wire('modules')->get('FieldtypeDatetime');
$field->name = self::FIELD;
$field->label = $this->_('Embargo date');
$field->description = $this->_('The page cannot be published before this date. It is released automatically on that day.');
$field->set('dateInputFormat', 'Y-m-d');
$field->set('dateOutputFormat', 'd.m.Y');
$field->set('timeInputFormat', '');
$field->set('inputType', 'html');
$field->save();
}
/* ------------------------------------------------------------------ Settings */
public function getModuleConfigInputfields(array $data)
{
$modules = $this->wire('modules');
$wrapper = $this->wire(new InputfieldWrapper());
$data = array_merge(self::defaults(), $data);
/** @var InputfieldCheckbox $field */
$field = $modules->get('InputfieldCheckbox');
$field->name = 'enabled';
$field->label = $this->_('Enabled');
$field->checked = !empty($data['enabled']);
$field->description = $this->_('Main switch: disables the guard and the cron job.');
$wrapper->append($field);
/** @var InputfieldSelect $field */
$field = $modules->get('InputfieldSelect');
$field->name = 'interval';
$field->label = $this->_('Cron interval');
$field->description = $this->_('How often LazyCron should check for pages that are due. LazyCron only runs on web requests; use `php index.php embargo run` for a manual run.');
foreach (self::INTERVALS as $interval) {
$field->addOption($interval, $interval);
}
$field->value = in_array($data['interval'] ?? '', self::INTERVALS, true) ? $data['interval'] : 'everyHour';
$wrapper->append($field);
/** @var InputfieldCheckbox $field */
$field = $modules->get('InputfieldCheckbox');
$field->name = 'clearProCache';
$field->label = $this->_('Clear ProCache completely after a release');
$field->checked = !empty($data['clearProCache']);
$field->description = $this->_('Normally not needed: the page save triggers the regular ProCache hooks. Use as an emergency exit only.');
$wrapper->append($field);
$wrapper->append($this->statusInputfield());
return $wrapper;
}
protected function statusInputfield(): Inputfield
{
$sanitizer = $this->wire('sanitizer');
$fields = $this->wire('fields');
$lines = [];
$field = $fields->get(self::FIELD);
$lines[] = $field
? $this->_('Field present: yes') . ' (' . $sanitizer->entities($field->type->name) . ')'
: '<strong>' . $this->_('Field present: no') . '</strong>';
$templates = [];
foreach ($this->wire('templates') as $template) {
if ($template->flags & Template::flagSystem) {
continue;
}
if ($template->hasField(self::FIELD)) {
$templates[] = $template->name;
}
}
$lines[] = $templates
? $this->_('Attached to templates:') . ' ' . $sanitizer->entities(implode(', ', $templates))
: '<strong>' . $this->_('Attached to no template') . '</strong> — '
. $this->_('the guard has no effect until the field is added to a template.');
$lastRun = (int) $this->wire('cache')->get('Embargo.lastRun');
$lines[] = $lastRun
? $this->_('Last cron run:') . ' ' . date('d.m.Y H:i', $lastRun)
: $this->_('The cron has not run yet.');
$logFile = rtrim((string) $this->wire('config')->paths->logs, '/') . '/embargo.txt';
if (is_file($logFile)) {
$all = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
$tail = array_slice($all, -5);
if ($tail) {
$lines[] = $this->_('Last log lines:') . '<br><code>'
. implode('<br>', array_map([$sanitizer, 'entities'], $tail)) . '</code>';
}
}
/** @var InputfieldMarkup $markup */
$markup = $this->wire('modules')->get('InputfieldMarkup');
$markup->name = 'embargo_status';
$markup->label = $this->_('Status');
$markup->value = '<p>' . implode('</p><p>', $lines) . '</p>';
return $markup;
}
/* ------------------------------------------------------------------ Helpers */
protected function logLine(string $message): void
{
$this->wire('log')->save('embargo', $message);
}
protected function clearProCache(): void
{
$procache = $this->wire('modules')->get('ProCache');
if ($procache && is_callable([$procache, 'clearAll'])) {
$procache->clearAll();
$this->logLine('ProCache cleared');
}
}
}