Completed
Push — develop ( d18ace...74dfae )
by Gennady
31:26 queued 17:39
created

GravityView_Delete_Entry::display_message()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 39.2221

Importance

Changes 0
Metric Value
cc 7
nc 5
nop 1
dl 0
loc 42
ccs 3
cts 23
cp 0.1303
crap 39.2221
rs 8.3146
c 0
b 0
f 0
1
<?php
2
/**
3
 * The GravityView Delete Entry Extension
4
 *
5
 * Delete entries in GravityView.
6
 *
7
 * @since     1.5.1
8
 * @package   GravityView
9
 * @license   GPL2+
10
 * @author    Katz Web Services, Inc.
11
 * @link      http://gravityview.co
12
 * @copyright Copyright 2014, Katz Web Services, Inc.
13
 */
14
15
if ( ! defined( 'WPINC' ) ) {
16
	die;
17
}
18
19
/**
20
 * @since 1.5.1
21
 */
22
final class GravityView_Delete_Entry {
23
24
	static $file;
25
	static $instance;
26
	var $entry;
27
	var $form;
28
	var $view_id;
29
	var $is_valid = NULL;
30
31
	function __construct() {
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...
32
33
		self::$file = plugin_dir_path( __FILE__ );
34
35
		$this->add_hooks();
36
	}
37
38
	/**
39
	 * @since 1.9.2
40
	 */
41
	private function add_hooks() {
42
43
		add_action( 'wp', array( $this, 'process_delete' ), 10000 );
44
45
		add_filter( 'gravityview_entry_default_fields', array( $this, 'add_default_field'), 10, 3 );
46
47
		add_action( 'gravityview_before', array( $this, 'display_message' ) );
48
49
		// For the Delete Entry Link, you don't want visible to all users.
50
		add_filter( 'gravityview_field_visibility_caps', array( $this, 'modify_visibility_caps'), 10, 5 );
51
52
		// Modify the field options based on the name of the field type
53
		add_filter( 'gravityview_template_delete_link_options', array( $this, 'delete_link_field_options' ), 10, 5 );
54
55
		// add template path to check for field
56
		add_filter( 'gravityview_template_paths', array( $this, 'add_template_path' ) );
57
58
		add_action( 'gravityview/edit-entry/publishing-action/after', array( $this, 'add_delete_button'), 10, 4 );
59
60
		add_action ( 'gravityview/delete-entry/deleted', array( $this, 'process_connected_posts' ), 10, 2 );
61
		add_action ( 'gravityview/delete-entry/trashed', array( $this, 'process_connected_posts' ), 10, 2 );
62
	}
63
64
	/**
65
	 * Return the instantiated class object
66
	 *
67
	 * @since  1.5.1
68
	 * @return GravityView_Delete_Entry
69
	 */
70 22
	static function getInstance() {
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...
71
72 22
		if( empty( self::$instance ) ) {
73
			self::$instance = new self;
74
		}
75
76 22
		return self::$instance;
77
	}
78
79
	/**
80
	 * Include this extension templates path
81
	 *
82
	 * @since  1.5.1
83
	 * @param array $file_paths List of template paths ordered
84
	 */
85 1
	function add_template_path( $file_paths ) {
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...
86
87
		// Index 100 is the default GravityView template path.
88
		// Index 110 is Edit Entry link
89 1
		$file_paths[ 115 ] = self::$file;
90
91 1
		return $file_paths;
92
	}
93
94
	/**
95
	 * Add "Delete Link Text" setting to the edit_link field settings
96
	 *
97
	 * @since  1.5.1
98
	 * @param  [type] $field_options [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...
99
	 * @param  [type] $template_id   [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...
100
	 * @param  [type] $field_id      [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...
101
	 * @param  [type] $context       [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...
102
	 * @param  [type] $input_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...
103
	 * @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...
104
	 */
105
	function delete_link_field_options( $field_options, $template_id, $field_id, $context, $input_type ) {
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...
106
107
		// Always a link, never a filter
108
		unset( $field_options['show_as_link'], $field_options['search_filter'] );
109
110
		// Delete Entry link should only appear to visitors capable of editing entries
111
		unset( $field_options['only_loggedin'], $field_options['only_loggedin_cap'] );
112
113
		$add_option['delete_link'] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$add_option was never initialized. Although not strictly required by PHP, it is generally a good practice to add $add_option = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
114
			'type' => 'text',
115
			'label' => __( 'Delete Link Text', 'gravityview' ),
116
			'desc' => NULL,
117
			'value' => __('Delete Entry', 'gravityview'),
118
			'merge_tags' => true,
119
		);
120
121
		$field_options['allow_edit_cap'] = array(
122
			'type' => 'select',
123
			'label' => __( 'Allow the following users to delete the entry:', 'gravityview' ),
124
			'choices' => GravityView_Render_Settings::get_cap_choices( $template_id, $field_id, $context, $input_type ),
125
			'tooltip' => 'allow_edit_cap',
126
			'class' => 'widefat',
127
			'value' => 'read', // Default: entry creator
128
		);
129
130
131
		return array_merge( $add_option, $field_options );
132
	}
