1 <?php
2
3 /**
4 * Base class for contexts.
5 *
6 * Contexts dictate where fields appear, how they load data, and where they
7 * save data.
8 *
9 * @package Fieldmanager_Context
10 */
11 abstract class Fieldmanager_Context {
12
13 /**
14 * @var Fieldmanager_Field
15 * The base field associated with this context
16 */
17 public $fm = Null;
18
19 /**
20 * @var string
21 * Unique ID of the form. Used for forms that are not built into WordPress.
22 */
23 public $uniqid;
24
25 /**
26 * Store the meta keys this field saves to, to catch naming conflicts.
27 * @var array
28 */
29 public $save_keys = array();
30
31 /**
32 * Check if the nonce is valid. Returns false if the nonce is missing and
33 * throws an exception if it's invalid. If all goes well, returns true.
34 *
35 * @return boolean
36 */
37 protected function is_valid_nonce() {
38 if ( empty( $_POST['fieldmanager-' . $this->fm->name . '-nonce'] ) ) {
39 return false;
40 }
41
42 if ( ! wp_verify_nonce( $_POST['fieldmanager-' . $this->fm->name . '-nonce'], 'fieldmanager-save-' . $this->fm->name ) ) {
43 $this->fm->_unauthorized_access( __( 'Nonce validation failed', 'fieldmanager' ) );
44 }
45
46 return true;
47 }
48
49
50 /**
51 * Prepare the data for saving.
52 *
53 * @param mixed $old_value Optional. The previous value.
54 * @param mixed $new_value Optional. The new value for the field.
55 * @param object $fm Optional. The Fieldmanager_Field to prepare.
56 * @return mixed The filtered and sanitized value, safe to save.
57 */
58 protected function prepare_data( $old_value = null, $new_value = null, $fm = null ) {
59 if ( null === $fm ) {
60 $fm = $this->fm;
61 }
62 if ( null === $new_value ) {
63 $new_value = isset( $_POST[ $this->fm->name ] ) ? $_POST[ $this->fm->name ] : '';
64 }
65 $new_value = apply_filters( "fm_context_before_presave_data", $new_value, $old_value, $this, $fm );
66 $data = $fm->presave_all( $new_value, $old_value );
67 return apply_filters( "fm_context_after_presave_data", $data, $old_value, $this, $fm );
68 }
69
70
71 /**
72 * Render the field.
73 *
74 * @param array $args {
75 * Optional. Arguments to adjust the rendering behavior.
76 *
77 * @type mixed $data The existing data to display with the field. If
78 * absent, data will be loaded using
79 * Fieldmanager_Context::_load().
80 * @type boolean $echo Output if true, return if false. Default is true.
81 * }
82 * @return string if $args['echo'] == false.
83 */
84 protected function render_field( $args = array() ) {
85 $data = array_key_exists( 'data', $args ) ? $args['data'] : null;
86 $echo = isset( $args['echo'] ) ? $args['echo'] : true;
87
88 $nonce = wp_nonce_field( 'fieldmanager-save-' . $this->fm->name, 'fieldmanager-' . $this->fm->name . '-nonce', true, false );
89 $field = $this->fm->element_markup( $data );
90 if ( $echo ) {
91 echo $nonce . $field;
92 } else {
93 return $nonce . $field;
94 }
95 }
96
97 }
98