Completed
Push — develop ( 36ef5f...cb1f6a )
by Zack
07:01
created

GravityView_frontend   F

Complexity

Total Complexity 190

Size/Duplication

Total Lines 1580
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 11

Test Coverage

Coverage 63.87%

Importance

Changes 0
Metric Value
dl 0
loc 1580
ccs 320
cts 501
cp 0.6387
rs 0.8
c 0
b 0
f 0
wmc 190
lcom 3
cbo 11

44 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 1 1
A initialize() 0 16 1
A getInstance() 0 9 2
A getGvOutputData() 0 3 1
A setGvOutputData() 0 3 1
A isSearch() 0 3 1
A setIsSearch() 0 3 1
A getSingleEntry() 0 3 1
A setSingleEntry() 0 5 1
A getEntry() 0 3 1
A setEntry() 0 8 2
A getPostId() 0 3 1
A setPostId() 0 3 1
A isPostHasShortcode() 0 3 1
A setPostHasShortcode() 0 3 1
A isGravityviewPostType() 0 3 1
A setIsGravityviewPostType() 0 3 1
B set_context_view_id() 0 21 6
A get_context_view_id() 0 3 1
C parse_query_fix_frontpage() 0 54 14
A set_entry_data() 0 5 1
B parse_content() 0 26 6
B is_searching() 0 42 8
C single_entry_title() 0 65 10
A _get_single_entry_title() 0 37 4
A insert_view_in_content() 0 4 1
A comments_open() 0 16 2
B context_not_configured_warning() 0 38 6
A render_view() 0 25 5
C process_search_dates() 0 66 13
A process_search_only_approved() 0 22 4
A is_entry_approved() 0 17 6
B get_search_criteria() 0 62 8
A get_view_entries() 0 37 1
B get_view_entries_parameters() 0 55 4
A get_search_criteria_paging() 0 32 5
F updateViewSorting() 0 79 16
D _override_sorting_id_by_field_type() 0 96 17
A is_single_entry() 0 29 3
D add_scripts_and_styles() 0 118 13
A enqueue_default_style() 0 17 3
A add_style() 0 12 4
B add_columns_sort_links() 0 43 6
A is_field_sortable() 0 30 4

How to fix   Complexity   

Complex Class

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

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

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

1
<?php
2
/**
3
 * GravityView Frontend functions
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
 * @since 1.0.0
12
 */
