1: <?php
2: /**
3: * DataTables PHP libraries.
4: *
5: * PHP libraries for DataTables and DataTables Editor, utilising PHP 5.3+.
6: *
7: * @author SpryMedia
8: * @copyright 2012 SpryMedia ( http://sprymedia.co.uk )
9: * @license http://editor.datatables.net/license DataTables Editor
10: * @link http://editor.datatables.net
11: */
12:
13: namespace DataTables\Editor;
14: if (!defined('DATATABLES')) exit();
15:
16: use
17: DataTables,
18: DataTables\Editor,
19: DataTables\Editor\Options,
20: DataTables\Editor\Join;
21:
22:
23: /**
24: * Field definitions for the DataTables Editor.
25: *
26: * Each Database column that is used with Editor can be described with this
27: * Field method (both for Editor and Join instances). It basically tells
28: * Editor what table column to use, how to format the data and if you want
29: * to read and/or write this column.
30: *
31: * Field instances are used with the {@link Editor::field} and
32: * {@link Join::field} methods to describe what fields should be interacted
33: * with by the editable table.
34: *
35: * @example
36: * Simply get a column with the name "city". No validation is performed.
37: * <code>
38: * Field::inst( 'city' )
39: * </code>
40: *
41: * @example
42: * Get a column with the name "first_name" - when edited a value must
43: * be given due to the "required" validation from the {@link Validate} class.
44: * <code>
45: * Field::inst( 'first_name' )->validator( 'Validate::required' )
46: * </code>
47: *
48: * @example
49: * Working with a date field, which is validated, and also has *get* and
50: * *set* formatters.
51: * <code>
52: * Field::inst( 'registered_date' )
53: * ->validator( 'Validate::dateFormat', 'D, d M y' )
54: * ->getFormatter( 'Format::date_sql_to_format', 'D, d M y' )
55: * ->setFormatter( 'Format::date_format_to_sql', 'D, d M y' )
56: * </code>
57: *
58: * @example
59: * Using an alias in the first parameter
60: * <code>
61: * Field::inst( 'name.first as first_name' )
62: * </code>
63: */
64: class Field extends DataTables\Ext {
65: /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
66: * Statics
67: */
68:
69: /** Set option flag (`set()`) - do not set data */
70: const SET_NONE = 'none';
71:
72: /** Set option flag (`set()`) - write to database on both create and edit */
73: const SET_BOTH = 'both';
74:
75: /** Set option flag (`set()`) - write to database only on create */
76: const SET_CREATE = 'create';
77:
78: /** Set option flag (`set()`) - write to database only on edit */
79: const SET_EDIT = 'edit';
80:
81:
82: /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
83: * Constructor
84: */
85:
86: /**
87: * Field instance constructor.
88: * @param string $dbField Name of the database column
89: * @param string $name Name to use in the JSON output from Editor and the
90: * HTTP submit from the client-side when editing. If not given then the
91: * $dbField name is used.
92: */
93: function __construct( $dbField=null, $name=null )
94: {
95: if ( $dbField !== null && $name === null ) {
96: // Allow just a single parameter to be passed - each can be
97: // overridden if needed later using the API.
98: $this->name( $dbField );
99: $this->dbField( $dbField );
100: }
101: else {
102: $this->name( $name );
103: $this->dbField( $dbField );
104: }
105: }
106:
107:
108:
109: /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
110: * Private parameters
111: */
112:
113: /** @var string */
114: private $_dbField = null;
115:
116: /** @var boolean */
117: private $_get = true;
118:
119: /** @var mixed */
120: private $_getFormatter = null;
121:
122: /** @var mixed */
123: private $_getFormatterOpts = null;
124:
125: /** @var mixed */
126: private $_getValue = null;
127:
128: /** @var Options */
129: private $_opts = null;
130:
131: /** @var callable */
132: private $_optsFn = null;
133:
134: /** @var string */
135: private $_name = null;
136:
137: /** @var string */
138: private $_set = Field::SET_BOTH;
139:
140: /** @var mixed */
141: private $_setFormatter = null;
142:
143: /** @var mixed */
144: private $_setFormatterOpts = null;
145:
146: /** @var mixed */
147: private $_setValue = null;
148:
149: /** @var mixed */
150: private $_validator = array();
151:
152: /** @var Upload */
153: private $_upload = null;
154:
155: /** @var callable */
156: private $_xss = null;
157:
158: /** @var boolean */
159: private $_xssFormat = true;
160:
161:
162:
163: /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
164: * Public methods
165: */
166:
167:
168: /**
169: * Get / set the DB field name.
170: *
171: * Note that when used as a setter, an alias can be given for the field
172: * using the SQL `as` keyword - for example: `firstName as name`. In this
173: * situation the dbField is set to the field name before the `as`, and the
174: * field's name (`name()`) is set to the name after the ` as `.
175: *
176: * As a result of this, the following constructs have identical
177: * functionality:
178: *
179: * Field::inst( 'firstName as name' );
180: * Field::inst( 'firstName', 'name' );
181: *
182: * @param string $_ Value to set if using as a setter.
183: * @return string|self The name of the db field if no parameter is given,
184: * or self if used as a setter.
185: */
186: public function dbField ( $_=null )
187: {
188: if ( $_ === null ) {
189: return $this->_dbField;
190: }
191:
192: if ( stripos( $_, ' as ' ) ) {
193: $a = preg_split( '/ as /i', $_ );
194: $this->_dbField = trim( $a[0] );
195: $this->_name = trim( $a[1] );
196: }
197: else {
198: $this->_dbField = $_;
199: }
200:
201: return $this;
202: }
203:
204:
205: /**
206: * Get / set the 'get' property of the field.
207: *
208: * A field can be marked as write only when setting the get property to false
209: * here.
210: * @param boolean $_ Value to set if using as a setter.
211: * @return boolean|self The get property if no parameter is given, or self
212: * if used as a setter.
213: */
214: public function get ( $_=null )
215: {
216: return $this->_getSet( $this->_get, $_ );
217: }
218:
219:
220: /**
221: * Get formatter for the field's data.
222: *
223: * When the data has been retrieved from the server, it can be passed through
224: * a formatter here, which will manipulate (format) the data as required. This
225: * can be useful when, for example, working with dates and a particular format
226: * is required on the client-side.
227: *
228: * Editor has a number of formatters available with the {@link Format} class
229: * which can be used directly with this method.
230: * @param callable|string $_ Value to set if using as a setter. Can be given as
231: * a closure function or a string with a reference to a function that will
232: * be called with call_user_func().
233: * @param mixed $opts Variable that is passed through to the get formatting
234: * function - can be useful for passing through extra information such as
235: * date formatting string, or a required flag. The actual options available
236: * depend upon the formatter used.
237: * @return callable|string|self The get formatter if no parameter is given, or
238: * self if used as a setter.
239: */
240: public function getFormatter ( $_=null, $opts=null )
241: {
242: if ( $opts !== null ) {
243: $this->_getFormatterOpts = $opts;
244: }
245: return $this->_getSet( $this->_getFormatter, $_ );
246: }
247:
248:
249: /**
250: * Get / set a get value. If given, then this value is used to send to the
251: * client-side, regardless of what value is held by the database.
252: *
253: * @param callable|string|number $_ Value to set, or no value to use as a
254: * getter
255: * @return callable|string|self Value if used as a getter, or self if used
256: * as a setter.
257: */
258: public function getValue ( $_=null )
259: {
260: return $this->_getSet( $this->_getValue, $_ );
261: }
262:
263:
264: /**
265: * Get / set the 'name' property of the field.
266: *
267: * The name is typically the same as the dbField name, since it makes things
268: * less confusing(!), but it is possible to set a different name for the data
269: * which is used in the JSON returned to DataTables in a 'get' operation and
270: * the field name used in a 'set' operation.
271: * @param string $_ Value to set if using as a setter.
272: * @return string|self The name property if no parameter is given, or self
273: * if used as a setter.
274: */
275: public function name ( $_=null )
276: {
277: return $this->_getSet( $this->_name, $_ );
278: }
279:
280:
281: /**
282: * Get a list of values that can be used for the options list in radio,
283: * select and checkbox inputs from the database for this field.
284: *
285: * Note that this is for simple 'label / value' pairs only. For more complex
286: * data, including pairs that require joins and where conditions, use a
287: * closure to provide a query
288: *
289: * @param string|callable $table Database table name to use to get the
290: * paired data from, or a closure function if providing a method
291: * @param string $value Table column name that contains the pair's
292: * value. Not used if the first parameter is given as a closure
293: * @param string $label Table column name that contains the pair's
294: * label. Not used if the first parameter is given as a closure
295: * @param callable $condition Function that will add `where`
296: * conditions to the query
297: * @param callable $format Function will render each label
298: * @param string $order SQL ordering
299: * @return Field Self for chaining
300: */
301: public function options ( $table=null, $value=null, $label=null, $condition=null, $format=null, $order=null )
302: {
303: if ( $table === null ) {
304: return $this->_opts;
305: }
306:
307: // Overloads for backwards compatibility
308: if ( is_a( $table, '\DataTables\Editor\Options' ) ) {
309: // Options class
310: $this->_optsFn = null;
311: $this->_opts = $table;
312: }
313: else if ( is_callable($table) && is_object($table) ) {
314: // Function
315: $this->_opts = null;
316: $this->_optsFn = $table;
317: }
318: else {
319: $this->_optsFn = null;
320: $this->_opts = Options::inst()
321: ->table( $table )
322: ->value( $value )
323: ->label( $label );
324:
325: if ( $condition ) {
326: $this->_opts->where( $condition );
327: }
328:
329: if ( $format ) {
330: $this->_opts->render( $format );
331: }
332:
333: if ( $order ) {
334: $this->_opts->order( $order );
335: }
336: }
337:
338: return $this;
339: }
340:
341:
342: /**
343: * Get / set the 'set' property of the field.
344: *
345: * A field can be marked as read only using this option, to be set only
346: * during an create or edit action or to be set during both actions. This
347: * provides the ability to have fields that are only set when a new row is
348: * created (for example a "created" time stamp).
349: * @param string|boolean $_ Value to set when the method is being used as a
350: * setter (leave as undefined to use as a getter). This can take the
351: * value of:
352: *
353: * * `true` - Same as `Field::SET_BOTH`
354: * * `false` - Same as `Field::SET_NONE`
355: * * `Field::SET_BOTH` - Set the database value on both create and edit commands
356: * * `Field::SET_NONE` - Never set the database value
357: * * `Field::SET_CREATE` - Set the database value only on create
358: * * `Field::SET_EDIT` - Set the database value only on edit
359: * @return string|self The set property if no parameter is given, or self
360: * if used as a setter.
361: */
362: public function set ( $_=null )
363: {
364: if ( $_ === true ) {
365: $_ = Field::SET_BOTH;
366: }
367: else if ( $_ === false ) {
368: $_ = Field::SET_NONE;
369: }
370:
371: return $this->_getSet( $this->_set, $_ );
372: }
373:
374:
375: /**
376: * Set formatter for the field's data.
377: *
378: * When the data has been retrieved from the server, it can be passed through
379: * a formatter here, which will manipulate (format) the data as required. This
380: * can be useful when, for example, working with dates and a particular format
381: * is required on the client-side.
382: *
383: * Editor has a number of formatters available with the {@link Format} class
384: * which can be used directly with this method.
385: * @param callable|string $_ Value to set if using as a setter. Can be given as
386: * a closure function or a string with a reference to a function that will
387: * be called with call_user_func().
388: * @param mixed $opts Variable that is passed through to the get formatting
389: * function - can be useful for passing through extra information such as
390: * date formatting string, or a required flag. The actual options available
391: * depend upon the formatter used.
392: * @return callable|string|self The set formatter if no parameter is given, or
393: * self if used as a setter.
394: */
395: public function setFormatter ( $_=null, $opts=null )
396: {
397: if ( $opts !== null ) {
398: $this->_setFormatterOpts = $opts;
399: }
400: return $this->_getSet( $this->_setFormatter, $_ );
401: }
402:
403:
404: /**
405: * Get / set a set value. If given, then this value is used to write to the
406: * database regardless of what data is sent from the client-side.
407: *
408: * @param callable|string|number $_ Value to set, or no value to use as a
409: * getter
410: * @return callable|string|self Value if used as a getter, or self if used
411: * as a setter.
412: */
413: public function setValue ( $_=null )
414: {
415: return $this->_getSet( $this->_setValue, $_ );
416: }
417:
418:
419: /**
420: * Get / set the upload class for this field.
421: * @param Upload $_ Upload class if used as a setter
422: * @return Upload|self Value if used as a getter, or self if used
423: * as a setter.
424: */
425: public function upload ( $_=null )
426: {
427: return $this->_getSet( $this->_upload, $_ );
428: }
429:
430:
431: /**
432: * Get / set the 'validator' of the field.
433: *
434: * The validator can be used to check if any abstract piece of data is valid
435: * or not according to the given rules of the validation function used.
436: *
437: * Multiple validation options can be applied to a field instance by calling
438: * this method multiple times. For example, it would be possible to have a
439: * 'required' validation and a 'maxLength' validation with multiple calls.
440: *
441: * Editor has a number of validation available with the {@link Validate} class
442: * which can be used directly with this method.
443: * @param callable|string $_ Value to set if using as the validation method.
444: * Can be given as a closure function or a string with a reference to a
445: * function that will be called with call_user_func().
446: * @param mixed $opts Variable that is passed through to the validation
447: * function - can be useful for passing through extra information such as
448: * date formatting string, or a required flag. The actual options available
449: * depend upon the validation function used.
450: * @return callable|string|self The validation method if no parameter is given,
451: * or self if used as a setter.
452: */
453: public function validator ( $_=null, $opts=null )
454: {
455: if ( $_ === null ) {
456: return $this->_validator;
457: }
458: else {
459: $this->_validator[] = array(
460: "func" => $_,
461: "opts" => $opts
462: );
463: }
464:
465: return $this;
466: }
467:
468:
469: /**
470: * Set a formatting method that will be used for XSS checking / removal.
471: * This should be a function that takes a single argument (the value to be
472: * cleaned) and returns the cleaned value.
473: *
474: * Editor will use HtmLawed by default for this operation, which is built
475: * into the software and no additional configuration is required, but a
476: * custom function can be used if you wish to use a different formatter such
477: * as HTMLPurifier.
478: *
479: * If you wish to disable this option (which you would only do if you are
480: * absolutely confident that your validation will pick up on any XSS inputs)
481: * simply provide a closure function that returns the value given to the
482: * function. This is _not_ recommended.
483: *
484: * @param callable|false $xssFormatter XSS cleaner function, use `false` or
485: * `null` to disable XSS cleaning.
486: * @return Field Self for chaining.
487: */
488: public function xss ( $xssFormatter )
489: {
490: if ( $xssFormatter === true || $xssFormatter === false || $xssFormatter === null ) {
491: $this->_xssFormat = $xssFormatter;
492: }
493: else {
494: $this->_xss = $xssFormatter;
495: }
496:
497: return $this;
498: }
499:
500:
501:
502: /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
503: * Internal methods
504: * Used by the Editor class and not generally for public use
505: */
506:
507: /**
508: * Check to see if a field should be used for a particular action (get or set).
509: *
510: * Called by the Editor / Join class instances - not expected for general
511: * consumption - internal.
512: * @param string $action Direction that the data is travelling - 'get' is
513: * reading DB data, `create` and `edit` for writing to the DB
514: * @param array $data Data submitted from the client-side when setting.
515: * @return boolean true if the field should be used in the get / set.
516: * @internal
517: */
518: public function apply ( $action, $data=null )
519: {
520: if ( $action === 'get' ) {
521: // Get action - can we get this field
522: return $this->_get;
523: }
524: else {
525: // Note that validation must be done on input data before we get here
526:
527: // Create or edit action, are we configured to use this field
528: if ( $action === 'create' &&
529: ($this->_set === Field::SET_NONE || $this->_set === Field::SET_EDIT)
530: ) {
531: return false;
532: }
533: else if ( $action === 'edit' &&
534: ($this->_set === Field::SET_NONE || $this->_set === Field::SET_CREATE)
535: ) {
536: return false;
537: }
538:
539: // Check it was in the submitted data. If not, then not required
540: // (validation would have failed if it was) and therefore we don't
541: // set it. Check for a value as well, as it can format data from
542: // some other source
543: if ( $this->_setValue === null && ! $this->_inData( $this->name(), $data ) ) {
544: return false;
545: }
546:
547: // In the data set, so use it
548: return true;
549: }
550: }
551:
552:
553: /**
554: * Execute the ipOpts to get the list of options to return to the client-
555: * side
556: *
557: * @param \DataTables\Database $db Database instance
558: * @return Array Array of value / label options for the list
559: * @internal
560: */
561: public function optionsExec ( $db )
562: {
563: if ( $this->_optsFn ) {
564: $fn = $this->_optsFn;
565: return $fn();
566: }
567: else if ( $this->_opts ) {
568: return $this->_opts->exec( $db );
569: }
570:
571: return false;
572: }
573:
574:
575: /**
576: * Get the value of the field, taking into account if it is coming from the
577: * DB or from a POST. If formatting has been specified for this field, it
578: * will be applied here.
579: *
580: * Called by the Editor / Join class instances - not expected for general
581: * consumption - internal.
582: * @param string $direction Direction that the data is travelling - 'get' is
583: * reading data, and 'set' is writing it to the DB.
584: * @param array $data Data submitted from the client-side when setting or the
585: * data for the row when getting data from the DB.
586: * @return string Value for the field
587: * @internal
588: */
589: public function val ( $direction, $data )
590: {
591: if ( $direction === 'get' ) {
592: if ( $this->_getValue !== null ) {
593: $val = $this->_getAssignedValue( $this->_getValue );
594: }
595: else {
596: // Getting data, so the db field name
597: $val = isset( $data[ $this->_dbField ] ) ?
598: $data[ $this->_dbField ] :
599: null;
600: }
601:
602: return $this->_format(
603: $val, $data, $this->_getFormatter, $this->_getFormatterOpts
604: );
605: }
606: else {
607: // Setting data, so using from the payload (POST usually) and thus
608: // use the 'name'
609: $val = $this->_setValue !== null ?
610: $this->_getAssignedValue( $this->_setValue ) :
611: $this->_readProp( $this->name(), $data );
612:
613: // XSS removal / checker
614: if ( $this->_xssFormat ) {
615: $val = $this->xssSafety( $val );
616: }
617:
618: return $this->_format(
619: $val, $data, $this->_setFormatter, $this->_setFormatterOpts
620: );
621: }
622: }
623:
624:
625: /**
626: * Check the validity of the field based on the data submitted. Note that
627: * this validation is performed on the wire data - i.e. that which is
628: * submitted, before any setFormatter is run
629: *
630: * Called by the Editor / Join class instances - not expected for general
631: * consumption - internal.
632: *
633: * @param array $data Data submitted from the client-side
634: * @param Editor $editor Editor instance
635: * @param * $id Row id that is being validated
636: * @return boolean|string `true` if valid, string with error message if not
637: * @internal
638: */
639: public function validate ( $data, $editor, $id=null )
640: {
641: // Three cases for the validator - closure, string or null
642: if ( ! count( $this->_validator ) ) {
643: return true;
644: }
645:
646: $val = $this->_readProp( $this->name(), $data );
647: $processData = $editor->inData();
648: $instances = array(
649: 'action' => $processData['action'],
650: 'id' => $id,
651: 'field' => $this,
652: 'editor' => $editor,
653: 'db' => $editor->db()
654: );
655:
656: for ( $i=0, $ien=count( $this->_validator ) ; $i<$ien ; $i++ ) {
657: $validator = $this->_validator[$i];
658:
659: if ( is_string( $validator['func'] ) ) {
660: // Don't require the Editor namespace if DataTables validator is given as a string
661: if ( strpos($validator['func'], "Validate::") === 0 ) {
662: $res = call_user_func( "\\DataTables\\Editor\\".$validator['func'], $val, $data, $validator['opts'], $instances );
663: }
664: else {
665: $res = call_user_func( $validator['func'], $val, $data, $validator['opts'], $instances );
666: }
667: }
668: else {
669: $func = $validator['func'];
670: $res = $func( $val, $data, $this, $instances );
671: }
672:
673: // Check if there was a validation error and if so, return it
674: if ( $res !== true ) {
675: return $res;
676: }
677: }
678:
679: // Validation methods all run, must be valid
680: return true;
681: }
682:
683:
684: /**
685: * Write the value for this field to the output array for a read operation
686: *
687: * @param array $out Row output data (to the JSON)
688: * @param mixed $srcData Row input data (raw, from the database)
689: * @internal
690: */
691: public function write( &$out, $srcData )
692: {
693: $this->_writeProp( $out, $this->name(), $this->val('get', $srcData) );
694: }
695:
696:
697: /**
698: * Perform XSS prevention on an input.
699: *
700: * @param * $val Value to be escaped
701: * @return string Safe value
702: */
703: public function xssSafety ( $val ) {
704: $xss = $this->_xss;
705:
706: if ( is_array( $val ) ) {
707: $res = array();
708:
709: foreach ( $val as $individual ) {
710: $res[] = $xss ?
711: $xss( $individual ) :
712: DataTables\Vendor\Htmlaw::filter( $individual );
713: }
714:
715: return $res;
716: }
717:
718: return $xss ?
719: $xss( $val ) :
720: DataTables\Vendor\Htmlaw::filter( $val );
721: }
722:
723:
724:
725: /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
726: * Private methods
727: */
728:
729: /**
730: * Apply a formatter to data. The caller will decide what formatter to apply
731: * (get or set)
732: *
733: * @param mixed $val Value to be formatted
734: * @param mixed $data Full row data
735: * @param callable $formatter Formatting function to be called
736: * @param array $opts Array of options to be passed to the formatter
737: * @return mixed Formatted value
738: */
739: private function _format( $val, $data, $formatter, $opts )
740: {
741: // Three cases for the formatter - closure, string or null
742: if ( $formatter ) {
743: if ( is_string( $formatter ) ) {
744: // Don't require the Editor namespace if DataTables validator is given as a string
745: if ( strpos($formatter, "Format::") === 0 ) {
746: // Editor formatter
747: return call_user_func(
748: "\\DataTables\\Editor\\".$formatter,
749: $val,
750: $data,
751: $opts
752: );
753: }
754:
755: // User function (string identifier)
756: return call_user_func( $formatter, $val, $data, $opts );
757: }
758:
759: // Closure
760: return $formatter( $val, $data, $opts );
761: }
762: return $val;
763: }
764:
765: /**
766: * Get the value from `_[gs]etValue` - taking into account if it is callable
767: * function or not
768: *
769: * @param mixed $val Value to be evaluated
770: * @return mixed Value assigned, or returned from the function
771: */
772: private function _getAssignedValue ( $val )
773: {
774: return is_callable($val) && is_object($val) ?
775: $val() :
776: $val;
777: }
778:
779: /**
780: * Check is a parameter is in the submitted data set. This is functionally
781: * the same as the `_readProp()` method, but in this case a binary value
782: * is required to indicate if the value is present or not.
783: *
784: * @param string $name Javascript dotted object name to write to
785: * @param array $data Data source array to read from
786: * @return boolean `true` if present, `false` otherwise
787: * @private
788: */
789: private function _inData ( $name, $data )
790: {
791: if ( strpos($name, '.') === false ) {
792: return isset( $data[ $name ] ) ?
793: true :
794: false;
795: }
796:
797: $names = explode( '.', $name );
798: $inner = $data;
799:
800: for ( $i=0 ; $i<count($names)-1 ; $i++ ) {
801: if ( ! isset( $inner[ $names[$i] ] ) ) {
802: return false;
803: }
804:
805: $inner = $inner[ $names[$i] ];
806: }
807:
808: return isset( $inner [ $names[count($names)-1] ] ) ?
809: true :
810: false;
811: }
812: }
813:
814: