Completed
Push — master ( 1b7620...a4da27 )
by Zack
12s
created

extensions/edit-entry/class-edit-entry-render.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
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
class GravityView_Edit_Entry_Render {
17
18
	/**
19
	 * @var GravityView_Edit_Entry
20
	 */
21
	protected $loader;
22
23
	/**
24
	 * @var string String used to generate unique nonce for the entry/form/view combination. Allows access to edit page.
25
	 */
26
	static $nonce_key;
27
28
	/**
29
	 * @since 1.9
30
	 * @var string String used for check valid edit entry form submission. Allows saving edit form values.
31
	 */
32
	private static $nonce_field = 'is_gv_edit_entry';
33
34
	/**
35
	 * @since 1.9
36
	 * @var bool Whether to allow save and continue functionality
37
	 */
38
	private static $supports_save_and_continue = false;
39
40
	/**
41
	 * Gravity Forms entry array
42
	 *
43
	 * @var array
44
	 */
45
	public $entry;
46
47
	/**
48
	 * Gravity Forms entry array (it won't get changed during this class lifecycle)
49
	 * @since 1.17.2
50
	 * @var array
51
	 */
52
	private static $original_entry = array();
53
54
	/**
55
	 * Gravity Forms form array (GravityView modifies the content through this class lifecycle)
56
	 *
57
	 * @var array
58
	 */
59
	public $form;
60
61
	/**
62
	 * Gravity Forms form array (it won't get changed during this class lifecycle)
63
	 * @since 1.16.2.1
64
	 * @var array
65
	 */
66
	private static $original_form;
67
68
	/**
69
	 * Gravity Forms form array after the form validation process
70
	 * @since 1.13
71
	 * @var array
72
	 */
73
	public $form_after_validation = null;
74
75
	/**
76
	 * Hold an array of GF field objects that have calculation rules
77
	 * @var array
78
	 */
79
	public $fields_with_calculation = array();
80
81
	/**
82
	 * Gravity Forms form id
83
	 *
84
	 * @var int
85
	 */
86
	public $form_id;
87
88
	/**
89
	 * ID of the current view
90
	 *
91
	 * @var int
92
	 */
93
	public $view_id;
94
95
	/**
96
	 * Updated entry is valid (GF Validation object)
97
	 *
98
	 * @var array
99
	 */
100
	public $is_valid = NULL;
101
102 3
	function __construct( GravityView_Edit_Entry $loader ) {
103 3
		$this->loader = $loader;
104 3
	}
105
106 3
	function load() {
107
108
		/** @define "GRAVITYVIEW_DIR" "../../../" */
109 3
		include_once( GRAVITYVIEW_DIR .'includes/class-admin-approve-entries.php' );
110
111
		// Don't display an embedded form when editing an entry
112 3
		add_action( 'wp_head', array( $this, 'prevent_render_form' ) );
113 3
		add_action( 'wp_footer', array( $this, 'prevent_render_form' ) );
114
115
		// Stop Gravity Forms processing what is ours!
116 3
		add_filter( 'wp', array( $this, 'prevent_maybe_process_form'), 8 );
117
118 3
		add_filter( 'gravityview_is_edit_entry', array( $this, 'is_edit_entry') );
119
120 3
		add_action( 'gravityview_edit_entry', array( $this, 'init' ) );
121
122
		// Disable conditional logic if needed (since 1.9)
123 3
		add_filter( 'gform_has_conditional_logic', array( $this, 'manage_conditional_logic' ), 10, 2 );
124
125
		// Make sure GF doesn't validate max files (since 1.9)
126 3
		add_filter( 'gform_plupload_settings', array( $this, 'modify_fileupload_settings' ), 10, 3 );
127
128
		// Add fields expected by GFFormDisplay::validate()
129 3
		add_filter( 'gform_pre_validation', array( $this, 'gform_pre_validation') );
130
131
		// Fix multiselect value for GF 2.2
132 3
		add_filter( 'gravityview/edit_entry/field_value_multiselect', array( $this, 'fix_multiselect_value_serialization' ), 10, 3 );
133 3
	}
134
135
	/**
136
	 * Don't show any forms embedded on a page when GravityView is in Edit Entry mode
137
	 *
138
	 * Adds a `__return_empty_string` filter on the Gravity Forms shortcode on the `wp_head` action
139
	 * And then removes it on the `wp_footer` action
140
	 *
141
	 * @since 1.16.1
142
	 *
143
	 * @return void
144
	 */
145 1
	public function prevent_render_form() {
146 1
		if( $this->is_edit_entry() ) {
147 1
			if( 'wp_head' === current_filter() ) {
148 1
				add_filter( 'gform_shortcode_form', '__return_empty_string' );
149
			} else {
150 1
				remove_filter( 'gform_shortcode_form', '__return_empty_string' );
151
			}
152
		}
153 1
	}
154
155
	/**
156
	 * Because we're mimicking being a front-end Gravity Forms form while using a Gravity Forms
157
	 * backend form, we need to prevent them from saving twice.
158
	 * @return void
159
	 */
160
	public function prevent_maybe_process_form() {
161
162
		if( ! empty( $_POST ) ) {
163
			do_action( 'gravityview_log_debug', 'GravityView_Edit_Entry[prevent_maybe_process_form] $_POSTed data (sanitized): ', esc_html( print_r( $_POST, true ) ) );
164
		}
165
166
		if( $this->is_edit_entry_submission() ) {
167
			remove_action( 'wp',  array( 'RGForms', 'maybe_process_form'), 9 );
168
			remove_action( 'wp',  array( 'GFForms', 'maybe_process_form'), 9 );
169
		}
170
	}
171
172
	/**
173
	 * Is the current page an Edit Entry page?
174
	 * @return boolean
175
	 */
176 4
	public function is_edit_entry() {
177
178 4
		$is_edit_entry = GravityView_frontend::is_single_entry() && ! empty( $_GET['edit'] );
179
180 4
		return ( $is_edit_entry || $this->is_edit_entry_submission() );
181
	}
182
183
	/**
184
	 * Is the current page an Edit Entry page?
185
	 * @since 1.9
186
	 * @return boolean
187
	 */
188 3
	public function is_edit_entry_submission() {
189 3
		return !empty( $_POST[ self::$nonce_field ] );
190
	}
191
192
	/**
193
	 * When Edit entry view is requested setup the vars
194
	 */
195 3
	private function setup_vars() {
196 3
		$gravityview_view = GravityView_View::getInstance();
197
198
199 3
		$entries = $gravityview_view->getEntries();
200 3
		self::$original_entry = $entries[0];
201 3
		$this->entry = $entries[0];
202
203 3
		self::$original_form = $gravityview_view->getForm();
204 3
		$this->form = $gravityview_view->getForm();
205 3
		$this->form_id = $gravityview_view->getFormId();
206 3
		$this->view_id = $gravityview_view->getViewId();
207
208 3
		self::$nonce_key = GravityView_Edit_Entry::get_nonce_key( $this->view_id, $this->form_id, $this->entry['id'] );
209 3
	}
210
211
212
	/**
213
	 * Load required files and trigger edit flow
214
	 *
215
	 * Run when the is_edit_entry returns true.
216
	 *
217
	 * @param GravityView_View_Data $gv_data GravityView Data object
218
	 * @return void
219
	 */
220 4
	public function init( $gv_data ) {
221
222 4
		require_once( GFCommon::get_base_path() . '/form_display.php' );
223 4
		require_once( GFCommon::get_base_path() . '/entry_detail.php' );
224
225 4
		$this->setup_vars();
226
227
		// Multiple Views embedded, don't proceed if nonce fails
228 4
		$multiple_views = defined( 'GRAVITYVIEW_FUTURE_CORE_LOADED' ) ? gravityview()->views->count() > 1 : $gv_data->has_multiple_views();
229 4
		if( $multiple_views && ! wp_verify_nonce( $_GET['edit'], self::$nonce_key ) ) {
230
			do_action('gravityview_log_error', __METHOD__ . ': Nonce validation failed for the Edit Entry request; returning' );
231
			return;
232
		}
233
234
		// Sorry, you're not allowed here.
235 4
		if( false === $this->user_can_edit_entry( true ) ) {
236 1
			do_action('gravityview_log_error', __METHOD__ . ': User is not allowed to edit this entry; returning', $this->entry );
237 1
			return;
238
		}
239
240 4
		$this->print_scripts();
241
242 4
		$this->process_save();
243
244 4
		$this->edit_entry_form();
245
246 4
	}
247
248
249
	/**
250
	 * Force Gravity Forms to output scripts as if it were in the admin
251
	 * @return void
252
	 */
253 3
	private function print_scripts() {
254 3
		$gravityview_view = GravityView_View::getInstance();
255
256 3
		wp_register_script( 'gform_gravityforms', GFCommon::get_base_url().'/js/gravityforms.js', array( 'jquery', 'gform_json', 'gform_placeholder', 'sack', 'plupload-all', 'gravityview-fe-view' ) );
257
258 3
		GFFormDisplay::enqueue_form_scripts($gravityview_view->getForm(), false);
259
260
		// Sack is required for images
261 3
		wp_print_scripts( array( 'sack', 'gform_gravityforms' ) );
262 3
	}
263
264
265
	/**
266
	 * Process edit entry form save
267
	 */
268 4
	private function process_save() {
269
270 4
		if( empty( $_POST ) || ! isset( $_POST['lid'] ) ) {
271 4
			return;
272
		}
273
274
		// Make sure the entry, view, and form IDs are all correct
275 4
		$valid = $this->verify_nonce();
276
277 4
		if( !$valid ) {
278
			do_action('gravityview_log_error', __METHOD__ . ' Nonce validation failed.' );
279
			return;
280
		}
281
282 4
		if( $this->entry['id'] !== $_POST['lid'] ) {
283
			do_action('gravityview_log_error', __METHOD__ . ' Entry ID did not match posted entry ID.' );
284
			return;
285
		}
286
287 4
		do_action('gravityview_log_debug', __METHOD__ . ': $_POSTed data (sanitized): ', esc_html( print_r( $_POST, true ) ) );
288
289 4
		$this->process_save_process_files( $this->form_id );
290
291 4
		$this->validate();
292
293 4
		if( $this->is_valid ) {
294
295 4
			do_action('gravityview_log_debug', __METHOD__ . ': Submission is valid.' );
296
297
			/**
298
			 * @hack This step is needed to unset the adminOnly from form fields, to add the calculation fields
299
			 */
300 4
			$form = $this->form_prepare_for_save();
301
302
			/**
303
			 * @hack to avoid the capability validation of the method save_lead for GF 1.9+
304
			 */
305 4
			unset( $_GET['page'] );
306
307 4
			$date_created = $this->entry['date_created'];
308
309
			/**
310
			 * @hack to force Gravity Forms to use $read_value_from_post in GFFormsModel::save_lead()
311
			 * @since 1.17.2
312
			 */
313 4
			unset( $this->entry['date_created'] );
314
315 4
			GFFormsModel::save_lead( $form, $this->entry );
316
317
			// Delete the values for hidden inputs
318 4
			$this->unset_hidden_field_values();
319
			
320 4
			$this->entry['date_created'] = $date_created;
321
322
			// Process calculation fields
323 4
			$this->update_calculation_fields();
324
325
			// Perform actions normally performed after updating a lead
326 4
			$this->after_update();
327
328
			/**
329
			 * Must be AFTER after_update()!
330
			 * @see https://github.com/gravityview/GravityView/issues/764
331
			 */
332 4
			$this->maybe_update_post_fields( $form );
333
334
			/**
335
			 * @action `gravityview/edit_entry/after_update` Perform an action after the entry has been updated using Edit Entry
336
			 * @param array $form Gravity Forms form array
337
			 * @param string $entry_id Numeric ID of the entry that was updated
338
			 * @param GravityView_Edit_Entry_Render $this This object
339
			 */
340 4
			do_action( 'gravityview/edit_entry/after_update', $this->form, $this->entry['id'], $this );
341
342
		} else {
343
			do_action('gravityview_log_error', __METHOD__ . ': Submission is NOT valid.', $this->entry );
344
		}
345
346 4
	} // process_save
347
348
	/**
349
	 * Delete the value of fields hidden by conditional logic when the entry is edited
350
	 *
351
	 * @uses GFFormsModel::update_lead_field_value()
352
	 *
353
	 * @since 1.17.4
354
	 *
355
	 * @return void
356
	 */
357 3
	private function unset_hidden_field_values() {
358 3
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
359
360 3
		if ( version_compare( GFFormsModel::get_database_version(), '2.3-dev-1', '>=' ) ) {
361
			$entry_meta_table = GFFormsModel::get_entry_meta_table_name();
362
			$current_fields = $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value FROM $entry_meta_table WHERE entry_id=%d", $this->entry['id'] ) );
363
		} else {
364 3
			$lead_detail_table = GFFormsModel::get_lead_details_table_name();
365 3
			$current_fields = $wpdb->get_results( $wpdb->prepare( "SELECT id, field_number FROM $lead_detail_table WHERE lead_id=%d", $this->entry['id'] ) );
366
		}
367
368 3
		foreach ( $this->entry as $input_id => $field_value ) {
369
370 3
			$field = RGFormsModel::get_field( $this->form, $input_id );
371
372
			// Reset fields that are hidden
373
			// Don't pass $entry as fourth parameter; force using $_POST values to calculate conditional logic
374 3
			if ( GFFormsModel::is_field_hidden( $this->form, $field, array(), NULL ) ) {
375
376
				// List fields are stored as empty arrays when empty
377
				$empty_value = $this->is_field_json_encoded( $field ) ? '[]' : '';
378
379
				$lead_detail_id = GFFormsModel::get_lead_detail_id( $current_fields, $input_id );
380
381
				GFFormsModel::update_lead_field_value( $this->form, $this->entry, $field, $lead_detail_id, $input_id, $empty_value );
382
383
				// Prevent the $_POST values of hidden fields from being used as default values when rendering the form
384
				// after submission
385
				$post_input_id = 'input_' . str_replace( '.', '_', $input_id );
386 3
				$_POST[ $post_input_id ] = '';
387
			}
388
		}
389 3
	}
390
391
	/**
392
	 * Have GF handle file uploads
393
	 *
394
	 * Copy of code from GFFormDisplay::process_form()
395
	 *
396
	 * @param int $form_id
397
	 */
398 3
	private function process_save_process_files( $form_id ) {
399
400
		//Loading files that have been uploaded to temp folder
401 3
		$files = GFCommon::json_decode( stripslashes( RGForms::post( 'gform_uploaded_files' ) ) );
402 3
		if ( ! is_array( $files ) ) {
403 2
			$files = array();
404
		}
405
406
		/**
407
		 * Make sure the fileuploads are not overwritten if no such request was done.
408
		 * @since 1.20.1
409
		 */
410 3
		add_filter( "gform_save_field_value_$form_id", array( $this, 'save_field_value' ), 99, 5 );
411
412 3
		RGFormsModel::$uploaded_files[ $form_id ] = $files;
413 3
	}
414
415
	/**
416
	 * Make sure the fileuploads are not overwritten if no such request was done.
417
	 *
418
	 * TO ONLY BE USED INTERNALLY; DO NOT DEVELOP ON; MAY BE REMOVED AT ANY TIME.
419
	 *
420
	 * @since 1.20.1
421
	 *
422
	 * @param string $value Field value
423
	 * @param array $entry GF entry array
424
	 * @param GF_Field_FileUpload $field
425
	 * @param array $form GF form array
426
	 * @param string $input_id ID of the input being saved
427
	 *
428
	 * @return string
429
	 */
430 3
	public function save_field_value( $value = '', $entry = array(), $field = null, $form = array(), $input_id = '' ) {
431
432 3
		if ( ! $field || $field->type != 'fileupload' ) {
433 3
			return $value;
434
		}
435
436 1
		$input_name = 'input_' . str_replace( '.', '_', $input_id );
437
438 1
		if ( $field->multipleFiles ) {
439
			if ( empty( $value ) ) {
440
				return json_decode( $entry[ $input_id ], true );
441
			}
442
			return $value;
443
		}
444
445
		/** No file is being uploaded. */
446 1
		if ( empty( $_FILES[ $input_name ]['name'] ) ) {
447
			/** So return the original upload */
448 1
			return $entry[ $input_id ];
449
		}
450
451 1
		return $value;
452
	}
453
454
	/**
455
	 * Remove max_files validation (done on gravityforms.js) to avoid conflicts with GravityView
456
	 * Late validation done on self::custom_validation
457
	 *
458
	 * @param $plupload_init array Plupload settings
459
	 * @param $form_id
460
	 * @param $instance
461
	 * @return mixed
462
	 */
463 1
	public function modify_fileupload_settings( $plupload_init, $form_id, $instance ) {
464 1
		if( ! $this->is_edit_entry() ) {
465
			return $plupload_init;
466
		}
467
468 1
		$plupload_init['gf_vars']['max_files'] = 0;
469
470 1
		return $plupload_init;
471
	}
472
473
474
	/**
475
	 * Unset adminOnly and convert field input key to string
476
	 * @return array $form
477
	 */
478 3
	private function form_prepare_for_save() {
479
480 3
		$form = $this->form;
481
482
		/** @var GF_Field $field */
483 3
		foreach( $form['fields'] as $k => &$field ) {
484
485
			/**
486
			 * Remove the fields with calculation formulas before save to avoid conflicts with GF logic
487
			 * @since 1.16.3
488
			 * @var GF_Field $field
489
			 */
490 3
			if( $field->has_calculation() ) {
491
				unset( $form['fields'][ $k ] );
492
			}
493
494 3
			$field->adminOnly = false;
495
496 3
			if( isset( $field->inputs ) && is_array( $field->inputs ) ) {
497
				foreach( $field->inputs as $key => $input ) {
498 3
					$field->inputs[ $key ][ 'id' ] = (string)$input['id'];
499
				}
500
			}
501
		}
502
503 3
		return $form;
504
	}
505
506 3
	private function update_calculation_fields() {
507
508 3
		$form = self::$original_form;
509 3
		$update = false;
510
511
		// get the most up to date entry values
512 3
		$entry = GFAPI::get_entry( $this->entry['id'] );
513
514 3
		if( !empty( $this->fields_with_calculation ) ) {
515
			$update = true;
516
			foreach ( $this->fields_with_calculation as $calc_field ) {
517
				$inputs = $calc_field->get_entry_inputs();
518
				if ( is_array( $inputs ) ) {
519
					foreach ( $inputs as $input ) {
520
						$input_name = 'input_' . str_replace( '.', '_', $input['id'] );
521
						list( $prefix, $field_id, $input_id ) = rgexplode( '_', $input_name, 3 );
522
523
						switch ( $input_id ) {
524
							case 1:
525
								/** Never void the labels. */
526
								$value = $entry[ $input['id'] ];
527
								break;
528
							case 2:
529
								/** Always recalcualte the final price. */
530
								$value = '';
531
								break;
532
							case 3:
533
								/** Fetch the quantity form the request. */
534
								$value = rgpost( $input_name, $entry[ $input['id'] ] );
535
								break;
536
						}
537
538
						$entry[ strval( $input['id'] ) ] = RGFormsModel::prepare_value( $form, $calc_field, $value, $input_name, $entry['id'], $entry );
0 ignored issues
show
The variable $value does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
539
					}
540
				} else {
541
					$input_name = 'input_' . str_replace( '.', '_', $calc_field->id);
542
					$entry[ strval( $calc_field->id ) ] = RGFormsModel::prepare_value( $form, $calc_field, '', $input_name, $entry['id'], $entry );
543
				}
544
			}
545
546
		}
547
548 3
		if( $update ) {
549
550
			$return_entry = GFAPI::update_entry( $entry );
551
552
			if( is_wp_error( $return_entry ) ) {
553
				do_action( 'gravityview_log_error', 'Updating the entry calculation fields failed', $return_entry );
554
			} else {
555
				do_action( 'gravityview_log_debug', 'Updating the entry calculation fields succeeded' );
556
			}
557
		}
558 3
	}
559
560
	/**
561
	 * Handle updating the Post Image field
562
	 *
563
	 * Sets a new Featured Image if configured in Gravity Forms; otherwise uploads/updates media
564
	 *
565
	 * @since 1.17
566
	 *
567
	 * @uses GFFormsModel::media_handle_upload
568
	 * @uses set_post_thumbnail
569
	 * 
570
	 * @param array $form GF Form array
571
	 * @param GF_Field $field GF Field
572
	 * @param string $field_id Numeric ID of the field
573
	 * @param string $value
574
	 * @param array $entry GF Entry currently being edited
575
	 * @param int $post_id ID of the Post being edited
576
	 *
577
	 * @return mixed|string
578
	 */
579 1
	private function update_post_image( $form, $field, $field_id, $value, $entry, $post_id ) {
580
581 1
		$input_name = 'input_' . $field_id;
582
583 1
		if ( !empty( $_FILES[ $input_name ]['name'] ) ) {
584
585
			// We have a new image
586
587
			$value = RGFormsModel::prepare_value( $form, $field, $value, $input_name, $entry['id'] );
588
589
			$ary = ! empty( $value ) ? explode( '|:|', $value ) : array();
590
			$img_url = rgar( $ary, 0 );
591
592
			$img_title	   = count( $ary ) > 1 ? $ary[1] : '';
593
			$img_caption	 = count( $ary ) > 2 ? $ary[2] : '';
594
			$img_description = count( $ary ) > 3 ? $ary[3] : '';
595
596
			$image_meta = array(
597
				'post_excerpt' => $img_caption,
598
				'post_content' => $img_description,
599
			);
600
601
			//adding title only if it is not empty. It will default to the file name if it is not in the array
602
			if ( ! empty( $img_title ) ) {
603
				$image_meta['post_title'] = $img_title;
604
			}
605
606
			/**
607
			 * todo: As soon as \GFFormsModel::media_handle_upload becomes a public method, move this call to \GFFormsModel::media_handle_upload and remove the hack from this class.
608
			 * Note: the method became public in GF 1.9.17.7, but we don't require that version yet.
609
			 */
610
			require_once GRAVITYVIEW_DIR . 'includes/class-gravityview-gfformsmodel.php';
611
			$media_id = GravityView_GFFormsModel::media_handle_upload( $img_url, $post_id, $image_meta );
612
613
			// is this field set as featured image?
614
			if ( $media_id && $field->postFeaturedImage ) {
615
				set_post_thumbnail( $post_id, $media_id );
616
			}
617
618 1
		} elseif ( !empty( $_POST[ $input_name ] ) && is_array( $value ) ) {
619
620 1
			$img_url = $_POST[ $input_name ];
621
622 1
			$img_title	   = rgar( $_POST, $input_name.'_1' );
623 1
			$img_caption	 = rgar( $_POST, $input_name .'_4' );
624 1
			$img_description = rgar( $_POST, $input_name .'_7' );
625
626 1
			$value = ! empty( $img_url ) ? $img_url . "|:|" . $img_title . "|:|" . $img_caption . "|:|" . $img_description : '';
627
628 1
			if ( $field->postFeaturedImage ) {
629
630
				$image_meta = array(
631 1
					'ID' => get_post_thumbnail_id( $post_id ),
632 1
					'post_title' => $img_title,
633 1
					'post_excerpt' => $img_caption,
634 1
					'post_content' => $img_description,
635
				);
636
637
				// update image title, caption or description
638 1
				wp_update_post( $image_meta );
639
			}
640
		} else {
641
642
			// if we get here, image was removed or not set.
643
			$value = '';
644
645
			if ( $field->postFeaturedImage ) {
646
				delete_post_thumbnail( $post_id );
647
			}
648
		}
649
650 1
		return $value;
651
	}
652
653
	/**
654
	 * Loop through the fields being edited and if they include Post fields, update the Entry's post object
655
	 *
656
	 * @param array $form Gravity Forms form
657
	 *
658
	 * @return void
659
	 */
660 3
	private function maybe_update_post_fields( $form ) {
661
662 3
		if( empty( $this->entry['post_id'] ) ) {
663 2
			do_action( 'gravityview_log_debug', __METHOD__ . ': This entry has no post fields. Continuing...' );
664 2
			return;
665
		}
666
667 1
		$post_id = $this->entry['post_id'];
668
669
		// Security check
670 1
		if( false === GVCommon::has_cap( 'edit_post', $post_id ) ) {
671
			do_action( 'gravityview_log_error', 'The current user does not have the ability to edit Post #'.$post_id );
672
			return;
673
		}
674
675 1
		$update_entry = false;
676
677 1
		$updated_post = $original_post = get_post( $post_id );
678
679 1
		foreach ( $this->entry as $field_id => $value ) {
680
681 1
			$field = RGFormsModel::get_field( $form, $field_id );
682
683 1
			if( ! $field ) {
684 1
				continue;
685
			}
686
687 1
			if( GFCommon::is_post_field( $field ) && 'post_category' !== $field->type ) {
688
689
				// Get the value of the field, including $_POSTed value
690 1
				$value = RGFormsModel::get_field_value( $field );
691
692
				// Use temporary entry variable, to make values available to fill_post_template() and update_post_image()
693 1
				$entry_tmp = $this->entry;
694 1
				$entry_tmp["{$field_id}"] = $value;
695
696 1
				switch( $field->type ) {
697
698 1
					case 'post_title':
699
						$post_title = $value;
700
						if( rgar( $form, 'postTitleTemplateEnabled' ) ) {
701
							$post_title = $this->fill_post_template( $form['postTitleTemplate'], $form, $entry_tmp );
702
						}
703
						$updated_post->post_title = $post_title;
704
						$updated_post->post_name  = $post_title;
705
						unset( $post_title );
706
						break;
707
708 1
					case 'post_content':
709
						$post_content = $value;
710
						if( rgar( $form, 'postContentTemplateEnabled' ) ) {
711
							$post_content = $this->fill_post_template( $form['postContentTemplate'], $form, $entry_tmp, true );
712
						}
713
						$updated_post->post_content = $post_content;
714
						unset( $post_content );
715
						break;
716 1
					case 'post_excerpt':
717
						$updated_post->post_excerpt = $value;
718
						break;
719 1
					case 'post_tags':
720
						wp_set_post_tags( $post_id, $value, false );
721
						break;
722 1
					case 'post_category':
723
						break;
724 1
					case 'post_custom_field':
725
						if ( is_array( $value ) && ( floatval( $field_id ) !== floatval( $field->id ) ) ) {
726
							$value = $value[ $field_id ];
727
						}
728
729
						if( ! empty( $field->customFieldTemplateEnabled ) ) {
730
							$value = $this->fill_post_template( $field->customFieldTemplate, $form, $entry_tmp, true );
731
						}
732
733
						if ( $this->is_field_json_encoded( $field ) && ! is_string( $value ) ) {
734
							$value = function_exists('wp_json_encode') ? wp_json_encode( $value ) : json_encode( $value );
735
						}
736
737
						update_post_meta( $post_id, $field->postCustomFieldName, $value );
738
						break;
739
740 1
					case 'post_image':
741 1
						$value = $this->update_post_image( $form, $field, $field_id, $value, $this->entry, $post_id );
742 1
						break;
743
744
				}
745
746
				// update entry after
747 1
				$this->entry["{$field_id}"] = $value;
748
749 1
				$update_entry = true;
750
751 1
				unset( $entry_tmp );
752
			}
753
754
		}
755
756 1
		if( $update_entry ) {
757
758 1
			$return_entry = GFAPI::update_entry( $this->entry );
759
760 1
			if( is_wp_error( $return_entry ) ) {
761
			   do_action( 'gravityview_log_error', 'Updating the entry post fields failed', array( '$this->entry' => $this->entry, '$return_entry' => $return_entry ) );
762
			} else {
763 1
				do_action( 'gravityview_log_debug', 'Updating the entry post fields for post #'.$post_id.' succeeded' );
764
			}
765
766
		}
767
768 1
		$return_post = wp_update_post( $updated_post, true );
769
770 1
		if( is_wp_error( $return_post ) ) {
771
			$return_post->add_data( $updated_post, '$updated_post' );
772
			do_action( 'gravityview_log_error', 'Updating the post content failed', compact( 'updated_post', 'return_post' ) );
773
		} else {
774 1
			do_action( 'gravityview_log_debug', 'Updating the post content for post #'.$post_id.' succeeded', $updated_post );
775
		}
776 1
	}
777
778
	/**
779
	 * Is the field stored in a JSON-encoded manner?
780
	 *
781
	 * @param GF_Field $field
782
	 *
783
	 * @return bool True: stored in DB json_encode()'d; False: not encoded
784
	 */
785
	private function is_field_json_encoded( $field ) {
786
787
		$json_encoded = false;
788
789
		$input_type = RGFormsModel::get_input_type( $field );
790
791
		// Only certain custom field types are supported
792
		switch( $input_type ) {
793
			case 'fileupload':
794
			case 'list':
795
			case 'multiselect':
796
				$json_encoded = true;
797
				break;
798
		}
799
800
		return $json_encoded;
801
	}
802
803
	/**
804
	 * Convert a field content template into prepared output
805
	 *
806
	 * @uses GravityView_GFFormsModel::get_post_field_images()
807
	 *
808
	 * @since 1.17
809
	 *
810
	 * @param string $template The content template for the field
811
	 * @param array $form Gravity Forms form
812
	 * @param bool $do_shortcode Whether to process shortcode inside content. In GF, only run on Custom Field and Post Content fields
813
	 *
814
	 * @return string
815
	 */
816
	private function fill_post_template( $template, $form, $entry, $do_shortcode = false ) {
817
818
		require_once GRAVITYVIEW_DIR . 'includes/class-gravityview-gfformsmodel.php';
819
820
		$post_images = GravityView_GFFormsModel::get_post_field_images( $form, $entry );
821
822
		//replacing post image variables
823
		$output = GFCommon::replace_variables_post_image( $template, $post_images, $entry );
824
825
		//replacing all other variables
826
		$output = GFCommon::replace_variables( $output, $form, $entry, false, false, false );
827
828
		// replace conditional shortcodes
829
		if( $do_shortcode ) {
830
			$output = do_shortcode( $output );
831
		}
832
833
		return $output;
834
	}
835
836
837
	/**
838
	 * Perform actions normally performed after updating a lead
839
	 *
840
	 * @since 1.8
841
	 *
842
	 * @see GFEntryDetail::lead_detail_page()
843
	 *
844
	 * @return void
845
	 */
846 3
	private function after_update() {
847
848 3
		do_action( 'gform_after_update_entry', $this->form, $this->entry['id'], self::$original_entry );
849 3
		do_action( "gform_after_update_entry_{$this->form['id']}", $this->form, $this->entry['id'], self::$original_entry );
850
851
		// Re-define the entry now that we've updated it.
852 3
		$entry = RGFormsModel::get_lead( $this->entry['id'] );
853
854 3
		$entry = GFFormsModel::set_entry_meta( $entry, $this->form );
855
856 3
		if ( version_compare( GFFormsModel::get_database_version(), '2.3-dev-1', '<' ) ) {
857
			// We need to clear the cache because Gravity Forms caches the field values, which
858
			// we have just updated.
859 3
			foreach ($this->form['fields'] as $key => $field) {
860 3
				GFFormsModel::refresh_lead_field_value( $entry['id'], $field->id );
861
			}
862
		}
863
864 3
		$this->entry = $entry;
865 3
	}
866
867
868
	/**
869
	 * Display the Edit Entry form
870
	 *
871
	 * @return void
872
	 */
873 3
	public function edit_entry_form() {
874
875
		?>
876
877
		<div class="gv-edit-entry-wrapper"><?php
878
879 3
			$javascript = gravityview_ob_include( GravityView_Edit_Entry::$file .'/partials/inline-javascript.php', $this );
880
881
			/**
882
			 * Fixes weird wpautop() issue
883
			 * @see https://github.com/katzwebservices/GravityView/issues/451
884
			 */
885 3
			echo gravityview_strip_whitespace( $javascript );
886
887
			?><h2 class="gv-edit-entry-title">
888
				<span><?php
889
890
					/**
891
					 * @filter `gravityview_edit_entry_title` Modify the edit entry title
892
					 * @param string $edit_entry_title Modify the "Edit Entry" title
893
					 * @param GravityView_Edit_Entry_Render $this This object
894
					 */
895 3
					$edit_entry_title = apply_filters('gravityview_edit_entry_title', __('Edit Entry', 'gravityview'), $this );
896
897 3
					echo esc_attr( $edit_entry_title );
898
			?></span>
899
			</h2>
900
901
			<?php $this->maybe_print_message(); ?>
902
903
			<?php // The ID of the form needs to be `gform_{form_id}` for the pluploader ?>
904
905
			<form method="post" id="gform_<?php echo $this->form_id; ?>" enctype="multipart/form-data">
906
907
				<?php
908
909 3
				wp_nonce_field( self::$nonce_key, self::$nonce_key );
910
911 3
				wp_nonce_field( self::$nonce_field, self::$nonce_field, false );
912
913
				// Print the actual form HTML
914 3
				$this->render_edit_form();
915
916
				?>
917 3
			</form>
918
919
			<script>
920
				gform.addFilter('gform_reset_pre_conditional_logic_field_action', function ( reset, formId, targetId, defaultValues, isInit ) {
921
					return false;
922
				});
923
			</script>
924
925
		</div>
926
927
	<?php
928 3
	}
929
930
	/**
931
	 * Display success or error message if the form has been submitted
932
	 *
933
	 * @uses GVCommon::generate_notice
934
	 *
935
	 * @since 1.16.2.2
936
	 *
937
	 * @return void
938
	 */
939 3
	private function maybe_print_message() {
940
941 3
		if( rgpost('action') === 'update' ) {
942
943
			$back_link = esc_url( remove_query_arg( array( 'page', 'view', 'edit' ) ) );
944
945
			if( ! $this->is_valid ){
946
947
				// Keeping this compatible with Gravity Forms.
948
				$validation_message = "<div class='validation_error'>" . __('There was a problem with your submission.', 'gravityview') . " " . __('Errors have been highlighted below.', 'gravityview') . "</div>";
949
				$message = apply_filters("gform_validation_message_{$this->form['id']}", apply_filters("gform_validation_message", $validation_message, $this->form), $this->form);
950
951
				echo GVCommon::generate_notice( $message , 'gv-error' );
952
953
			} else {
954
				$entry_updated_message = sprintf( esc_attr__('Entry Updated. %sReturn to Entry%s', 'gravityview'), '<a href="'. $back_link .'">', '</a>' );
955
956
				/**
957
				 * @filter `gravityview/edit_entry/success` Modify the edit entry success message (including the anchor link)
958
				 * @since 1.5.4
959
				 * @param string $entry_updated_message Existing message
960
				 * @param int $view_id View ID
961
				 * @param array $entry Gravity Forms entry array
962
				 * @param string $back_link URL to return to the original entry. @since 1.6
963
				 */
964
				$message = apply_filters( 'gravityview/edit_entry/success', $entry_updated_message , $this->view_id, $this->entry, $back_link );
965
966
				echo GVCommon::generate_notice( $message );
967
			}
968
969
		}
970 3
	}
971
972
	/**
973
	 * Display the Edit Entry form in the original Gravity Forms format
974
	 *
975
	 * @since 1.9
976
	 *
977
	 * @return void
978
	 */
979 3
	private function render_edit_form() {
980
981
		/**
982
		 * @action `gravityview/edit-entry/render/before` Before rendering the Edit Entry form
983
		 * @since 1.17
984
		 * @param GravityView_Edit_Entry_Render $this
985
		 */
986 3
		do_action( 'gravityview/edit-entry/render/before', $this );
987
988 3
		add_filter( 'gform_pre_render', array( $this, 'filter_modify_form_fields'), 5000, 3 );
989 3
		add_filter( 'gform_submit_button', array( $this, 'render_form_buttons') );
990 3
		add_filter( 'gform_disable_view_counter', '__return_true' );
991
992 3
		add_filter( 'gform_field_input', array( $this, 'verify_user_can_edit_post' ), 5, 5 );
993 3
		add_filter( 'gform_field_input', array( $this, 'modify_edit_field_input' ), 10, 5 );
994
995
		// We need to remove the fake $_GET['page'] arg to avoid rendering form as if in admin.
996 3
		unset( $_GET['page'] );
997
998
		// TODO: Verify multiple-page forms
999
1000 3
		ob_start(); // Prevent PHP warnings possibly caused by prefilling list fields for conditional logic
1001
1002 3
		$html = GFFormDisplay::get_form( $this->form['id'], false, false, true, $this->entry );
1003
1004 3
		ob_get_clean();
1005
1006 3
		remove_filter( 'gform_pre_render', array( $this, 'filter_modify_form_fields' ), 5000 );
1007 3
		remove_filter( 'gform_submit_button', array( $this, 'render_form_buttons' ) );
1008 3
		remove_filter( 'gform_disable_view_counter', '__return_true' );
1009 3
		remove_filter( 'gform_field_input', array( $this, 'verify_user_can_edit_post' ), 5 );
1010 3
		remove_filter( 'gform_field_input', array( $this, 'modify_edit_field_input' ), 10 );
1011
1012 3
		echo $html;
1013
1014
		/**
1015
		 * @action `gravityview/edit-entry/render/after` After rendering the Edit Entry form
1016
		 * @since 1.17
1017
		 * @param GravityView_Edit_Entry_Render $this
1018
		 */
1019 3
		do_action( 'gravityview/edit-entry/render/after', $this );
1020 3
	}
1021
1022
	/**
1023
	 * Display the Update/Cancel/Delete buttons for the Edit Entry form
1024
	 * @since 1.8
1025
	 * @return string
1026
	 */
1027 3
	public function render_form_buttons() {
1028 3
		return gravityview_ob_include( GravityView_Edit_Entry::$file .'/partials/form-buttons.php', $this );
1029
	}
1030
1031
1032
	/**
1033
	 * Modify the form fields that are shown when using GFFormDisplay::get_form()
1034
	 *
1035
	 * By default, all fields will be shown. We only want the Edit Tab configured fields to be shown.
1036
	 *
1037
	 * @param array $form
1038
	 * @param boolean $ajax Whether in AJAX mode
1039
	 * @param array|string $field_values Passed parameters to the form
1040
	 *
1041
	 * @since 1.9
1042
	 *
1043
	 * @return array Modified form array
1044
	 */
1045 3
	public function filter_modify_form_fields( $form, $ajax = false, $field_values = '' ) {
1046
1047
		// In case we have validated the form, use it to inject the validation results into the form render
1048 3
		if( isset( $this->form_after_validation ) ) {
1049 3
			$form = $this->form_after_validation;
1050
		} else {
1051 3
			$form['fields'] = $this->get_configured_edit_fields( $form, $this->view_id );
1052
		}
1053
1054 3
		$form = $this->filter_conditional_logic( $form );
1055
1056 3
		$form = $this->prefill_conditional_logic( $form );
1057
1058
		// for now we don't support Save and Continue feature.
1059 3
		if( ! self::$supports_save_and_continue ) {
1060 3
			unset( $form['save'] );
1061
		}
1062
1063 3
		return $form;
1064
	}
1065
1066
	/**
1067
	 * When displaying a field, check if it's a Post Field, and if so, make sure the post exists and current user has edit rights.
1068
	 *
1069
	 * @since 1.16.2.2
1070
	 *
1071
	 * @param string $field_content Always empty. Returning not-empty overrides the input.
1072
	 * @param GF_Field $field
1073
	 * @param string|array $value If array, it's a field with multiple inputs. If string, single input.
1074
	 * @param int $lead_id Lead ID. Always 0 for the `gform_field_input` filter.
1075
	 * @param int $form_id Form ID
1076
	 *
1077
	 * @return string If error, the error message. If no error, blank string (modify_edit_field_input() runs next)
1078
	 */
1079 3
	public function verify_user_can_edit_post( $field_content = '', $field, $value, $lead_id = 0, $form_id ) {
1080
1081 3
		if( GFCommon::is_post_field( $field ) ) {
1082
1083 1
			$message = null;
1084
1085
			// First, make sure they have the capability to edit the post.
1086 1
			if( false === current_user_can( 'edit_post', $this->entry['post_id'] ) ) {
1087
1088
				/**
1089
				 * @filter `gravityview/edit_entry/unsupported_post_field_text` Modify the message when someone isn't able to edit a post
1090
				 * @param string $message The existing "You don't have permission..." text
1091
				 */
1092
				$message = apply_filters('gravityview/edit_entry/unsupported_post_field_text', __('You don&rsquo;t have permission to edit this post.', 'gravityview') );
1093
1094 1
			} elseif( null === get_post( $this->entry['post_id'] ) ) {
1095
				/**
1096
				 * @filter `gravityview/edit_entry/no_post_text` Modify the message when someone is editing an entry attached to a post that no longer exists
1097
				 * @param string $message The existing "This field is not editable; the post no longer exists." text
1098
				 */
1099
				$message = apply_filters('gravityview/edit_entry/no_post_text', __('This field is not editable; the post no longer exists.', 'gravityview' ) );
1100
			}
1101
1102 1
			if( $message ) {
1103
				$field_content = sprintf('<div class="ginput_container ginput_container_' . $field->type . '">%s</div>', wpautop( $message ) );
1104
			}
1105
		}
1106
1107 3
		return $field_content;
1108
	}
1109
1110
	/**
1111
	 *
1112
	 * Fill-in the saved values into the form inputs
1113
	 *
1114
	 * @param string $field_content Always empty. Returning not-empty overrides the input.
1115
	 * @param GF_Field $field
1116
	 * @param string|array $value If array, it's a field with multiple inputs. If string, single input.
1117
	 * @param int $lead_id Lead ID. Always 0 for the `gform_field_input` filter.
1118
	 * @param int $form_id Form ID
1119
	 *
1120
	 * @return mixed
1121
	 */
1122 3
	public function modify_edit_field_input( $field_content = '', $field, $value, $lead_id = 0, $form_id ) {
1123
1124 3
		$gv_field = GravityView_Fields::get_associated_field( $field );
1125
1126
		// If the form has been submitted, then we don't need to pre-fill the values,
1127
		// Except for fileupload type and when a field input is overridden- run always!!
1128
		if(
1129 3
			( $this->is_edit_entry_submission() && !in_array( $field->type, array( 'fileupload', 'post_image' ) ) )
1130 3
			&& false === ( $gv_field && is_callable( array( $gv_field, 'get_field_input' ) ) )
1131
			&& ! GFCommon::is_product_field( $field->type )
1132 3
			|| ! empty( $field_content )
1133 3
			|| in_array( $field->type, array( 'honeypot' ) )
1134
		) {
1135
			return $field_content;
1136
		}
1137
1138
		// SET SOME FIELD DEFAULTS TO PREVENT ISSUES
1139 3
		$field->adminOnly = false; /** @see GFFormDisplay::get_counter_init_script() need to prevent adminOnly */
1140
1141 3
		$field_value = $this->get_field_value( $field );
1142
1143
		// Prevent any PHP warnings, like undefined index
1144 3
		ob_start();
1145
1146 3
		$return = null;
1147
1148
		/** @var GravityView_Field $gv_field */
1149 3
		if( $gv_field && is_callable( array( $gv_field, 'get_field_input' ) ) ) {
1150 2
			$return = $gv_field->get_field_input( $this->form, $field_value, $this->entry, $field );
1151
		} else {
1152 3
			$return = $field->get_field_input( $this->form, $field_value, $this->entry );
1153
		}
1154
1155
		// If there was output, it's an error
1156 3
		$warnings = ob_get_clean();
1157
1158 3
		if( !empty( $warnings ) ) {
1159
			do_action( 'gravityview_log_error', __METHOD__ . $warnings, $field_value );
1160
		}
1161
1162 3
		return $return;
1163
	}
1164
1165
	/**
1166
	 * Modify the value for the current field input
1167
	 *
1168
	 * @param GF_Field $field
1169
	 *
1170
	 * @return array|mixed|string
1171
	 */
1172 3
	private function get_field_value( $field ) {
1173
1174
		/**
1175
		 * @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.
1176
		 * @param boolean True: override saved values; False: don't override (default)
1177
		 * @param $field GF_Field object Gravity Forms field object
1178
		 * @since 1.13
1179
		 */
1180 3
		$override_saved_value = apply_filters( 'gravityview/edit_entry/pre_populate/override', false, $field );
1181
1182
		// We're dealing with multiple inputs (e.g. checkbox) but not time or date (as it doesn't store data in input IDs)
1183 3
		if( isset( $field->inputs ) && is_array( $field->inputs ) && !in_array( $field->type, array( 'time', 'date' ) ) ) {
1184
1185
			$field_value = array();
1186
1187
			// only accept pre-populated values if the field doesn't have any choice selected.
1188
			$allow_pre_populated = $field->allowsPrepopulate;
1189
1190
			foreach ( (array)$field->inputs as $input ) {
1191
1192
				$input_id = strval( $input['id'] );
1193
				
1194
				if ( isset( $this->entry[ $input_id ] ) && ! gv_empty( $this->entry[ $input_id ], false, false ) ) {
1195
					$field_value[ $input_id ] =  'post_category' === $field->type ? GFCommon::format_post_category( $this->entry[ $input_id ], true ) : $this->entry[ $input_id ];
1196
					$allow_pre_populated = false;
1197
				}
1198
1199
			}
1200
1201
			$pre_value = $field->get_value_submission( array(), false );
1202
1203
			$field_value = ! $allow_pre_populated && ! ( $override_saved_value && !gv_empty( $pre_value, false, false ) ) ? $field_value : $pre_value;
1204
1205
		} else {
1206
1207 3
			$id = intval( $field->id );
1208
1209
			// get pre-populated value if exists
1210 3
			$pre_value = $field->allowsPrepopulate ? GFFormsModel::get_parameter_value( $field->inputName, array(), $field ) : '';
1211
1212
			// saved field entry value (if empty, fallback to the pre-populated value, if exists)
1213
			// or pre-populated value if not empty and set to override saved value
1214 3
			$field_value = !gv_empty( $this->entry[ $id ], false, false ) && ! ( $override_saved_value && !gv_empty( $pre_value, false, false ) ) ? $this->entry[ $id ] : $pre_value;
1215
1216
			// in case field is post_category but inputType is select, multi-select or radio, convert value into array of category IDs.
1217 3
			if ( 'post_category' === $field->type && !gv_empty( $field_value, false, false ) ) {
1218
				$categories = array();
1219
				foreach ( explode( ',', $field_value ) as $cat_string ) {
1220
					$categories[] = GFCommon::format_post_category( $cat_string, true );
1221
				}
1222
				$field_value = 'multiselect' === $field->get_input_type() ? $categories : implode( '', $categories );
1223
			}
1224
1225
		}
1226
1227
		// if value is empty get the default value if defined
1228 3
		$field_value = $field->get_value_default_if_empty( $field_value );
1229
1230
		/**
1231
		 * @filter `gravityview/edit_entry/field_value` Change the value of an Edit Entry field, if needed
1232
		 * @since 1.11
1233
		 * @since 1.20 Added third param
1234
		 * @param mixed $field_value field value used to populate the input
1235
		 * @param object $field Gravity Forms field object ( Class GF_Field )
1236
		 * @param GravityView_Edit_Entry_Render $this Current object
1237
		 */
1238 3
		$field_value = apply_filters( 'gravityview/edit_entry/field_value', $field_value, $field, $this );
1239
1240
		/**
1241
		 * @filter `gravityview/edit_entry/field_value_{field_type}` Change the value of an Edit Entry field for a specific field type
1242
		 * @since 1.17
1243
		 * @since 1.20 Added third param
1244
		 * @param mixed $field_value field value used to populate the input
1245
		 * @param GF_Field $field Gravity Forms field object
1246
		 * @param GravityView_Edit_Entry_Render $this Current object
1247
		 */
1248 3
		$field_value = apply_filters( 'gravityview/edit_entry/field_value_' . $field->type , $field_value, $field, $this );
1249
1250 3
		return $field_value;
1251
	}
1252
1253
1254
	// ---- Entry validation
1255
1256
	/**
1257
	 * Add field keys that Gravity Forms expects.
1258
	 *
1259
	 * @see GFFormDisplay::validate()
1260
	 * @param  array $form GF Form
1261
	 * @return array	   Modified GF Form
1262
	 */
1263 3
	public function gform_pre_validation( $form ) {
1264
1265 3
		if( ! $this->verify_nonce() ) {
1266
			return $form;
1267
		}
1268
1269
		// Fix PHP warning regarding undefined index.
1270 3
		foreach ( $form['fields'] as &$field) {
1271
1272
			// This is because we're doing admin form pretending to be front-end, so Gravity Forms
1273
			// expects certain field array items to be set.
1274 3
			foreach ( array( 'noDuplicates', 'adminOnly', 'inputType', 'isRequired', 'enablePrice', 'inputs', 'allowedExtensions' ) as $key ) {
1275 3
				$field->{$key} = isset( $field->{$key} ) ? $field->{$key} : NULL;
1276
			}
1277
1278 3
			switch( RGFormsModel::get_input_type( $field ) ) {
1279
1280
				/**
1281
				 * 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.
1282
				 *
1283
				 * 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.
1284
				 *
1285
				 * @hack
1286
				 */
1287 3
				case 'fileupload':
1288
1289
					// Set the previous value
1290 1
					$entry = $this->get_entry();
1291
1292 1
					$input_name = 'input_'.$field->id;
1293 1
					$form_id = $form['id'];
1294
1295 1
					$value = NULL;
1296
1297
					// Use the previous entry value as the default.
1298 1
					if( isset( $entry[ $field->id ] ) ) {
1299 1
						$value = $entry[ $field->id ];
1300
					}
1301
1302
					// If this is a single upload file
1303 1
					if( !empty( $_FILES[ $input_name ] ) && !empty( $_FILES[ $input_name ]['name'] ) ) {
1304 1
						$file_path = GFFormsModel::get_file_upload_path( $form['id'], $_FILES[ $input_name ]['name'] );
1305 1
						$value = $file_path['url'];
1306
1307
					} else {
1308
1309
						// Fix PHP warning on line 1498 of form_display.php for post_image fields
1310
						// Fix PHP Notice:  Undefined index:  size in form_display.php on line 1511
1311 1
						$_FILES[ $input_name ] = array('name' => '', 'size' => '' );
1312
1313
					}
1314
1315 1
					if( rgar($field, "multipleFiles") ) {
1316
1317
						// If there are fresh uploads, process and merge them.
1318
						// Otherwise, use the passed values, which should be json-encoded array of URLs
1319 1
						if( isset( GFFormsModel::$uploaded_files[$form_id][$input_name] ) ) {
1320
							$value = empty( $value ) ? '[]' : $value;
1321
							$value = stripslashes_deep( $value );
1322 1
							$value = GFFormsModel::prepare_value( $form, $field, $value, $input_name, $entry['id'], array());
1323
						}
1324
1325
					} else {
1326
1327
						// A file already exists when editing an entry
1328
						// We set this to solve issue when file upload fields are required.
1329 1
						GFFormsModel::$uploaded_files[ $form_id ][ $input_name ] = $value;
1330
1331
					}
1332
1333 1
					$this->entry[ $input_name ] = $value;
1334 1
					$_POST[ $input_name ] = $value;
1335
1336 1
					break;
1337
1338 3
				case 'number':
1339
					// Fix "undefined index" issue at line 1286 in form_display.php
1340 1
					if( !isset( $_POST['input_'.$field->id ] ) ) {
1341
						$_POST['input_'.$field->id ] = NULL;
1342
					}
1343 3
					break;
1344
			}
1345
1346
		}
1347
1348 3
		return $form;
1349
	}
1350
1351
1352
	/**
1353
	 * Process validation for a edit entry submission
1354
	 *
1355
	 * Sets the `is_valid` object var
1356
	 *
1357
	 * @return void
1358
	 */
1359 4
	private function validate() {
1360
1361
		/**
1362
		 * If using GF User Registration Add-on, remove the validation step, otherwise generates error when updating the entry
1363
		 * GF User Registration Add-on version > 3.x has a different class name
1364
		 * @since 1.16.2
1365
		 */
1366 4
		if ( class_exists( 'GF_User_Registration' ) ) {
1367 4
			remove_filter( 'gform_validation', array( GF_User_Registration::get_instance(), 'validate' ) );
1368
			/**
1369
			 * Add some custom validation either way.
1370
			 * https://secure.helpscout.net/conversation/430858351/10957/?folderId=1210164
1371
			 */
1372 4
			add_filter( 'gform_validation_' . $this->form_id, array( $this, 'user_registration_validation' ), 10, 4 );
1373
		} else  if ( class_exists( 'GFUser' ) ) {
1374
			remove_filter( 'gform_validation', array( 'GFUser', 'user_registration_validation' ) );
1375
		}
1376
1377
1378
		/**
1379
		 * For some crazy reason, Gravity Forms doesn't validate Edit Entry form submissions.
1380
		 * You can enter whatever you want!
1381
		 * We try validating, and customize the results using `self::custom_validation()`
1382
		 */
1383 4
		add_filter( 'gform_validation_'. $this->form_id, array( $this, 'custom_validation' ), 10, 4);
1384
1385
		// Needed by the validate funtion
1386 4
		$failed_validation_page = NULL;
1387 4
		$field_values = RGForms::post( 'gform_field_values' );
1388
1389
		// Prevent entry limit from running when editing an entry, also
1390
		// prevent form scheduling from preventing editing
1391 4
		unset( $this->form['limitEntries'], $this->form['scheduleForm'] );
1392
1393
		// Hide fields depending on Edit Entry settings
1394 4
		$this->form['fields'] = $this->get_configured_edit_fields( $this->form, $this->view_id );
1395
1396 4
		$this->is_valid = GFFormDisplay::validate( $this->form, $field_values, 1, $failed_validation_page );
1397
1398 4
		remove_filter( 'gform_validation_'. $this->form_id, array( $this, 'custom_validation' ), 10 );
1399 4
		remove_filter( 'gform_validation_' . $this->form_id, array( $this, 'user_registration_validation' ), 10 );
1400 4
	}
1401
1402
	/**
1403
	 * Make validation work for User Registration feeds.
1404
	 *
1405
	 * The default validation does a bit too much for our liking.
1406
	 * Email, username validation should work. Called on the `gform_validation` filter.
1407
	 *
1408
	 * @param array $validation_results The validation results.
1409
	 * @return array The modified validation results.
1410
	 */
1411 3
	public function user_registration_validation( $validation_results ) {
1412 3
		$user_registration = GF_User_Registration::get_instance();
1413
1414 3
		$entry = $this->get_entry();
1415 3
		$form = $validation_results['form'];
1416
1417 3
		if ( ! $feed = $user_registration->get_single_submission_feed( $entry, $form ) ) {
1418
			return $validation_results;
1419
		}
1420
1421 3
		$username_field = GFFormsModel::get_field( $form, rgars( $feed, 'meta/username' ) );
1422 3
		$email_field    = GFFormsModel::get_field( $form, rgars( $feed, 'meta/email' ) );
1423
1424 3
		$username   = $user_registration->get_meta_value( 'username', $feed, $form, $entry );
1425 3
		$user_email = $user_registration->get_meta_value( 'email', $feed, $form, $entry );
1426
1427 3
		$value = RGFormsModel::get_field_value( $email_field );
1428 3
		if ( $user_email != $value && email_exists( $value ) ) {
1429
			$email_field->failed_validation = 1;
1430
			$email_field->validation_message = __( 'This email is already in use', 'gravityview' );
1431
			$validation_results['is_valid'] = false;
1432
		}
1433
1434 3
		$value = RGFormsModel::get_field_value( $username_field );
1435 3
		if ( $username != $value ) {
1436
			$username_field->failed_validation = 1;
1437
			$username_field->validation_message = __( 'Usernames cannot be changed', 'gravityview' );
1438
			$validation_results['is_valid'] = false;
1439
		}
1440
1441
		// We'll need this result when rendering the form ( on GFFormDisplay::get_form )
1442 3
		$this->form_after_validation = $validation_results['form'];
1443
1444 3
		return $validation_results;
1445
	}
1446
1447
	/**
1448
	 * Make validation work for Edit Entry
1449
	 *
1450
	 * Because we're calling the GFFormDisplay::validate() in an unusual way (as a front-end
1451
	 * form pretending to be a back-end form), validate() doesn't know we _can't_ edit post
1452
	 * fields. This goes through all the fields and if they're an invalid post field, we
1453
	 * set them as valid. If there are still issues, we'll return false.
1454
	 *
1455
	 * @param  [type] $validation_results [description]
1456
	 * @return [type]					 [description]
1457
	 */
1458 4
	public function custom_validation( $validation_results ) {
1459
1460 4
		do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] Validation results: ', $validation_results );
1461
1462 4
		do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] $_POSTed data (sanitized): ', esc_html( print_r( $_POST, true ) ) );