13
14
15
class GravityView_frontend {
0 ignored issues
show
Coding Style introduced by
Since you have declared the constructor as private, maybe you should also declare the class as final.
Loading history...
16
17
	/**
18
	 * Regex strings that are used to determine whether the current request is a GravityView search or not.
19
	 * @see GravityView_frontend::is_searching()
20
	 * @since 1.7.4.1
21
	 * @var array
22
	 */
23
	private static $search_parameters = array( 'gv_search', 'gv_start', 'gv_end', 'gv_id', 'gv_by', 'filter_*' );
24
25
	/**
26
	 * Is the currently viewed post a `gravityview` post type?
27
	 * @var boolean
28
	 */
29
	var $is_gravityview_post_type = false;
30
31
	/**
32
	 * Does the current post have a `[gravityview]` shortcode?
33
	 * @var boolean
34
	 */
35
	var $post_has_shortcode = false;
36
37
	/**
38
	 * The Post ID of the currently viewed post. Not necessarily GV
39
	 * @var int
40
	 */
41
	var $post_id = null;
42
43
	/**
44
	 * Are we currently viewing a single entry?
45
	 * If so, the int value of the entry ID. Otherwise, false.
46
	 * @var int|boolean
47
	 */
48
	var $single_entry = false;
49
50
	/**
51
	 * If we are viewing a single entry, the entry data
52
	 * @var array|false
53
	 */
54
	var $entry = false;
55
56
	/**
57
	 * When displaying the single entry we should always know to which View it belongs (the context is everything!)
58
	 * @var null
59
	 */
60
	var $context_view_id = null;
61
62
	/**
63
	 * The View is showing search results
64
	 * @since 1.5.4
65
	 * @var boolean
66
	 */
67
	var $is_search = false;
68
69
	/**
70
	 * The view data parsed from the $post
71
	 *
72
	 * @see  GravityView_View_Data::__construct()
73
	 * @var GravityView_View_Data
74
	 */
75
	var $gv_output_data = null;
76
77
	/**
78
	 * @var GravityView_frontend
79
	 */
80
	static $instance;
81
82
	/**
83
	 * Class constructor, enforce Singleton pattern
84
	 */
85
	private function __construct() {}
86
87 39
	private function initialize() {
88 39
		add_action( 'wp', array( $this, 'parse_content'), 11 );
89 39
		add_filter( 'parse_query', array( $this, 'parse_query_fix_frontpage' ), 10 );
90 39
		add_action( 'template_redirect', array( $this, 'set_entry_data'), 1 );
91
92
		// Enqueue scripts and styles after GravityView_Template::register_styles()
93 39
		add_action( 'wp_enqueue_scripts', array( $this, 'add_scripts_and_styles' ), 20 );
94
95
		// Enqueue and print styles in the footer. Added 1 priorty so stuff gets printed at 10 priority.
96 39
		add_action( 'wp_print_footer_scripts', array( $this, 'add_scripts_and_styles' ), 1 );
97
98 39
		add_filter( 'the_title', array( $this, 'single_entry_title' ), 1, 2 );
99 39
		add_filter( 'comments_open', array( $this, 'comments_open' ), 10, 2 );
100
101 39
		add_action( 'gravityview_after', array( $this, 'context_not_configured_warning' ) );
102 39
	}
103
104
	/**
105
	 * Get the one true instantiated self
106
	 * @return GravityView_frontend
107
	 */
108 42
	public static function getInstance() {
109
110 42
		if ( empty( self::$instance ) ) {
111 39
			self::$instance = new self;
112 39
			self::$instance->initialize();
113
		}
114
115 42
		return self::$instance;
116
	}
117
118
	/**
119
	 * @return GravityView_View_Data
120
	 */
121 40
	public function getGvOutputData() {
122 40
		return $this->gv_output_data;
123
	}
124
125
	/**
126
	 * @param \GravityView_View_Data $gv_output_data
127
	 */
128 40
	public function setGvOutputData( $gv_output_data ) {
129 40
		$this->gv_output_data = $gv_output_data;
130 40
	}
131
132
	/**
133
	 * @return boolean
134
	 */
135 39
	public function isSearch() {
136 39
		return $this->is_search;
137
	}
138
139
	/**
140
	 * @param boolean $is_search
141
	 */
142 40
	public function setIsSearch( $is_search ) {
143 40
		$this->is_search = $is_search;
144 40
	}
145
146
	/**
147
	 * @return bool|int
148
	 */
149 41
	public function getSingleEntry() {
150 41
		return $this->single_entry;
151
	}
152
153
	/**
154
	 * Sets the single entry ID and also the entry
155
	 * @param bool|int|string $single_entry
156
	 */
157 39
	public function setSingleEntry( $single_entry ) {
158
159 39
		$this->single_entry = $single_entry;
160
161 39
	}
162
163
	/**
164
	 * @return array
165
	 */
166 39
	public function getEntry() {
167 39
		return $this->entry;
168
	}
169
170
	/**
171
	 * Set the current entry
172
	 * @param array|int $entry Entry array or entry slug or ID
173
	 */
174 39
	public function setEntry( $entry ) {
175
176 39
		if ( ! is_array( $entry ) ) {
177 30
			$entry = GVCommon::get_entry( $entry );
178
		}
179
180 39
		$this->entry = $entry;
181 39
	}
182
183
	/**
184
	 * @return int
185
	 */
186 40
	public function getPostId() {
187 40
		return $this->post_id;
188
	}
189
190
	/**
191
	 * @param int $post_id
192
	 */
193 40
	public function setPostId( $post_id ) {
194 40
		$this->post_id = $post_id;
195 40
	}
196
197
	/**
198
	 * @return boolean
199
	 */
200 41
	public function isPostHasShortcode() {
201 41
		return $this->post_has_shortcode;
202
	}
203
204
	/**
205
	 * @param boolean $post_has_shortcode
206
	 */
207 40
	public function setPostHasShortcode( $post_has_shortcode ) {
208 40
		$this->post_has_shortcode = $post_has_shortcode;
209 40
	}
210
211
	/**
212
	 * @return boolean
213
	 */
214 42
	public function isGravityviewPostType() {
215 42
		return $this->is_gravityview_post_type;
216
	}
217
218
	/**
219
	 * @param boolean $is_gravityview_post_type
220
	 */
221 40
	public function setIsGravityviewPostType( $is_gravityview_post_type ) {
222 40
		$this->is_gravityview_post_type = $is_gravityview_post_type;
223 40
	}
224
225
	/**
226
	 * Set the context view ID used when page contains multiple embedded views or displaying the single entry view
227
	 *
228
	 *
229
	 *
230
	 * @param null $view_id
231
	 */
232 3
	public function set_context_view_id( $view_id = null ) {
233 3
		$multiple_views = $this->getGvOutputData() && $this->getGvOutputData()->has_multiple_views();
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_View_Data::has_multiple_views() has been deprecated.

This method has been deprecated.

Loading history...
234
235 3
		if ( ! empty( $view_id ) ) {
236
237 1
			$this->context_view_id = (int) $view_id;
238
239 3
		} elseif ( isset( $_GET['gvid'] ) && $multiple_views ) {
240
			/**
241
			 * used on a has_multiple_views context
242
			 * @see GravityView_API::entry_link
243
			 */
244
			$this->context_view_id = (int) $_GET['gvid'];
245
246 3
		} elseif ( ! $multiple_views ) {
247 3
			$array_keys = array_keys( $this->getGvOutputData()->get_views() );
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_View_Data::get_views() has been deprecated.

This method has been deprecated.

Loading history...
248 3
			$this->context_view_id = (int) array_pop( $array_keys );
249 3
			unset( $array_keys );
250
		}
251
252 3
	}
253
254
	/**
255
	 * Returns the the view_id context when page contains multiple embedded views or displaying single entry view
256
	 *
257
	 * @since 1.5.4
258
	 *
259
	 * @return int|null
260
	 */
261 39
	public function get_context_view_id() {
262 39
		return $this->context_view_id;
263
	}
264
265
	/**
266
	 * Allow GravityView entry endpoints on the front page of a site
267
	 *
268
	 * @link  https://core.trac.wordpress.org/ticket/23867 Fixes this core issue
269
	 * @link https://wordpress.org/plugins/cpt-on-front-page/ Code is based on this
270
	 *
271
	 * @since 1.17.3
272
	 *
273
	 * @param WP_Query &$query (passed by reference)
274
	 *
275
	 * @return void
276
	 */
277 185
	public function parse_query_fix_frontpage( &$query ) {
278 185
		global $wp_rewrite;
279
280 185
		$is_front_page = ( $query->is_home || $query->is_page );
281 185
		$show_on_front = ( 'page' === get_option('show_on_front') );
282 185
		$front_page_id = get_option('page_on_front');
283
284 185
		if (  $is_front_page && $show_on_front && $front_page_id ) {
285
286
			// Force to be an array, potentially a query string ( entry=16 )
287
			$_query = wp_parse_args( $query->query );
288
289
			// pagename can be set and empty depending on matched rewrite rules. Ignore an empty pagename.
290
			if ( isset( $_query['pagename'] ) && '' === $_query['pagename'] ) {
291
				unset( $_query['pagename'] );
292
			}
293
294
			// this is where will break from core wordpress
295
			/** @internal Don't use this filter; it will be unnecessary soon - it's just a patch for specific use case */
296
			$ignore = apply_filters( 'gravityview/internal/ignored_endpoints', array( 'preview', 'page', 'paged', 'cpage' ), $query );
297
			$endpoints = \GV\Utils::get( $wp_rewrite, 'endpoints' );
298
			foreach ( (array) $endpoints as $endpoint ) {
299
				$ignore[] = $endpoint[1];
300
			}
301
			unset( $endpoints );
302
303
			// Modify the query if:
304
			// - We're on the "Page on front" page (which we are), and:
305
			// - The query is empty OR
306
			// - The query includes keys that are associated with registered endpoints. `entry`, for example.
307
			if ( empty( $_query ) || ! array_diff( array_keys( $_query ), $ignore ) ) {
308
309
				$qv =& $query->query_vars;
310
311
				// Prevent redirect when on the single entry endpoint
312
				if( self::is_single_entry() ) {
313
					add_filter( 'redirect_canonical', '__return_false' );
314
				}
315
316
				$query->is_page = true;
317
				$query->is_home = false;
318
				$qv['page_id']  = $front_page_id;
319
320
				// Correct <!--nextpage--> for page_on_front
321
				if ( ! empty( $qv['paged'] ) ) {
322
					$qv['page'] = $qv['paged'];
323
					unset( $qv['paged'] );
324
				}
325
			}
326
327
			// reset the is_singular flag after our updated code above
328
			$query->is_singular = $query->is_single || $query->is_page || $query->is_attachment;
329
		}
330 185
	}
331
332
	/**
333
	 * Read the $post and process the View data inside
334
	 * @param  array  $wp Passed in the `wp` hook. Not used.
335
	 * @return void
336
	 */
337 2
	public function parse_content( $wp = array() ) {
0 ignored issues
show
Unused Code introduced by
The parameter $wp 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...
338 2
		global $post;
339
340
		// If in admin and NOT AJAX request, get outta here.
341 2
		if ( gravityview()->request->is_admin() ) {
342
			return;
343
		}
344
345
		// Calculate requested Views
346 2
		$this->setGvOutputData( GravityView_View_Data::getInstance( $post ) );
347
348
		// !important: we need to run this before getting single entry (to kick the advanced filter)
349 2
		$this->set_context_view_id();
350
351 2
		$this->setIsGravityviewPostType( get_post_type( $post ) === 'gravityview' );
352
353 2
		$post_id = $this->getPostId() ? $this->getPostId() : (isset( $post ) ? $post->ID : null );
354 2
		$this->setPostId( $post_id );
355 2
		$post_has_shortcode = ! empty( $post->post_content ) ? gravityview_has_shortcode_r( $post->post_content, 'gravityview' ) : false;
356 2
		$this->setPostHasShortcode( $this->isGravityviewPostType() ? null : ! empty( $post_has_shortcode ) );
357
358
		// check if the View is showing search results (only for multiple entries View)
359 2
		$this->setIsSearch( $this->is_searching() );
360
361 2
		unset( $entry, $post_id, $post_has_shortcode );
362 2
	}
363
364
	/**
365
	 * Set the entry
366
	 */
367
	function set_entry_data() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

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

Loading history...
368
		$entry_id = self::is_single_entry();
369
		$this->setSingleEntry( $entry_id );
370
		$this->setEntry( $entry_id );
371
	}
372
373
	/**
374
	 * Checks if the current View is presenting search results
375
	 *
376
	 * @since 1.5.4
377
	 *
378
	 * @return boolean True: Yes, it's a search; False: No, not a search.
379
	 */
380 2
	function is_searching() {
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...
381
382
		// It's a single entry, not search
383 2
		if ( $this->getSingleEntry() ) {
384 2
			return false;
385
		}
386
387 2
		$search_method = GravityView_Widget_Search::getInstance()->get_search_method();
388
389 2
		if( 'post' === $search_method ) {
390
			$get = $_POST;
391
		} else {
392 2
			$get = $_GET;
393
		}
394
395
		// No $_GET parameters
396 2
		if ( empty( $get ) || ! is_array( $get ) ) {
397 2
			return false;
398
		}
399
400
		// Remove empty values
401 1
		$get = array_filter( $get );
402
403
		// If the $_GET parameters are empty, it's no search.
404 1
		if ( empty( $get ) ) {
405
			return false;
406
		}
407
408 1
		$search_keys = array_keys( $get );
409
410 1
		$search_match = implode( '|', self::$search_parameters );
411
412 1
		foreach ( $search_keys as $search_key ) {
413
414
			// Analyze the search key $_GET parameter and see if it matches known GV args
415 1
			if ( preg_match( '/(' . $search_match . ')/i', $search_key ) ) {
416
				return true;
417
			}
418
		}
419
420 1
		return false;
421
	}
422
423
	/**
424
	 * Filter the title for the single entry view
425
	 *
426
	 * @param  string $passed_title  Current title
427
	 * @param  int $passed_post_id Post ID
428
	 * @return string (modified) title
429
	 */