133
134
135
	/**
136
	 * Add Edit Link as a default field, outside those set in the Gravity Form form
137
	 *
138
	 * @since 1.5.1
139
	 * @param array $entry_default_fields Existing fields
140
	 * @param  string|array $form form_ID or form object
141
	 * @param  string $zone   Either 'single', 'directory', 'edit', 'header', 'footer'
142
	 */
143
	function add_default_field( $entry_default_fields, $form = array(), $zone = '' ) {
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
		if( 'edit' !== $zone ) {
146
			$entry_default_fields['delete_link'] = array(
147
				'label' => __( 'Delete Entry', 'gravityview' ),
148
				'type'  => 'delete_link',
149
				'desc'  => __( 'A link to delete the entry. Respects the Delete Entry permissions.', 'gravityview' ),
150
			);
151
		}
152
153
		return $entry_default_fields;
154
	}
155
156
	/**
157
	 * Add Delete Entry Link to the Add Field dialog
158
	 * @since 1.5.1
159
	 * @param array $available_fields
160
	 */
161
	function add_available_field( $available_fields = array() ) {
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...
162
163
		$available_fields['delete_link'] = array(
164
			'label_text' => __( 'Delete Entry', 'gravityview' ),
165
			'field_id' => 'delete_link',
166
			'label_type' => 'field',
167
			'input_type' => 'delete_link',
168
			'field_options' => NULL
169
		);
170
171
		return $available_fields;
172
	}
173
174
	/**
175
	 * Change wording for the Edit context to read Entry Creator
176
	 *
177
	 * @since 1.5.1
178
	 * @param  array 	   $visibility_caps        Array of capabilities to display in field dropdown.
179
	 * @param  string      $field_type  Type of field options to render (`field` or `widget`)
0 ignored issues
show
Bug introduced by
There is no parameter named $field_type. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

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

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

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

Loading history...
180
	 * @param  string      $template_id Table slug
181
	 * @param  float       $field_id    GF Field ID - Example: `3`, `5.2`, `entry_link`, `created_by`
182
	 * @param  string      $context     What context are we in? Example: `single` or `directory`
183
	 * @param  string      $input_type  (textarea, list, select, etc.)
184
	 * @return array                   Array of field options with `label`, `value`, `type`, `default` keys
185
	 */
186
	public function modify_visibility_caps( $visibility_caps = array(), $template_id = '', $field_id = '', $context = '', $input_type = '' ) {
0 ignored issues
show
Unused Code introduced by
The parameter $context 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 $input_type 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...
187
188
		$caps = $visibility_caps;
189
190
		// If we're configuring fields in the edit context, we want a limited selection
191
		if( $field_id === 'delete_link' ) {
192
193
			// Remove other built-in caps.
194
			unset( $caps['publish_posts'], $caps['gravityforms_view_entries'], $caps['delete_others_posts'] );
195
196
			$caps['read'] = _x('Entry Creator', 'User capability', 'gravityview');
197
		}
198
199
		return $caps;
200
	}
201
202
	/**
203
	 * Make sure there's an entry
204
	 *
205
	 * @since 1.5.1
206
	 * @param [type] $entry [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...
207
	 */
