/
class.forms.php
6143 lines (5302 loc) · 193 KB
/
class.forms.php
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*********************************************************************
class.forms.php
osTicket forms framework
Jared Hancock <jared@osticket.com>
Copyright (c) 2006-2013 osTicket
http://www.osticket.com
Released under the GNU General Public License WITHOUT ANY WARRANTY.
See LICENSE.TXT for details.
vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/
/**
* Form template, used for designing the custom form and for entering custom
* data for a ticket
*/
class Form {
static $renderer = 'GridFluidLayout';
static $id = 0;
var $options = array();
var $fields = array();
var $title = '';
var $instructions = '';
var $validators = array();
var $_errors = null;
var $_source = false;
function __construct($source=null, $options=array()) {
$this->options = $options;
if (isset($options['title']))
$this->title = $options['title'];
if (isset($options['instructions']))
$this->instructions = $options['instructions'];
if (isset($options['id']))
$this->id = $options['id'];
// Use POST data if source was not specified
$this->_source = $source ?: $_POST;
}
function getFormId() {
return @$this->id ?: static::$id;
}
function setId($id) {
$this->id = $id;
}
function data($source) {
foreach ($this->fields as $name=>$f)
if (isset($source[$name]))
$f->value = $source[$name];
}
function setFields($fields) {
if (!is_array($fields) && !$fields instanceof Traversable)
return;
$this->fields = $fields;
foreach ($fields as $k=>$f) {
$f->setForm($this);
if (!$f->get('name') && $k && !is_numeric($k))
$f->set('name', $k);
}
}
function getFields() {
return $this->fields;
}
function getField($name) {
$fields = $this->getFields();
foreach($fields as $f)
if(!strcasecmp($f->get('name'), $name))
return $f;
if (isset($fields[$name]))
return $fields[$name];
}
function hasField($name) {
return $this->getField($name);
}
function hasAnyEnabledFields() {
return $this->hasAnyVisibleFields(false);
}
function hasAnyVisibleFields($user=false) {
$visible = 0;
$isstaff = $user instanceof Staff;
foreach ($this->getFields() as $F) {
if (!$user) {
// Assume hasAnyEnabledFields
if ($F->isEnabled())
$visible++;
} elseif($isstaff) {
if ($F->isVisibleToStaff())
$visible++;
} elseif ($F->isVisibleToUsers()) {
$visible++;
}
}
return $visible > 0;
}
function getTitle() { return $this->title; }
function getInstructions() { return Format::htmldecode($this->instructions); }
function getSource() { return $this->_source; }
function setSource($source) { $this->_source = $source; }
/**
* Validate the form and indicate if there no errors.
*
* Parameters:
* $filter - (callback) function to receive each field and return
* boolean true if the field's errors are significant
*/
function isValid($include=false) {
if (!isset($this->_errors)) {
$this->_errors = array();
$this->validate($this->getClean());
foreach ($this->getFields() as $field)
if ($field->errors() && (!$include || $include($field)))
$this->_errors[$field->get('id')] = $field->errors();
}
return !$this->_errors;
}
function validate($clean_data) {
// Validate the whole form so that errors can be added to the
// individual fields and collected below.
foreach ($this->validators as $V) {
$V($this);
}
}
function getClean($validate=true) {
if (!$this->_clean) {
$this->_clean = array();
foreach ($this->getFields() as $key=>$field) {
if (!$field->hasData())
continue;
// Prefer indexing by field.id if indexing numerically
if (is_int($key) && $field->get('id'))
$key = $field->get('id');
$this->_clean[$key] = $this->_clean[$field->get('name')]
= $field->getClean($validate);
}
unset($this->_clean[""]);
}
return $this->_clean;
}
/*
* Process the form input and return clean data.
*
* It's similar to getClean but forms downstream can use it to return
* database ready data.
*/
function process($validate=true) {
return $this->getClean($validate);
}
function errors($formOnly=false) {
return ($formOnly) ? $this->_errors['form'] : $this->_errors;
}
function addError($message, $index=false) {
if ($index)
$this->_errors[$index] = $message;
else
$this->_errors['form'][] = $message;
}
function addErrors($errors=array()) {
foreach ($errors as $k => $v) {
if (($f=$this->getField($k)))
$f->addError($v);
else
$this->addError($v, $k);
}
}
function addValidator($function) {
if (!is_callable($function))
throw new Exception('Form validator must be callable');
$this->validators[] = $function;
}
function render($options=array()) {
if (isset($options['title']))
$this->title = $options['title'];
if (isset($options['instructions']))
$this->instructions = $options['instructions'];
$form = $this;
$template = $options['template'] ?: 'dynamic-form.tmpl.php';
if (isset($options['staff']) && $options['staff'])
include(STAFFINC_DIR . 'templates/' . $template);
else
include(CLIENTINC_DIR . 'templates/' . $template);
echo $this->getMedia();
}
function getLayout($title=false, $options=array()) {
$rc = @$options['renderer'] ?: static::$renderer;
return new $rc($title, $options);
}
function asTable($title=false, $options=array()) {
return $this->getLayout($title, $options)->asTable($this);
// XXX: Media can't go in a table
echo $this->getMedia();
}
function getMedia() {
static $dedup = array();
foreach ($this->getFields() as $f) {
if (($M = $f->getMedia()) && is_array($M)) {
foreach ($M as $type=>$files) {
foreach ($files as $url) {
$key = strtolower($type.$url);
if (isset($dedup[$key]))
continue;
self::emitMedia($url, $type);
$dedup[$key] = true;
}
}
}
}
}
function emitJavascript($options=array()) {
// Check if we need to emit javascript
if (!($fid=$this->getFormId()))
return;
?>
<script type="text/javascript">
$(function() {
<?php
//XXX: We ONLY want to watch field on this form. We'll only
// watch form inputs if form_id is specified. Current FORM API
// doesn't generate the entire form (just fields)
if ($fid) {
?>
$(document).off('change.<?php echo $fid; ?>');
$(document).on('change.<?php echo $fid; ?>',
'form#<?php echo $fid; ?> :input',
function() {
//Clear any current errors...
var errors = $('#field'+$(this).attr('id')+'_error');
if (errors.length)
errors.slideUp('fast', function (){
$(this).remove();
});
//TODO: Validation input inplace or via ajax call
// and set any new errors AND visibilty changes
}
);
<?php
}
?>
});
</script>
<?php
}
static function emitMedia($url, $type) {
if ($url[0] == '/')
$url = ROOT_PATH . substr($url, 1);
switch (strtolower($type)) {
case 'css': ?>
<link rel="stylesheet" type="text/css" href="<?php echo $url; ?>"/><?php
break;
case 'js': ?>
<script type="text/javascript" src="<?php echo $url; ?>"></script><?php
break;
}
}
/**
* getState
*
* Retrieves an array of information which can be passed to the
* ::loadState method later to recreate the current state of the form
* fields and values.
*/
function getState() {
$info = array();
foreach ($this->getFields() as $f) {
// Skip invisible fields
if (!$f->isVisible())
continue;
// Skip fields set to default values
$v = $f->getClean();
$d = $f->get('default');
if ($v == $d)
continue;
// Skip empty values
if (!$v)
continue;
$info[$f->get('name') ?: $f->get('id')] = $f->to_database($v);
}
return $info;
}
/**
* loadState
*
* Reset this form to the state previously recorded by the ::getState()
* method
*/
function loadState($state) {
foreach ($this->getFields() as $f) {
$name = $f->get('name');
$f->reset();
if (isset($state[$name])) {
$f->value = $f->to_php($state[$name]);
}
}
}
/*
* Initialize a generic static form
*/
static function instantiate() {
$r = new ReflectionClass(get_called_class());
return $r->newInstanceArgs(func_get_args());
}
}
/**
* SimpleForm
* Wrapper for inline/static forms.
*
*/
class SimpleForm extends Form {
function __construct($fields=array(), $source=null, $options=array()) {
parent::__construct($source, $options);
if (isset($options['type']))
$this->type = $options['type'];
$this->setFields($fields);
}
function getId() {
return $this->getFormId();
}
}
class CustomForm extends SimpleForm {
function getFields() {
global $thisstaff, $thisclient;
$options = $this->options;
$user = $options['user'] ?: $thisstaff ?: $thisclient;
$isedit = ($options['mode'] == 'edit');
$fields = array();
foreach (parent::getFields() as $field) {
if ($isedit && !$field->isEditable($user))
continue;
$fields[] = $field;
}
return $fields;
}
}
abstract class AbstractForm extends Form {
function __construct($source=null, $options=array()) {
parent::__construct($source, $options);
$this->setFields($this->buildFields());
}
/**
* Fetch the fields defined for this form. This method is only called
* once.
*/
abstract function buildFields();
}
/**
* Container class to represent the connection between the form fields and the
* rendered state of the form.
*/
interface FormRenderer {
// Render the form fields into a table
function asTable($form);
// Render the form fields into divs
function asBlock($form);
}
abstract class FormLayout {
static $default_cell_layout = 'Cell';
var $title;
var $options;
function __construct($title=false, $options=array()) {
$this->title = $title;
$this->options = $options;
}
function getLayout($field) {
$layout = $field->get('layout') ?: static::$default_cell_layout;
if (is_string($layout))
$layout = new $layout();
return $layout;
}
}
class GridFluidLayout
extends FormLayout
implements FormRenderer {
function asTable($form) {
ob_start();
?>
<table class="<?php echo 'grid form' ?>">
<caption><?php echo Format::htmlchars($this->title ?: $form->getTitle()); ?>
<div><small><?php echo Format::viewableImages($form->getInstructions()); ?></small></div>
</caption>
<tbody><tr><?php for ($i=0; $i<12; $i++) echo '<td style="width:8.3333%"/>'; ?></tr></tbody>
<?php
$row_size = 12;
$cols = $row = 0;
//Layout and rendering options
$options = $this->options;
foreach ($form->getFields() as $f) {
$layout = $this->getLayout($f);
$size = $layout->getWidth() ?: 12;
if ($offs = $layout->getOffset()) {
$size += $offs;
}
if ($cols < $size || $layout->isBreakForced()) {
if ($row) echo '</tr>';
echo '<tr>';
$cols = $row_size;
$row++;
}
// Render the cell
$cols -= $size;
$attrs = array('colspan' => $size, 'rowspan' => $layout->getHeight(),
'style' => '"'.$layout->getOption('style').'"');
if ($offs) { ?>
<td colspan="<?php echo $offs; ?>"></td> <?php
}
?>
<td class="cell" <?php echo Format::array_implode('=', ' ', array_filter($attrs)); ?>
data-field-id="<?php echo $f->get('id'); ?>">
<fieldset class="field <?php if (!$f->isVisible()) echo 'hidden'; ?>"
id="field<?php echo $f->getWidget()->id; ?>"
data-field-id="<?php echo $f->get('id'); ?>">
<?php $label = $f->get('label'); ?>
<label class="<?php if ($f->isRequired()) echo 'required'; ?>"
for="<?php echo $f->getWidget()->id; ?>">
<?php echo $label ? (Format::htmlchars($label).':') : ' '; ?>
<?php if ($f->isRequired()) { ?>
<span class="error">*</span>
</label>
<?php }
if ($f->get('hint')) { ?>
<div class="field-hint-text">
<?php echo Format::htmlchars($f->get('hint')); ?>
</div>
<?php }
$f->render($options);
if ($f->errors())
foreach ($f->errors() as $e)
echo sprintf('<div class="error">%s</div>', Format::htmlchars($e));
?>
</fieldset>
</td>
<?php
}
if ($row)
echo '</tr>';
echo '</tbody></table>';
return ob_get_clean();
}
function asBlock($form) {}
}
/**
* Basic container for field and form layouts. By default every cell takes
* a whole output row and does not imply any sort of width.
*/
class Cell {
function isBreakForced() { return true; }
function getWidth() { return false; }
function getHeight() { return 1; }
function getOffset() { return 0; }
function getOption($prop) { return false; }
}
/**
* Fluid grid layout, meaning each cell renders to the right of the previous
* cell (for left-to-right layouts). A width in columns can be specified for
* each cell along with an offset from the previous cell. A height of columns
* along with an optional break is supported.
*/
class GridFluidCell
extends Cell {
var $span;
var $options;
function __construct($span, $options=array()) {
$this->span = $span;
$this->options = $options + array(
'rows' => 1, # rowspan
'offset' => 0, # skip some columns
'break' => false, # start on a new row
);
}
function isBreakForced() { return $this->options['break']; }
function getWidth() { return $this->span; }
function getHeight() { return $this->options['rows']; }
function getOffset() { return $this->options['offset']; }
function getOption($prop) { return $this->options[$prop]; }
}
require_once(INCLUDE_DIR . "class.json.php");
class FormField {
static $widget = false;
var $ht = array(
'label' => false,
'required' => false,
'default' => false,
'configuration' => array(),
);
var $_form;
var $_cform;
var $_clean;
var $_errors = array();
var $_widget;
var $answer;
var $parent;
var $presentation_only = false;
static $types = array(
/* @trans */ 'Basic Fields' => array(
'text' => array( /* @trans */ 'Short Answer', 'TextboxField'),
'memo' => array( /* @trans */ 'Long Answer', 'TextareaField'),
'thread' => array( /* @trans */ 'Thread Entry', 'ThreadEntryField', false),
'datetime' => array(/* @trans */ 'Date and Time', 'DatetimeField'),
'timezone' => array(/* @trans */ 'Timezone', 'TimezoneField'),
'phone' => array( /* @trans */ 'Phone Number', 'PhoneField'),
'bool' => array( /* @trans */ 'Checkbox', 'BooleanField'),
'choices' => array( /* @trans */ 'Choices', 'ChoiceField'),
'files' => array( /* @trans */ 'File Upload', 'FileUploadField'),
'break' => array( /* @trans */ 'Section Break', 'SectionBreakField'),
'info' => array( /* @trans */ 'Information', 'FreeTextField'),
),
);
static $more_types = array();
static $uid = null;
static function _uid() {
return ++self::$uid;
}
function __construct($options=array()) {
$this->ht = array_merge($this->ht, $options);
if (!isset($this->ht['id']))
$this->ht['id'] = self::_uid();
}
function __clone() {
$this->_widget = null;
$this->ht['id'] = self::_uid();
}
static function addFieldTypes($group, $callable) {
static::$more_types[$group][] = $callable;
}
static function allTypes() {
if (static::$more_types) {
foreach (static::$more_types as $group => $entries)
foreach ($entries as $c)
static::$types[$group] = array_merge(
static::$types[$group] ?? array(), call_user_func($c));
static::$more_types = array();
}
return static::$types;
}
static function getFieldType($type) {
foreach (static::allTypes() as $group=>$types)
if (isset($types[$type]))
return $types[$type];
}
function get($what, $default=null) {
return array_key_exists($what, $this->ht)
? $this->ht[$what]
: $default;
}
function set($field, $value) {
$this->ht[$field] = $value;
}
function getId() {
return $this->ht['id'];
}
/**
* getClean
*
* Validates and cleans inputs from POST request. This is performed on a
* field instance, after a DynamicFormSet / DynamicFormSection is
* submitted via POST, in order to kick off parsing and validation of
* user-entered data.
*/
function getClean($validate=true) {
if (!isset($this->_clean)) {
$this->_clean = (isset($this->value))
// XXX: The widget value may be parsed already if this is
// linked to dynamic data via ::getAnswer()
? $this->value : $this->parse($this->getWidget()->value);
if ($vs = $this->get('cleaners')) {
if (is_array($vs)) {
foreach ($vs as $cleaner)
if (is_callable($cleaner))
$this->_clean = call_user_func_array(
$cleaner, array($this, $this->_clean));
}
elseif (is_callable($vs))
$this->_clean = call_user_func_array(
$vs, array($this, $this->_clean));
}
if (!isset($this->_clean) && ($d = $this->get('default')))
$this->_clean = $d;
if ($this->isVisible() && $validate)
$this->validateEntry($this->_clean);
}
return $this->_clean;
}
function reset() {
$this->value = $this->_clean = $this->_widget = null;
}
function getValue() {
return $this->getWidget()->getValue();
}
function errors() {
return $this->_errors;
}
function addError($message, $index=false) {
if ($index)
$this->_errors[$index] = $message;
else
$this->_errors[] = $message;
// Update parent form errors for the field
if ($this->_form)
$this->_form->addError($this->errors(), $this->get('id'));
}
function isValidEntry() {
$this->validateEntry();
return count($this->_errors) == 0;
}
/**
* validateEntry
*
* Validates user entry on an instance of the field on a dynamic form.
* This is called when an instance of this field (like a TextboxField)
* receives data from the user and that value should be validated.
*
* Parameters:
* $value - (string) input from the user
*/
function validateEntry($value) {
if (!$value && count($this->_errors))
return;
# Validates a user-input into an instance of this field on a dynamic
# form
if ($this->get('required') && !$value && $this->hasData())
$this->_errors[] = $this->getLocal('label')
? sprintf(__('%s is a required field'), $this->getLocal('label'))
: __('This is a required field');
# Perform declared validators for the field
if ($vs = $this->get('validators')) {
if (is_array($vs)) {
foreach ($vs as $validator)
if (is_callable($validator))
$validator($this, $value);
}
elseif (is_callable($vs))
$vs($this, $value);
}
}
/**
* isVisible
*
* If this field has visibility configuration, then it will parse the
* constraints with the visibility configuration to determine if the
* field is visible and should be considered for validation
*/
function isVisible() {
if ($this->get('visibility') instanceof VisibilityConstraint) {
return $this->get('visibility')->isVisible($this);
}
return true;
}
/**
* Check if the user has edit rights
*
*/
function isEditable($user=null) {
// Internal editable flag used by internal forms e.g internal lists
if (!$user && isset($this->ht['editable']))
return $this->ht['editable'];
if ($user instanceof Staff)
$flag = DynamicFormField::FLAG_AGENT_EDIT;
else
$flag = DynamicFormField::FLAG_CLIENT_EDIT;
return (($this->get('flags') & $flag) != 0);
}
/**
* isStorable
*
* Indicate if this field data is storable locally (default).Some field's data
* might beed to be stored elsewhere for optimization reasons at the
* application level.
*
*/
function isStorable() {
return (($this->get('flags') & DynamicFormField::FLAG_EXT_STORED) == 0);
}
function isRequired() {
return $this->get('required');
}
/**
* parse
*
* Used to transform user-submitted data to a PHP value. This value is
* not yet considered valid. The ::validateEntry() method will be called
* on the value to determine if the entry is valid. Therefore, if the
* data is clearly invalid, return something like NULL that can easily
* be deemed invalid in ::validateEntry(), however, can still produce a
* useful error message indicating what is wrong with the input.
*/
function parse($value) {
return is_string($value) ? trim($value) : $value;
}
/**
* to_php
*
* Transforms the data from the value stored in the database to a PHP
* value. The ::to_database() method is used to produce the database
* valse, so this method is the compliment to ::to_database().
*
* Parameters:
* $value - (string or null) database representation of the field's
* content
*/
function to_php($value) {
return $value;
}
/**
* to_config
*
* Transform the data from the value to config form (as determined by
* field). to_php is used for each field returned from
* ::getConfigurationOptions(), and when the whole configuration is
* built, to_config() is called and receives the config array. The array
* should be returned, perhaps with modifications, and will be JSON
* encoded and stashed in the database.
*/
function to_config($value) {
return $value;
}
/**
* to_database
*
* Determines the value to be stored in the database. The database
* backend for all fields is a text field, so this method should return
* a text value or NULL to represent the value of the field. The
* ::to_php() method will convert this value back to PHP.
*
* Paremeters:
* $value - PHP value of the field's content
*/
function to_database($value) {
return $value;
}
/**
* toString
*
* Converts the PHP value created in ::parse() or ::to_php() to a
* pretty-printed value to show to the user. This is especially useful
* for something like dates which are stored considerably different in
* the database from their respective human-friendly versions.
* Furthermore, this method allows for internationalization and
* localization.
*
* Parametes:
* $value - PHP value of the field's content
*/
function toString($value) {
return (string) $value;
}
function __toString() {
return $this->toString($this->value);
}
/**
* When data for this field is deleted permanently from some storage
* backend (like a database), other associated data may need to be
* cleaned as well. This hook allows fields to participate when the data
* for a field is cleaned up.
*/
function db_cleanup($field=false) {
}
/**
* Returns an HTML friendly value for the data in the field.
*/
function display($value) {
return Format::htmlchars($this->toString($value ?: $this->value));
}
/**
* Returns a value suitable for exporting to a foreign system. Mostly
* useful for things like dates and phone numbers which should be
* formatted using a standard when exported
*/
function export($value) {
return $this->toString($value);
}
/**
* Fetch a value suitable for embedding the value of this field in an
* email template. Reference implementation uses ::to_php();
*/
function asVar($value, $id=false) {
return $this->to_php($value, $id);
}
/**
* Fetch the var type used with the email templating system's typeahead
* feature. This helps with variable expansion if supported by this
* field's ::asVar() method. This method should return a valid classname
* which implements the `TemplateVariable` interface.
*/
function asVarType() {
return false;
}
/**
* Describe the difference between the to two values. Note that the
* values should be passed through ::parse() or to_php() before
* utilizing this method.
*/
function whatChanged($before, $after) {
if ($before)
$desc = __('changed from <strong>%1$s</strong> to <strong>%2$s</strong>');
else
$desc = __('set to <strong>%2$s</strong>');
return sprintf($desc, $this->display($before), $this->display($after));
}
/**
* Convert the field data to something matchable by filtering. The
* primary use of this is for ticket filtering.
*/
function getFilterData() {
return $this->toString($this->getClean());
}
/**
* Fetches a value that represents this content in a consistent,
* searchable format. This is used by the search engine system and
* backend.
*/
function searchable($value) {
return Format::searchable($this->toString($value));
}
function getKeys($value) {
return $this->to_database($value);
}
/**
* Fetches a list of options for searching. The values returned from
* this method are passed to the widget's `::render()` method so that
* the widget can be affected by this setting. For instance, date fields
* might have a 'between' search option which should trigger rendering
* of two date widgets for search results.
*/
function getSearchMethods() {
return array(
'set' => __('has a value'),
'nset' => __('does not have a value'),
'equal' => __('is'),
'nequal' => __('is not'),
'contains' => __('contains'),
'match' => __('matches'),
);
}
function getSearchMethodWidgets() {
return array(
'set' => null,
'nset' => null,
'equal' => array('TextboxField', array('configuration' => array('size' => 40))),
'nequal' => array('TextboxField', array('configuration' => array('size' => 40))),
'contains' => array('TextboxField', array('configuration' => array('size' => 40))),
'match' => array('TextboxField', array(
'placeholder' => __('Valid regular expression'),
'configuration' => array('size'=>30),
'validators' => function($self, $v) {
if (false === @preg_match($v, ' ')
&& false === @preg_match("/$v/", ' '))
$self->addError(__('Cannot compile this regular expression'));
})),
);
}
/**
* This is used by the searching system to build a query for the search
* engine. The function should return a criteria listing to match
* content saved by the field by the `::to_database()` function.
*/
function getSearchQ($method, $value, $name=false) {
$criteria = array();
$Q = new Q();
$name = $name ?: $this->get('name');
switch ($method) {
case 'nset':
$Q->negate();
case 'set':
$criteria[$name . '__isnull'] = false;
break;
case 'nequal':
$Q->negate();
case 'equal':
$criteria[$name] = $value;
break;
case 'contains':
$criteria[$name . '__contains'] = $value;
break;
case 'match':
$criteria[$name . '__regex'] = $value;
break;