430 9
	public function single_entry_title( $passed_title, $passed_post_id = null ) {
431 9
		global $post;
432
433 9
		$gventry = gravityview()->request->is_entry();
434
435
		// If this is the directory view, return.
436 9
		if( ! $gventry ) {
437 8
			return $passed_title;
438
		}
439
440 1
		$entry = $gventry->as_entry();
441
442
		/**
443
		 * @filter `gravityview/single/title/out_loop` Apply the Single Entry Title filter outside the WordPress loop?
444
		 * @param boolean $in_the_loop Whether to apply the filter to the menu title and the meta tag <title> - outside the loop
445
		 * @param array $entry Current entry
446
		 */
447 1
		$apply_outside_loop = apply_filters( 'gravityview/single/title/out_loop', in_the_loop(), $entry );
448
449 1
		if ( ! $apply_outside_loop ) {
450 1
			return $passed_title;
451
		}
452
453
		// WooCommerce doesn't $post_id
454 1
		if ( empty( $passed_post_id ) )  {
455 1
			return $passed_title;
456
		}
457
458
		// Don't modify the title for anything other than the current view/post.
459
		// This is true for embedded shortcodes and Views.
460 1
		if ( is_object( $post ) && (int) $post->ID !== (int) $passed_post_id ) {
461 1
			return $passed_title;
462
		}
463
464 1
		$view = gravityview()->request->is_view();
465
466 1
		if( $view ) {
467 1
			return $this->_get_single_entry_title( $view, $entry, $passed_title );
468
		}
469
470 1
		$_gvid = \GV\Utils::_GET( 'gvid', null );
471
472
		// $_GET['gvid'] is set; we know what View to render
473 1
		if ( $_gvid ) {
474
475 1
			$view = \GV\View::by_id( $_gvid );
476
477 1
			return $this->_get_single_entry_title( $view, $entry, $passed_title );
478
		}
479
480 1
		global $post;
481
482 1
		if ( ! $post ) {
483
			return $passed_title;
484
		}
485
486 1
		$view_collection = \GV\View_Collection::from_post( $post );
487
488
		// We have multiple Views, but no gvid...this isn't valid security
489 1
		if( 1 < $view_collection->count() ) {
490 1
			return $passed_title;
491
		}
492
493
		return $this->_get_single_entry_title( $view_collection->first(), $entry, $passed_title );
494
	}
495
496
	/**
497
	 * Returns the single entry title for a View with variables replaced and shortcodes parsed
498
	 *
499
	 * @since 2.7.2
500
	 *
501
	 * @param \GV\View|null $view
502
	 * @param array $entry
503
	 * @param string $passed_title
504
	 *
505
	 * @return mixed|string|null
506
	 */
507
	private function _get_single_entry_title( $view, $entry = array(), $passed_title = '' ) {
508
509
		if ( ! $view ) {
510
			return $passed_title;
511
		}
512
513
		/**
514
		 * @filter `gravityview/single/title/check_entry_display` Override whether to check entry display rules against filters
515
		 * @internal This might change in the future! Don't rely on it.
516
		 * @since 2.7.2
517
		 * @param bool $check_entry_display Check whether the entry is visible for the current View configuration. Default: true.
518
		 * @param array $entry Gravity Forms entry array
519
		 * @param \GV\View $view The View
520
		 */
521
		$check_entry_display = apply_filters( 'gravityview/single/title/check_entry_display', true, $entry, $view );
522
523
		if( $check_entry_display ) {
524
525
			$check_display = GVCommon::check_entry_display( $entry, $view );
526
527
			if( is_wp_error( $check_display ) ) {
528
				return $passed_title;
529
			}
530
		}
531
532
533
		$title = $view->settings->get( 'single_title', $passed_title );
534
535
		$form = GVCommon::get_form( $entry['form_id'] );
536
537
		// We are allowing HTML in the fields, so no escaping the output
538
		$title = GravityView_API::replace_variables( $title, $form, $entry );
539
540
		$title = do_shortcode( $title );
541
542
		return $title;
543
	}
544
545
546
	/**
547
	 * In case View post is called directly, insert the view in the post content
548
	 *
549
	 * @deprecated Use \GV\View::content() instead.
550
	 *
551
	 * @access public
552
	 * @static
553
	 * @param mixed $content
554
	 * @return string Add the View output into View CPT content
555
	 */
556 4
	public function insert_view_in_content( $content ) {
557 4
		gravityview()->log->notice( '\GravityView_frontend::insert_view_in_content is deprecated. Use \GV\View::content()' );
558 4
		return \GV\View::content( $content );
559
	}
560
561
	/**
562
	 * Disable comments on GravityView post types
563
	 * @param  boolean $open    existing status
564
	 * @param  int $post_id Post ID
565
	 * @return boolean
566
	 */
567
	public function comments_open( $open, $post_id ) {
568
569
		if ( $this->isGravityviewPostType() ) {
570
			$open = false;
571
		}
572
573
		/**
574
		 * @filter `gravityview/comments_open` Whether to set comments to open or closed.
575
		 * @since  1.5.4
576
		 * @param  boolean $open Open or closed status
577
		 * @param  int $post_id Post ID to set comment status for
578
		 */
579
		$open = apply_filters( 'gravityview/comments_open', $open, $post_id );
580
581
		return $open;
582
	}
583
584
	/**
585
	 * Display a warning when a View has not been configured
586
	 *
587
	 * @since 1.19.2
588
	 *
589
	 * @param int $view_id The ID of the View currently being displayed
590
	 *
591
	 * @return void
592
	 */
593 2
	public function context_not_configured_warning( $view_id = 0 ) {
594
595 2
		if ( ! class_exists( 'GravityView_View' ) ) {
596
			return;
597
		}
598
599 2
		$fields = GravityView_View::getInstance()->getContextFields();
600
601 2
		if ( ! empty( $fields ) ) {
602 2
			return;
603
		}
604
605
		$context = GravityView_View::getInstance()->getContext();
606
607
		switch( $context ) {
608
			case 'directory':
609
				$tab = __( 'Multiple Entries', 'gravityview' );
610
				break;
611
			case 'edit':
612
				$tab = __( 'Edit Entry', 'gravityview' );
613
				break;
614
			case 'single':
615
			default:
616
				$tab = __( 'Single Entry', 'gravityview' );
617
				break;
618
		}
619
620
621
		$title = sprintf( esc_html_x('The %s layout has not been configured.', 'Displayed when a View is not configured. %s is replaced by the tab label', 'gravityview' ), $tab );
622
		$edit_link = admin_url( sprintf( 'post.php?post=%d&action=edit#%s-view', $view_id, $context ) );
623
		$action_text = sprintf( esc_html__('Add fields to %s', 'gravityview' ), $tab );
624
		$message = esc_html__( 'You can only see this message because you are able to edit this View.', 'gravityview' );
625
626
		$image =  sprintf( '<img alt="%s" src="%s" style="margin-top: 10px;" />', $tab, esc_url(plugins_url( sprintf( 'assets/images/tab-%s.png', $context ), GRAVITYVIEW_FILE ) ) );
627
		$output = sprintf( '<h3>%s <strong><a href="%s">%s</a></strong></h3><p>%s</p>', $title, esc_url( $edit_link ), $action_text, $message );
628
629
		echo GVCommon::generate_notice( $output . $image, 'gv-error error', 'edit_gravityview', $view_id );
630
	}
631
632
633
	/**
634
	 * Core function to render a View based on a set of arguments
635
	 *
636
	 * @access public
637
	 * @static
638
	 * @param array $passed_args {
639
	 *
640
	 *      Settings for rendering the View
641
	 *
642
	 *      @type int $id View id
643
	 *      @type int $page_size Number of entries to show per page
644
	 *      @type string $sort_field Form field id to sort
645
	 *      @type string $sort_direction Sorting direction ('ASC', 'DESC', or 'RAND')
646
	 *      @type string $start_date - Ymd
647
	 *      @type string $end_date - Ymd
648
	 *      @type string $class - assign a html class to the view
649
	 *      @type string $offset (optional) - This is the start point in the current data set (0 index based).
650
	 * }
651
	 *
652
	 * @deprecated Use \GV\View_Renderer
653
	 *
654
	 * @return string|null HTML output of a View, NULL if View isn't found
655
	 */
