Completed
Push — master ( 5d3455...ebef7a )
by Zack
10s
created

process_connected_posts()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 32
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 15
c 2
b 0
f 0
nc 6
nop 2
dl 0
loc 32
rs 8.439
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 22 and the first side effect is on line 16.

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

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

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

Loading history...
2
/**
3
 * 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;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $file.

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

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
25
	static $instance;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $instance.

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

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
26
	var $entry;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $entry.

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

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
27
	var $form;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $form.

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

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
28
	var $view_id;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $view_id.

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

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
29
	var $is_valid = NULL;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $is_valid.

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

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
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 );
0 ignored issues
show
introduced by
No space before closing parenthesis of array is bad style
Loading history...
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 );
0 ignored issues
show
introduced by
No space before closing parenthesis of array is bad style
Loading history...
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, 3 );
0 ignored issues
show
introduced by
No space before closing parenthesis of array is bad style
Loading history...
59
60
		add_action ( 'gravityview/delete-entry/deleted', array( $this, 'process_connected_posts' ), 10, 2 );
0 ignored issues
show
Coding Style introduced by
Space before opening parenthesis of function call prohibited
Loading history...
61
		add_action ( 'gravityview/delete-entry/trashed', array( $this, 'process_connected_posts' ), 10, 2 );
0 ignored issues
show
Coding Style introduced by
Space before opening parenthesis of function call prohibited
Loading history...
62
	}
63
64
	/**
65
	 * Return the instantiated class object
66
	 *
67
	 * @since  1.5.1
68
	 * @return GravityView_Delete_Entry
69
	 */
70
	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...
Coding Style introduced by
The function name getInstance is in camel caps, but expected get_instance instead as per the coding standard.
Loading history...
71
72
		if( empty( self::$instance ) ) {
73
			self::$instance = new self;
74
		}
75
76
		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
	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
		$file_paths[ 115 ] = self::$file;
0 ignored issues
show
introduced by
Array keys should NOT be surrounded by spaces if they only contain a string or an integer.
Loading history...
90
91
		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,
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
117
			'value' => __('Delete Entry', 'gravityview'),
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
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
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
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', 'header', 'footer'
142
	 */
143
	function add_default_field( $entry_default_fields, $form = array(), $zone = '' ) {
0 ignored issues
show
Unused Code introduced by
The parameter $form 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 $zone is not used and could be removed.

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

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

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

Loading history...
144
145
		$entry_default_fields['delete_link'] = array(
146
			'label' => __('Delete Entry', 'gravityview'),
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
147
			'type' => 'delete_link',
148
			'desc'	=> __('A link to delete the entry. Respects the Delete Entry permissions.', 'gravityview'),
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
149
		);
150
151
		return $entry_default_fields;
152
	}
153
154
	/**
155
	 * Add Delete Entry Link to the Add Field dialog
156
	 * @since 1.5.1
157
	 * @param array $available_fields
158
	 */
159
	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...
160
161
		$available_fields['delete_link'] = array(
162
			'label_text' => __( 'Delete Entry', 'gravityview' ),
163
			'field_id' => 'delete_link',
164
			'label_type' => 'field',
165
			'input_type' => 'delete_link',
166
			'field_options' => NULL
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
167
		);
168
169
		return $available_fields;
170
	}
171
172
	/**
173
	 * Change wording for the Edit context to read Entry Creator
174
	 *
175
	 * @since 1.5.1
176
	 * @param  array 	   $visibility_caps        Array of capabilities to display in field dropdown.
177
	 * @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...
178
	 * @param  string      $template_id Table slug
179
	 * @param  float       $field_id    GF Field ID - Example: `3`, `5.2`, `entry_link`, `created_by`
180
	 * @param  string      $context     What context are we in? Example: `single` or `directory`
181
	 * @param  string      $input_type  (textarea, list, select, etc.)
182
	 * @return array                   Array of field options with `label`, `value`, `type`, `default` keys
183
	 */
184
	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...
185
186
		$caps = $visibility_caps;
187
188
		// If we're configuring fields in the edit context, we want a limited selection