1463
1464 4
		$gv_valid = true;
1465
1466 4
		foreach ( $validation_results['form']['fields'] as $key => &$field ) {
1467
1468 4
			$value = RGFormsModel::get_field_value( $field );
1469 4
			$field_type = RGFormsModel::get_input_type( $field );
1470
1471
			// Validate always
1472
			switch ( $field_type ) {
1473
1474
1475 4
				case 'fileupload' :
1476 4
				case 'post_image':
1477
1478
					// in case nothing is uploaded but there are already files saved
1479 2
					if( !empty( $field->failed_validation ) && !empty( $field->isRequired ) && !empty( $value ) ) {
1480
						$field->failed_validation = false;
1481
						unset( $field->validation_message );
1482
					}
1483
1484
					// validate if multi file upload reached max number of files [maxFiles] => 2
1485 2
					if( rgobj( $field, 'maxFiles') && rgobj( $field, 'multipleFiles') ) {
1486
1487
						$input_name = 'input_' . $field->id;
1488
						//uploaded
1489
						$file_names = isset( GFFormsModel::$uploaded_files[ $validation_results['form']['id'] ][ $input_name ] ) ? GFFormsModel::$uploaded_files[ $validation_results['form']['id'] ][ $input_name ] : array();
1490
1491
						//existent
1492
						$entry = $this->get_entry();
1493
						$value = NULL;
1494
						if( isset( $entry[ $field->id ] ) ) {
1495
							$value = json_decode( $entry[ $field->id ], true );
1496
						}
1497
1498
						// count uploaded files and existent entry files
1499
						$count_files = count( $file_names ) + count( $value );
1500
1501
						if( $count_files > $field->maxFiles ) {
1502
							$field->validation_message = __( 'Maximum number of files reached', 'gravityview' );
1503
							$field->failed_validation = 1;
1504
							$gv_valid = false;
1505
1506
							// in case of error make sure the newest upload files are removed from the upload input
1507
							GFFormsModel::$uploaded_files[ $validation_results['form']['id'] ] = null;
1508
						}
1509
1510
					}
1511
1512
1513 2
					break;
1514
1515
			}
1516
1517
			// This field has failed validation.
1518 4
			if( !empty( $field->failed_validation ) ) {
1519
1520 1
				do_action( 'gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] Field is invalid.', array( 'field' => $field, 'value' => $value ) );
1521
1522
				switch ( $field_type ) {
1523
1524
					// Captchas don't need to be re-entered.
1525 1
					case 'captcha':
1526
1527
						// Post Image fields aren't editable, so we un-fail them.
1528 1
					case 'post_image':
1529
						$field->failed_validation = false;
1530
						unset( $field->validation_message );
1531
						break;
1532
1533
				}
1534
1535
				// You can't continue inside a switch, so we do it after.
1536 1
				if( empty( $field->failed_validation ) ) {
1537
					continue;
1538
				}
1539
1540
				// checks if the No Duplicates option is not validating entry against itself, since
1541
				// we're editing a stored entry, it would also assume it's a duplicate.
1542 1
				if( !empty( $field->noDuplicates ) ) {
1543
1544
					$entry = $this->get_entry();
1545
1546
					// If the value of the entry is the same as the stored value
1547
					// Then we can assume it's not a duplicate, it's the same.
1548
					if( !empty( $entry ) && $value == $entry[ $field->id ] ) {
1549
						//if value submitted was not changed, then don't validate
1550
						$field->failed_validation = false;
1551
1552
						unset( $field->validation_message );
1553
1554
						do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] Field not a duplicate; it is the same entry.', $entry );
1555
1556
						continue;
1557
					}
1558
				}
1559
1560
				// if here then probably we are facing the validation 'At least one field must be filled out'
1561 1
				if( GFFormDisplay::is_empty( $field, $this->form_id  ) && empty( $field->isRequired ) ) {
1562
					unset( $field->validation_message );
1563
					$field->validation_message = false;
1564
					continue;
1565
				}
1566
1567 4
				$gv_valid = false;
1568
1569
			}