208 22
	function set_entry( $entry = null ) {
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...
209 22
		$this->entry = empty( $entry ) ? GravityView_View::getInstance()->entries[0] : $entry;
0 ignored issues
show
Documentation introduced by
The property $entries is declared protected in GravityView_View. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
210 22
	}
211
212
	/**
213
	 * Generate a consistent nonce key based on the Entry ID
214
	 *
215
	 * @since 1.5.1
216
	 * @param  int $entry_id Entry ID
217
	 * @return string           Key used to validate request
218
	 */
219
	public static function get_nonce_key( $entry_id ) {
220
		return sprintf( 'delete_%s', $entry_id );
221
	}
222
223
224
	/**
225
	 * Generate a nonce link with the base URL of the current View embed
226
	 *
227
	 * We don't want to link to the single entry, because when deleted, there would be nothing to return to.
228
	 *
229
	 * @since 1.5.1
230
	 * @param  array       $entry Gravity Forms entry array
231
	 * @param  int         $view_id The View id. Not optional since 2.0
232
	 * @return string|null If directory link is valid, the URL to process the delete request. Otherwise, `NULL`.
233
	 */
234 22
	public static function get_delete_link( $entry, $view_id = 0, $post_id = null ) {
235 22
		if ( ! $view_id ) {
236
			/** @deprecated path */
237
			$view_id = gravityview_get_view_id();
238
		}
239
240 22
		self::getInstance()->set_entry( $entry );
241
242 22
        $base = GravityView_API::directory_link( $post_id ? : $view_id, true );
243
244 22
		if ( empty( $base ) ) {
245
			gravityview()->log->error( 'Post ID does not exist: {post_id}', array( 'post_id' => $post_id ) );
246
			return NULL;
247
		}
248
249
		// Use the slug instead of the ID for consistent security
250 22
		$entry_slug = GravityView_API::get_entry_slug( $entry['id'], $entry );
251
252 22
		$actionurl = add_query_arg( array(
253 22
			'action'	=> 'delete',
254 22
			'entry_id'		=> $entry_slug,
255 22
			'gvid' => $view_id,
256 22
            'view_id' => $view_id,
257 22
		), $base );
258
259 22
		$url = wp_nonce_url( $actionurl, 'delete_'.$entry_slug, 'delete' );
260
261 22
		return $url;
262
	}
263
264
265
	/**
266
	 * Add a Delete button to the #publishing-action section of the Delete Entry form
267
	 *
268
	 * @since 1.5.1
269
	 * @since 2.0.13 Added $post_id
270
	 *
271
	 * @param array $form    Gravity Forms form array
272
	 * @param array $entry   Gravity Forms entry array
273
	 * @param int $view_id GravityView View ID
274
	 * @param int $post_id Current post ID. May be same as View ID.
275
	 *
276
	 * @return void
277
	 */
278 22
	public function add_delete_button( $form = array(), $entry = array(), $view_id = null, $post_id = null ) {
279
280
		// Only show the link to those who are allowed to see it.
281 22
		if( !self::check_user_cap_delete_entry( $entry, array(), $view_id ) ) {
282 1
			return;
283
		}
284
285
		/**
286
		 * @filter `gravityview/delete-entry/show-delete-button` Should the Delete button be shown in the Edit Entry screen?
287
		 * @param boolean $show_entry Default: true
288
		 */
289 21
		$show_delete_button = apply_filters( 'gravityview/delete-entry/show-delete-button', true );
290
291
		// If the button is hidden by the filter, don't show.
292 21
		if( !$show_delete_button ) {
293
			return;
294
		}
295
296
		$attributes = array(
297 21
			'class' => 'btn btn-sm button button-small alignright pull-right btn-danger gv-button-delete',
298 21
			'tabindex' => ( GFCommon::$tab_index ++ ),
299 21
			'onclick' => self::get_confirm_dialog(),
300
		);
301
302 21
		echo gravityview_get_link( self::get_delete_link( $entry, $view_id, $post_id ), esc_attr__( 'Delete', 'gravityview' ), $attributes );
303
304 21
	}