189
		if( $field_id === 'delete_link' ) {
0 ignored issues
show
introduced by
Found "=== '". Use Yoda Condition checks, you must
Loading history...
190
191
			// Remove other built-in caps.
192
			unset( $caps['publish_posts'], $caps['gravityforms_view_entries'], $caps['delete_others_posts'] );
193
194
			$caps['read'] = _x('Entry Creator', 'User capability', 'gravityview');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
195
		}
196
197
		return $caps;
198
	}
199
200
	/**
201
	 * Make sure there's an entry
202
	 *
203
	 * @since 1.5.1
204
	 * @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...
205
	 */
206
	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...
207
		$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...
208
	}
209
210
	/**
211
	 * Generate a consistent nonce key based on the Entry ID
212
	 *
213
	 * @since 1.5.1
214
	 * @param  int $entry_id Entry ID
215
	 * @return string           Key used to validate request
216
	 */
217
	public static function get_nonce_key( $entry_id ) {
218
		return sprintf( 'delete_%s', $entry_id );
219
	}
220
221
222
	/**
223
	 * Generate a nonce link with the base URL of the current View embed
224
	 *
225
	 * We don't want to link to the single entry, because when deleted, there would be nothing to return to.
226
	 *
227
	 * @since 1.5.1
228
	 * @param  array      $entry Gravity Forms entry array
229
	 * @return string|null             If directory link is valid, the URL to process the delete request. Otherwise, `NULL`.
230
	 */
231
	public static function get_delete_link( $entry, $view_id = 0, $post_id = null ) {
232
233
		self::getInstance()->set_entry( $entry );
234
235
        $base = GravityView_API::directory_link( $post_id, true );
236
237
		if( empty( $base ) ) {
238
			do_action( 'gravityview_log_error', __METHOD__ . ' - Post ID does not exist: '.$post_id );
239
			return NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
240
		}
241
242
		// Use the slug instead of the ID for consistent security
243
		$entry_slug = GravityView_API::get_entry_slug( $entry['id'], $entry );
244
245
        $view_id = empty( $view_id ) ? gravityview_get_view_id() : $view_id;
246
247
		$actionurl = add_query_arg( array(
248
			'action'	=> 'delete',
249
			'entry_id'		=> $entry_slug,
250
			'gvid' => $view_id,
251
            'view_id' => $view_id,
252
		), $base );
253
254
		$url = wp_nonce_url( $actionurl, 'delete_'.$entry_slug, 'delete' );
255
256
		return $url;
257
	}
258
259
260
	/**
261
	 * Add a Delete button to the #publishing-action section of the Delete Entry form
262
	 *
263
	 * @since 1.5.1
264
	 * @param array $form    Gravity Forms form array
265
	 * @param array $entry   Gravity Forms entry array
266
	 * @param int $view_id GravityView View ID
267
	 */