1570
1571
		}
1572
1573 4
		$validation_results['is_valid'] = $gv_valid;
1574
1575 4
		do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] Validation results.', $validation_results );
1576
1577
		// We'll need this result when rendering the form ( on GFFormDisplay::get_form )
1578 4
		$this->form_after_validation = $validation_results['form'];
1579
1580 4
		return $validation_results;
1581
	}
1582
1583
1584
	/**
1585
	 * TODO: This seems to be hacky... we should remove it. Entry is set when updating the form using setup_vars()!
1586
	 * Get the current entry and set it if it's not yet set.
1587
	 * @return array Gravity Forms entry array
1588
	 */
1589 3
	public function get_entry() {
1590
1591 3
		if( empty( $this->entry ) ) {
1592
			// Get the database value of the entry that's being edited
1593 1
			$this->entry = gravityview_get_entry( GravityView_frontend::is_single_entry() );
1594
		}
1595
1596 3
		return $this->entry;
1597
	}
1598
1599
1600
1601
	// --- Filters
1602
1603
	/**
1604
	 * Get the Edit Entry fields as configured in the View
1605
	 *
1606
	 * @since 1.8
1607
	 *
1608
	 * @param int $view_id
1609
	 *
1610
	 * @return array Array of fields that are configured in the Edit tab in the Admin
1611
	 */