656 1
	public function render_view( $passed_args ) {
657 1
		gravityview()->log->notice( '\GravityView_frontend::render_view is deprecated. Use \GV\View_Renderer etc.' );
658
659
		/**
660
		 * We can use a shortcode here, since it's pretty much the same.
661
		 *
662
		 * But we do need to check embed permissions, since shortcodes don't do this.
663
		 */
664
665 1
		if ( ! $view = gravityview()->views->get( $passed_args ) ) {
0 ignored issues
show
Documentation introduced by
The property views does not exist on object<GV\Core>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
666
			return null;
667
		}
668
669 1
		$view->settings->update( $passed_args );
670
671 1
		$direct_access = apply_filters( 'gravityview_direct_access', true, $view->ID );
672 1
		$embed_only = $view->settings->get( 'embed_only' );
673
674 1
		if( ! $direct_access || ( $embed_only && ! GVCommon::has_cap( 'read_private_gravityviews' ) ) ) {
675 1
			return __( 'You are not allowed to view this content.', 'gravityview' );
676
		}
677
678 1
		$shortcode = new \GV\Shortcodes\gravityview();
679 1
		return $shortcode->callback( $passed_args );
680
	}
681
682
	/**
683
	 * Process the start and end dates for a view - overrides values defined in shortcode (if needed)
684
	 *
685
	 * The `start_date` and `end_date` keys need to be in a format processable by GFFormsModel::get_date_range_where(),
686
	 * which uses \DateTime() format.
687
	 *
688
	 * You can set the `start_date` or `end_date` to any value allowed by {@link http://www.php.net//manual/en/function.strtotime.php strtotime()},
689
	 * including strings like "now" or "-1 year" or "-3 days".
690
	 *
691
	 * @see GFFormsModel::get_date_range_where
692
	 *
693
	 * @param  array      $args            View settings
694
	 * @param  array      $search_criteria Search being performed, if any
695
	 * @return array                       Modified `$search_criteria` array
696
	 */
697 74
	public static function process_search_dates( $args, $search_criteria = array() ) {
698
699 74
		$return_search_criteria = $search_criteria;
700
701 74
		foreach ( array( 'start_date', 'end_date' ) as $key ) {
702
703
704
			// Is the start date or end date set in the view or shortcode?
705
			// If so, we want to make sure that the search doesn't go outside the bounds defined.
706 74
			if ( ! empty( $args[ $key ] ) ) {
707
708
				// Get a timestamp and see if it's a valid date format
709 2
				$date = strtotime( $args[ $key ] );
710
711
				// The date was invalid
712 2
				if ( empty( $date ) ) {
713
					gravityview()->log->error( ' Invalid {key} date format: {format}', array( 'key' => $key, 'format' => $args[ $key ] ) );
714
					continue;
715
				}
716
717
				// The format that Gravity Forms expects for start_date and day-specific (not hour/second-specific) end_date
718 2
				$datetime_format = 'Y-m-d H:i:s';
719 2
				$search_is_outside_view_bounds = false;
720
721 2
				if( ! empty( $search_criteria[ $key ] ) ) {
722
723 1
					$search_date = strtotime( $search_criteria[ $key ] );
724
725
					// The search is for entries before the start date defined by the settings
726 1
					switch ( $key ) {
727 1
						case 'end_date':
728
							/**
729
							 * If the end date is formatted as 'Y-m-d', it should be formatted without hours and seconds
730
							 * so that Gravity Forms can convert the day to 23:59:59 the previous day.
731
							 *
732
							 * If it's a relative date ("now" or "-1 day"), then it should use the precise date format
733
							 *
734
							 * @see GFFormsModel::get_date_range_where
735
							 */
736 1
							$datetime_format               = gravityview_is_valid_datetime( $args[ $key ] ) ? 'Y-m-d' : 'Y-m-d H:i:s';
737 1
							$search_is_outside_view_bounds = ( $search_date > $date );
738 1
							break;
739 1
						case 'start_date':
740 1
							$search_is_outside_view_bounds = ( $search_date < $date );
741 1
							break;
742
					}
743
				}
744
745
				// If there is no search being performed, or if there is a search being performed that's outside the bounds
746 2
				if ( empty( $search_criteria[ $key ] ) || $search_is_outside_view_bounds ) {
747
748
					// Then we override the search and re-set the start date
749 2
					$return_search_criteria[ $key ] = date_i18n( $datetime_format , $date, true );
750
				}
751
			}
752
		}
753
754 74
		if( isset( $return_search_criteria['start_date'] ) && isset( $return_search_criteria['end_date'] ) ) {
755
			// The start date is AFTER the end date. This will result in no results, but let's not force the issue.
756 2
			if ( strtotime( $return_search_criteria['start_date'] ) > strtotime( $return_search_criteria['end_date'] ) ) {
757 1
				gravityview()->log->error( 'Invalid search: the start date is after the end date.', array( 'data' => $return_search_criteria ) );
758
			}
759
		}
760
761 74
		return $return_search_criteria;
762
	}
763
764
765
	/**
766
	 * Process the approved only search criteria according to the View settings
767
	 *
768
	 * @param  array      $args            View settings
769
	 * @param  array      $search_criteria Search being performed, if any
770
	 * @return array                       Modified `$search_criteria` array
771
	 */
772 73
	public static function process_search_only_approved( $args, $search_criteria ) {
773
774
		/** @since 1.19 */
775 73
		if( ! empty( $args['admin_show_all_statuses'] ) && GVCommon::has_cap('gravityview_moderate_entries') ) {
776
			gravityview()->log->debug( 'User can moderate entries; showing all approval statuses' );
777
			return $search_criteria;
778
		}
779
780 73
		if ( ! empty( $args['show_only_approved'] ) ) {
781
782 6
			$search_criteria['field_filters'][] = array(
783
				'key' => GravityView_Entry_Approval::meta_key,
784
				'value' => GravityView_Entry_Approval_Status::APPROVED
785
			);
786
787 6
			$search_criteria['field_filters']['mode'] = 'all'; // force all the criterias to be met
788
789 6
			gravityview()->log->debug( '[process_search_only_approved] Search Criteria if show only approved: ', array( 'data' => $search_criteria ) );
790
		}
791
792 73
		return $search_criteria;
793
	}
794
795
796
	/**
797
	 * Check if a certain entry is approved.
798
	 *
799
	 * If we pass the View settings ($args) it will check the 'show_only_approved' setting before
800
	 *   checking the entry approved field, returning true if show_only_approved = false.
801
	 *
802
	 * @since 1.7
803
	 * @since 1.18 Converted check to use GravityView_Entry_Approval_Status::is_approved
804
	 *
805
	 * @uses GravityView_Entry_Approval_Status::is_approved
806
	 *
807
	 * @param array $entry  Entry object
808
	 * @param array $args   View settings (optional)
809
	 *
810
	 * @return bool
811
	 */
812
	public static function is_entry_approved( $entry, $args = array() ) {
813
814
		if ( empty( $entry['id'] ) || ( array_key_exists( 'show_only_approved', $args ) && ! $args['show_only_approved'] ) ) {
815
			// is implicitly approved if entry is null or View settings doesn't require to check for approval
816
			return true;
817
		}
818
819
		/** @since 1.19 */
820
		if( ! empty( $args['admin_show_all_statuses'] ) && GVCommon::has_cap('gravityview_moderate_entries') ) {
821
			gravityview()->log->debug( 'User can moderate entries, so entry is approved for viewing' );
822
			return true;
823
		}
824
825
		$is_approved = gform_get_meta( $entry['id'], GravityView_Entry_Approval::meta_key );
826
827
		return GravityView_Entry_Approval_Status::is_approved( $is_approved );
828
	}
829
830
	/**
831
	 * Parse search criteria for a entries search.
832
	 *
833
	 * array(
834
	 * 	'search_field' => 1, // ID of the field
835
	 *  'search_value' => '', // Value of the field to search
836
	 *  'search_operator' => 'contains', // 'is', 'isnot', '>', '<', 'contains'
837
	 *  'show_only_approved' => 0 or 1 // Boolean
838
	 * )
839
	 *
840
	 * @param  array $args    Array of args
841
	 * @param  int $form_id Gravity Forms form ID
842
	 * @return array          Array of search parameters, formatted in Gravity Forms mode, using `status` key set to "active" by default, `field_filters` array with `key`, `value` and `operator` keys.
843
	 */