305
306
	/**
307
	 * Handle the deletion request, if $_GET['action'] is set to "delete"
308
	 *
309
	 * 1. Check referrer validity
310
	 * 2. Make sure there's an entry with the slug of $_GET['entry_id']
311
	 * 3. If so, attempt to delete the entry. If not, set the error status
312
	 * 4. Remove `action=delete` from the URL
313
	 * 5. Redirect to the page using `wp_safe_redirect()`
314
	 *
315
	 * @since 1.5.1
316
	 * @uses wp_safe_redirect()
317
	 * @return void
318
	 */
319 1
	function process_delete() {
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...
320
321
		// If the form is submitted
322 1
		if( isset( $_GET['action'] ) && 'delete' === $_GET['action'] && isset( $_GET['entry_id'] ) ) {
323
324
			// Make sure it's a GravityView request
325
			$valid_nonce_key = wp_verify_nonce( $_GET['delete'], self::get_nonce_key( $_GET['entry_id'] ) );
326
327
			if( ! $valid_nonce_key ) {
328
				gravityview()->log->debug( 'Delete entry not processed: nonce validation failed.' );
329
				return;
330
			}
331
332
			// Get the entry slug
333
			$entry_slug = esc_attr( $_GET['entry_id'] );
334
335
			// See if there's an entry there
336
			$entry = gravityview_get_entry( $entry_slug, true, false );
337
338
			if( $entry ) {
339
340
				$has_permission = $this->user_can_delete_entry( $entry );
341
342
				if( is_wp_error( $has_permission ) ) {
343
344
					$messages = array(
345
						'message' => urlencode( $has_permission->get_error_message() ),
346
						'status' => 'error',
347
					);
348
349
				} else {
350
351
					// Delete the entry
352
					$delete_response = $this->delete_or_trash_entry( $entry );
353
354
					if( is_wp_error( $delete_response ) ) {
355
356
						$messages = array(
357
							'message' => urlencode( $delete_response->get_error_message() ),
358
							'status' => 'error',
359
						);
360
361
					} else {
362
363
						$messages = array(
364
							'status' => $delete_response,
365
						);
366
367
					}
368
369
				}
370
371
			} else {
372
373
				gravityview()->log->debug( 'Delete entry failed: there was no entry with the entry slug {entry_slug}', array( 'entry_slug' => $entry_slug ) );
374
375
				$messages = array(
376
					'message' => urlencode( __('The entry does not exist.', 'gravityview') ),
377
					'status' => 'error',
378
				);
379
			}
380
381
			$redirect_to_base = esc_url_raw( remove_query_arg( array( 'action', 'gvid' ) ) );
382
			$redirect_to = add_query_arg( $messages, $redirect_to_base );
383
384
			wp_safe_redirect( $redirect_to );
385
386
			exit();
387
388
		} // endif action is delete.
389
390 1
	}
391
392
	/**
393
	 * Delete mode: permanently delete, or move to trash?
394
	 *
395
	 * @return string `delete` or `trash`
396
	 */
397
	private function get_delete_mode() {
398
399
		/**
400
		 * @filter `gravityview/delete-entry/mode` Delete mode: permanently delete, or move to trash?
401
		 * @since 1.13.1
402
		 * @param string $delete_mode Delete mode: `trash` or `delete`. Default: `delete`
403
		 */
404
		$delete_mode = apply_filters( 'gravityview/delete-entry/mode', 'delete' );
405
406
		return ( 'trash' === $delete_mode ) ? 'trash' : 'delete';
407
	}
408
409
	/**
410
	 * @since 1.13.1
411
	 * @see GFAPI::delete_entry()
412
	 * @return WP_Error|boolean GFAPI::delete_entry() returns a WP_Error on error
413
	 */