1612 4
	private function get_configured_edit_fields( $form, $view_id ) {
1613
1614
		// Get all fields for form
1615 4
		if ( defined( 'GRAVITYVIEW_FUTURE_CORE_LOADED' ) ) {
1616 4
			if ( \GV\View::exists( $view_id ) ) {
1617 4
				$view = \GV\View::by_id( $view_id );
1618 4
				$properties = $view->fields->as_configuration();
1619
			}
1620
		} else {
1621
			/** GravityView_View_Data is deprecated. */
1622
			$properties = GravityView_View_Data::getInstance()->get_fields( $view_id );
1623
		}
1624
1625
		// If edit tab not yet configured, show all fields
1626 4
		$edit_fields = !empty( $properties['edit_edit-fields'] ) ? $properties['edit_edit-fields'] : NULL;
1627
1628
		// Hide fields depending on admin settings
1629 4
		$fields = $this->filter_fields( $form['fields'], $edit_fields );
1630
1631
		// If Edit Entry fields are configured, remove adminOnly field settings. Otherwise, don't.
1632 4
		$fields = $this->filter_admin_only_fields( $fields, $edit_fields, $form, $view_id );
1633
1634
		/**
1635
		 * @filter `gravityview/edit_entry/form_fields` Modify the fields displayed in Edit Entry form
1636
		 * @since 1.17
1637
		 * @param GF_Field[] $fields Gravity Forms form fields
1638
		 * @param array|null $edit_fields Fields for the Edit Entry tab configured in the View Configuration
1639
		 * @param array $form GF Form array (`fields` key modified to have only fields configured to show in Edit Entry)
1640
		 * @param int $view_id View ID
1641
		 */
1642 4
		$fields = apply_filters( 'gravityview/edit_entry/form_fields', $fields, $edit_fields, $form, $view_id );
1643
1644 4
		return $fields;
1645
	}
