Completed
Push — develop ( d51a80...6ded93 )
by Zack
04:19
created

GravityView_Edit_Entry_Render   D

Complexity

Total Complexity 184

Size/Duplication

Total Lines 1547
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6
Metric Value
wmc 184
lcom 1
cbo 6
dl 0
loc 1547
rs 4.4102

36 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B load() 0 26 1
A prevent_render_form() 0 9 3
A prevent_maybe_process_form() 0 8 3
A is_edit_entry() 0 6 3
A is_edit_entry_submission() 0 3 1
A setup_vars() 0 14 1
B init() 0 24 4
A print_scripts() 0 10 1
B process_save() 0 58 6
A process_save_process_files() 0 10 2
A modify_fileupload_settings() 0 9 2
B form_prepare_for_save() 0 16 5
F maybe_update_post_fields() 0 120 21
A after_update() 0 18 2
B edit_entry_form() 0 97 3
B render_edit_form() 0 25 1
A render_form_buttons() 0 3 1
A filter_modify_form_fields() 0 18 3
F modify_edit_field_input() 0 109 24
A get_field_value() 0 9 2
D gform_pre_validation() 0 97 16
B validate() 0 29 2
F custom_validation() 0 123 20
A get_entry() 0 9 2
A get_configured_edit_fields() 0 19 2
A fix_hidden_fields() 0 13 3
C filter_fields() 0 58 11
B merge_field_properties() 0 23 4
B filter_admin_only_fields() 0 23 4
B filter_conditional_logic() 0 24 3
A manage_conditional_logic() 0 9 2
C user_can_edit_entry() 0 64 14
B user_can_edit_field() 0 22 4
A check_user_cap_edit_field() 0 16 4
B verify_nonce() 0 26 3

How to fix   Complexity   

Complex Class

Complex classes like GravityView_Edit_Entry_Render often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use GravityView_Edit_Entry_Render, and based on these observations, apply Extract Interface, too.

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 17 and the first side effect is on line 13.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * GravityView Edit Entry - render frontend
4
 *
5
 * @package   GravityView
6
 * @license   GPL2+
7
 * @author    Katz Web Services, Inc.
8
 * @link      http://gravityview.co
9
 * @copyright Copyright 2014, Katz Web Services, Inc.
10
 */
11
12
if ( ! defined( 'WPINC' ) ) {
13
    die;
14
}
15
16
17
class GravityView_Edit_Entry_Render {
18
19
    protected $loader;
20
21
	/**
22
	 * @var string String used to generate unique nonce for the entry/form/view combination. Allows access to edit page.
23
	 */
24
    static $nonce_key;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $nonce_key.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
25
26
	/**
27
	 * @since 1.9
28
	 * @var string String used for check valid edit entry form submission. Allows saving edit form values.
29
	 */
30
	private static $nonce_field = 'is_gv_edit_entry';
31
32
	/**
33
	 * @since 1.9
34
	 * @var bool Whether to allow save and continue functionality
35
	 */
36
	private static $supports_save_and_continue = false;
37
38
	/**
39
	 * @since 1.9
40
	 * @var bool Whether to allow editing product fields
41
	 */
42
	private static $supports_product_fields = false;
43
44
    /**
45
     * Gravity Forms entry array
46
     *
47
     * @var array
48
     */
49
    var $entry;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $entry.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
50
51
    /**
52
     * Gravity Forms form array
53
     *
54
     * @var array
55
     */
56
    var $form;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $form.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
57
58
    /**
59
     * Gravity Forms form array after the form validation process
60
     * @since 1.13
61
     * @var array
62
     */
63
    var $form_after_validation = null;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $form_after_validation.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
64
65
    /**
66
     * Gravity Forms form id
67
     *
68
     * @var array
69
     */
70
    var $form_id;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $form_id.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
71
72
    /**
73
     * ID of the current view
74
     *
75
     * @var int
76
     */
77
    var $view_id;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $view_id.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
78
79
80
    /**
81
     * Updated entry is valid (GF Validation object)
82
     *
83
     * @var array
84
     */
85
    var $is_valid = NULL;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $is_valid.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
86
87
    function __construct( GravityView_Edit_Entry $loader ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
88
        $this->loader = $loader;
89
    }
90
91
    function load() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
92
93
        /** @define "GRAVITYVIEW_DIR" "../../../" */
94
        include_once( GRAVITYVIEW_DIR .'includes/class-admin-approve-entries.php' );
95
96
        // Don't display an embedded form when editing an entry
97
        add_action( 'wp_head', array( $this, 'prevent_render_form' ) );
98
        add_action( 'wp_footer', array( $this, 'prevent_render_form' ) );
99
100
        // Stop Gravity Forms processing what is ours!
101
        add_filter( 'wp', array( $this, 'prevent_maybe_process_form'), 8 );
0 ignored issues
show
introduced by
No space before closing parenthesis of array is bad style
Loading history...
102
103
        add_filter( 'gravityview_is_edit_entry', array( $this, 'is_edit_entry') );
0 ignored issues
show
introduced by
No space before closing parenthesis of array is bad style
Loading history...
104
105
        add_action( 'gravityview_edit_entry', array( $this, 'init' ) );
106
107
        // Disable conditional logic if needed (since 1.9)
108
        add_filter( 'gform_has_conditional_logic', array( $this, 'manage_conditional_logic' ), 10, 2 );
109
110
        // Make sure GF doesn't validate max files (since 1.9)
111
        add_filter( 'gform_plupload_settings', array( $this, 'modify_fileupload_settings' ), 10, 3 );
112
113
        // Add fields expected by GFFormDisplay::validate()
114
        add_filter( 'gform_pre_validation', array( $this, 'gform_pre_validation') );
0 ignored issues
show
introduced by
No space before closing parenthesis of array is bad style
Loading history...
115
116
    }
117
118
    /**
119
     * Don't show any forms embedded on a page when GravityView is in Edit Entry mode
120
     *
121
     * Adds a `__return_empty_string` filter on the Gravity Forms shortcode on the `wp_head` action
122
     * And then removes it on the `wp_footer` action
123
     *
124
     * @since 1.16.1
125
     *
126
     * @return void
127
     */
128
    function prevent_render_form() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
129
        if( $this->is_edit_entry() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
130
            if( 'wp_head' === current_filter() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
131
                add_filter( 'gform_shortcode_form', '__return_empty_string' );
132
            } else {
133
                remove_filter( 'gform_shortcode_form', '__return_empty_string' );
134
            }
135
        }
136
    }
137
138
    /**
139
     * Because we're mimicking being a front-end Gravity Forms form while using a Gravity Forms
140
     * backend form, we need to prevent them from saving twice.
141
     * @return void
142
     */
143
    function prevent_maybe_process_form() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
144
145
        do_action('gravityview_log_debug', 'GravityView_Edit_Entry[prevent_maybe_process_form] $_POSTed data (sanitized): ', esc_html( print_r( $_POST, true ) ) );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
introduced by
The use of function print_r() is discouraged
Loading history...
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
146
147
        if( $this->is_edit_entry_submission() && $this->verify_nonce() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
148
            remove_action( 'wp',  array( 'RGForms', 'maybe_process_form'), 9 );
0 ignored issues
show
introduced by
No space before closing parenthesis of array is bad style
Loading history...
149
        }
150
    }
151
152
    /**
153
     * Is the current page an Edit Entry page?
154
     * @return boolean
155
     */
156
    public function is_edit_entry() {
157
158
        $gf_page = ( 'entry' === RGForms::get( 'view' ) );
159
160
        return ( $gf_page && isset( $_GET['edit'] ) || RGForms::post( 'action' ) === 'update' );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
161
    }
162
163
	/**
164
	 * Is the current page an Edit Entry page?
165
	 * @since 1.9
166
	 * @return boolean
167
	 */