414
	private function delete_or_trash_entry( $entry ) {
415
416
		$entry_id = $entry['id'];
417
		
418
		$mode = $this->get_delete_mode();
419
420
		if( 'delete' === $mode ) {
421
422
			gravityview()->log->debug( 'Starting delete entry: {entry_id}', array( 'entry_id' => $entry_id ) );
423
424
			// Delete the entry
425
			$delete_response = GFAPI::delete_entry( $entry_id );
426
427
			if( ! is_wp_error( $delete_response ) ) {
428
				$delete_response = 'deleted';
429
430
				/**
431
				 * @action `gravityview/delete-entry/deleted` Triggered when an entry is deleted
432
				 * @since 1.16.4
433
				 * @param  int $entry_id ID of the Gravity Forms entry
434
				 * @param  array $entry Deleted entry array
435
				*/
436
				do_action( 'gravityview/delete-entry/deleted', $entry_id, $entry );
437
			}
438
439
			gravityview()->log->debug( 'Delete response: {delete_response}', array( 'delete_response' => $delete_response ) );
440
441
		} else {
442
443
			gravityview()->log->debug( 'Starting trash entry: {entry_id}', array( 'entry_id' => $entry_id ) );
444
445
			$trashed = GFAPI::update_entry_property( $entry_id, 'status', 'trash' );
446
			new GravityView_Cache;
447
448
			if( ! $trashed ) {
449
				$delete_response = new WP_Error( 'trash_entry_failed', __('Moving the entry to the trash failed.', 'gravityview' ) );
450
			} else {
451
452
				/**
453
				 * @action `gravityview/delete-entry/trashed` Triggered when an entry is trashed
454
				 * @since 1.16.4
455
				 * @param  int $entry_id ID of the Gravity Forms entry
456
				 * @param  array $entry Deleted entry array
457
				 */
458
				do_action( 'gravityview/delete-entry/trashed', $entry_id, $entry );
459
460
				$delete_response = 'trashed';
461
			}
462
463
			gravityview()->log->debug( ' Trashed? {delete_response}', array( 'delete_response' => $delete_response ) );
464
		}
465
466
		return $delete_response;
467
	}
468
469
	/**
470
	 * Delete or trash a post connected to an entry
471
	 *
472
	 * @since 1.17
473
	 *
474
	 * @param int $entry_id ID of entry being deleted/trashed
475
	 * @param array $entry Array of the entry being deleted/trashed
476
	 */
477
	public function process_connected_posts( $entry_id = 0, $entry = array() ) {
478
479
		// The entry had no connected post
480
		if( empty( $entry['post_id'] ) ) {
481
			return;
482
		}
483
484
		/**
485
		 * @filter `gravityview/delete-entry/delete-connected-post` Should posts connected to an entry be deleted when the entry is deleted?
486
		 * @since 1.17
487
		 * @param boolean $delete_post If trashing an entry, trash the post. If deleting an entry, delete the post. Default: true
488
		 */
489
		$delete_post = apply_filters( 'gravityview/delete-entry/delete-connected-post', true );
490
		
491
		if( false === $delete_post ) {
492
			return;
493
		}
494
495
		$action = current_action();
496
497
		if( 'gravityview/delete-entry/deleted' === $action ) {
498
			$result = wp_delete_post( $entry['post_id'], true );
499
		} else {
500
			$result = wp_trash_post( $entry['post_id'] );
501
		}
502
503
		if( false === $result ) {
504
			gravityview()->log->error( '(called by {action}): Error processing the Post connected to the entry.', array( 'action' => $action, 'data' => $entry ) );
505
		} else {
506
			gravityview()->log->debug( '(called by {action}): Successfully processed Post connected to the entry.', array( 'action' => $action, 'data' => $entry ) );
507
		}
508
	}
509
510
	/**
511
	 * Is the current nonce valid for editing the entry?
512
	 *
513
	 * @since 1.5.1
514
	 * @return boolean
515
	 */
516
	public function verify_nonce() {
517
518
		// No delete entry request was made
519
		if( empty( $_GET['entry_id'] ) || empty( $_GET['delete'] ) ) {
520
			return false;
521
		}
522
523
		$nonce_key = self::get_nonce_key( $_GET['entry_id'] );
524
525
		$valid = wp_verify_nonce( $_GET['delete'], $nonce_key );
526
527
		/**
528
		 * @filter `gravityview/delete-entry/verify_nonce` Override Delete Entry nonce validation. Return true to declare nonce valid.
529
		 * @since 1.15.2
530
		 * @see wp_verify_nonce()
531
		 * @param int|boolean $valid False if invalid; 1 or 2 when nonce was generated
532
		 * @param string $nonce_key Name of nonce action used in wp_verify_nonce. $_GET['delete'] holds the nonce value itself. Default: `delete_{entry_id}`
533
		 */
534
		$valid = apply_filters( 'gravityview/delete-entry/verify_nonce', $valid, $nonce_key );
535
536
		return $valid;
537
	}