1646
1647
1648
	/**
1649
	 * Filter area fields based on specified conditions
1650
	 *  - This filter removes the fields that have calculation configured
1651
	 *
1652
	 * @uses GravityView_Edit_Entry::user_can_edit_field() Check caps
1653
	 * @access private
1654
	 * @param GF_Field[] $fields
1655
	 * @param array $configured_fields
1656
	 * @since  1.5
1657
	 * @return array $fields
1658
	 */
1659 3
	private function filter_fields( $fields, $configured_fields ) {
1660
1661 3
		if( empty( $fields ) || !is_array( $fields ) ) {
1662
			return $fields;
1663
		}
1664
1665 3
		$edit_fields = array();
1666
1667 3
		$field_type_blacklist = $this->loader->get_field_blacklist( $this->entry );
1668
1669
		// First, remove blacklist or calculation fields
1670 3
		foreach ( $fields as $key => $field ) {
1671
1672
			// Remove the fields that have calculation properties and keep them to be used later
1673
			// @since 1.16.2
1674 3
			if( $field->has_calculation() ) {
1675
				$this->fields_with_calculation[] = $field;
1676
				// don't remove the calculation fields on form render.
1677
			}
1678
1679 3
			if( in_array( $field->type, $field_type_blacklist ) ) {
1680 3
				unset( $fields[ $key ] );
1681
			}
1682
		}
1683
1684
		// The Edit tab has not been configured, so we return all fields by default.
1685 3
		if( empty( $configured_fields ) ) {
1686 3
			return $fields;
1687
		}
1688
1689
		// The edit tab has been configured, so we loop through to configured settings
1690
		foreach ( $configured_fields as $configured_field ) {
1691
1692
			/** @var GF_Field $field */
1693
			foreach ( $fields as $field ) {
1694
1695
				if( intval( $configured_field['id'] ) === intval( $field->id ) && $this->user_can_edit_field( $configured_field, false ) ) {
1696
					$edit_fields[] = $this->merge_field_properties( $field, $configured_field );
1697
					break;
1698
				}
1699
1700
			}
1701
1702
		}
1703
1704
		return $edit_fields;
1705
1706
	}