268
	function add_delete_button( $form = array(), $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...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
269
270
		// Only show the link to those who are allowed to see it.
271
		if( !self::check_user_cap_delete_entry( $entry ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
272
			return;
273
		}
274
275
		/**
276
		 * @filter `gravityview/delete-entry/show-delete-button` Should the Delete button be shown in the Edit Entry screen?
277
		 * @param boolean $show_entry Default: true
278
		 */
279
		$show_delete_button = apply_filters( 'gravityview/delete-entry/show-delete-button', true );
280
281
		// If the button is hidden by the filter, don't show.
282
		if( !$show_delete_button ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
283
			return;
284
		}
285
286
		$attributes = array(
287
			'class' => 'btn btn-sm button button-small alignright pull-right btn-danger gv-button-delete',
288
			'tabindex' => '5',
289
			'onclick' => self::get_confirm_dialog(),
290
		);
291
292
		echo gravityview_get_link( self::get_delete_link( $entry, $view_id ), esc_attr__( 'Delete', 'gravityview' ), $attributes );
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'gravityview_get_link'
Loading history...
293
294
	}
295
296
	/**
297
	 * Handle the deletion request, if $_GET['action'] is set to "delete"
298
	 *
299
	 * 1. Check referrer validity
300
	 * 2. Make sure there's an entry with the slug of $_GET['entry_id']
301
	 * 3. If so, attempt to delete the entry. If not, set the error status
302
	 * 4. Remove `action=delete` from the URL
303
	 * 5. Redirect to the page using `wp_safe_redirect()`
304
	 *
305
	 * @since 1.5.1
306
	 * @uses wp_safe_redirect()
307
	 * @return void
308
	 */
309
	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...
310
311
		// If the form is submitted
312
		if( isset( $_GET['action'] ) && 'delete' === $_GET['action'] && isset( $_GET['entry_id'] ) ) {
313
314
			// Make sure it's a GravityView request
315
			$valid_nonce_key = wp_verify_nonce( $_GET['delete'], self::get_nonce_key( $_GET['entry_id'] ) );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_GET
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
316
317
			if( ! $valid_nonce_key ) {
318
				do_action('gravityview_log_debug', __METHOD__ . ' Delete entry not processed: nonce validation failed.' );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
319
				return;
320
			}
321
322
			// Get the entry slug
323
			$entry_slug = esc_attr( $_GET['entry_id'] );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
324
325
			// See if there's an entry there
326
			$entry = gravityview_get_entry( $entry_slug );
327
328
			if( $entry ) {
329
330
				$has_permission = $this->user_can_delete_entry( $entry );
331
332
				if( is_wp_error( $has_permission ) ) {
333
334
					$messages = array(
335
						'message' => urlencode( $has_permission->get_error_message() ),
336
						'status' => 'error',
337
					);
338
339
				} else {
340
341
					// Delete the entry
342
					$delete_response = $this->delete_or_trash_entry( $entry );
343
344
					if( is_wp_error( $delete_response ) ) {
345
346
						$messages = array(
347
							'message' => urlencode( $delete_response->get_error_message() ),
348
							'status' => 'error',
349
						);
350
351
					} else {
352
353
						$messages = array(
354
							'status' => $delete_response,
355
						);
356
357
					}
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
358
359
				}
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
360
361
			} else {
362
363
				do_action('gravityview_log_debug', __METHOD__ . ' Delete entry failed: there was no entry with the entry slug '. $entry_slug );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
364
365
				$messages = array(
366
					'message' => urlencode( __('The entry does not exist.', 'gravityview') ),
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
367
					'status' => 'error',
368
				);
369
			}
370
371
			$redirect_to_base = esc_url_raw( remove_query_arg( array( 'action' ) ) );
372
			$redirect_to = add_query_arg( $messages, $redirect_to_base );
373
374
			wp_safe_redirect( $redirect_to );
375
376
			exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method process_delete() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
377
378
		} // endif action is delete.
379
380
	}
381
382
	/**
383
	 * Delete mode: permanently delete, or move to trash?
384
	 *
385
	 * @return string `delete` or `trash`
386
	 */
387
	private function get_delete_mode() {
388
389
		/**
390
		 * @filter `gravityview/delete-entry/mode` Delete mode: permanently delete, or move to trash?
391
		 * @since 1.13.1
392
		 * @param string $delete_mode Delete mode: `trash` or `delete`. Default: `delete`
393
		 */
394
		$delete_mode = apply_filters( 'gravityview/delete-entry/mode', 'delete' );
395
396
		return ( 'trash' === $delete_mode ) ? 'trash' : 'delete';
397
	}
398
399
	/**
400
	 * @since 1.13.1
401
	 * @see GFAPI::delete_entry()
402
	 * @return WP_Error|boolean GFAPI::delete_entry() returns a WP_Error on error
403
	 */