538
539
	/**
540
	 * Get the onclick attribute for the confirm dialogs that warns users before they delete an entry
541
	 *
542
	 * @since 1.5.1
543
	 * @return string HTML `onclick` attribute
544
	 */
545 22
	public static function get_confirm_dialog() {
546
547 22
		$confirm = __('Are you sure you want to delete this entry? This cannot be undone.', 'gravityview');
548
549
		/**
550
		 * @filter `gravityview/delete-entry/confirm-text` Modify the Delete Entry Javascript confirmation text
551
		 * @param string $confirm Default: "Are you sure you want to delete this entry? This cannot be undone."
552
		 */
553 22
		$confirm = apply_filters( 'gravityview/delete-entry/confirm-text', $confirm );
554
555 22
		return 'return window.confirm(\''. esc_js( $confirm ) .'\');';
556
	}
557
558
	/**
559
	 * Check if the user can edit the entry
560
	 *
561
	 * - Is the nonce valid?
562
	 * - Does the user have the right caps for the entry
563
	 * - Is the entry in the trash?
564
	 *
565
	 * @since 1.5.1
566
	 * @param  array $entry Gravity Forms entry array
567
	 * @return boolean|WP_Error        True: can edit form. WP_Error: nope.
568
	 */
569
	function user_can_delete_entry( $entry = array(), $view_id = null ) {
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...
570
571
		$error = NULL;
572
573
		if( ! $this->verify_nonce() ) {
574
			$error = __( 'The link to delete this entry is not valid; it may have expired.', 'gravityview');
575
		}
576
577
		if( ! self::check_user_cap_delete_entry( $entry, array(), $view_id ) ) {
578
			$error = __( 'You do not have permission to delete this entry.', 'gravityview');
579
		}
580
581
		if( $entry['status'] === 'trash' ) {
582
			if( 'trash' === $this->get_delete_mode() ) {
583
				$error = __( 'The entry is already in the trash.', 'gravityview' );
584
			} else {
585
				$error = __( 'You cannot delete the entry; it is already in the trash.', 'gravityview' );
586
			}
587
		}
588
589
		// No errors; everything's fine here!
590
		if( empty( $error ) ) {
591
			return true;
592
		}
593
594
		gravityview()->log->error( '{error}', array( 'erorr' => $error ) );
595
596
		return new WP_Error( 'gravityview-delete-entry-permissions', $error );
597
	}
598
599
600
	/**
601
	 * checks if user has permissions to view the link or delete a specific entry
602
	 *
603
	 * @since 1.5.1
604
	 * @since 1.15 Added `$view_id` param
605
	 *
606
	 * @param  array $entry Gravity Forms entry array
607
	 * @param array $field Field settings (optional)
608
	 * @param int $view_id Pass a View ID to check caps against. If not set, check against current View (@deprecated no longer optional)
609
	 * @return bool
610
	 */