1707
1708
	/**
1709
	 * Override GF Form field properties with the ones defined on the View
1710
	 * @param  GF_Field $field GF Form field object
1711
	 * @param  array $field_setting  GV field options
1712
	 * @since  1.5
1713
	 * @return array|GF_Field
1714
	 */
1715
	private function merge_field_properties( $field, $field_setting ) {
1716
1717
		$return_field = $field;
1718
1719
		if( empty( $field_setting['show_label'] ) ) {
1720
			$return_field->label = '';
1721
		} elseif ( !empty( $field_setting['custom_label'] ) ) {
1722
			$return_field->label = $field_setting['custom_label'];
1723
		}
1724
1725
		if( !empty( $field_setting['custom_class'] ) ) {
1726
			$return_field->cssClass .= ' '. gravityview_sanitize_html_class( $field_setting['custom_class'] );
1727
		}
1728
1729
		/**
1730
		 * Normalize page numbers - avoid conflicts with page validation
1731
		 * @since 1.6
1732
		 */
1733
		$return_field->pageNumber = 1;
1734
1735
		return $return_field;
1736
1737
	}
1738
1739
	/**
1740
	 * Remove fields that shouldn't be visible based on the Gravity Forms adminOnly field property
1741
	 *
1742
	 * @since 1.9.1
1743
	 *
1744
	 * @param array|GF_Field[] $fields Gravity Forms form fields
1745
	 * @param array|null $edit_fields Fields for the Edit Entry tab configured in the View Configuration
1746
	 * @param array $form GF Form array
1747
	 * @param int $view_id View ID
1748
	 *
1749
	 * @return array Possibly modified form array
1750
	 */
