-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFieldtypeRecurringDates.module
547 lines (477 loc) · 17.2 KB
/
FieldtypeRecurringDates.module
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
<?php namespace ProcessWire;
use RRule\RRule;
class FieldtypeRecurringDates extends FieldtypeMulti
{
const defaultLimit = 10;
const EXTRAS_TABLE_NAME_SUFFIX = '_extras';
const EXTRAS_TABLE_COLS = [
'pages_id',
'rrule',
'settings'
];
/**
* Construct the Fieldtype, make sure all dependencies are in place
*
*/
public function __construct()
{
$this->set('usePagination', true);
$this->set('useOrderByCols', false);
require_once(__DIR__ . '/RecurringDateSettings.php');
require_once(__DIR__ . '/RecurringDate.php');
require_once(__DIR__ . '/Occurrence.php');
require_once(__DIR__ . '/OccurrenceArray.php');
parent::__construct();
}
public function init(){
$this->addHook('/fieldtype-recurring-dates/get-dates/', $this, 'hookGetDates');
$this->addHookAfter('Fields::added', $this, 'hookAfterFieldAdded');
$this->addHookAfter('Fields::deleted', $this, 'hookAfterFieldDeleted');
}
public function ready()
{
$this->addHookBefore('Pages::deleted', $this, 'hookAfterPageDelete');
}
public function hookGetDates($event)
{
if (!$event->user->isLoggedin()) return false;
$input = $event->input;
$page = $input->get->int('id');
$field = $input->get->int('field_id');
$start = $input->get->int('start');
$limit = $input->get->int('limit');
if (!$page || !$field) return "{}";
$field_name = $event->fields->get($field)->name;
$page = $event->pages->get($page);
$value = $page->$field_name("start=$start, limit=$limit, sort=data");
return $value->occurrences;
}
/**
* Adds the rrule settings table
*
* @return void
*
*/
public function hookAfterFieldAdded($event)
{
$item = $event->arguments(0);
if ($item->type->name == $this->name) {
$table_name = $this->getExtrasTableName($item);
$create_rrules_table = "";
$create_rrules_table .=
"DROP TABLE IF EXISTS $table_name;" .
"CREATE TABLE $table_name (" .
"pages_id INT UNSIGNED NOT NULL, " .
"rrule MEDIUMTEXT NOT NULL," .
"settings MEDIUMTEXT NOT NULL," .
"PRIMARY KEY (`pages_id`)," .
"UNIQUE KEY (`pages_id`)" .
")";
try {
$query = $this->database->prepare($create_rrules_table);
$query->execute();
} catch (\Exception $e) {
$this->database->error($e->getMessage());
}
}
}
/**
* Deletes the settings row for the database
*
* @param HookEvent $event
* @return void
*
*/
public function hookAfterPageDelete($event)
{
$page = $event->arguments(0);
$recurring_fields = $page->getFields()->find("type={$this->name}");
foreach ($recurring_fields as $f) {
$this->deleteSettings($page, $f);
}
}
/**
* Deletes the table where settings for the inputfield are saved
*
* @return void
*
*/
public function hookAfterFieldDeleted($event)
{
$item = $event->arguments(0);
if ($item->type->name == $this->name) {
$table_name = $this->getExtrasTableName($item);
$delete_rrules_table = "";
$delete_rrules_table .= "DROP TABLE IF EXISTS $table_name";
try {
$query = $this->database->prepare($delete_rrules_table);
$query->execute();
} catch (\Exception $e) {
$this->database->error($e->getMessage());
}
}
}
public function getRruleOcurrences($value)
{
$rrule = new RRule($value);
return $rrule;
}
/**
* Return the database schema that defines an Occurrence
*
* @param Field $field
* @return array
*
*/
public function getDatabaseSchema(Field $field)
{
$schema = parent::getDatabaseSchema($field);
$schema['id'] = 'INT UNSIGNED NOT NULL AUTO_INCREMENT';
$schema['data'] = 'datetime NOT NULL';
$schema['keys']['primary'] = 'PRIMARY KEY (id)';
$schema['keys']['pages_id_sort_data'] = 'UNIQUE (pages_id, sort, data)';
$schema['keys']['data'] = 'KEY data (data)';
return $schema;
}
/**
* Return the Inputfield used to collect input for a field of this type
*
* @param Page $page
* @param Field $field
* @return Inputfield|InputfieldRecurringDates
*
*/
public function getInputfield(Page $page, Field $field)
{
$inputfield = $this->modules->get('InputfieldRecurringDates');
/** @var InputfieldRecurringDates $inputfield */
return $inputfield;
}
/**
* Return a blank ready-to-populate value
*
* @param Page $page
* @param Field $field
* @return RecurringDate
*
*/
public function getBlankValue(Page $page, Field $field)
{
return new RecurringDate();
}
/**
* Given a value, make it clean and of the correct type for storage within a Page
*
* @param Page $page
* @param Field $field
* @param EventArray $value
* @return mixed
*
*/
public function sanitizeValue(Page $page, Field $field, $value)
{
// if given an invalid value, return a valid blank value
return $value;
}
protected function isSettingsValue($value)
{
$count = 0;
$keys = self::EXTRAS_TABLE_COLS;
foreach ($keys as $key) {
if (isset($value[$key]) || array_key_exists($key, $value)) {
$count++;
}
}
if ($count == 3) {
return true;
} else {
return false;
}
//if(array_key_exists(''))
}
public function ___wakeupValue(Page $page, Field $field, $value)
{
$recurring_date = $this->getBlankValue($page, $field);
$recurring_date->settings = json_encode($recurring_date->settings, true);
if (empty($value) || !is_array($value)) return $recurring_date;
if ($this->isSettingsValue($value)) {
$recurring_date->settings = $value['settings'];
$rrule_value = json_decode($value['rrule'], true);
$rrule = new RRule($rrule_value);
$recurring_date->rrule = $rrule;
} else {
$settings = $this->getSettings($page, $field);
if ($settings) {
$recurring_date->settings = $settings->settings;
$rrule_value = json_decode($settings->rrule, true);
$rrule = new RRule($rrule_value);
$recurring_date->rrule = $rrule;
}
if (isset($value['_pagination_limit'])) {
$recurring_date->occurrences->setLimit($value['_pagination_limit']);
$recurring_date->occurrences->setStart($value['_pagination_start']);
$recurring_date->occurrences->setTotal($value['_pagination_total']);
}
unset($value['_pagination_limit'], $value['_pagination_start'], $value['_pagination_total']);
if (isset($value['_filters']) && $value['_filters'] instanceof Selectors) {
$recurring_date->occurrences->data('filters', $value['_filters']);
unset($value['_filters']);
}
foreach ($value as $key => $v) {
$occurrence = new Occurrence();
$occurrence->date = (new \DateTime($v['data']));
// $occurrence->excluded = $v['excluded'] ? true : false;
$occurrence->resetTrackChanges();
$recurring_date->occurrences->add($occurrence);
}
}
// tell it to start tracking changes from this point forward
$recurring_date->resetTrackChanges();
return $recurring_date;
}
/**
*
* @param Page $page
* @param Field $field
* @param array $value
* @return array
*
*/
public function ___sleepValue(Page $page, Field $field, $value)
{
$sleepValue = array();
if ($value->rrule) {
if ($value->occurrences->count() == 0) {
$this->saveSettings($page, $field, $value);
foreach ($value->rrule as $date) {
$occurrence_date = new Occurrence();
// TODO
// $occurrence_date->excluded = false;
$occurrence_date->date = $date;
$value->occurrences->add($occurrence_date);
}
}
$this->saveSettings($page, $field, $value);
}
if (!$value instanceof RecurringDate) return $sleepValue;
foreach ($value->occurrences as $occurrence) {
$sleepValue[] = array(
'data' => (string) $occurrence, // note: 'date' is becoming 'data' (with an 'a')
// 'excluded' => $occurrence->excluded
);
}
return $sleepValue;
}
/**
* Render a markup string of the value (optional for Fieldtypes to implement)
*
* @param Page $page
* @param Field $field
* @param EventArray $value
* @param string $property Property to render or omit for all
* @return string|MarkupFieldtype
*
*/
public function ___markupValue(Page $page, Field $field, $value = null, $property = '')
{
return $value;
}
public function getMonths()
{
$months = [];
for ($m = 1; $m <= 12; $m++) {
$months[] = date('F', mktime(0, 0, 0, $m, 1, date('Y')));
}
return $months;
}
public function getLoadQuery(Field $field, DatabaseQuerySelect $query)
{
if ($this->wire()->process instanceof WirePageEditor) {
$query = parent::getLoadQuery($field, $query);
$query->set('select', []);
foreach (self::EXTRAS_TABLE_COLS as $col) {
$selects[] = "{$this->getExtrasTableName($field)}.{$col} AS `{$field->name}__{$col}`";
}
$query->remove('orderby');
foreach ($selects as $s) {
$query->select($s);
}
return $query;
} else {
return parent::getLoadQuery($field, $query);
}
}
public function ___loadPageField(Page $page, Field $field)
{
if (!$page->id || !$field->id) return null;
if ($this->wire()->process instanceof WirePageEditor) {
/* Copied from Fieldtype.php */
$database = $this->wire()->database;
$schema = $this->getDatabaseSchema($field);
$table = $this->getExtrasTableName($field);
$stmt = null;
/** @var DatabaseQuerySelect $query */
$query = $this->wire(new DatabaseQuerySelect());
$query = $this->getLoadQuery($field, $query);
$bindKey = $query->bindValueGetKey($page->id);
$query->where("$table.pages_id=$bindKey");
$query->from($table);
try {
$stmt = $query->prepare();
$result = $database->execute($stmt);
} catch (\Exception $e) {
$result = false;
$this->trackException($e, false, true);
}
if (!$result) return null;
$fieldName = $database->escapeCol($field->name);
$columns = $database->getColumns($this->getExtrasTableName($field));
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
if (!$row) return null;
$value = array();
foreach ($columns as $k) {
$key = $fieldName . '__' . $k;
$value[$k] = $row[$key];
}
// if there is just one 'data' field here, then just make 'data' the value
if (count($value) == 1 && isset($value['data'])) $value = $value['data'];
return $value;
} else {
return parent::___loadPageField($page, $field);
}
}
/**
* Saves rrule string when field is saved.
*
* @param Page $page
* @param Field $field
* @param RecurringDate $rule
* @return void
*/
protected function saveSettings(Page $page, Field $field, RecurringDate $rdate)
{
$sql = "INSERT INTO {$this->getExtrasTableName($field)} (pages_id, rrule, settings) VALUES(:pages_id, :rrule, :settings) ON DUPLICATE KEY UPDATE pages_id=:pages_id, rrule=:rrule, settings=:settings";
/** @var \PDOStatement $pdo */
$pdo = $this->database->prepare($sql);
$pdo->bindValue(':pages_id', $page->id);
$rrule_array = $rdate->rrule->getRule();
$rrule_array['DTSTART'] = (new \DateTime($rrule_array['DTSTART']))->format('Y-m-d H:i:s');
$pdo->bindValue(':rrule', json_encode($rrule_array));
$pdo->bindValue(':settings', (string)$rdate->settings);
$pdo->execute();
}
/**
* Deletes rrule JSON string when the page containing the field is deleted.
*
* @param Page $page
* @param Field $field
* @return void
*/
protected function deleteSettings(Page $page, Field $field)
{
$sql = "DELETE FROM {$this->getExtrasTableName($field)} WHERE pages_id = :id";
/** @var \PDOStatement $pdo */
$pdo = $this->database->prepare($sql);
$pdo->bindValue(':id', $page->id);
$pdo->execute();
}
/**
* @param Page $page
* @param Field $field
* @return string
*/
protected function getSettings(Page $page, Field $field)
{
$sql = "SELECT rrule, settings FROM {$this->getExtrasTableName($field)} WHERE pages_id=:pages_id";
$pdo = $this->database->prepare($sql);
$pdo->bindValue(':pages_id', $page->id);
$pdo->execute();
return $pdo->fetch(\PDO::FETCH_OBJ);
}
public function getExtrasTableName(Field $field)
{
return $field->getTable() . self::EXTRAS_TABLE_NAME_SUFFIX;
}
/**
* Sanitize a value assumed to be either a timestamp or in strtotime() compatible format
*
* @param string|int|\DateTime
* @return int|string Returns unix timestamp integer or blank string if empty or invalid value
*
*/
protected function _sanitizeValue($value) {
if(empty($value)) {
// empty value
$value = '';
} else if(is_int($value)) {
// value okay as-is
} else if($value instanceof \DateTime) {
// instance of DateTime
$value = $value->getTimestamp();
} else if(ctype_digit(ltrim("$value", '-'))) {
// already a timestamp
$value = (int) $value;
} else {
// convert date string to time
$value = strtotime($value);
if($value === false) $value = '';
}
return $value;
}
/*
* TODO Implement properly.
* Known issue is blank value on selector throws an error. Normal date
* fields don't do this, so predictable behaviour like existing fields is desired
*/
public function isEmptyValue(Field $field, $value) {
return true;
}
public function getMatchQuery($query, $table, $subfield, $operator, $value) {
if($subfield === 'count') {
return parent::getMatchQuery($query, $table, $subfield, $operator ,$value);
}
// limit to operators: =, !=, >, >=, <, <= (exclude things like %=, *=, etc.)
if(!$this->wire()->database->isOperator($operator)) {
throw new WireException('You can only use DB-native operators here');
}
if(empty($value)) {
// empty value, which we'll let FieldtypeMulti handle
if(in_array($operator, [ '=', '<', '<=' ])) {
// match non-presence of rows
return parent::getMatchQuery($query, $table, 'count', '=', 0);
} else {
// match presence of rows
return parent::getMatchQuery($query, $table, 'count', '>', 0);
}
}
// convert value to ISO-8601 and create the WHERE condition
if(!ctype_digit("$value")) $value = strtotime($value);
$value = date('Y-m-d H:i:s', (int) $value);
$query->where("$table.data{$operator}?", $value);
return $query;
}
/**
* Get selector info
*
* @param Field $field
* @param array $data
* @return array
*
*/
public function ___getSelectorInfo(Field $field, array $data = array()) {
$a = parent::___getSelectorInfo($field, $data);
$a['operators'] = array('=', '!=', '>', '>=', '<', '<=', '%=', '^=', '=""', '!=""');
return $a;
}
public function ___upgrade($fromVersion, $toVersion){
if($fromVersion == "0.0.1-alpha4" && $toVersion == "0.0.1"){
foreach($this->fields->find("type={$this->name}") as $field){
$table = $field->getTable();
$update_schema = "ALTER TABLE `{$table}`ADD UNIQUE `pages_id_sort_data` (`pages_id`, `sort`, `data`), DROP INDEX `pages_id`";
$pdo = $this->database->prepare($update_schema);
$pdo->execute();
}
}
}
}