844 74
	public static function get_search_criteria( $args, $form_id ) {
845
		/**
846
		 * Compatibility with filters hooking in `gravityview_search_criteria` instead of `gravityview_fe_search_criteria`.
847
		 */
848 74
		$criteria = apply_filters( 'gravityview_search_criteria', array(), array( $form_id ), \GV\Utils::get( $args, 'id' ) );
849 74
		$search_criteria = isset( $criteria['search_criteria'] ) ? $criteria['search_criteria'] : array( 'field_filters' => array() );
850
851
		/**
852
		 * @filter `gravityview_fe_search_criteria` Modify the search criteria
853
		 * @see GravityView_Widget_Search::filter_entries Adds the default search criteria
854
		 * @param array $search_criteria Empty `field_filters` key
855
		 * @param int $form_id ID of the Gravity Forms form that is being searched
856
		 * @param array $args The View settings.
857
		 */
858 74
		$search_criteria = apply_filters( 'gravityview_fe_search_criteria', $search_criteria, $form_id, $args );
859
860 74
		if ( ! is_array( $search_criteria ) ) {
861
			return array();
862
		}
863
864 74
		$original_search_criteria = $search_criteria;
865
866 74
		gravityview()->log->debug( '[get_search_criteria] Search Criteria after hook gravityview_fe_search_criteria: ', array( 'data' =>$search_criteria ) );
867
868
		// implicity search
869 74
		if ( ! empty( $args['search_value'] ) ) {
870
871
			// Search operator options. Options: `is` or `contains`
872 3
			$operator = ! empty( $args['search_operator'] ) && in_array( $args['search_operator'], array( 'is', 'isnot', '>', '<', 'contains' ) ) ? $args['search_operator'] : 'contains';
873
874 3
			$search_criteria['field_filters'][] = array(
875 3
				'key' => \GV\Utils::_GET( 'search_field', \GV\Utils::get( $args, 'search_field' ) ), // The field ID to search
876 3
				'value' => _wp_specialchars( $args['search_value'] ), // The value to search. Encode ampersands but not quotes.
877 3
				'operator' => $operator,
878
			);
879
880
			// Lock search mode to "all" with implicit presearch filter.
881 3
			$search_criteria['field_filters']['mode'] = 'all';
882
		}
883
884 74
		if( $search_criteria !== $original_search_criteria ) {
885 3
			gravityview()->log->debug( '[get_search_criteria] Search Criteria after implicity search: ', array( 'data' => $search_criteria ) );
886
		}
887
888
		// Handle setting date range
889 74
		$search_criteria = self::process_search_dates( $args, $search_criteria );
890
891 74
		if( $search_criteria !== $original_search_criteria ) {
892 4
			gravityview()->log->debug( '[get_search_criteria] Search Criteria after date params: ', array( 'data' => $search_criteria ) );
893
		}
894
895
		// remove not approved entries
896 74
		$search_criteria = self::process_search_only_approved( $args, $search_criteria );
897
898
		/**
899
		 * @filter `gravityview_status` Modify entry status requirements to be included in search results.
900
		 * @param string $status Default: `active`. Accepts all Gravity Forms entry statuses, including `spam` and `trash`
901
		 */
902 74
		$search_criteria['status'] = apply_filters( 'gravityview_status', 'active', $args );
903
904 74
		return $search_criteria;
905
	}
906
907
908
909
	/**
910
	 * Core function to calculate View multi entries (directory) based on a set of arguments ($args):
911
	 *   $id - View id
912
	 *   $page_size - Page
913
	 *   $sort_field - form field id to sort
914
	 *   $sort_direction - ASC / DESC
915
	 *   $start_date - Ymd
916
	 *   $end_date - Ymd
917
	 *   $class - assign a html class to the view
918
	 *   $offset (optional) - This is the start point in the current data set (0 index based).
919
	 *
920
	 *
921
	 *
922
	 * @uses  gravityview_get_entries()
923
	 * @access public
924
	 * @param array $args\n
0 ignored issues
show
Bug introduced by
There is no parameter named $args\n. 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...
925
	 *   - $id - View id
926
	 *   - $page_size - Page
927
	 *   - $sort_field - form field id to sort
928
	 *   - $sort_direction - ASC / DESC
929
	 *   - $start_date - Ymd
930
	 *   - $end_date - Ymd
931
	 *   - $class - assign a html class to the view
932
	 *   - $offset (optional) - This is the start point in the current data set (0 index based).
933
	 * @param int $form_id Gravity Forms Form ID
934
	 * @return array Associative array with `count`, `entries`, and `paging` keys. `count` has the total entries count, `entries` is an array with Gravity Forms full entry data, `paging` is an array with `offset` and `page_size` keys
935
	 */
936 1
	public static function get_view_entries( $args, $form_id ) {
937
938 1
		gravityview()->log->debug( '[get_view_entries] init' );
939
		// start filters and sorting
940
941 1
		$parameters = self::get_view_entries_parameters( $args, $form_id );
942
943 1
		$count = 0; // Must be defined so that gravityview_get_entries can use by reference
944
945
		// fetch entries
946
		list( $entries, $paging, $count ) =
947 1
			\GV\Mocks\GravityView_frontend_get_view_entries( $args, $form_id, $parameters, $count );
948
949 1
		gravityview()->log->debug( 'Get Entries. Found: {count} entries', array( 'count' => $count, 'data' => $entries ) );
950
951
		/**
952
		 * @filter `gravityview_view_entries` Filter the entries output to the View
953
		 * @deprecated since 1.5.2
954
		 * @param array $args View settings associative array
955
		 * @var array
956
		 */
957 1
		$entries = apply_filters( 'gravityview_view_entries', $entries, $args );
958
959
		$return = array(
960 1
			'count' => $count,
961 1
			'entries' => $entries,
962 1
			'paging' => $paging,
963
		);
964
965
		/**
966
		 * @filter `gravityview/view/entries` Filter the entries output to the View
967
		 * @param array $criteria associative array containing count, entries & paging
968
		 * @param array $args View settings associative array
969
		 * @since 1.5.2
970
		 */
971 1
		return apply_filters( 'gravityview/view/entries', $return, $args );
972
	}
973
974
	/**
975
	 * Get an array of search parameters formatted as Gravity Forms requires
976
	 *
977
	 * Results are filtered by `gravityview_get_entries` and `gravityview_get_entries_{View ID}` filters
978
	 *
979
	 * @uses GravityView_frontend::get_search_criteria
980
	 * @uses GravityView_frontend::get_search_criteria_paging
981
	 *
982
	 * @since 1.20
983
	 *
984
	 * @see \GV\View_Settings::defaults For $args options
985
	 *
986
	 * @param array $args Array of View settings, as structured in \GV\View_Settings::defaults
987
	 * @param int $form_id Gravity Forms form ID to search
988
	 *
989
	 * @return array With `search_criteria`, `sorting`, `paging`, `cache` keys
990
	 */
991 73
	public static function get_view_entries_parameters( $args = array(), $form_id = 0 ) {
992
993
994 73
		if ( ! is_array( $args ) || ! is_numeric( $form_id ) ) {
995
996
			gravityview()->log->error( 'Passed args are not an array or the form ID is not numeric' );
997
998
			return array();
999
		}
1000
1001 73
		$form_id = intval( $form_id );
1002
1003
		/**
1004
		 * Process search parameters
1005
		 * @var array
1006
		 */
1007 73
		$search_criteria = self::get_search_criteria( $args, $form_id );
1008
1009 73
		$paging = self::get_search_criteria_paging( $args );
1010
1011
		$parameters = array(
1012 73
			'search_criteria' => $search_criteria,
1013 73
			'sorting' => self::updateViewSorting( $args, $form_id ),
1014 73
			'paging' => $paging,
1015 73
			'cache' => isset( $args['cache'] ) ? $args['cache'] : true,
1016
		);
1017
1018
		/**
1019
		 * @filter `gravityview_get_entries` Filter get entries criteria
1020
		 * @param array $parameters Array with `search_criteria`, `sorting` and `paging` keys.
1021
		 * @param array $args View configuration args. {
1022
		 *      @type int $id View id
1023
		 *      @type int $page_size Number of entries to show per page
1024
		 *      @type string $sort_field Form field id to sort
1025
		 *      @type string $sort_direction Sorting direction ('ASC', 'DESC', or 'RAND')
1026
		 *      @type string $start_date - Ymd
1027
		 *      @type string $end_date - Ymd
1028
		 *      @type string $class - assign a html class to the view
1029
		 *      @type string $offset (optional) - This is the start point in the current data set (0 index based).
1030
		 * }
1031
		 * @param int $form_id ID of Gravity Forms form
1032
		 */
1033 73
		$parameters = apply_filters( 'gravityview_get_entries', $parameters, $args, $form_id );
1034
1035
		/**
1036
		 * @filter `gravityview_get_entries_{View ID}` Filter get entries criteria
1037
		 * @param array $parameters Array with `search_criteria`, `sorting` and `paging` keys.
1038
		 * @param array $args View configuration args.
1039
		 */
1040 73
		$parameters = apply_filters( 'gravityview_get_entries_'.\GV\Utils::get( $args, 'id' ), $parameters, $args, $form_id );
1041
1042 73
		gravityview()->log->debug( '$parameters passed to gravityview_get_entries(): ', array( 'data' => $parameters ) );
1043
1044 73
		return $parameters;
1045
	}