1751 3
	private function filter_admin_only_fields( $fields = array(), $edit_fields = null, $form = array(), $view_id = 0 ) {
1752
1753
		/**
1754
		 * @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
1755
		 * If the Edit Entry tab is not configured, adminOnly fields will not be shown to non-administrators.
1756
		 * If the Edit Entry tab *is* configured, adminOnly fields will be shown to non-administrators, using the configured GV permissions
1757
		 * @since 1.9.1
1758
		 * @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.
1759
		 * @param array $form GF Form array
1760
		 * @param int $view_id View ID
1761
		 */
1762 3
		$use_gf_adminonly_setting = apply_filters( 'gravityview/edit_entry/use_gf_admin_only_setting', empty( $edit_fields ), $form, $view_id );
1763
1764 3
		if( $use_gf_adminonly_setting && false === GVCommon::has_cap( 'gravityforms_edit_entries', $this->entry['id'] ) ) {
1765
			foreach( $fields as $k => $field ) {
1766
				if( $field->adminOnly ) {
1767
					unset( $fields[ $k ] );
1768
				}
1769
			}
1770
			return $fields;
1771
		}
1772
1773 3
		foreach( $fields as &$field ) {
1774 3
			$field->adminOnly = false;
1775
		}
1776
1777 3
		return $fields;
1778
	}
1779
1780
	// --- Conditional Logic
1781
1782
	/**
1783
	 * Conditional logic isn't designed to work with forms that already have content. When switching input values,
1784
	 * the dependent fields will be blank.
1785
	 *
1786
	 * Note: This is because GF populates a JavaScript variable with the input values. This is tough to filter at the input level;
1787
	 * via the `gform_field_value` filter; it requires lots of legwork. Doing it at the form level is easier.
1788
	 *
1789
	 * @since 1.17.4
1790
	 *
1791
	 * @param array $form Gravity Forms array object
1792
	 *
1793
	 * @return array $form, modified to fix conditional
1794
	 */