168
	public function is_edit_entry_submission() {
169
		return !empty( $_POST[ self::$nonce_field ] );
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
170
	}
171
172
    /**
173
     * When Edit entry view is requested setup the vars
174
     */
175
    function setup_vars() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
176
        $gravityview_view = GravityView_View::getInstance();
177
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
178
179
        $entries = $gravityview_view->getEntries();
180
        $this->entry = $entries[0];
181
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
182
183
        $this->form = $gravityview_view->getForm();
184
        $this->form_id = $gravityview_view->getFormId();
185
        $this->view_id = $gravityview_view->getViewId();
186
187
        self::$nonce_key = GravityView_Edit_Entry::get_nonce_key( $this->view_id, $this->form_id, $this->entry['id'] );
188
    }
189
190
191
    /**
192
     * Load required files and trigger edit flow
193
     *
194
     * Run when the is_edit_entry returns true.
195
     *
196
     * @param GravityView_View_Data $gv_data GravityView Data object
197
     * @return void
198
     */
199
    function init( $gv_data ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
200
201
        require_once( GFCommon::get_base_path() . '/form_display.php' );
202
        require_once( GFCommon::get_base_path() . '/entry_detail.php' );
203
204
        $this->setup_vars();
205
206
        // Multiple Views embedded, don't proceed if nonce fails
207
        if( $gv_data->has_multiple_views() && ! wp_verify_nonce( $_GET['edit'], self::$nonce_key ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_GET
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
208
            return;
209
        }
210
211
        // Sorry, you're not allowed here.
212
        if( false === $this->user_can_edit_entry( true ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
213
            return;
214
        }
215
216
        $this->print_scripts();
217
218
        $this->process_save();
219
220
        $this->edit_entry_form();
221
222
    }
223
224
225
    /**
226
     * Force Gravity Forms to output scripts as if it were in the admin
227
     * @return void
228
     */
229
    function print_scripts() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
230
        $gravityview_view = GravityView_View::getInstance();
231
232
        wp_register_script( 'gform_gravityforms', GFCommon::get_base_url().'/js/gravityforms.js', array( 'jquery', 'gform_json', 'gform_placeholder', 'sack', 'plupload-all', 'gravityview-fe-view' ) );
233
234
        GFFormDisplay::enqueue_form_scripts($gravityview_view->getForm(), false);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
235
236
        // Sack is required for images
237
        wp_print_scripts( array( 'sack', 'gform_gravityforms' ) );
238
    }
239
240
241
    /**
242
     * Process edit entry form save
243
     */
244
    function process_save() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
245
246
        if( empty( $_POST ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
247
            return;
248
        }
249
250
        // Make sure the entry, view, and form IDs are all correct
251
        $valid = $this->verify_nonce();
252
253
        if( !$valid ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
254
            do_action('gravityview_log_error', __METHOD__ . ' Nonce validation failed.' );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
255
            return;
256
        }
257
258
        if( $this->entry['id'] !== $_POST['lid'] ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_POST
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
259
            do_action('gravityview_log_error', __METHOD__ . ' Entry ID did not match posted entry ID.' );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
260
            return;
261
        }
262
263
        do_action('gravityview_log_debug', 'GravityView_Edit_Entry[process_save] $_POSTed data (sanitized): ', esc_html( print_r( $_POST, true ) ) );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
introduced by
The use of function print_r() is discouraged
Loading history...
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
264
265
        $this->process_save_process_files( $this->form_id );
266
267
        $this->validate();
268
269
        if( $this->is_valid ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->is_valid of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
introduced by
Space after opening control structure is required
Loading history...
270
271
            do_action('gravityview_log_debug', 'GravityView_Edit_Entry[process_save] Submission is valid.' );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
272
273
            /**
274
             * @hack This step is needed to unset the adminOnly from form fields
275
             */
276
            $form = $this->form_prepare_for_save();
277
278
            /**
279
             * @hack to avoid the capability validation of the method save_lead for GF 1.9+
280
             */
281
            unset( $_GET['page'] );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
282
283
            GFFormsModel::save_lead( $form, $this->entry );
284
285
            // If there's a post associated with the entry, process post fields
286
            if( !empty( $this->entry['post_id'] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
287
                $this->maybe_update_post_fields( $form );
288
            }
289
290
            // Perform actions normally performed after updating a lead
291
            $this->after_update();
292
293
            /**
294
             * @action `gravityview/edit_entry/after_update` Perform an action after the entry has been updated using Edit Entry
295
             * @param array $form Gravity Forms form array
296
             * @param string $entry_id Numeric ID of the entry that was updated
297
             */
298
            do_action( 'gravityview/edit_entry/after_update', $this->form, $this->entry['id'] );
299
        }
300
301
    } // process_save
302
303
304
    /**
305
     * Have GF handle file uploads
306
     *
307
     * Copy of code from GFFormDisplay::process_form()
308
     *
309
     * @param int $form_id
310
     */
311
    function process_save_process_files( $form_id ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
312
313
        //Loading files that have been uploaded to temp folder
314
        $files = GFCommon::json_decode( stripslashes( RGForms::post( 'gform_uploaded_files' ) ) );
315
        if ( ! is_array( $files ) ) {
316
            $files = array();
317
        }
318
319
        RGFormsModel::$uploaded_files[ $form_id ] = $files;
320
    }
321
322
    /**
323
     * Remove max_files validation (done on gravityforms.js) to avoid conflicts with GravityView
324
     * Late validation done on self::custom_validation
325
     *
326
     * @param $plupload_init array Plupload settings
327
     * @param $form_id
328
     * @param $instance
329
     * @return mixed
330
     */
331
    public function modify_fileupload_settings( $plupload_init, $form_id, $instance ) {
0 ignored issues
show
Unused Code introduced by
The parameter $form_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $instance is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
332
        if( ! $this->is_edit_entry() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
333
            return $plupload_init;
334
        }
335
336
        $plupload_init['gf_vars']['max_files'] = 0;
337
338
        return $plupload_init;
339
    }
340
341
342
    /**
343
     * Unset adminOnly and convert field input key to string
344
     * @return array $form
345
     */
346
    private function form_prepare_for_save() {
347
        $form = $this->form;
348
349
        foreach( $form['fields'] as &$field ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
350
351
            $field->adminOnly = false;
352
353
            if( isset( $field->inputs ) && is_array( $field->inputs ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
354
                foreach( $field->inputs as $key => $input ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
355
                    $field->inputs[ $key ][ 'id' ] = (string)$input['id'];
0 ignored issues
show
introduced by
Array keys should NOT be surrounded by spaces if they only contain a string or an integer.
Loading history...
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
356
                }
357
            }
358
        }
359
360
        return $form;
361
    }
362
363
364
    /**
365
     * Loop through the fields being edited and if they include Post fields, update the Entry's post object
366
     *
367
     * @param array $form Gravity Forms form
368
     *
369
     * @return void
370
     */
371
    function maybe_update_post_fields( $form ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
372
373
        $post_id = $this->entry['post_id'];
374
375
        // Security check
376
        if( false === GVCommon::has_cap( 'edit_post', $post_id ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
377
            do_action( 'gravityview_log_error', 'The current user does not have the ability to edit Post #'.$post_id );
378
            return;
379
        }
380
381
        $update_entry = false;
382
383
        $updated_post = $original_post = get_post( $post_id );
384
385
        foreach ( $this->entry as $field_id => $value ) {
386
387
            //todo: only run through the edit entry configured fields
388
389
            $field = RGFormsModel::get_field( $form, $field_id );
390
391
            if( class_exists('GF_Fields') ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
392
                $field = GF_Fields::create( $field );
393
            }
394
395
            if( GFCommon::is_post_field( $field ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
396
397
                // Get the value of the field, including $_POSTed value
398
                $value = RGFormsModel::get_field_value( $field );
399
400
                // Convert the field object in 1.9 to an array for backward compatibility
401
                $field_array = GVCommon::get_field_array( $field );
402
403
                switch( $field_array['type'] ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
404
405
                    case 'post_title':
406
                    case 'post_content':
407
                    case 'post_excerpt':
408
                        $updated_post->{$field_array['type']} = $value;
409
                        break;
410
                    case 'post_tags':
411
                        wp_set_post_tags( $post_id, $value, false );
412
                        break;
413
                    case 'post_category':
414
415
                        $categories = is_array( $value ) ? array_values( $value ) : (array)$value;
0 ignored issues
show
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
416
                        $categories = array_filter( $categories );
417
418
                        wp_set_post_categories( $post_id, $categories, false );
419
420
                        // prepare value to be saved in the entry
421
                        $field = GFCommon::add_categories_as_choices( $field, '' );
422
423
                        // if post_category is type checkbox, then value is an array of inputs
424
                        if( isset( $value[ strval( $field_id ) ] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
425
                            foreach( $value as $input_id => $val ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
426
                                $input_name = 'input_' . str_replace( '.', '_', $input_id );
427
                                $this->entry[ strval( $input_id ) ] = RGFormsModel::prepare_value( $form, $field, $val, $input_name, $this->entry['id'] );
428
                            }
429
                        } else {
430
                            $input_name = 'input_' . str_replace( '.', '_', $field_id );
431
                            $this->entry[ strval( $field_id ) ] = RGFormsModel::prepare_value( $form, $field, $value, $input_name, $this->entry['id'] );
432
                        }
433
434
                        break;
435
                    case 'post_custom_field':
436
437
                        $input_type = RGFormsModel::get_input_type( $field );
438
                        $custom_field_name = $field_array['postCustomFieldName'];
439
440
                        // Only certain custom field types are supported
441
                        if( !in_array( $input_type, array( 'list', 'fileupload' ) ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
442
                            update_post_meta( $post_id, $custom_field_name, $value );
443
                        }
444
445
                        break;
446
447
                    case 'post_image':
448
449
                        $value = '';
450
                        break;
451
452
                }
453
454
                //ignore fields that have not changed
455
                if ( $value === rgget( (string) $field_id, $this->entry ) ) {
456
                    continue;
457
                }
458
459
                // update entry
460
                if( 'post_category' !== $field->type ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
461
                    $this->entry[ strval( $field_id ) ] = $value;
462
                }
463
464
                $update_entry = true;
465
466
            }
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
467
468
        }
469
470
        if( $update_entry ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
471
472
            $return_entry = GFAPI::update_entry( $this->entry );
473
474
            if( is_wp_error( $return_entry ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
475
                do_action( 'gravityview_log_error', 'Updating the entry post fields failed', $return_entry );
476
            } else {
477
                do_action( 'gravityview_log_debug', 'Updating the entry post fields for post #'.$post_id.' succeeded' );
478
            }
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
479
480
        }
481
482
        $return_post = wp_update_post( $updated_post, true );
483
484
        if( is_wp_error( $return_post ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
485
            do_action( 'gravityview_log_error', 'Updating the post content failed', $return_post );
486
        } else {
487
            do_action( 'gravityview_log_debug', 'Updating the post content for post #'.$post_id.' succeeded' );
488
        }
489
490
    }
491
492
    /**
493
     * Perform actions normally performed after updating a lead
494
     *
495
     * @since 1.8
496
     *
497
     * @see GFEntryDetail::lead_detail_page()
498
     *
499
     * @return void
500
     */
501
    function after_update() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
502
503
        do_action( 'gform_after_update_entry', $this->form, $this->entry['id'] );
504
        do_action( "gform_after_update_entry_{$this->form['id']}", $this->form, $this->entry['id'] );
505
506
        // Re-define the entry now that we've updated it.
507
        $entry = RGFormsModel::get_lead( $this->entry['id'] );
508
509
        $entry = GFFormsModel::set_entry_meta( $entry, $this->form );
510
511
        // We need to clear the cache because Gravity Forms caches the field values, which
512
        // we have just updated.
513
        foreach ($this->form['fields'] as $key => $field) {
0 ignored issues
show
introduced by
No space after opening parenthesis is prohibited
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
514
            GFFormsModel::refresh_lead_field_value( $entry['id'], $field->id );
515
        }
516
517
        $this->entry = $entry;
518
    }
519
520
521
    /**
522
     * Display the Edit Entry form
523
     *
524
     * @return [type] [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
525
     */
526
    public function edit_entry_form() {
527
528
        $back_link = esc_url( remove_query_arg( array( 'page', 'view', 'edit' ) ) );
529
530
        ?>
531
532
        <div class="gv-edit-entry-wrapper"><?php
533
534
            $javascript = gravityview_ob_include( GravityView_Edit_Entry::$file .'/partials/inline-javascript.php', $this );
0 ignored issues
show
Bug introduced by
The property file cannot be accessed from this context as it is declared private in class GravityView_Edit_Entry.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
535
536
            /**
537
             * Fixes weird wpautop() issue
538
             * @see https://github.com/katzwebservices/GravityView/issues/451
539
             */
540
            echo gravityview_strip_whitespace( $javascript );
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'gravityview_strip_whitespace'
Loading history...
541
542
            ?><h2 class="gv-edit-entry-title">
543
                <span><?php
544
545
                    /**
546
                     * @filter `gravityview_edit_entry_title` Modify the edit entry title
547
                     * @param string $edit_entry_title Modify the "Edit Entry" title
548
                     * @param GravityView_Edit_Entry_Render $this This object
549
                     */
550
                    $edit_entry_title = apply_filters('gravityview_edit_entry_title', __('Edit Entry', 'gravityview'), $this );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
551
552
                    echo esc_attr( $edit_entry_title );
553
            ?></span>
554
            </h2>
555
556
            <?php
557
558
            // Display the success message
559
            if( rgpost('action') === 'update' ) {
0 ignored issues
show
introduced by
Found "=== '". Use Yoda Condition checks, you must
Loading history...
introduced by
Space after opening control structure is required
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
560
561
                if( ! $this->is_valid ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->is_valid of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
introduced by
Space after opening control structure is required
Loading history...
562
563
                    // Keeping this compatible with Gravity Forms.
564
                    $validation_message = "<div class='validation_error'>" . __('There was a problem with your submission.', 'gravityview') . " " . __('Errors have been highlighted below.', 'gravityview') . "</div>";
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
Coding Style Comprehensibility introduced by
The string literal does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw '__'
Loading history...
Coding Style Comprehensibility introduced by
The string literal </div> does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
565
                    $message = apply_filters("gform_validation_message_{$this->form['id']}", apply_filters("gform_validation_message", $validation_message, $this->form), $this->form);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
Coding Style Comprehensibility introduced by
The string literal gform_validation_message does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
566
567
                    echo GVCommon::generate_notice( $message , 'gv-error' );
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'GVCommon'
Loading history...
568
569
                } else {
570
                    $entry_updated_message = sprintf( esc_attr__('Entry Updated. %sReturn to Entry%s', 'gravityview'), '<a href="'. $back_link .'">', '</a>' );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
571
572
                    /**
573
                     * @filter `gravityview/edit_entry/success` Modify the edit entry success message (including the anchor link)
574
                     * @since 1.5.4
575
                     * @param string $entry_updated_message Existing message
576
                     * @param int $view_id View ID
577
                     * @param array $entry Gravity Forms entry array
578
                     * @param string $back_link URL to return to the original entry. @since 1.6
579
                     */
580
                    $message = apply_filters( 'gravityview/edit_entry/success', $entry_updated_message , $this->view_id, $this->entry, $back_link );
581
582
                    echo GVCommon::generate_notice( $message );
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'GVCommon'
Loading history...
583
                }
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
584
585
            }
586
587
            ?>
588
589
            <?php // The ID of the form needs to be `gform_{form_id}` for the pluploader ?>
590
591
            <form method="post" id="gform_<?php echo $this->form_id; ?>" enctype="multipart/form-data">
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$this'
Loading history...
592
593
                <?php
594
595
                wp_nonce_field( self::$nonce_key, self::$nonce_key );
596
597
                wp_nonce_field( self::$nonce_field, self::$nonce_field, false );
598
599
                // Most of this is needed for GFFormDisplay::validate(), but `gform_unique_id` is needed for file cleanup.
600
601
                ?>
602
603
604
                <?php
605
606
                /**
607
                 * By default, the lead_detail_edit method uses the `RGFormsModel::get_lead_field_value()` method, which doesn't fill in $_POST values when there is a validation error, because it was designed to work in the admin. We want to use the `RGFormsModel::get_field_value()` If the form has been submitted, use the values for the fields.
608
                 */
609
                //add_filter( 'gform_get_field_value', array( $this, 'get_field_value' ), 10, 3 );
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
610
611
                // Print the actual form HTML
612
                $this->render_edit_form();
613
614
                //echo $this->render_form_buttons();
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
615
616
                ?>
617
            </form>
618
619
        </div>
620
621
    <?php
622
    }
623
624
    /**
625
     * Display the Edit Entry form in the original Gravity Forms format
626
     *
627
     * @since 1.9
628
     *
629
     * @param $form
630
     * @param $lead
631
     * @param $view_id
632
     *
633
     * @return void
634
     */
635
    private function render_edit_form() {
636
637
        add_filter( 'gform_pre_render', array( $this, 'filter_modify_form_fields'), 5000, 3 );
0 ignored issues
show
introduced by
No space before closing parenthesis of array is bad style
Loading history...
638
        add_filter( 'gform_submit_button', array( $this, 'render_form_buttons') );
0 ignored issues
show
introduced by
No space before closing parenthesis of array is bad style
Loading history...
639
        add_filter( 'gform_disable_view_counter', '__return_true' );
640
        add_filter( 'gform_field_input', array( $this, 'modify_edit_field_input' ), 10, 5 );
641
642
        // We need to remove the fake $_GET['page'] arg to avoid rendering form as if in admin.
643
        unset( $_GET['page'] );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
644
645
        // TODO: Make sure validation isn't handled by GF
646
        // TODO: Include CSS for file upload fields
647
        // TODO: Verify multiple-page forms
648
        // TODO: Product fields are not editable
649
        // TODO: Check Updated and Error messages
650
651
        $html = GFFormDisplay::get_form( $this->form['id'], false, false, true, $this->entry );
652
653
	    remove_filter( 'gform_pre_render', array( $this, 'filter_modify_form_fields' ), 5000 );
654
        remove_filter( 'gform_submit_button', array( $this, 'render_form_buttons' ) );
655
        remove_filter( 'gform_disable_view_counter', '__return_true' );
656
        remove_filter( 'gform_field_input', array( $this, 'modify_edit_field_input' ), 10 );
657
658
        echo $html;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$html'
Loading history...
659
    }
660
661
    /**
662
     * Display the Update/Cancel/Delete buttons for the Edit Entry form
663
     * @since 1.8
664
     * @return string
665
     */
666
    public function render_form_buttons() {
667
        return gravityview_ob_include( GravityView_Edit_Entry::$file .'/partials/form-buttons.php', $this );
0 ignored issues
show
Bug introduced by
The property file cannot be accessed from this context as it is declared private in class GravityView_Edit_Entry.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
668
    }
669
670
671
    /**
672
     * Modify the form fields that are shown when using GFFormDisplay::get_form()
673
     *
674
     * By default, all fields will be shown. We only want the Edit Tab configured fields to be shown.
675
     *
676
     * @param array $form
677
     * @param boolean $ajax Whether in AJAX mode
678
     * @param array|string $field_values Passed parameters to the form
679
     *
680
     * @since 1.9
681
     *
682
     * @return array Modified form array
683
     */
684
    public function filter_modify_form_fields( $form, $ajax = false, $field_values = '' ) {
0 ignored issues
show
Unused Code introduced by
The parameter $ajax is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $field_values is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
685
686
        // In case we have validated the form, use it to inject the validation results into the form render
687
        if( isset( $this->form_after_validation ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
688
            $form = $this->form_after_validation;
689
        } else {
690
            $form['fields'] = $this->get_configured_edit_fields( $form, $this->view_id );
691
        }
692
693
        $form = $this->filter_conditional_logic( $form );
694
695
        // for now we don't support Save and Continue feature.
696
        if( ! self::$supports_save_and_continue ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
697
	        unset( $form['save'] );
698
        }
699
700
        return $form;
701
    }
702
703
704
    /**
705
     *
706
     * Fill-in the saved values into the form inputs
707
     *
708
     * @param string $field_content Always empty.
709
     * @param GF_Field $field
710
     * @param string|array $value If array, it's a field with multiple inputs. If string, single input.
711
     * @param int $lead_id Lead ID. Always 0 for the `gform_field_input` filter.
712
     * @param int $form_id Form ID
713
     *
714
     * @return mixed
715
     */
716
    function modify_edit_field_input( $field_content = '', $field, $value, $lead_id = 0, $form_id ) {
0 ignored issues
show
Unused Code introduced by
The parameter $lead_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $form_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
717
718
        // If the form has been submitted, then we don't need to pre-fill the values,
719
        // Except for fileupload type - run always!!
720
        if(
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
721
	        $this->is_edit_entry_submission() && 'fileupload' !== $field->type
722
        ||  GFCommon::is_product_field( $field->type ) // Prevent product fields from appearing editable
723
        ) {
724
	        return $field_content;
725
        }
726
727
        // Turn on Admin-style display for file upload fields only
728
        if( 'fileupload' === $field->type ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
729
            $_GET['page'] = 'gf_entries';
730
        }
731
732
        // SET SOME FIELD DEFAULTS TO PREVENT ISSUES
733
        $field->adminOnly = false; /** @see GFFormDisplay::get_counter_init_script() need to prevent adminOnly */
734
735
        // add categories as choices for Post Category field
736
        if ( 'post_category' === $field->type ) {
737
            $field = GFCommon::add_categories_as_choices( $field, $value );
738
        }
739
740
        /**
741
         * @filter `gravityview/edit_entry/pre_populate/override` Allow the pre-populated value to override saved value in Edit Entry form. By default, pre-populate mechanism only kicks on empty fields.
742
         * @param boolean True: override saved values; False: don't override (default)
743
         * @param $field GF_Field object Gravity Forms field object
744
         * @since 1.13
745
         */
746
        $override_saved_value = apply_filters( 'gravityview/edit_entry/pre_populate/override', false, $field );
747
748
        // We're dealing with multiple inputs (e.g. checkbox) but not time or date (as it doesn't store data in input IDs)
749
        if( isset( $field->inputs ) && is_array( $field->inputs ) && !in_array( $field->type, array( 'time', 'date' ) ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
750
751
            $field_value = array();
752
753
            // only accept pre-populated values if the field doesn't have any choice selected.
754
            $allow_pre_populated = $field->allowsPrepopulate;
755
756
	        foreach ( (array)$field->inputs as $input ) {
0 ignored issues
show
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
757
758
	            $input_id = strval( $input['id'] );
759
760
                if ( ! empty( $this->entry[ $input_id ] ) ) {
761
                    $field_value[ $input_id ] =  'post_category' === $field->type ? GFCommon::format_post_category( $this->entry[ $input_id ], true ) : $this->entry[ $input_id ];
0 ignored issues
show
introduced by
Expected 1 space after "="; 2 found
Loading history...
762
                    $allow_pre_populated = false;
763
                }
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
764
765
            }
766
767
            $pre_value = $field->get_value_submission( array(), false );
768
769
            $field_value = ! $allow_pre_populated && ! ( $override_saved_value && !empty( $pre_value ) ) ? $field_value : $pre_value;
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
770
771
        } else {
772
773
            $id = intval( $field->id );
774
775
            // get pre-populated value if exists
776
            $pre_value = $field->allowsPrepopulate ? GFFormsModel::get_parameter_value( $field->inputName, array(), $field ) : '';
777
778
            // saved field entry value (if empty, fallback to the pre-populated value, if exists)
779
            // or pre-populated value if not empty and set to override saved value
780
            $field_value = !empty( $this->entry[ $id ] ) && ! ( $override_saved_value && !empty( $pre_value ) ) ? $this->entry[ $id ] : $pre_value;
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
781
782
            // in case field is post_category but inputType is select, multi-select or radio, convert value into array of category IDs.
783
            if ( 'post_category' === $field->type && !empty( $field_value ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
784
                $categories = array();
785
                foreach ( explode( ',', $field_value ) as $cat_string ) {
786
                    $categories[] = GFCommon::format_post_category( $cat_string, true );
787
                }
788
                $field_value = 'multiselect' === $field->get_input_type() ? $categories : implode( '', $categories );
789
            }
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
790
791
        }
792
793
        // if value is empty get the default value if defined
794
        $field_value = $field->get_value_default_if_empty( $field_value );
795
796
        /**
797
         * @filter `gravityview/edit_entry/field_value` Change the value of an Edit Entry field, if needed
798
         * @since 1.11
799
         * @param mixed $field_value field value used to populate the input
800
         * @param object $field Gravity Forms field object ( Class GF_Field )
801
         */
802
        $field_value = apply_filters( 'gravityview/edit_entry/field_value', $field_value, $field );
803
804
	    // Prevent any PHP warnings, like undefined index
805
	    ob_start();
806
807
	    $return = $field->get_field_input( $this->form, $field_value, $this->entry );
808
809
	    // If there was output, it's an error
810
	    $warnings = ob_get_clean();
811
812
	    if( !empty( $warnings ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
813
		    do_action( 'gravityview_log_error', __METHOD__ . $warnings, $field_value );
814
	    }
815
816
        /**
817
         * Unset hack $_GET['page'] = 'gf_entries'
818
         * We need the fileupload html field to render with the proper id
819
         *  ( <li id="field_80_16" ... > )
820
         */
821
        unset( $_GET['page'] );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
822
823
        return $return;
824
    }
825
826
827
    /**
828
     * Get the posted values from the edit form submission
829
     *
830
     * @hack
831
     * @uses GFFormsModel::get_field_value()
832
     * @param  mixed $value Existing field value, before edit
833
     * @param  array $lead  Gravity Forms entry array
834
     * @param  array $field Gravity Forms field array
835
     * @return string        [description]
836
     */
837
    public function get_field_value( $value, $lead, $field ) {
838
839
        // The form's not being edited; use the original value
840
        if( ! $this->is_edit_entry_submission() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
841
            return $value;
842
        }
843
844
        return GFFormsModel::get_field_value( $field, $lead, true );
845
    }
846
847
848
849
850
    // ---- Entry validation
851
852
    /**
853
     * Add field keys that Gravity Forms expects.
854
     *
855
     * @see GFFormDisplay::validate()
856
     * @param  array $form GF Form
857
     * @return array       Modified GF Form
858
     */
859
    function gform_pre_validation( $form ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
860
861
        if( ! $this->verify_nonce() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
862
            return $form;
863
        }
864
865
        // Fix PHP warning regarding undefined index.
866
        foreach ( $form['fields'] as &$field) {
0 ignored issues
show
introduced by
No space before closing parenthesis is prohibited
Loading history...
867
868
            // This is because we're doing admin form pretending to be front-end, so Gravity Forms
869
            // expects certain field array items to be set.
870
            foreach ( array( 'noDuplicates', 'adminOnly', 'inputType', 'isRequired', 'enablePrice', 'inputs', 'allowedExtensions' ) as $key ) {
871
	            $field->{$key} = isset( $field->{$key} ) ? $field->{$key} : NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
872
            }
873
874
            // unset emailConfirmEnabled for email type fields
875
           /* if( 'email' === $field['type'] && !empty( $field['emailConfirmEnabled'] ) ) {
1 ignored issue
show
Unused Code Comprehensibility introduced by
61% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 3 tabs, found 2
Loading history...
876
                $field['emailConfirmEnabled'] = '';
877
            }*/
878
879
            switch( RGFormsModel::get_input_type( $field ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
880
881
                /**
882
                 * this whole fileupload hack is because in the admin, Gravity Forms simply doesn't update any fileupload field if it's empty, but it DOES in the frontend.
883
                 *
884
                 * What we have to do is set the value so that it doesn't get overwritten as empty on save and appears immediately in the Edit Entry screen again.
885
                 *
886
                 * @hack
887
                 */
888
                case 'fileupload':
889
                case 'post_image':
890
891
                    // Set the previous value
892
                    $entry = $this->get_entry();
893
894
                    $input_name = 'input_'.$field->id;
895
                    $form_id = $form['id'];
896
897
                    $value = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
898
899
                    // Use the previous entry value as the default.
900
                    if( isset( $entry[ $field->id ] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
901
                        $value = $entry[ $field->id ];
902
                    }
903
904
                    // If this is a single upload file
905
                    if( !empty( $_FILES[ $input_name ] ) && !empty( $_FILES[ $input_name ]['name'] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
906
                        $file_path = GFFormsModel::get_file_upload_path( $form['id'], $_FILES[ $input_name ]['name'] );
907
                        $value = $file_path['url'];
908
909
                    } else {
910
911
                        // Fix PHP warning on line 1498 of form_display.php for post_image fields
912
                        // Fix PHP Notice:  Undefined index:  size in form_display.php on line 1511
913
                        $_FILES[ $input_name ] = array('name' => '', 'size' => '' );
0 ignored issues
show
introduced by
No space after opening parenthesis of array is bad style
Loading history...
914
915
                    }
916
917
                    if( rgar($field, "multipleFiles") ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
Coding Style Comprehensibility introduced by
The string literal multipleFiles does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
918
919
                        // If there are fresh uploads, process and merge them.
920
                        // Otherwise, use the passed values, which should be json-encoded array of URLs
921
                        if( isset( GFFormsModel::$uploaded_files[$form_id][$input_name] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Array keys should be surrounded by spaces unless they contain a string or an integer.
Loading history...
922
923
                            $value = empty( $value ) ? '[]' : $value;
924
                            $value = stripslashes_deep( $value );
925
                            $value = GFFormsModel::prepare_value( $form, $field, $value, $input_name, $entry['id'], array());
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
926
                        }
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
927
928
                    } else {
929
930
                        // A file already exists when editing an entry
931
                        // We set this to solve issue when file upload fields are required.
932
                        GFFormsModel::$uploaded_files[ $form_id ][ $input_name ] = $value;
933
934
                    }
935
936
                    $_POST[ $input_name ] = $value;
937
938
                    break;
939
                case 'number':
940
                    // Fix "undefined index" issue at line 1286 in form_display.php
941
                    if( !isset( $_POST['input_'.$field->id ] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
introduced by
Array keys should be surrounded by spaces unless they contain a string or an integer.
Loading history...
942
                        $_POST['input_'.$field->id ] = NULL;
0 ignored issues
show
introduced by
Array keys should be surrounded by spaces unless they contain a string or an integer.
Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
943
                    }
944
                    break;
945
                case 'captcha':
946
                    // Fix issue with recaptcha_check_answer() on line 1458 in form_display.php
947
                    $_POST['recaptcha_challenge_field'] = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
948
                    $_POST['recaptcha_response_field'] = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
949
                    break;
950
            }
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
951
952
        }
953
954
        return $form;
955
    }
956
957
958
    /**
959
     * Process validation for a edit entry submission
960
     *
961
     * Sets the `is_valid` object var
962
     *
963
     * @return void
964
     */
965
    function validate() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
966
967
        // If using GF User Registration Add-on, remove the validation step, otherwise generates error when updating the entry
968
        if ( class_exists( 'GFUser' ) ) {
969
            remove_filter( 'gform_validation', array( 'GFUser', 'user_registration_validation' ) );
970
        }
971
972
        /**
973
         * For some crazy reason, Gravity Forms doesn't validate Edit Entry form submissions.
974
         * You can enter whatever you want!
975
         * We try validating, and customize the results using `self::custom_validation()`
976
         */
977
        add_filter( 'gform_validation_'. $this->form_id, array( $this, 'custom_validation' ), 10, 4);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
978
979
        // Needed by the validate funtion
980
        $failed_validation_page = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
981
        $field_values = RGForms::post( 'gform_field_values' );
982
983
        // Prevent entry limit from running when editing an entry, also
984
        // prevent form scheduling from preventing editing
985
        unset( $this->form['limitEntries'], $this->form['scheduleForm'] );
986
987
        // Hide fields depending on Edit Entry settings
988
        $this->form['fields'] = $this->get_configured_edit_fields( $this->form, $this->view_id );
989
990
        $this->is_valid = GFFormDisplay::validate( $this->form, $field_values, 1, $failed_validation_page );
991
992
        remove_filter( 'gform_validation_'.$this->form_id, array( $this, 'custom_validation' ), 10 );
993
    }
994
995
996
    /**
997
     * Make validation work for Edit Entry
998
     *
999
     * Because we're calling the GFFormDisplay::validate() in an unusual way (as a front-end
1000
     * form pretending to be a back-end form), validate() doesn't know we _can't_ edit post
1001
     * fields. This goes through all the fields and if they're an invalid post field, we
1002
     * set them as valid. If there are still issues, we'll return false.
1003
     *
1004
     * @param  [type] $validation_results [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1005
     * @return [type]                     [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1006
     */
1007
    function custom_validation( $validation_results ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1008
1009
        do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] Validation results: ', $validation_results );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
1010
1011
        do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] $_POSTed data (sanitized): ', esc_html( print_r( $_POST, true ) ) );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
introduced by
The use of function print_r() is discouraged
Loading history...
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
1012
1013
        $gv_valid = true;
1014
1015
        foreach ( $validation_results['form']['fields'] as $key => &$field ) {
1016
1017
            $value = RGFormsModel::get_field_value( $field );
1018
            $field_type = RGFormsModel::get_input_type( $field );
1019
1020
            // Validate always
1021
            switch ( $field_type ) {
1022
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1023
1024
                case 'fileupload' :
1025
1026
                    // in case nothing is uploaded but there are already files saved
1027
                    if( !empty( $field->failed_validation ) && !empty( $field->isRequired ) && !empty( $value ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
1028
                        $field->failed_validation = false;
1029
                        unset( $field->validation_message );
1030
                    }
1031
1032
                    // validate if multi file upload reached max number of files [maxFiles] => 2
1033
                    if( rgar( $field, 'maxFiles') && rgar( $field, 'multipleFiles') ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
1034
1035
                        $input_name = 'input_' . $field->id;
1036
                        //uploaded
1037
                        $file_names = isset( GFFormsModel::$uploaded_files[ $validation_results['form']['id'] ][ $input_name ] ) ? GFFormsModel::$uploaded_files[ $validation_results['form']['id'] ][ $input_name ] : array();
1038
1039
                        //existent
1040
                        $entry = $this->get_entry();
1041
                        $value = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
1042
                        if( isset( $entry[ $field->id ] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1043
                            $value = json_decode( $entry[ $field->id ], true );
1044
                        }
1045
1046
                        // count uploaded files and existent entry files
1047
                        $count_files = count( $file_names ) + count( $value );
1048
1049
                        if( $count_files > $field->maxFiles ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1050
                            $field->validation_message = __( 'Maximum number of files reached', 'gravityview' );
1051
                            $field->failed_validation = 1;
1052
                            $gv_valid = false;
1053
1054
                            // in case of error make sure the newest upload files are removed from the upload input
1055
                            GFFormsModel::$uploaded_files[ $validation_results['form']['id'] ] = null;
1056
                        }
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
1057
1058
                    }
1059
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1060
1061
                    break;
1062
1063
            }
1064
1065
            // This field has failed validation.
1066
            if( !empty( $field->failed_validation ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
1067
1068
                do_action( 'gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] Field is invalid.', array( 'field' => $field, 'value' => $value ) );
1069
1070
                switch ( $field_type ) {
1071
1072
                    // Captchas don't need to be re-entered.
1073
                    case 'captcha':
1074
1075
                        // Post Image fields aren't editable, so we un-fail them.
1076
                    case 'post_image':
1077
                        $field->failed_validation = false;
1078
                        unset( $field->validation_message );
1079
                        break;
1080
1081
                }
1082
1083
                // You can't continue inside a switch, so we do it after.
1084
                if( empty( $field->failed_validation ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1085
                    continue;
1086
                }
1087
1088
                // checks if the No Duplicates option is not validating entry against itself, since
1089
                // we're editing a stored entry, it would also assume it's a duplicate.
1090
                if( !empty( $field->noDuplicates ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
1091
1092
                    $entry = $this->get_entry();
1093
1094
                    // If the value of the entry is the same as the stored value
1095
                    // Then we can assume it's not a duplicate, it's the same.
1096
                    if( !empty( $entry ) && $value == $entry[ $field->id ] ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
1097
                        //if value submitted was not changed, then don't validate
1098
                        $field->failed_validation = false;
1099
1100
                        unset( $field->validation_message );
1101
1102
                        do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] Field not a duplicate; it is the same entry.', $entry );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
1103
1104
                        continue;
1105
                    }
1106
                }
1107
1108
                // if here then probably we are facing the validation 'At least one field must be filled out'
1109
                if( GFFormDisplay::is_empty( $field, $this->form_id  ) && empty( $field->isRequired ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 2 found
Loading history...
1110
                    unset( $field->validation_message );
1111
	                $field->validation_message = false;
1112
                    continue;
1113
                }
1114
1115
                $gv_valid = false;
1116
1117
            }
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
1118
1119
        }
1120
1121
        $validation_results['is_valid'] = $gv_valid;
1122
1123
        do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] Validation results.', $validation_results );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
1124
1125
        // We'll need this result when rendering the form ( on GFFormDisplay::get_form )
1126
        $this->form_after_validation = $validation_results['form'];
1127
1128
        return $validation_results;
1129
    }
1130
1131
1132
    /**
1133
     * TODO: This seems to be hacky... we should remove it. Entry is set when updating the form using setup_vars()!
1134
     * Get the current entry and set it if it's not yet set.
1135
     * @return array Gravity Forms entry array
1136
     */
1137
    private function get_entry() {
1138
1139
        if( empty( $this->entry ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1140
            // Get the database value of the entry that's being edited
1141
            $this->entry = gravityview_get_entry( GravityView_frontend::is_single_entry() );
1142
        }
1143
1144
        return $this->entry;
1145
    }
1146
1147
1148
1149
    // --- Filters
1150
1151
    /**
1152
     * Get the Edit Entry fields as configured in the View
1153
     *
1154
     * @since 1.8
1155
     *
1156
     * @param int $view_id
1157
     *
1158
     * @return array Array of fields that are configured in the Edit tab in the Admin
1159
     */
1160
    private function get_configured_edit_fields( $form, $view_id ) {
1161
1162
        // Get all fields for form
1163
        $properties = GravityView_View_Data::getInstance()->get_fields( $view_id );
1164
1165
        // If edit tab not yet configured, show all fields
1166
        $edit_fields = !empty( $properties['edit_edit-fields'] ) ? $properties['edit_edit-fields'] : NULL;
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
1167
1168
	    // Show hidden fields as text fields
1169
	    $form = $this->fix_hidden_fields( $form );
1170
1171
        // Hide fields depending on admin settings
1172
        $fields = $this->filter_fields( $form['fields'], $edit_fields );
1173
1174
	    // If Edit Entry fields are configured, remove adminOnly field settings. Otherwise, don't.
1175
	    $fields = $this->filter_admin_only_fields( $fields, $edit_fields, $form, $view_id );
1176
1177
        return $fields;
1178
    }
1179
1180
	/**
1181
	 * @since 1.9.2
1182
	 *
1183
	 * @param $fields
1184
	 *
1185
	 * @return mixed
1186
	 */
1187
	private function fix_hidden_fields( $form ) {
1188
1189
		/** @var GF_Field $field */
1190
		foreach( $form['fields'] as $key => $field ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1191
			if( 'hidden' === $field->type ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1192
				$text_field = new GF_Field_Text( $field );
1193
				$text_field->type = 'text';
1194
				$form['fields'][ $key ] = $text_field;
1195
			}
1196
		}
1197
1198
		return $form;
1199
	}
1200
1201
1202
    /**
1203
     * Filter area fields based on specified conditions
1204
     *
1205
     * @uses GravityView_Edit_Entry::user_can_edit_field() Check caps
1206
     * @access private
1207
     * @param GF_Field[] $fields
1208
     * @param array $configured_fields
1209
     * @since  1.5
1210
     * @return array $fields
1211
     */
1212
    private function filter_fields( $fields, $configured_fields ) {
1213
1214
        if( empty( $fields ) || !is_array( $fields ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
1215
            return $fields;
1216
        }
1217
1218
        $edit_fields = array();
1219
1220
        $field_type_blacklist = array(
1221
            'page',
1222
        );
1223
1224
	    /**
1225
	     * @filter `gravityview/edit_entry/hide-product-fields` Hide product fields from being editable.
1226
	     * @since 1.9.1
1227
         * @param boolean $hide_product_fields Whether to hide product fields in the editor.  Default: false
1228
	     */
1229
	    $hide_product_fields = apply_filters( 'gravityview/edit_entry/hide-product-fields', empty( self::$supports_product_fields ) );
1230
1231
	    if( $hide_product_fields ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1232
		    $field_type_blacklist[] = 'option';
1233
		    $field_type_blacklist[] = 'quantity';
1234
            $field_type_blacklist[] = 'product';
1235
            $field_type_blacklist[] = 'total';
1236
            $field_type_blacklist[] = 'shipping';
1237
            $field_type_blacklist[] = 'calculation';
1238
	    }
1239
1240
        // First, remove blacklist
1241
        foreach ( $fields as $key => $field ) {
1242
            if( in_array( $field->type, $field_type_blacklist ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1243
                unset( $fields[ $key ] );
1244
            }
1245
        }
1246
1247
        // The Edit tab has not been configured, so we return all fields by default.
1248
        if( empty( $configured_fields ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1249
            return $fields;
1250
        }
1251
1252
        // The edit tab has been configured, so we loop through to configured settings
1253
        foreach ( $configured_fields as $configured_field ) {
1254
1255
	        /** @var GF_Field $field */
1256
	        foreach ( $fields as $field ) {
1257
1258
                if( intval( $configured_field['id'] ) === intval( $field->id ) && $this->user_can_edit_field( $configured_field, false ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1259
                    $edit_fields[] = $this->merge_field_properties( $field, $configured_field );
1260
                    break;
1261
                }
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
1262
1263
            }
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
1264
1265
        }
1266
1267
        return $edit_fields;
1268
1269
    }
1270
1271
    /**
1272
     * Override GF Form field properties with the ones defined on the View
1273
     * @param  GF_Field $field GF Form field object
1274
     * @param  array $setting  GV field options
0 ignored issues
show
Documentation introduced by
There is no parameter named $setting. Did you maybe mean $field_setting?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
1275
     * @since  1.5
1276
     * @return array
1277
     */
1278
    private function merge_field_properties( $field, $field_setting ) {
1279
1280
        $return_field = $field;
1281
1282
        if( empty( $field_setting['show_label'] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1283
            $return_field->label = '';
1284
        } elseif ( !empty( $field_setting['custom_label'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
1285
            $return_field->label = $field_setting['custom_label'];
1286
        }
1287
1288
        if( !empty( $field_setting['custom_class'] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
1289
            $return_field->cssClass .= ' '. gravityview_sanitize_html_class( $field_setting['custom_class'] );
1290
        }
1291
1292
        /**
1293
         * Normalize page numbers - avoid conflicts with page validation
1294
         * @since 1.6
1295
         */
1296
        $return_field->pageNumber = 1;
1297
1298
        return $return_field;
1299
1300
    }
1301
1302
    /**
1303
     * Remove fields that shouldn't be visible based on the Gravity Forms adminOnly field property
1304
     *
1305
     * @since 1.9.1
1306
     *
1307
     * @param array|GF_Field[] $fields Gravity Forms form fields
1308
     * @param array|null $edit_fields Fields for the Edit Entry tab configured in the View Configuration
1309
     * @param array $form GF Form array
1310
     * @param int $view_id View ID
1311
     *
1312
     * @return array Possibly modified form array
1313
     */
1314
    function filter_admin_only_fields( $fields = array(), $edit_fields = null, $form = array(), $view_id = 0 ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1315
1316
	    /**
1317
         * @filter `gravityview/edit_entry/use_gf_admin_only_setting` When Edit tab isn't configured, should the Gravity Forms "Admin Only" field settings be used to control field display to non-admins? Default: true
1318
	     * If the Edit Entry tab is not configured, adminOnly fields will not be shown to non-administrators.
1319
	     * If the Edit Entry tab *is* configured, adminOnly fields will be shown to non-administrators, using the configured GV permissions
1320
	     * @since 1.9.1
1321
	     * @param boolean $use_gf_adminonly_setting True: Hide field if set to Admin Only in GF and the user is not an admin. False: show field based on GV permissions, ignoring GF permissions.
1322
	     * @param array $form GF Form array
1323
	     * @param int $view_id View ID
1324
	     */
1325
	    $use_gf_adminonly_setting = apply_filters( 'gravityview/edit_entry/use_gf_admin_only_setting', empty( $edit_fields ), $form, $view_id );
1326
1327
	    if( $use_gf_adminonly_setting && false === GVCommon::has_cap( 'gravityforms_edit_entries', $this->entry['id'] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1328
            return $fields;
1329
        }
1330
1331
	    foreach( $fields as &$field ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1332
		    $field->adminOnly = false;
1333
        }
1334
1335
        return $fields;
1336
    }
1337
1338
    // --- Conditional Logic
1339
1340
    /**
1341
     * Remove the conditional logic rules from the form button and the form fields, if needed.
1342
     *
1343
     * @since 1.9
1344
     *
1345
     * @param array $form Gravity Forms form
1346
     * @return array Modified form, if not using Conditional Logic
1347
     */
1348
    function filter_conditional_logic( $form ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1349
1350
        /**
1351
         * @filter `gravityview/edit_entry/conditional_logic` Should the Edit Entry form use Gravity Forms conditional logic showing/hiding of fields?
1352
         * @since 1.9
1353
         * @param bool $use_conditional_logic True: Gravity Forms will show/hide fields just like in the original form; False: conditional logic will be disabled and fields will be shown based on configuration. Default: true
1354
         * @param array $form Gravity Forms form
1355
         */
1356
        $use_conditional_logic = apply_filters( 'gravityview/edit_entry/conditional_logic', true, $form );
1357
1358
        if( $use_conditional_logic ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1359
            return $form;
1360
        }
1361
1362
        foreach( $form['fields'] as &$field ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1363
            /* @var GF_Field $field */
1364
            $field->conditionalLogic = null;
1365
        }
1366
1367
        unset( $form['button']['conditionalLogic'] );
1368
1369
        return $form;
1370
1371
    }
1372
1373
    /**
1374
     * Disable the Gravity Forms conditional logic script and features on the Edit Entry screen
1375
     *
1376
     * @since 1.9
1377
     *
1378
     * @param $has_conditional_logic
1379
     * @param $form
1380
     * @return mixed|void
1381
     */
1382
    function manage_conditional_logic( $has_conditional_logic, $form ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1383
1384
        if( ! $this->is_edit_entry() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1385
            return $has_conditional_logic;
1386
        }
1387
1388
        return apply_filters( 'gravityview/edit_entry/conditional_logic', $has_conditional_logic, $form );
1389
1390
    }
1391
1392
1393
    // --- User checks and nonces
1394
1395
    /**
1396
     * Check if the user can edit the entry
1397
     *
1398
     * - Is the nonce valid?
1399
     * - Does the user have the right caps for the entry
1400
     * - Is the entry in the trash?
1401
     *
1402
     * @todo Move to GVCommon
1403
     *
1404
     * @param  boolean $echo Show error messages in the form?
1405
     * @return boolean        True: can edit form. False: nope.
1406
     */
1407
    function user_can_edit_entry( $echo = false ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1408
1409
        $error = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
1410
1411
        /**
1412
         *  1. Permalinks are turned off
1413
         *  2. There are two entries embedded using oEmbed
1414
         *  3. One of the entries has just been saved
1415
         */
1416
        if( !empty( $_POST['lid'] ) && !empty( $_GET['entry'] ) && ( $_POST['lid'] !== $_GET['entry'] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
1417
1418
            $error = true;
1419
1420
        }
1421
1422
        if( !empty( $_GET['entry'] ) && (string)$this->entry['id'] !== $_GET['entry'] ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
1423
1424
            $error = true;
1425
1426
        } elseif( ! $this->verify_nonce() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1427
1428
            /**
1429
             * If the Entry is embedded, there may be two entries on the same page.
1430
             * If that's the case, and one is being edited, the other should fail gracefully and not display an error.
1431
             */
1432
            if( GravityView_oEmbed::getInstance()->get_entry_id() ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression \GravityView_oEmbed::get...tance()->get_entry_id() of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
introduced by
Space after opening control structure is required
Loading history...
1433
                $error = true;
1434
            } else {
1435
                $error = __( 'The link to edit this entry is not valid; it may have expired.', 'gravityview');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
1436
            }
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
1437
1438
        }
1439
1440
        if( ! GravityView_Edit_Entry::check_user_cap_edit_entry( $this->entry ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1441
            $error = __( 'You do not have permission to edit this entry.', 'gravityview');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
1442
        }
1443
1444
        if( $this->entry['status'] === 'trash' ) {
0 ignored issues
show
introduced by
Found "=== '". Use Yoda Condition checks, you must
Loading history...
introduced by
Space after opening control structure is required
Loading history...
1445
            $error = __('You cannot edit the entry; it is in the trash.', 'gravityview' );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
1446
        }
1447
1448
        // No errors; everything's fine here!
1449
        if( empty( $error ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1450
            return true;
1451
        }
1452
1453
        if( $echo && $error !== true ) {
0 ignored issues
show
introduced by
Found "!== true". Use Yoda Condition checks, you must
Loading history...
introduced by
Space after opening control structure is required
Loading history...
1454
1455
	        $error = esc_html( $error );
1456
1457
	        /**
1458
	         * @since 1.9
1459
	         */
1460
	        if ( ! empty( $this->entry ) ) {
1461
		        $error .= ' ' . gravityview_get_link( '#', _x('Go back.', 'Link shown when invalid Edit Entry link is clicked', 'gravityview' ), array( 'onclick' => "window.history.go(-1); return false;" ) );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style Comprehensibility introduced by
The string literal window.history.go(-1); return false; does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
1462
	        }
1463
1464
            echo GVCommon::generate_notice( wpautop( $error ), 'gv-error error');
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'GVCommon'
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
1465
        }
1466
1467
        do_action('gravityview_log_error', 'GravityView_Edit_Entry[user_can_edit_entry]' . $error );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
1468
1469
        return false;
1470
    }
1471
1472
1473
    /**
1474
     * Check whether a field is editable by the current user, and optionally display an error message
1475
     * @uses  GravityView_Edit_Entry->check_user_cap_edit_field() Check user capabilities
1476
     * @param  array  $field Field or field settings array
1477
     * @param  boolean $echo  Whether to show error message telling user they aren't allowed
1478
     * @return boolean         True: user can edit the current field; False: nope, they can't.
1479
     */
1480
    private function user_can_edit_field( $field, $echo = false ) {
1481
1482
        $error = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
1483
1484
        if( ! $this->check_user_cap_edit_field( $field ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1485
            $error = __( 'You do not have permission to edit this field.', 'gravityview');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
1486
        }
1487
1488
        // No errors; everything's fine here!
1489
        if( empty( $error ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1490
            return true;
1491
        }
1492
1493
        if( $echo ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1494
            echo GVCommon::generate_notice( wpautop( esc_html( $error ) ), 'gv-error error');
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'GVCommon'
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
1495
        }
1496
1497
        do_action('gravityview_log_error', 'GravityView_Edit_Entry[user_can_edit_field]' . $error );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
1498
1499
        return false;
1500
1501
    }
1502
1503
1504
    /**
1505
     * checks if user has permissions to edit a specific field
1506
     *
1507
     * Needs to be used combined with GravityView_Edit_Entry::user_can_edit_field for maximum security!!
1508
     *
1509
     * @param  [type] $field [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1510
     * @return bool
1511
     */
1512
    private function check_user_cap_edit_field( $field ) {
1513
1514
        // If they can edit any entries (as defined in Gravity Forms), we're good.
1515
        if( GVCommon::has_cap( array( 'gravityforms_edit_entries', 'gravityview_edit_others_entries' ) ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1516
            return true;
1517
        }
1518
1519
        $field_cap = isset( $field['allow_edit_cap'] ) ? $field['allow_edit_cap'] : false;
1520
1521
        // If the field has custom editing capaibilities set, check those
1522
        if( $field_cap ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1523
            return GVCommon::has_cap( $field['allow_edit_cap'] );
1524
        }
1525
1526
        return false;
1527
    }
1528
1529
1530
    /**
1531
     * Is the current nonce valid for editing the entry?
1532
     * @return boolean
1533
     */
1534
    public function verify_nonce() {
1535
1536
        // Verify form submitted for editing single
1537
        if( $this->is_edit_entry_submission() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1538
            $valid = wp_verify_nonce( $_POST[ self::$nonce_field ], self::$nonce_field );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_POST
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
1539
        }
1540
1541
        // Verify
1542
        else if( ! $this->is_edit_entry() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
1543
            $valid = false;
1544
        }
1545
1546
        else {
1547
            $valid = wp_verify_nonce( $_GET['edit'], self::$nonce_key );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_GET
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
1548
        }
1549
1550
        /**
1551
         * @filter `gravityview/edit_entry/verify_nonce` Override Edit Entry nonce validation. Return true to declare nonce valid.
1552
         * @since 1.13
1553
         * @param int|boolean $valid False if invalid; 1 or 2 when nonce was generated
1554
         * @param string $nonce_field Key used when validating submissions. Default: is_gv_edit_entry
1555
         */
1556
        $valid = apply_filters( 'gravityview/edit_entry/verify_nonce', $valid, self::$nonce_field );
1557
1558
        return $valid;
1559
    }
1560
1561
1562
1563
} //end class