1046
1047
	/**
1048
	 * Get the paging array for the View
1049
	 *
1050
	 * @since 1.19.5
1051
	 *
1052
	 * @param $args
1053
	 * @param int $form_id
0 ignored issues
show
Bug introduced by
There is no parameter named $form_id. 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...
1054
	 */
1055 73
	public static function get_search_criteria_paging( $args ) {
1056
1057
		/**
1058
		 * @filter `gravityview_default_page_size` The default number of entries displayed in a View
1059
		 * @since 1.1.6
1060
		 * @param int $default_page_size Default: 25
1061
		 */
1062 73
		$default_page_size = apply_filters( 'gravityview_default_page_size', 25 );
1063
1064
		// Paging & offset
1065 73
		$page_size = ! empty( $args['page_size'] ) ? intval( $args['page_size'] ) : $default_page_size;
1066
1067 73
		if ( -1 === $page_size ) {
1068 1
			$page_size = PHP_INT_MAX;
1069
		}
1070
1071 73
		$curr_page = empty( $_GET['pagenum'] ) ? 1 : intval( $_GET['pagenum'] );
1072 73
		$offset = ( $curr_page - 1 ) * $page_size;
1073
1074 73
		if ( ! empty( $args['offset'] ) ) {
1075
			$offset += intval( $args['offset'] );
1076
		}
1077
1078
		$paging = array(
1079 73
			'offset' => $offset,
1080 73
			'page_size' => $page_size,
1081
		);
1082
1083 73
		gravityview()->log->debug( 'Paging: ', array( 'data' => $paging ) );
1084
1085 73
		return $paging;
1086
	}
1087
1088
	/**
1089
	 * Updates the View sorting criteria
1090
	 *
1091
	 * @since 1.7
1092
	 *
1093
	 * @param array $args View settings. Required to have `sort_field` and `sort_direction` keys
1094
	 * @param int $form_id The ID of the form used to sort
1095
	 * @return array $sorting Array with `key`, `direction` and `is_numeric` keys
1096
	 */
1097 73
	public static function updateViewSorting( $args, $form_id ) {
1098 73
		$sorting = array();
1099
1100 73
		$has_values = isset( $_GET['sort'] );
1101
1102 73
		if ( $has_values && is_array( $_GET['sort'] ) ) {
1103 2
			$sorts = array_keys( $_GET['sort'] );
1104 2
			$dirs  = array_values( $_GET['sort'] );
1105
1106 2
			if ( $has_values = array_filter( $dirs ) ) {
1107 2
				$sort_field_id = end( $sorts );
1108 2
				$sort_direction = end( $dirs );
1109
			}
1110
		}
1111
1112 73
		if ( ! isset( $sort_field_id ) ) {
1113 73
			$sort_field_id = isset( $_GET['sort'] ) ? $_GET['sort'] : \GV\Utils::get( $args, 'sort_field' );
1114
		}
1115
1116 73
		if ( ! isset( $sort_direction ) ) {
1117 73
			$sort_direction = isset( $_GET['dir'] ) ? $_GET['dir'] : \GV\Utils::get( $args, 'sort_direction' );
1118
		}
1119
1120 73
		if ( is_array( $sort_field_id ) ) {
1121 1
			$sort_field_id = array_pop( $sort_field_id );
1122
		}
1123
1124 73
		if ( is_array( $sort_direction ) ) {
1125
			$sort_direction = array_pop( $sort_direction );
1126
		}
1127
1128 73
		if ( ! empty( $sort_field_id ) ) {
1129 5
			if ( is_array( $sort_field_id ) ) {
1130
				$sort_direction = array_values( $sort_field_id );
1131
				$sort_field_id = array_keys( $sort_field_id );
1132
1133
				$sort_field_id = reset( $sort_field_id );
1134
				$sort_direction = reset( $sort_direction );
1135
			}
1136
1137 5
			$sort_field_id = self::_override_sorting_id_by_field_type( $sort_field_id, $form_id );
1138
			$sorting = array(
1139 5
				'key' => $sort_field_id,
1140 5
				'direction' => strtolower( $sort_direction ),
1141 5
				'is_numeric' => GVCommon::is_field_numeric( $form_id, $sort_field_id )
1142
			);
1143
1144 5
			if ( 'RAND' === $sort_direction ) {
1145
1146
				$form = GFAPI::get_form( $form_id );
1147
1148
				// Get the first GF_Field field ID, set as the key for entry randomization
1149
				if ( ! empty( $form['fields'] ) ) {
1150
1151
					/** @var GF_Field $field */
1152
					foreach ( $form['fields'] as $field ) {
1153
						if ( ! is_a( $field, 'GF_Field' ) ) {
1154
							continue;
1155
						}
1156
1157
						$sorting = array(
1158
							'key'        => $field->id,
1159
							'is_numeric' => false,
1160
							'direction'  => 'RAND',
1161
						);
1162
1163
						break;
1164
					}
1165
				}
1166
			}
1167
		}
1168
1169 73
		GravityView_View::getInstance()->setSorting( $sorting );
1170
1171 73
		gravityview()->log->debug( '[updateViewSorting] Sort Criteria : ', array( 'data' => $sorting ) );
1172
1173 73
		return $sorting;
1174
1175
	}
1176
1177
	/**
1178
	 * Override sorting per field
1179
	 *
1180
	 * Currently only modifies sorting ID when sorting by the full name. Sorts by first name.
1181
	 * Use the `gravityview/sorting/full-name` filter to override.
1182
	 *
1183
	 * @todo Filter from GravityView_Field
1184
	 * @since 1.7.4
1185
	 * @internal Hi developer! Although this is public, don't call this method; we're going to replace it.
1186
	 *
1187
	 * @param int|string|array $sort_field_id Field used for sorting (`id` or `1.2`), or an array for multisorts
1188
	 * @param int $form_id GF Form ID
1189
	 *
1190
	 * @return string Possibly modified sorting ID
1191
	 */