611 23
	public static function check_user_cap_delete_entry( $entry, $field = array(), $view_id = 0 ) {
612 23
		if ( ! $view_id ) {
613
			/** @deprecated path */
614
			$view_id = GravityView_View::getInstance()->getViewId();
615
		}
616
617 23
		$current_user = wp_get_current_user();
618
619 23
		$entry_id = isset( $entry['id'] ) ? $entry['id'] : NULL;
620
621
		// Or if they can delete any entries (as defined in Gravity Forms), we're good.
622 23
		if( GVCommon::has_cap( array( 'gravityforms_delete_entries', 'gravityview_delete_others_entries' ), $entry_id ) ) {
623
624 22
			gravityview()->log->debug( 'Current user has `gravityforms_delete_entries` or `gravityview_delete_others_entries` capability.' );
625
626 22
			return true;
627
		}
628
629
630
		// If field options are passed, check if current user can view the link
631 2
		if( !empty( $field ) ) {
632
633
			// If capability is not defined, something is not right!
634 1
			if( empty( $field['allow_edit_cap'] ) ) {
635
636 1
				gravityview()->log->error( 'Cannot read delete entry field caps', array( 'data' => $field ) );
637
638 1
				return false;
639
			}
640
641
			if( GVCommon::has_cap( $field['allow_edit_cap'] ) ) {
642
643
				// Do not return true if cap is read, as we need to check if the current user created the entry
644
				if( $field['allow_edit_cap'] !== 'read' ) {
645
					return true;
646
				}
647
648
			} else {
649
650
				gravityview()->log->debug( 'User {user_id} is not authorized to view delete entry link ', array( 'user_id' => $current_user->ID ) );
651
652
				return false;
653
			}
654
655
		}
656
657 1
		if( !isset( $entry['created_by'] ) ) {
658
659
			gravityview()->log->error( 'Entry `created_by` doesn\'t exist.');
660
661
			return false;
662
		}
663
664
		// Only checks user_delete view option if view is already set
665 1
		if( $view_id ) {
666
667 1
			if ( ! $view = \GV\View::by_id( $view_id ) ) {
668
				return false;
669
			}
670
671 1
			$user_delete = $view->settings->get( 'user_delete', false );
672
673 1
			if ( empty( $user_delete ) ) {
674
675 1
				gravityview()->log->debug( 'User Delete is disabled. Returning false.' );
676
677 1
				return false;
678
			}
679
		}
680
681
		// If the logged-in user is the same as the user who created the entry, we're good.
682
		if( is_user_logged_in() && intval( $current_user->ID ) === intval( $entry['created_by'] ) ) {
683
684
			gravityview()->log->debug( 'User {user_id} created the entry.', array( 'user_id' => $current_user->ID ) );
685
686
			return true;
687
		}
688
689
		return false;
690
	}
691
692
693
	/**
694
	 * After processing delete entry, the user will be redirected to the referring View or embedded post/page. Display a message on redirection.
695
	 *
696
	 * If success, there will be `status` URL parameters `status=>success`
697
	 * If an error, there will be `status` and `message` URL parameters `status=>error&message=example`
698
	 *
699
	 * @since 1.15.2 Only show message when the URL parameter's View ID matches the current View ID
700
	 * @since 1.5.1
701
	 *
702
	 * @param int $current_view_id The ID of the View being rendered
703
	 * @return void
704
	 */
705 36
	public function display_message( $current_view_id = 0 ) {
706
707 36
		if( empty( $_GET['status'] ) || ! self::verify_nonce() ) {
708 36
			return;
709
		}
710
711
		// Entry wasn't deleted from current View
712
		if( isset( $_GET['view_id'] ) && intval( $_GET['view_id'] ) !== intval( $current_view_id ) ) {
713
			return;
714
		}
715
716
		$status = esc_attr( $_GET['status'] );
717
		$message_from_url = \GV\Utils::_GET( 'message' );
718
		$message_from_url = rawurldecode( stripslashes_deep( $message_from_url ) );
719
		$class = '';
720
721
		switch ( $status ) {
722
			case 'error':
723
				$class = ' gv-error error';
724
				$error_message = __('There was an error deleting the entry: %s', 'gravityview');
725
				$message = sprintf( $error_message, $message_from_url );
726
				break;
727
			case 'trashed':
728
				$message = __('The entry was successfully moved to the trash.', 'gravityview');
729
				break;
730
			default:
731
				$message = __('The entry was successfully deleted.', 'gravityview');
732
				break;
733
		}
734
735
		/**
736
		 * @filter `gravityview/delete-entry/message` Modify the Delete Entry messages
737
		 * @since 1.13.1
738
		 * @param string $message Message to be displayed
739
		 * @param string $status Message status (`error` or `success`)
740
		 * @param string $message_from_url The original error message, if any, without the "There was an error deleting the entry:" prefix
741
		 */
742
		$message = apply_filters( 'gravityview/delete-entry/message', esc_attr( $message ), $status, $message_from_url );
743
744
		// DISPLAY ERROR/SUCCESS MESSAGE
745
		echo '<div class="gv-notice' . esc_attr( $class ) .'">'. $message .'</div>';
746
	}
747
748
749
} // end class
750
751
GravityView_Delete_Entry::getInstance();
752
753