404
	private function delete_or_trash_entry( $entry ) {
405
406
		$entry_id = $entry['id'];
407
		
408
		$mode = $this->get_delete_mode();
409
410
		if( 'delete' === $mode ) {
411
412
			do_action( 'gravityview_log_debug', __METHOD__ . ' Starting delete entry: ', $entry_id );
413
414
			// Delete the entry
415
			$delete_response = GFAPI::delete_entry( $entry_id );
416
417
			if( ! is_wp_error( $delete_response ) ) {
418
				$delete_response = 'deleted';
419
420
				/**
421
				 * @action `gravityview/delete-entry/deleted` Triggered when an entry is deleted
422
				 * @since 1.16.4
423
				 * @param  int $entry_id ID of the Gravity Forms entry
424
				 * @param  array $entry Deleted entry array
425
				*/
426
				do_action( 'gravityview/delete-entry/deleted', $entry_id, $entry );
427
			}
428
429
			do_action( 'gravityview_log_debug', __METHOD__ . ' Delete response: ', $delete_response );
430
431
		} else {
432
433
			do_action( 'gravityview_log_debug', __METHOD__ . ' Starting trash entry: ', $entry_id );
434
435
			$trashed = GFAPI::update_entry_property( $entry_id, 'status', 'trash' );
436
			new GravityView_Cache;
437
438
			if( ! $trashed ) {
439
				$delete_response = new WP_Error( 'trash_entry_failed', __('Moving the entry to the trash failed.', 'gravityview' ) );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
440
			} else {
441
442
				/**
443
				 * @action `gravityview/delete-entry/trashed` Triggered when an entry is trashed
444
				 * @since 1.16.4
445
				 * @param  int $entry_id ID of the Gravity Forms entry
446
				 * @param  array $entry Deleted entry array
447
				 */
448
				do_action( 'gravityview/delete-entry/trashed', $entry_id, $entry );
449
450
				$delete_response = 'trashed';
451
			}
452
453
			do_action( 'gravityview_log_debug', __METHOD__ . ' Trashed? ', $delete_response );
454
		}
455
456
		return $delete_response;
457
	}
458
459
	/**
460
	 * Delete or trash a post connected to an entry
461
	 *
462
	 * @since 1.17
463
	 *
464
	 * @param int $entry_id ID of entry being deleted/trashed
465
	 * @param array $entry Array of the entry being deleted/trashed
466
	 */
467
	public function process_connected_posts( $entry_id = 0, $entry = array() ) {
468
469
		// The entry had no connected post
470
		if( empty( $entry['post_id'] ) ) {
471
			return;
472
		}
473
474
		/**
475
		 * @filter `gravityview/delete-entry/delete-connected-post` Should posts connected to an entry be deleted when the entry is deleted?
476
		 * @since 1.17
477
		 * @param boolean $delete_post If trashing an entry, trash the post. If deleting an entry, delete the post. Default: true
478
		 */
479
		$delete_post = apply_filters( 'gravityview/delete-entry/delete-connected-post', true );
480
		
481
		if( false === $delete_post ) {
482
			return;
483
		}
484
485
		$action = current_action();
486
487
		if( 'gravityview/delete-entry/deleted' === $action ) {
488
			$result = wp_delete_post( $entry['post_id'], true );
489
		} else {
490
			$result = wp_trash_post( $entry['post_id'] );
491
		}
492
493
		if( false === $result ) {
494
			do_action( 'gravityview_log_error', __METHOD__ . ' (called by '.$action.'): Error processing the Post connected to the entry.', $entry );
495
		} else {
496
			do_action( 'gravityview_log_debug', __METHOD__ . ' (called by '.$action.'): Successfully processed Post connected to the entry.', $entry );
497
		}
498
	}
499
500
	/**
501
	 * Is the current nonce valid for editing the entry?
502
	 *
503
	 * @since 1.5.1
504
	 * @return boolean
505
	 */