1795 3
	function prefill_conditional_logic( $form ) {
1796
1797 3
		if( ! GFFormDisplay::has_conditional_logic( $form ) ) {
1798 3
			return $form;
1799
		}
1800
1801
		// Have Conditional Logic pre-fill fields as if the data were default values
1802
		/** @var GF_Field $field */
1803
		foreach ( $form['fields'] as &$field ) {
1804
1805
			if( 'checkbox' === $field->type ) {
1806
				foreach ( $field->get_entry_inputs() as $key => $input ) {
1807
					$input_id = $input['id'];
1808
					$choice = $field->choices[ $key ];
1809
					$value = rgar( $this->entry, $input_id );
1810
					$match = RGFormsModel::choice_value_match( $field, $choice, $value );
1811
					if( $match ) {
1812
						$field->choices[ $key ]['isSelected'] = true;
1813
					}
1814
				}
1815
			} else {
1816
1817
				// We need to run through each field to set the default values
1818
				foreach ( $this->entry as $field_id => $field_value ) {
1819
1820
					if( floatval( $field_id ) === floatval( $field->id ) ) {
1821
1822
						if( 'list' === $field->type ) {
1823
							$list_rows = maybe_unserialize( $field_value );
1824
1825
							$list_field_value = array();
1826
							foreach ( (array) $list_rows as $row ) {
1827
								foreach ( (array) $row as $column ) {
1828
									$list_field_value[] = $column;
1829
								}
1830
							}
1831
1832
							$field->defaultValue = serialize( $list_field_value );
1833
						} else {
1834
							$field->defaultValue = $field_value;
1835
						}
1836
					}
1837
				}
1838
			}
1839
		}
1840
1841
		return $form;
1842
	}
1843
1844
	/**
1845
	 * Remove the conditional logic rules from the form button and the form fields, if needed.
1846
	 *
1847
	 * @todo Merge with caller method
1848
	 * @since 1.9
1849
	 *
1850
	 * @param array $form Gravity Forms form
1851
	 * @return array Modified form, if not using Conditional Logic
1852
	 */
1853 3
	private function filter_conditional_logic( $form ) {
1854
1855
		/**
1856
		 * @filter `gravityview/edit_entry/conditional_logic` Should the Edit Entry form use Gravity Forms conditional logic showing/hiding of fields?
1857
		 * @since 1.9
1858
		 * @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
1859
		 * @param array $form Gravity Forms form
1860
		 */
1861 3
		$use_conditional_logic = apply_filters( 'gravityview/edit_entry/conditional_logic', true, $form );
1862
1863 3
		if( $use_conditional_logic ) {
1864 3
			return $form;
1865
		}
1866
1867
		foreach( $form['fields'] as &$field ) {
1868
			/* @var GF_Field $field */
1869
			$field->conditionalLogic = null;
1870
		}
1871
1872
		unset( $form['button']['conditionalLogic'] );
1873
1874
		return $form;
1875
1876
	}
1877
1878
	/**
1879
	 * Disable the Gravity Forms conditional logic script and features on the Edit Entry screen
1880
	 *
1881
	 * @since 1.9
1882
	 *
1883
	 * @param $has_conditional_logic
1884
	 * @param $form
1885
	 * @return mixed
1886
	 */
1887 3
	public function manage_conditional_logic( $has_conditional_logic, $form ) {
1888
1889 3
		if( ! $this->is_edit_entry() ) {
1890
			return $has_conditional_logic;
1891
		}
1892
1893
		/** @see GravityView_Edit_Entry_Render::filter_conditional_logic for filter documentation */
1894 3
		return apply_filters( 'gravityview/edit_entry/conditional_logic', $has_conditional_logic, $form );
1895
	}
1896
1897
1898
	// --- User checks and nonces
1899
1900
	/**
1901
	 * Check if the user can edit the entry
1902
	 *
1903
	 * - Is the nonce valid?
1904
	 * - Does the user have the right caps for the entry
1905
	 * - Is the entry in the trash?
1906
	 *
1907
	 * @todo Move to GVCommon
1908
	 *
1909
	 * @param  boolean $echo Show error messages in the form?
1910
	 * @return boolean		True: can edit form. False: nope.
1911
	 */
1912 4
	private function user_can_edit_entry( $echo = false ) {
1913
1914 4
		$error = NULL;
1915
1916
		/**
1917
		 *  1. Permalinks are turned off
1918
		 *  2. There are two entries embedded using oEmbed
1919
		 *  3. One of the entries has just been saved
1920
		 */
1921 4
		if( !empty( $_POST['lid'] ) && !empty( $_GET['entry'] ) && ( $_POST['lid'] !== $_GET['entry'] ) ) {
1922
1923
			$error = true;
1924
1925
		}
1926
1927 4
		if( !empty( $_GET['entry'] ) && (string)$this->entry['id'] !== $_GET['entry'] ) {
1928
1929
			$error = true;
1930
1931 4
		} elseif( ! $this->verify_nonce() ) {
1932
1933
			/**
1934
			 * If the Entry is embedded, there may be two entries on the same page.
1935
			 * If that's the case, and one is being edited, the other should fail gracefully and not display an error.
1936
			 */
1937
			if( GravityView_oEmbed::getInstance()->get_entry_id() ) {
1938
				$error = true;
1939
			} else {
1940
				$error = __( 'The link to edit this entry is not valid; it may have expired.', 'gravityview');
1941
			}
1942
1943
		}
1944
1945 4
		if( ! GravityView_Edit_Entry::check_user_cap_edit_entry( $this->entry ) ) {
1946 1
			$error = __( 'You do not have permission to edit this entry.', 'gravityview');
1947
		}
1948
1949 4
		if( $this->entry['status'] === 'trash' ) {
1950
			$error = __('You cannot edit the entry; it is in the trash.', 'gravityview' );
1951
		}
1952
1953
		// No errors; everything's fine here!
1954 4
		if( empty( $error ) ) {
1955 4
			return true;
1956
		}
1957
1958 1
		if( $echo && $error !== true ) {
1959
1960 1
			$error = esc_html( $error );
1961
1962
			/**
1963
			 * @since 1.9
1964
			 */
1965 1
			if ( ! empty( $this->entry ) ) {
1966 1
				$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;" ) );
1967
			}
1968
1969 1
			echo GVCommon::generate_notice( wpautop( $error ), 'gv-error error');
1970
		}
1971
1972 1
		do_action('gravityview_log_error', 'GravityView_Edit_Entry[user_can_edit_entry]' . $error );
1973
1974 1
		return false;
1975
	}
1976
1977
1978
	/**
1979
	 * Check whether a field is editable by the current user, and optionally display an error message
1980
	 * @uses  GravityView_Edit_Entry->check_user_cap_edit_field() Check user capabilities
1981
	 * @param  array  $field Field or field settings array
1982
	 * @param  boolean $echo  Whether to show error message telling user they aren't allowed
1983
	 * @return boolean		 True: user can edit the current field; False: nope, they can't.
1984
	 */
1985
	private function user_can_edit_field( $field, $echo = false ) {
1986
1987
		$error = NULL;
1988
1989
		if( ! $this->check_user_cap_edit_field( $field ) ) {
1990
			$error = __( 'You do not have permission to edit this field.', 'gravityview');
1991
		}
1992
1993
		// No errors; everything's fine here!
1994
		if( empty( $error ) ) {
1995
			return true;
1996
		}
1997
1998
		if( $echo ) {
1999
			echo GVCommon::generate_notice( wpautop( esc_html( $error ) ), 'gv-error error');
2000
		}
2001
2002
		do_action('gravityview_log_error', 'GravityView_Edit_Entry[user_can_edit_field]' . $error );
2003
2004
		return false;
2005
2006
	}
2007
2008
2009
	/**
2010
	 * checks if user has permissions to edit a specific field
2011
	 *
2012
	 * Needs to be used combined with GravityView_Edit_Entry::user_can_edit_field for maximum security!!
2013
	 *
2014
	 * @param  [type] $field [description]
2015
	 * @return bool
2016
	 */
2017
	private function check_user_cap_edit_field( $field ) {
2018
2019
		// If they can edit any entries (as defined in Gravity Forms), we're good.
2020
		if( GVCommon::has_cap( array( 'gravityforms_edit_entries', 'gravityview_edit_others_entries' ) ) ) {
2021
			return true;
2022
		}
2023
2024
		$field_cap = isset( $field['allow_edit_cap'] ) ? $field['allow_edit_cap'] : false;
2025
2026
		// If the field has custom editing capaibilities set, check those
2027
		if( $field_cap ) {
2028
			return GVCommon::has_cap( $field['allow_edit_cap'] );
2029
		}
2030
2031
		return false;
2032
	}
2033
2034
2035
	/**
2036
	 * Is the current nonce valid for editing the entry?
2037
	 * @return boolean
2038
	 */
2039 3
	public function verify_nonce() {
2040
2041
		// Verify form submitted for editing single
2042 3
		if( $this->is_edit_entry_submission() ) {
2043
			$valid = wp_verify_nonce( $_POST[ self::$nonce_field ], self::$nonce_field );
2044
		}
2045
2046
		// Verify
2047 3
		else if( ! $this->is_edit_entry() ) {
2048
			$valid = false;
2049
		}
2050
2051
		else {
2052 3
			$valid = wp_verify_nonce( $_GET['edit'], self::$nonce_key );
2053
		}
2054
2055
		/**
2056
		 * @filter `gravityview/edit_entry/verify_nonce` Override Edit Entry nonce validation. Return true to declare nonce valid.
2057
		 * @since 1.13
2058
		 * @param int|boolean $valid False if invalid; 1 or 2 when nonce was generated
2059
		 * @param string $nonce_field Key used when validating submissions. Default: is_gv_edit_entry
2060
		 */
2061 3
		$valid = apply_filters( 'gravityview/edit_entry/verify_nonce', $valid, self::$nonce_field );
2062
2063 3
		return $valid;
2064
	}
2065
2066
2067
	/**
2068
	 * Multiselect in GF 2.2 became a json_encoded value. Fix it.
2069
	 *
2070
	 * As a hack for now we'll implode it back.
2071
	 */
2072
	public function fix_multiselect_value_serialization( $field_value, $field, $_this ) {
2073
		if ( empty ( $field->storageType ) || $field->storageType != 'json' ) {
2074
			return $field_value;
2075
		}
2076
2077
		$maybe_json = @json_decode( $field_value, true );
2078
2079
		if ( $maybe_json ) {
2080
			return implode( ',', $maybe_json );
2081
		}
2082
2083
		return $field_value;
2084
	}
2085
2086
2087
2088
} //end class
2089