1192 5
	public static function _override_sorting_id_by_field_type( $sort_field_id, $form_id ) {
1193
1194 5
		if ( is_array( $sort_field_id ) ) {
1195
			$modified_ids = array();
1196
			foreach ( $sort_field_id as $_sort_field_id ) {
1197
				$modified_ids []= self::_override_sorting_id_by_field_type( $_sort_field_id, $form_id );
1198
			}
1199
			return $modified_ids;
1200
		}
1201
1202 5
		$form = gravityview_get_form( $form_id );
1203
1204 5
		$sort_field = GFFormsModel::get_field( $form, $sort_field_id );
1205
1206 5
		if( ! $sort_field ) {
1207
			return $sort_field_id;
1208
		}
1209
1210 5
		switch ( $sort_field['type'] ) {
1211
1212 5
			case 'address':
1213
				// Sorting by full address
1214
				if ( floatval( $sort_field_id ) === floor( $sort_field_id ) ) {
1215
1216
					/**
1217
					 * Override how to sort when sorting address
1218
					 *
1219
					 * @since 1.8
1220
					 *
1221
					 * @param string $address_part `street`, `street2`, `city`, `state`, `zip`, or `country` (default: `city`)
1222
					 * @param string $sort_field_id Field used for sorting
1223
					 * @param int $form_id GF Form ID
1224
					 */
1225
					$address_part = apply_filters( 'gravityview/sorting/address', 'city', $sort_field_id, $form_id );
1226
1227
					switch( strtolower( $address_part ) ){
1228
						case 'street':
1229
							$sort_field_id .= '.1';
1230
							break;
1231
						case 'street2':
1232
							$sort_field_id .= '.2';
1233
							break;
1234
						default:
1235
						case 'city':
0 ignored issues
show
Unused Code introduced by
case 'city': $sort_f..._id .= '.3'; break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1236
							$sort_field_id .= '.3';
1237
							break;
1238
						case 'state':
1239
							$sort_field_id .= '.4';
1240
							break;
1241
						case 'zip':
1242
							$sort_field_id .= '.5';
1243
							break;
1244
						case 'country':
1245
							$sort_field_id .= '.6';
1246
							break;
1247
					}
1248
1249
				}
1250
				break;
1251 5
			case 'name':
1252
				// Sorting by full name, not first, last, etc.
1253
				if ( floatval( $sort_field_id ) === floor( $sort_field_id ) ) {
1254
					/**
1255
					 * @filter `gravityview/sorting/full-name` Override how to sort when sorting full name.
1256
					 * @since 1.7.4
1257
					 * @param[in,out] string $name_part Sort by `first` or `last` (default: `first`)
1258
					 * @param[in] string $sort_field_id Field used for sorting
1259
					 * @param[in] int $form_id GF Form ID
1260
					 */
1261
					$name_part = apply_filters( 'gravityview/sorting/full-name', 'first', $sort_field_id, $form_id );
1262
1263
					if ( 'last' === strtolower( $name_part ) ) {
1264
						$sort_field_id .= '.6';
1265
					} else {
1266
						$sort_field_id .= '.3';
1267
					}
1268
				}
1269
				break;
1270 5
			case 'list':
1271
				$sort_field_id = false;
1272
				break;
1273 5
			case 'time':
1274
1275
				/**
1276
				 * @filter `gravityview/sorting/time` Override how to sort when sorting time
1277
				 * @see GravityView_Field_Time
1278
				 * @since 1.14
1279
				 * @param[in,out] string $name_part Field used for sorting
1280
				 * @param[in] int $form_id GF Form ID
1281
				 */
1282 1
				$sort_field_id = apply_filters( 'gravityview/sorting/time', $sort_field_id, $form_id );
1283 1
				break;
1284
		}
1285
1286 5
		return $sort_field_id;
1287
	}
1288
1289
	/**
1290
	 * Verify if user requested a single entry view
1291
	 * @since 2.3.3 Added return null
1292
	 * @return boolean|string|null false if not, single entry slug if true, null if \GV\Entry doesn't exist yet
1293
	 */
1294 26
	public static function is_single_entry() {
1295
1296
		// Since this is a public method, it can be called outside of the plugin. Don't assume things have been loaded properly.
1297 26
		if ( ! class_exists( '\GV\Entry' ) ) {
1298
1299
			// Not using gravityview()->log->error(), since that may not exist yet either!
1300
			do_action( 'gravityview_log_error', '\GV\Entry not defined yet. Backtrace: ' . wp_debug_backtrace_summary()  );
1301
1302
			return null;
1303
		}
1304
1305 26
		$var_name = \GV\Entry::get_endpoint_name();
1306
1307 26
		$single_entry = get_query_var( $var_name );
1308
1309
		/**
1310
		 * Modify the entry that is being displayed.
1311
		 *
1312
		 * @internal Should only be used by things like the oEmbed functionality.
1313
		 * @since 1.6
1314
		 */
1315 26
		$single_entry = apply_filters( 'gravityview/is_single_entry', $single_entry );
1316
1317 26
		if ( empty( $single_entry ) ){
1318 4
			return false;
1319
		} else {
1320 22
			return $single_entry;
1321
		}
1322
	}
1323
1324
1325
	/**
1326
	 * Register styles and scripts
1327
	 *
1328
	 * @access public
1329
	 * @return void
1330
	 */
1331 1
	public function add_scripts_and_styles() {
1332 1
		global $post, $posts;
1333
		// enqueue template specific styles
1334 1
		if ( $this->getGvOutputData() ) {
1335
1336 1
			$views = $this->getGvOutputData()->get_views();
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_View_Data::get_views() has been deprecated.

This method has been deprecated.

Loading history...
1337
1338 1
			foreach ( $views as $view_id => $data ) {
1339 1
				$view = \GV\View::by_id( $data['id'] );
1340 1
				$view_id = $view->ID;
1341 1
				$template_id = gravityview_get_template_id( $view->ID );
1342 1
				$data = $view->as_data();
0 ignored issues
show
Deprecated Code introduced by
The method GV\View::as_data() has been deprecated.

This method has been deprecated.

Loading history...
1343
1344
				/**
1345
				 * Don't enqueue the scripts or styles if it's not going to be displayed.
1346
				 * @since 1.15
1347
				 */
1348 1
				if( is_user_logged_in() && false === GVCommon::has_cap( 'read_gravityview', $view_id ) ) {
1349
					continue;
1350
				}
1351
1352
				// By default, no thickbox
1353 1
				$js_dependencies = array( 'jquery', 'gravityview-jquery-cookie' );
1354 1
				$css_dependencies = array();
1355
1356 1
				$lightbox = $view->settings->get( 'lightbox' );
1357
1358
				// If the thickbox is enqueued, add dependencies
1359 1
				if ( $lightbox ) {
1360
1361 1
					global $wp_filter;
1362
1363 1
					if ( ! empty( $wp_filter[ 'gravity_view_lightbox_script' ] ) ) {
1364
						gravityview()->log->warning( 'gravity_view_lightbox_script filter is deprecated use gravityview_lightbox_script instead' );
1365
					}
1366
1367
					/**
1368
					 * @filter `gravity_view_lightbox_script` Override the lightbox script to enqueue. Default: `thickbox`
1369
					 * @param string $script_slug If you want to use a different lightbox script, return the name of it here.
1370
					 * @deprecated 2.5.1 Naming. See `gravityview_lightbox_script` instead.
1371
					 */
1372 1
					$js_dependency = apply_filters( 'gravity_view_lightbox_script', 'thickbox' );
1373
1374
					/**
1375
					 * @filter `gravityview_lightbox_script` Override the lightbox script to enqueue. Default: `thickbox`
1376
					 * @since 2.5.1
1377
					 * @param string $script_slug If you want to use a different lightbox script, return the name of it here.
1378
					 * @param \GV\View The View.
1379
					 */
1380 1
					apply_filters( 'gravityview_lightbox_script', $js_dependency, $view );
1381 1
					$js_dependencies[] = $js_dependency;
1382
1383 1
					if ( ! empty( $wp_filter[ 'gravity_view_lightbox_style' ] ) ) {
1384
						gravityview()->log->warning( 'gravity_view_lightbox_style filter is deprecated use gravityview_lightbox_style instead' );
1385
					}
1386
1387
					/**
1388
					 * @filter `gravity_view_lightbox_style` Modify the lightbox CSS slug. Default: `thickbox`
1389
					 * @param string $script_slug If you want to use a different lightbox script, return the name of its CSS file here.
1390
					 * @deprecated 2.5.1 Naming. See `gravityview_lightbox_style` instead.
1391
					 */
1392 1
					$css_dependency = apply_filters( 'gravity_view_lightbox_style', 'thickbox' );
1393
1394
					/**
1395
					 * @filter `gravityview_lightbox_script` Override the lightbox script to enqueue. Default: `thickbox`
1396
					 * @since 2.5.1
1397
					 * @param string $script_slug If you want to use a different lightbox script, return the name of it here.
1398
					 * @param \GV\View The View.
1399
					 */
1400 1
					$css_dependency = apply_filters( 'gravityview_lightbox_style', $css_dependency, $view );
1401 1
					$css_dependencies[] = $css_dependency;
1402
				}
1403
1404
				/**
1405
				 * If the form has checkbox fields, enqueue dashicons
1406
				 * @see https://github.com/katzwebservices/GravityView/issues/536
1407
				 * @since 1.15
1408
				 */
1409 1
				if( gravityview_view_has_single_checkbox_or_radio( $data['form'], $data['fields'] ) ) {
1410
					$css_dependencies[] = 'dashicons';
1411
				}
1412
1413 1
				wp_register_script( 'gravityview-jquery-cookie', plugins_url( 'assets/lib/jquery.cookie/jquery.cookie.min.js', GRAVITYVIEW_FILE ), array( 'jquery' ), GravityView_Plugin::version, true );
0 ignored issues
show
Deprecated Code introduced by
The constant GravityView_Plugin::version has been deprecated with message: Use \GV\Plugin::$version

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
1414
1415 1
				$script_debug = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
1416
1417 1
				wp_register_script( 'gravityview-fe-view', plugins_url( 'assets/js/fe-views' . $script_debug . '.js', GRAVITYVIEW_FILE ), apply_filters( 'gravityview_js_dependencies', $js_dependencies ) , GravityView_Plugin::version, true );
0 ignored issues
show
Deprecated Code introduced by
The constant GravityView_Plugin::version has been deprecated with message: Use \GV\Plugin::$version

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
1418
1419 1
				wp_enqueue_script( 'gravityview-fe-view' );
1420
1421 1
				if ( ! empty( $data['atts']['sort_columns'] ) ) {
1422
					wp_enqueue_style( 'gravityview_font', plugins_url( 'assets/css/font.css', GRAVITYVIEW_FILE ), $css_dependencies, GravityView_Plugin::version, 'all' );
0 ignored issues
show
Deprecated Code introduced by
The constant GravityView_Plugin::version has been deprecated with message: Use \GV\Plugin::$version

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
1423
				}
1424
1425 1
				$this->enqueue_default_style( $css_dependencies );
1426
1427 1
				self::add_style( $template_id );
1428
			}
1429
1430 1
			if ( 'wp_print_footer_scripts' === current_filter() ) {
1431
1432
				$js_localization = array(
1433
					'cookiepath' => COOKIEPATH,
1434
					'clear' => _x( 'Clear', 'Clear all data from the form', 'gravityview' ),
1435
					'reset' => _x( 'Reset', 'Reset the search form to the state that existed on page load', 'gravityview' ),
1436
				);
1437
1438
				/**
1439
				 * @filter `gravityview_js_localization` Modify the array passed to wp_localize_script()
1440
				 * @param array $js_localization The data padded to the Javascript file
1441
				 * @param array $views Array of View data arrays with View settings
1442
				 */
1443
				$js_localization = apply_filters( 'gravityview_js_localization', $js_localization, $views );
1444
1445
				wp_localize_script( 'gravityview-fe-view', 'gvGlobals', $js_localization );
1446
			}
1447
		}
1448 1
	}