506
	public function verify_nonce() {
507
508
		// No delete entry request was made
509
		if( empty( $_GET['entry_id'] ) || empty( $_GET['delete'] ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
510
			return false;
511
		}
512
513
		$nonce_key = self::get_nonce_key( $_GET['entry_id'] );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
514
515
		$valid = wp_verify_nonce( $_GET['delete'], $nonce_key );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
516
517
		/**
518
		 * @filter `gravityview/delete-entry/verify_nonce` Override Delete Entry nonce validation. Return true to declare nonce valid.
519
		 * @since 1.15.2
520
		 * @see wp_verify_nonce()
521
		 * @param int|boolean $valid False if invalid; 1 or 2 when nonce was generated
522
		 * @param string $nonce_key Name of nonce action used in wp_verify_nonce. $_GET['delete'] holds the nonce value itself. Default: `delete_{entry_id}`
523
		 */
524
		$valid = apply_filters( 'gravityview/delete-entry/verify_nonce', $valid, $nonce_key );
525
526
		return $valid;
527
	}
528
529
	/**
530
	 * Get the onclick attribute for the confirm dialogs that warns users before they delete an entry
531
	 *
532
	 * @since 1.5.1
533
	 * @return string HTML `onclick` attribute
534
	 */
535
	public static function get_confirm_dialog() {
536
537
		$confirm = __('Are you sure you want to delete this entry? This cannot be undone.', 'gravityview');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
538
539
		/**
540
		 * @filter `gravityview/delete-entry/confirm-text` Modify the Delete Entry Javascript confirmation text
541
		 * @param string $confirm Default: "Are you sure you want to delete this entry? This cannot be undone."
542
		 */
543
		$confirm = apply_filters( 'gravityview/delete-entry/confirm-text', $confirm );
544
545
		return 'return window.confirm(\''. esc_js( $confirm ) .'\');';
546
	}
547
548
	/**
549
	 * Check if the user can edit the entry
550
	 *
551
	 * - Is the nonce valid?
552
	 * - Does the user have the right caps for the entry
553
	 * - Is the entry in the trash?
554
	 *
555
	 * @since 1.5.1
556
	 * @param  array $entry Gravity Forms entry array
557
	 * @return boolean|WP_Error        True: can edit form. WP_Error: nope.
558
	 */
559
	function user_can_delete_entry( $entry = 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...
560
561
		$error = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
562
563
		if( ! $this->verify_nonce() ) {
564
			$error = __( 'The link to delete this entry is not valid; it may have expired.', 'gravityview');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
565
		}
566
567
		if( ! self::check_user_cap_delete_entry( $entry ) ) {
568
			$error = __( 'You do not have permission to delete this entry.', 'gravityview');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
569
		}
570
571
		if( $entry['status'] === 'trash' ) {
0 ignored issues
show
introduced by
Found "=== '". Use Yoda Condition checks, you must
Loading history...
572
			if( 'trash' === $this->get_delete_mode() ) {
573
				$error = __( 'The entry is already in the trash.', 'gravityview' );
574
			} else {
575
				$error = __( 'You cannot delete the entry; it is already in the trash.', 'gravityview' );
576
			}
577
		}
578
579
		// No errors; everything's fine here!
580
		if( empty( $error ) ) {
581
			return true;
582
		}
583
584
		do_action('gravityview_log_error', 'GravityView_Delete_Entry[user_can_delete_entry]' . $error );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
585
586
		return new WP_Error( 'gravityview-delete-entry-permissions', $error );
587
	}
588
589
590
	/**
591
	 * checks if user has permissions to view the link or delete a specific entry
592
	 *
593
	 * @since 1.5.1
594
	 * @since 1.15 Added `$view_id` param
595
	 *
596
	 * @param  array $entry Gravity Forms entry array
597
	 * @param array $field Field settings (optional)
598
	 * @param int $view_id Pass a View ID to check caps against. If not set, check against current View (optional)
599
	 * @return bool
600
	 */
601
	public static function check_user_cap_delete_entry( $entry, $field = array(), $view_id = 0 ) {
602
		$gravityview_view = GravityView_View::getInstance();
603
604
		$current_user = wp_get_current_user();
605
606
		$entry_id = isset( $entry['id'] ) ? $entry['id'] : NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
607
608
		// Or if they can delete any entries (as defined in Gravity Forms), we're good.
609
		if( GVCommon::has_cap( array( 'gravityforms_delete_entries', 'gravityview_delete_others_entries' ), $entry_id ) ) {
610
611
			do_action('gravityview_log_debug', 'GravityView_Delete_Entry[check_user_cap_delete_entry] Current user has `gravityforms_delete_entries` or `gravityview_delete_others_entries` capability.' );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
612
613
			return true;
614
		}
615
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
616
617
		// If field options are passed, check if current user can view the link
618
		if( !empty( $field ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
619
620
			// If capability is not defined, something is not right!
621
			if( empty( $field['allow_edit_cap'] ) ) {
622
623
				do_action( 'gravityview_log_error', 'GravityView_Delete_Entry[check_user_cap_delete_entry] Cannot read delete entry field caps', $field );
624
625
				return false;
626
			}
627
628
			if( GVCommon::has_cap( $field['allow_edit_cap'] ) ) {
629
630
				// Do not return true if cap is read, as we need to check if the current user created the entry
631
				if( $field['allow_edit_cap'] !== 'read' ) {
0 ignored issues
show
introduced by
Found "!== '". Use Yoda Condition checks, you must
Loading history...
632
					return true;
633
				}
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
634
635
			} else {
636
637
				do_action( 'gravityview_log_debug', sprintf( 'GravityView_Delete_Entry[check_user_cap_delete_entry] User %s is not authorized to view delete entry link ', $current_user->ID ) );
638
639
				return false;
640
			}
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
641
642
		}
643
644
		if( !isset( $entry['created_by'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
645
646
			do_action('gravityview_log_error', 'GravityView_Delete_Entry[check_user_cap_delete_entry] Entry `created_by` doesn\'t exist.');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
647
648
			return false;
649
		}
650
651
		$view_id = empty( $view_id ) ? $gravityview_view->getViewId() : $view_id;
652
653
		// Only checks user_delete view option if view is already set
654
		if( $view_id ) {
655
656
			$current_view = gravityview_get_current_view_data( $view_id );
657
658
			$user_delete = isset( $current_view['atts']['user_delete'] ) ? $current_view['atts']['user_delete'] : false;
659
660
			if( empty( $user_delete ) ) {
661
662
				do_action('gravityview_log_debug', 'GravityView_Delete_Entry[check_user_cap_delete_entry] User Delete is disabled. Returning false.' );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
663
664
				return false;
665
			}
666
		}
667
668
		// If the logged-in user is the same as the user who created the entry, we're good.
669
		if( is_user_logged_in() && intval( $current_user->ID ) === intval( $entry['created_by'] ) ) {
670
671
			do_action('gravityview_log_debug', sprintf( 'GravityView_Delete_Entry[check_user_cap_delete_entry] User %s created the entry.', $current_user->ID ) );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
672
673
			return true;
674
		}
675
676
		return false;
677
	}
678
679
680
	/**
681
	 * After processing delete entry, the user will be redirected to the referring View or embedded post/page. Display a message on redirection.
682
	 *
683
	 * If success, there will be `status` URL parameters `status=>success`
684
	 * If an error, there will be `status` and `message` URL parameters `status=>error&message=example`
685
	 *
686
	 * @since 1.15.2 Only show message when the URL parameter's View ID matches the current View ID
687
	 * @since 1.5.1
688
	 *
689
	 * @param int $current_view_id The ID of the View being rendered
690
	 * @return void
691
	 */
692
	public function display_message( $current_view_id = 0 ) {
693
694
		if( empty( $_GET['status'] ) || ! self::verify_nonce() ) {
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
695
			return;
696
		}
697
698
		// Entry wasn't deleted from current View
699
		if( intval( $_GET['gvid'] ) !== intval( $current_view_id ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_GET
Loading history...
700
			return;
701
		}
702
703
		$status = esc_attr( $_GET['status'] );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
704
		$message_from_url = rgget('message');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
705
		$message_from_url = urldecode( stripslashes_deep( $message_from_url ) );
706
		$class = '';
707
708
		switch ( $status ) {
709
			case 'error':
710
				$class = ' gv-error error';
711
				$error_message = __('There was an error deleting the entry: %s', 'gravityview');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
712
				$message = sprintf( $error_message, $message_from_url );
713
				break;
714
			case 'trashed':
715
				$message = __('The entry was successfully moved to the trash.', 'gravityview');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
716
				break;
717
			default:
718
				$message = __('The entry was successfully deleted.', 'gravityview');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
719
				break;
720
		}
721
722
		/**
723
		 * @filter `gravityview/delete-entry/message` Modify the Delete Entry messages
724
		 * @since 1.13.1
725
		 * @param string $message Message to be displayed
726
		 * @param string $status Message status (`error` or `success`)
727
		 * @param string $message_from_url The original error message, if any, without the "There was an error deleting the entry:" prefix
728
		 */
729
		$message = apply_filters( 'gravityview/delete-entry/message', esc_attr( $message ), $status, $message_from_url );
730
731
		// DISPLAY ERROR/SUCCESS MESSAGE
732
		echo '<div class="gv-notice' . esc_attr( $class ) .'">'. $message .'</div>';
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$message'
Loading history...
733
	}
734
735
736
} // end class
737
738
GravityView_Delete_Entry::getInstance();
739
740