1449
1450
	/**
1451
	 * Handle enqueuing the `gravityview_default_style` stylesheet
1452
	 *
1453
	 * @since 1.17
1454
	 *
1455
	 * @param array $css_dependencies Dependencies for the `gravityview_default_style` stylesheet
1456
	 *
1457
	 * @return void
1458
	 */
1459
	private function enqueue_default_style( $css_dependencies = array() ) {
1460
1461
		/**
1462
		 * @filter `gravityview_use_legacy_search_css` Should GravityView use the legacy Search Bar stylesheet (from before Version 1.17)?
1463
		 * @since 1.17
1464
		 * @param bool $use_legacy_search_style If true, loads `gv-legacy-search(-rtl).css`. If false, loads `gv-default-styles(-rtl).css`. `-rtl` is added on RTL websites. Default: `false`
1465
		 */
1466
		$use_legacy_search_style = apply_filters( 'gravityview_use_legacy_search_style', false );
1467
1468
		$rtl = is_rtl() ? '-rtl' : '';
1469
1470
		$css_file_base = $use_legacy_search_style ? 'gv-legacy-search' : 'gv-default-styles';
1471
1472
		$path = gravityview_css_url( $css_file_base . $rtl . '.css' );
1473
1474
		wp_enqueue_style( 'gravityview_default_style', $path, $css_dependencies, GravityView_Plugin::version, 'all' );
0 ignored issues
show
Deprecated Code introduced by
The constant GravityView_Plugin::version has been deprecated with message: Use \GV\Plugin::$version

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
1475
	}
1476
1477
	/**
1478
	 * Add template extra style if exists
1479
	 * @param string $template_id
1480
	 */
1481
	public static function add_style( $template_id ) {
1482
1483
		if ( ! empty( $template_id ) && wp_style_is( 'gravityview_style_' . $template_id, 'registered' ) ) {
1484
			gravityview()->log->debug(  'Adding extra template style for {template_id}', array( 'template_id' => $template_id ) );
1485
			wp_enqueue_style( 'gravityview_style_' . $template_id );
1486
		} elseif ( empty( $template_id ) ) {
1487
			gravityview()->log->error( 'Cannot add template style; template_id is empty' );
1488
		} else {
1489
			gravityview()->log->error( 'Cannot add template style; {template_id} is not registered', array( 'template_id' => 'gravityview_style_' . $template_id ) );
1490
		}
1491
1492
	}
1493
1494
1495
	/**
1496
	 * Inject the sorting links on the table columns
1497
	 *
1498
	 * Callback function for hook 'gravityview/template/field_label'
1499
	 * @see GravityView_API::field_label() (in includes/class-api.php)
1500
	 *
1501
	 * @since 1.7
1502
	 *
1503
	 * @param string $label Field label
1504
	 * @param array $field Field settings
1505
	 * @param array $form Form object
1506
	 *
1507
	 * @return string Field Label
1508
	 */
1509
	public function add_columns_sort_links( $label = '', $field, $form ) {
1510
1511
		/**
1512
		 * Not a table-based template; don't add sort icons
1513
		 * @since 1.12
1514
		 */
1515
		if( ! preg_match( '/table/ism', GravityView_View::getInstance()->getTemplatePartSlug() ) ) {
1516
			return $label;
1517
		}
1518
1519
		if ( ! $this->is_field_sortable( $field['id'], $form ) ) {
1520
			return $label;
1521
		}
1522
1523
		$sorting = GravityView_View::getInstance()->getSorting();
1524
1525
		$class = 'gv-sort';
1526
1527
		$sort_field_id = self::_override_sorting_id_by_field_type( $field['id'], $form['id'] );
1528
1529
		$sort_args = array(
1530
			'sort' => $field['id'],
1531
			'dir' => 'asc',
1532
		);
1533
1534
		if ( ! empty( $sorting['key'] ) && (string) $sort_field_id === (string) $sorting['key'] ) {
1535
			//toggle sorting direction.
1536
			if ( 'asc' === $sorting['direction'] ) {
1537
				$sort_args['dir'] = 'desc';
1538
				$class .= ' gv-icon-sort-desc';
1539
			} else {
1540
				$sort_args['dir'] = 'asc';
1541
				$class .= ' gv-icon-sort-asc';
1542
			}
1543
		} else {
1544
			$class .= ' gv-icon-caret-up-down';
1545
		}
1546
1547
		$url = add_query_arg( $sort_args, remove_query_arg( array('pagenum') ) );
1548
1549
		return '<a href="'. esc_url_raw( $url ) .'" class="'. $class .'" ></a>&nbsp;'. $label;
1550
1551
	}
1552
1553
	/**
1554
	 * Checks if field (column) is sortable
1555
	 *
1556
	 * @param string $field Field settings
0 ignored issues
show
Bug introduced by
There is no parameter named $field. 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...
1557
	 * @param array $form Gravity Forms form array
1558
	 *
1559
	 * @since 1.7
1560
	 *
1561
	 * @return bool True: Yes, field is sortable; False: not sortable
1562
	 */
1563 1
	public function is_field_sortable( $field_id = '', $form = array() ) {
1564
1565 1
		$field_type = $field_id;
1566
1567 1
		if( is_numeric( $field_id ) ) {
1568 1
			$field = GFFormsModel::get_field( $form, $field_id );
1569 1
			$field_type = $field ? $field->type : $field_id;
1570
		}
1571
1572
		$not_sortable = array(
1573 1
			'edit_link',
1574
			'delete_link',
1575
		);
1576
1577
		/**
1578
		 * @filter `gravityview/sortable/field_blacklist` Modify what fields should never be sortable.
1579
		 * @since 1.7
1580
		 * @param[in,out] array $not_sortable Array of field types that aren't sortable
1581
		 * @param string $field_type Field type to check whether the field is sortable
1582
		 * @param array $form Gravity Forms form
1583
		 */
1584 1
		$not_sortable = apply_filters( 'gravityview/sortable/field_blacklist', $not_sortable, $field_type, $form );
1585
1586 1
		if ( in_array( $field_type, $not_sortable ) ) {
1587
			return false;
1588
		}
1589
1590 1
		return apply_filters( "gravityview/sortable/formfield_{$form['id']}_{$field_id}", apply_filters( "gravityview/sortable/field_{$field_id}", true, $form ) );
1591
1592
	}
1593
1594
}
1595
1596
GravityView_frontend::getInstance();
1597
1598
1599
1600