Completed
Pull Request — develop (#1444)
by Zack
06:23
created

class-api.php ➔ gv_value()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 2
dl 0
loc 14
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 9.7998
c 0
b 0
f 0
1
<?php
2
/**
3
 * GravityView template tags API
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
class GravityView_API {
15
16
	/**
17
	 * Fetch Field Label
18
	 *
19
	 * @deprecated Use \GV\Field::get_label()
20
	 *
21
	 * @access public
22
	 * @static
23
	 * @param array $field GravityView field array
24
	 * @param array $entry Gravity Forms entry array
25
	 * @param boolean $force_show_label Whether to always show the label, regardless of field settings
26
	 * @return string
27
	 */
28 2
	public static function field_label( $field, $entry = array(), $force_show_label = false ) {
29
30 2
		$gravityview_view = GravityView_View::getInstance();
31
32 2
		$form = $gravityview_view->getForm();
33
34 2
		if ( defined( 'DOING_GRAVITYVIEW_TESTS' ) && ! empty( $GLOBALS['GravityView_API_field_label_override'] ) ) {
35
			/** Allow to fall through for back compatibility testing purposes. */
36
		} else {
37 2
			return \GV\Mocks\GravityView_API_field_label( $form, $field, $entry, $force_show_label );
38
		}
39
40 1
		$label = '';
41
42 1
		if( !empty( $field['show_label'] ) || $force_show_label ) {
43
44 1
			$label = $field['label'];
45
46
			// Support Gravity Forms 1.9+
47 1
			if( class_exists( 'GF_Field' ) ) {
48
49 1
				$field_object = RGFormsModel::get_field( $form, $field['id'] );
50
51 1
				if( $field_object ) {
52
53 1
					$input = GFFormsModel::get_input( $field_object, $field['id'] );
54
55
					// This is a complex field, with labels on a per-input basis
56 1
					if( $input ) {
57
58
						// Does the input have a custom label on a per-input basis? Otherwise, default label.
59 1
						$label = ! empty( $input['customLabel'] ) ? $input['customLabel'] : $input['label'];
60
61
					} else {
62
63
						// This is a field with one label
64 1
						$label = $field_object->get_field_label( true, $field['label'] );
65
66
					}
67
68
				}
69
70
			}
71
72
			// Use Gravity Forms label by default, but if a custom label is defined in GV, use it.
73 1
			if ( !empty( $field['custom_label'] ) ) {
74
75 1
				$label = self::replace_variables( $field['custom_label'], $form, $entry );
76
77
			}
78
79
			/**
80
			 * @filter `gravityview_render_after_label` Append content to a field label
81
			 * @param[in,out] string $appended_content Content you can add after a label. Empty by default.
82
			 * @param[in] array $field GravityView field array
83
			 */
84 1
			$label .= apply_filters( 'gravityview_render_after_label', '', $field );
85
86
		} // End $field['show_label']
87
88
		/**
89
		 * @filter `gravityview/template/field_label` Modify field label output
90
		 * @since 1.7
91
		 * @param[in,out] string $label Field label HTML
92
		 * @param[in] array $field GravityView field array
93
		 * @param[in] array $form Gravity Forms form array
94
		 * @param[in] array $entry Gravity Forms entry array
95
		 *
96
		 * @deprecated Use the context-aware version `gravityview/template/field/label`
97
		 */
98 1
		$label = apply_filters( 'gravityview/template/field_label', $label, $field, $form, $entry );
99
100 1
		return $label;
101
	}
102
103
	/**
104
	 * Alias for GravityView_Merge_Tags::replace_variables()
105
	 *
106
	 * @see GravityView_Merge_Tags::replace_variables() Moved in 1.8.4
107
	 * @since 1.22.4 - Added $nl2br, $format, $aux_data args
108
	 *
109
	 * @param  string     $text         Text to replace variables in
110
	 * @param  array      $form         GF Form array
111
	 * @param  array      $entry        GF Entry array
112
	 * @param  bool       $url_encode   Pass return value through `url_encode()`
113
	 * @param  bool       $esc_html     Pass return value through `esc_html()`
114
	 * @param  bool       $nl2br        Convert newlines to <br> HTML tags
115
	 * @param  string     $format       The format requested for the location the merge is being used. Possible values: html, text or url.
116
	 * @param  array      $aux_data     Additional data to be used to replace merge tags {@see https://www.gravityhelp.com/documentation/article/gform_merge_tag_data/}
117
	 * @return string                   Text with variables maybe replaced
118
	 */
119 32
	public static function replace_variables( $text, $form = array(), $entry = array(), $url_encode = false, $esc_html = true, $nl2br = true, $format = 'html', $aux_data = array() ) {
120 32
		return GravityView_Merge_Tags::replace_variables( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format, $aux_data );
121
	}
122
123
	/**
124
	 * Get column width from the field setting
125
	 *
126
	 * @since 1.9
127
	 *
128
	 * @param array $field Array of settings for the field
129
	 * @param string $format Format for width. "%" (default) will return
130
	 *
131
	 * @return string|null If not empty, string in $format format. Otherwise, null.
132
	 */
133 20
	public static function field_width( $field, $format = '%d%%' ) {
134
135 20
		$width = NULL;
136
137 20
		if( !empty( $field['width'] ) ) {
138 1
			$width = absint( $field['width'] );
139
140
			// If using percentages, limit to 100%
141 1
			if( '%d%%' === $format && $width > 100 ) {
142 1
				$width = 100;
143
			}
144
145 1
			$width = sprintf( $format, $width );
146
		}
147
148 20
		return $width;
149
	}
150
151
	/**
152
	 * Fetch Field class
153
	 *
154
	 * @access public
155
	 * @static
156
	 * @param mixed $field
157
	 * @return string
158
	 */
159 23
	public static function field_class( $field, $form = NULL, $entry = NULL ) {
160 23
		$classes = array();
161
162 23
		if( !empty( $field['custom_class'] ) ) {
163
164 1
            $custom_class = $field['custom_class'];
165
166 1
            if( !empty( $entry ) ) {
167
168
                // We want the merge tag to be formatted as a class. The merge tag may be
169
                // replaced by a multiple-word value that should be output as a single class.
170
                // "Office Manager" will be formatted as `.OfficeManager`, not `.Office` and `.Manager`
171 1
                add_filter('gform_merge_tag_filter', 'sanitize_html_class');
172
173 1
                $custom_class = self::replace_variables( $custom_class, $form, $entry);
174
175
                // And then we want life to return to normal
176 1
                remove_filter('gform_merge_tag_filter', 'sanitize_html_class');
177
            }
178
179
			// And now we want the spaces to be handled nicely.
180 1
			$classes[] = gravityview_sanitize_html_class( $custom_class );
181
182
		}
183
184 23
		if(!empty($field['id'])) {
185 23
			if( !empty( $form ) && !empty( $form['id'] ) ) {
186 23
				$form_id = '-'.$form['id'];
187
			} else {
188
				// @deprecated path. Form should always be given.
189
				gravityview()->log->warning( 'GravityView_View::getInstance() legacy API called' );
190
				$gravityview_view = GravityView_View::getInstance();
191
				$form_id = $gravityview_view->getFormId() ? '-'. $gravityview_view->getFormId() : '';
192
			}
193
194 23
			$classes[] = 'gv-field'.$form_id.'-'.$field['id'];
195
		}
196
197 23
		return esc_attr(implode(' ', $classes));
198
	}
199
200
	/**
201
	 * Fetch Field HTML ID
202
	 *
203
	 * @since 1.11
204
	 *
205
	 * @access public
206
	 * @static
207
	 * @param array $field GravityView field array passed to gravityview_field_output()
208
	 * @param array $form Gravity Forms form array, if set.
209
	 * @param array $entry Gravity Forms entry array
210
	 * @return string Sanitized unique HTML `id` attribute for the field
211
	 */
212 19
	public static function field_html_attr_id( $field, $form = array(), $entry = array() ) {
0 ignored issues
show
Unused Code introduced by
The parameter $entry 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...
213 19
		$id = $field['id'];
214
215 19
		if ( ! empty( $id ) ) {
216 19
			if ( ! empty( $form ) && ! empty( $form['id'] ) ) {
217 19
				$form_id = '-' . $form['id'];
218
			} else {
219
				// @deprecated path. Form should always be given.
220
				gravityview()->log->warning( 'GravityView_View::getInstance() legacy API called' );
221
				$gravityview_view = GravityView_View::getInstance();
222
				$form_id = $gravityview_view->getFormId() ? '-' . $gravityview_view->getFormId() : '';
223
			}
224
225 19
			$id = 'gv-field' . $form_id . '-' . $field['id'];
226
		}
227
228 19
		return esc_attr( $id );
229
	}
230
231
232
	/**
233
	 * Given an entry and a form field id, calculate the entry value for that field.
234
	 *
235
	 * @deprecated Use \GV\Field_Template::render() or the more low-level \GV\Field::get_value()
236
	 *
237
	 * @access public
238
	 * @param array $entry
239
	 * @param array $field
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...
240
	 * @return null|string
241
	 */
242 2
	public static function field_value( $entry, $field_settings, $format = 'html' ) {
243 2
		gravityview()->log->notice( '\GravityView_API::field_value is deprecated. Use \GV\Field_Template::render() or \GV\Field::get_value()' );
244 2
		return \GV\Mocks\GravityView_API_field_value( $entry, $field_settings, $format );
0 ignored issues
show
Deprecated Code introduced by
The function GV\Mocks\GravityView_API_field_value() has been deprecated with message: Use \GV\Field_Template::render()

This function has been deprecated. The supplier of the file has supplied an explanatory message.

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

Loading history...
245
	}
246
247
	/**
248
	 * Generate an anchor tag that links to an entry.
249
	 *
250
	 * @since 1.6
251
	 * @see GVCommon::get_link_html()
252
	 *
253
	 * @param string $anchor_text The text or HTML inside the link
254
	 * @param array $entry Gravity Forms entry array
255
	 * @param array|string $passed_tag_atts Attributes to be added to the anchor tag, such as `title` or `rel`.
256
	 * @param array $field_settings Array of field settings. Optional, but passed to the `gravityview_field_entry_link` filter
257
	 *
258
	 * @since 2.0
259
	 * @param int $base_id The post or the view that this entry is linked from.
260
	 *
261
	 * @return string|null Returns HTML for an anchor link. Null if $entry isn't defined or is missing an ID.
262
	 */
263 2
	public static function entry_link_html( $entry = array(), $anchor_text = '', $passed_tag_atts = array(), $field_settings = array(), $base_id = null ) {
264
265 2
		if ( empty( $entry ) || ! is_array( $entry ) || ! isset( $entry['id'] ) ) {
266 1
			gravityview()->log->debug( 'Entry not defined; returning null', array( 'data' => $entry ) );
267 1
			return NULL;
268
		}
269
270 2
		$href = self::entry_link( $entry, $base_id );
271
272 2
		if( '' === $href ) {
273
			return NULL;
274
		}
275
276 2
		$link = gravityview_get_link( $href, $anchor_text, $passed_tag_atts );
277
278
		/**
279
		 * @filter `gravityview_field_entry_link` Modify the link HTML
280
		 * @param string $link HTML output of the link
281
		 * @param string $href URL of the link
282
		 * @param array  $entry The GF entry array
283
		 * @param  array $field_settings Settings for the particular GV field
284
		 */
285 2
		$output = apply_filters( 'gravityview_field_entry_link', $link, $href, $entry, $field_settings );
286
287 2
		return $output;
288
	}
289
290
	/**
291
	 * Get the "No Results" text depending on whether there were results.
292
	 * @param  boolean     $wpautop Apply wpautop() to the output?
293
	 *
294
	 * @since 2.0
295
	 * @param \GV\Template_Context $context The context
296
	 *
297
	 * @return string               HTML of "no results" text
298
	 */
299 20
	public static function no_results( $wpautop = true, $context = null ) {
300 20
		$is_search = false;
301
302 20
		if ( $context instanceof \GV\Template_Context ) {
303 16
			if ( $context->request->is_search() ) {
304 16
				$is_search = true;
305
			}
306
		} else {
307 4
			$gravityview_view = GravityView_View::getInstance();
308
309 4
			if( $gravityview_view && ( $gravityview_view->curr_start || $gravityview_view->curr_end || $gravityview_view->curr_search ) ) {
0 ignored issues
show
Documentation introduced by
The property curr_start does not exist on object<GravityView_View>. 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...
Documentation introduced by
The property curr_end does not exist on object<GravityView_View>. 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...
Documentation introduced by
The property curr_search does not exist on object<GravityView_View>. 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...
310 1
				$is_search = true;
311
			}
312
		}
313
314 20
		if ( $is_search ) {
315 1
			$output = __( 'This search returned no results.', 'gravityview' );
316
		} else {
317 20
			$output = __( 'No entries match your request.', 'gravityview' );
318
		}
319
320
		/**
321
		 * @filter `gravitview_no_entries_text` Modify the text displayed when there are no entries.
322
		 * Note: this filter is, and always has been, misspelled. This will not be fixed, since the filter is deprecated.
323
		 * @param string $output The existing "No Entries" text
324
		 * @param boolean $is_search Is the current page a search result, or just a multiple entries screen?
325
		 * @return string The modified text.
326
		 * @deprecated Use `gravityview/template/text/no_entries`
327
		 */
328 20
		$output = apply_filters( 'gravitview_no_entries_text', $output, $is_search );
329
330
		/**
331
		 * @filter `gravityview/template/text/no_entries` Modify the text displayed when there are no entries.
332
		 * @since 2.0
333
		 * @param string $output The existing "No Entries" text
334
		 * @param boolean $is_search Is the current page a search result, or just a multiple entries screen?
335
		 * @param \GV\Template_Context $context The context.
336
		 * @return string The modified text.
337
		 */
338 20
		$output = apply_filters( 'gravityview/template/text/no_entries', $output, $is_search, $context );
339
340 20
		return $wpautop ? wpautop( $output ) : $output;
341
	}
342
343
	/**
344
	 * Generate a URL to the Directory context
345
	 *
346
	 * Uses `wp_cache_get` and `wp_cache_get` (since 1.3) to speed up repeated requests to get permalink, which improves load time. Since we may be doing this hundreds of times per request, it adds up!
347
	 *
348
	 * @param int $post_id Post ID
349
	 * @param boolean $add_query_args Add pagination and sorting arguments
350
	 *
351
	 * @since 2.0
352
	 * @param \GV\Template_Context $context The context this is being used in.
353
	 *
354
	 * @return string      Permalink to multiple entries view
355
	 */
356 33
	public static function directory_link( $post_id = NULL, $add_query_args = true, $context = null ) {
357 33
		global $post;
358
359 33
		if ( empty( $post_id ) ) {
360
			// DataTables passes the Post ID
361 10
			if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
362
				$post_id = \GV\Utils::_POST( 'post_id', false );
363
			} else {
364 10
				if ( $context instanceof \GV\Template_Context ) {
365
					// Shortcodes, embeds
366 6
					if ( is_a( $post, 'WP_Post' ) ) {
367 1
						$post_id = $post->ID;
368
369
					// Actual views
370
					} else {
371 6
						$post_id = $context->view ? $context->view->ID : false;
372
					}
373
				} else {
374
					/** @deprecated path of execution */
375 4
					$gravityview_view = GravityView_View::getInstance();
376
377
					// The Post ID has been passed via the shortcode
378 4
					if ( ! empty( $gravityview_view ) && $gravityview_view->getPostId() ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $gravityview_view->getPostId() of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
379 2
						$post_id = $gravityview_view->getPostId();
380
					} else {
381
						// This is a GravityView post type
382 2
						if ( GravityView_frontend::getInstance()->isGravityviewPostType() ) {
383
							$post_id = isset( $gravityview_view ) ? $gravityview_view->getViewId() : $post->ID;
384
						} else {
385
							// This is an embedded GravityView; use the embedded post's ID as the base.
386 2
							if ( GravityView_frontend::getInstance()->isPostHasShortcode() && is_a( $post, 'WP_Post' ) ) {
387
								$post_id = $post->ID;
388 2
							} elseif ( $gravityview_view->getViewId() ) {
389
								// The GravityView has been embedded in a widget or in a template, and
390
								// is not in the current content. Thus, we defer to the View's own ID.
391 1
								$post_id = $gravityview_view->getViewId();
392
							}
393
						}
394
					}
395
				}
396
			}
397
		}
398
399
		// No post ID, get outta here.
400 33
		if ( empty( $post_id ) ) {
401 1
			return null;
402
		}
403
404
		// If we've saved the permalink in memory, use it
405
		// @since 1.3
406 32
		$link = wp_cache_get( 'gv_directory_link_'.$post_id );
407
408 32
		if ( (int) $post_id === (int) get_option( 'page_on_front' ) ) {
409
			$link = home_url();
410
		}
411
412 32
		if ( empty( $link ) ) {
413 32
			$link = get_permalink( $post_id );
414
415
			// If not yet saved, cache the permalink.
416
			// @since 1.3
417 32
			wp_cache_set( 'gv_directory_link_'.$post_id, $link );
418
		}
419
420
		// Deal with returning to proper pagination for embedded views
421 32
		if ( $link && $add_query_args ) {
422
423 30
			$args = array();
424
425 30
			if( $pagenum = \GV\Utils::_GET( 'pagenum' ) ) {
426 2
				$args['pagenum'] = intval( $pagenum );
427
			}
428
429 30
			if( $sort = \GV\Utils::_GET( 'sort' ) ) {
430
				$args['sort'] = $sort;
431
				$args['dir'] = \GV\Utils::_GET( 'dir' );
432
			}
433
434 30
			$link = add_query_arg( $args, $link );
435
		}
436
437
		/**
438
		 * @filter `gravityview_directory_link` Modify the URL to the View "directory" context
439
		 * @since 1.19.4
440
		 * @param string $link URL to the View's "directory" context (Multiple Entries screen)
441
		 * @param int $post_id ID of the post to link to. If the View is embedded, it is the post or page ID
442
		 */
443 32
		$link = apply_filters( 'gravityview_directory_link', $link, $post_id );
444
445
		/**
446
		 * @filter `gravityview/view/links/directory` Modify the URL to the View "directory" context
447
		 * @since 2.0
448
		 * @param string $link URL to the View's "directory" context (Multiple Entries screen)
449
		 * @param \GV\Template_Context $context
450
		 */
451 32
		return apply_filters( 'gravityview/view/links/directory', $link, $context );
452
	}
453
454
	/**
455
	 * Calculate an *unique* hash for an entry based on the entry ID
456
	 *
457
	 * This allows you to be more discrete as to the number of the entry - if you don't want users to know that you have made a certain number of sales, for example, or that their entry in the giveaway is entry #3.
458
	 *
459
	 * The hashed value MUST be unique, otherwise multiple entries will share the same URL, which leads to obvious problems.
460
	 *
461
	 * @param  int|string $id Entry ID to generate the hash for.
462
	 * @param  array  $entry        Entry data passed to provide additional information when generating the hash. Optional - don't rely on it being available.
463
	 * @return string               Hashed unique value for entry
464
	 */
465 3
	private static function get_custom_entry_slug( $id, $entry = array() ) {
466
467
		// Generate an unique hash to use as the default value
468 3
		$slug = substr( wp_hash( $id, 'gravityview'.$id ), 0, 8 );
469
470
		/**
471
		 * @filter `gravityview_entry_slug` Modify the unique hash ID generated, if you want to improve usability or change the format. This will allow for custom URLs, such as `{entryid}-{first-name}` or even, if unique, `{first-name}-{last-name}`
472
		 * @param string $hash Existing hash generated by GravityView
473
		 * @param  string $id The entry ID
474
		 * @param  array $entry Entry data array. May be empty.
475
		 */
476 3
		$slug = apply_filters( 'gravityview_entry_slug', $slug, $id, $entry );
477
478
		// Make sure we have something - use the original ID as backup.
479 3
		if( empty( $slug ) ) {
480
			$slug = $id;
481
		}
482
483 3
		return sanitize_title( $slug );
484
	}
485
486
	/**
487
	 * Get the entry slug for the entry. By default, it is the entry ID.
488
	 *
489
	 *
490
	 * @see gravityview_get_entry()
491
	 * @uses GravityView_API::get_custom_entry_slug() If using custom slug, gets the custom slug value
492
	 * @since 1.4
493
	 * @param  int|string $id_or_string ID of the entry, or custom slug string
494
	 * @param  array  $entry        Gravity Forms Entry array, optional. Used only to provide data to customize the `gravityview_entry_slug` filter
495
	 * @return string               Unique slug ID, passed through `sanitize_title()`
496
	 */
497 120
	public static function get_entry_slug( $id_or_string, $entry = array() ) {
498
499
		/**
500
		 * Default: use the entry ID as the unique identifier
501
		 */
502 120
		$slug = $id_or_string;
503
504
		/**
505
		 * @filter `gravityview_custom_entry_slug` Whether to enable and use custom entry slugs.
506
		 * @param boolean True: Allow for slugs based on entry values. False: always use entry IDs (default)
507
		 */
508 120
		$custom = apply_filters( 'gravityview_custom_entry_slug', false );
509
510
		// If we're using custom slug...
511 120
		if ( $custom ) {
512
513
			// Get the entry hash
514 3
			$hash = self::get_custom_entry_slug( $id_or_string, $entry );
515
516
			// Cache the slugs
517 3
			static $cache = array();
518
519 3
			if ( ! isset( $cache[ $id_or_string ] ) ) {
520 3
				global $wpdb;
521
522 3
				if ( version_compare( GFFormsModel::get_database_version(), '2.3-dev-1', '>=' ) ) {
523 3
					$table = GFFormsModel::get_entry_meta_table_name();
524 3
					$column = 'entry_id';
525
				} else {
526
					$table = RGFormsModel::get_lead_meta_table_name();
527
					$column = 'lead_id';
528
				}
529
530 3
				$results = $wpdb->get_results( $wpdb->prepare( "SELECT $column, meta_value FROM $table WHERE form_id = (SELECT form_id FROM $table WHERE $column = %d LIMIT 1) AND meta_key = 'gravityview_unique_id'", $id_or_string ) );
531
532 3
				if ( $results ) {
533
					$cache = array_replace( $cache, array_combine( wp_list_pluck( $results, $column ), wp_list_pluck( $results, 'meta_value' ) ) );
534
				}
535
536 3
				if ( ! isset( $cache[ $id_or_string ] ) ) {
537 3
					$cache[ $id_or_string ] = false;
538
				}
539
			}
540
541 3
			$value = $cache[ $id_or_string ];
542
543
			// If it does have a hash set, and the hash is expected, use it.
544
			// This check allows users to change the hash structure using the
545
			// gravityview_entry_hash filter and have the old hashes expire.
546 3
			if ( empty( $value ) || $value !== $hash ) {
547 3
				gravityview()->log->debug( 'Setting hash for entry {entry}: {hash}', array( 'entry' => $id_or_string, 'hash' => $hash ) );
548 3
				gform_update_meta( $id_or_string, 'gravityview_unique_id', $hash, \GV\Utils::get( $entry, 'form_id' ) );
549
			}
550
551 3
			$slug = $hash;
552
553 3
			unset( $value, $hash );
554
		}
555
556 120
		return sanitize_title( $slug );
557
	}
558
559
    /**
560
     * If using the entry custom slug feature, make sure the new entries have the custom slug created and saved as meta
561
     *
562
     * Triggered by add_action( 'gform_entry_created', array( 'GravityView_API', 'entry_create_custom_slug' ), 10, 2 );
563
     *
564
     * @param $entry array Gravity Forms entry object
565
     * @param $form array Gravity Forms form object
566
     */
567
    public static function entry_create_custom_slug( $entry, $form ) {
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...
568
        /**
569
         * @filter `gravityview_custom_entry_slug` On entry creation, check if we are using the custom entry slug feature and update the meta
570
         * @param boolean $custom Should we process the custom entry slug?
571
         */
572
        $custom = apply_filters( 'gravityview_custom_entry_slug', false );
573
        if( $custom ) {
574
            // create the gravityview_unique_id and save it
575
576
            // Get the entry hash
577
            $hash = self::get_custom_entry_slug( $entry['id'], $entry );
578
579
	        gravityview()->log->debug( 'Setting hash for entry {entry_id}: {hash}', array( 'entry_id' => $entry['id'], 'hash' => $hash ) );
580
581
            gform_update_meta( $entry['id'], 'gravityview_unique_id', $hash, \GV\Utils::get( $entry, 'form_id' ) );
582
583
        }
584
    }
585
586
587
588
589
	/**
590
	 * return href for single entry
591
	 *
592
	 * @since 1.7.3 Added $add_directory_args parameter
593
	 * @since 2.7.2 Added $view_id parameter
594
	 *
595
	 * @param  array|int $entry   Entry array or entry ID
596
	 * @param  int|null $post_id If wanting to define the parent post, pass a post ID
597
	 * @param boolean $add_directory_args True: Add args to help return to directory; False: only include args required to get to entry
598
	 * @param int $view_id
599
	 *
600
	 * @return string Link to the entry with the directory parent slug, or empty string if embedded post or View doesn't exist
601
	 */
602 4
	public static function entry_link( $entry, $post_id = NULL, $add_directory_args = true, $view_id = 0 ) {
603
604 4
		if ( ! empty( $entry ) && ! is_array( $entry ) ) {
605
			$entry = GVCommon::get_entry( $entry );
606 4
		} else if( empty( $entry ) ) {
607
			// @deprecated path
608
			$entry = GravityView_frontend::getInstance()->getEntry();
609
		}
610
611
		// Second parameter used to be passed as $field; this makes sure it's not an array
612 4
		if ( ! is_numeric( $post_id ) ) {
613 1
			$post_id = NULL;
614
		}
615
616
		// Get the permalink to the View
617 4
		$directory_link = self::directory_link( $post_id, false );
618
619
		// No post ID? Get outta here.
620 4
		if ( empty( $directory_link ) ) {
621 1
			return '';
622
		}
623
624 3
		$query_arg_name = \GV\Entry::get_endpoint_name();
625
626 3
		if ( ! empty( $entry['_multi'] ) ) {
627 1
			$entry_slugs = array();
628
629 1
			foreach ( $entry['_multi'] as $_multi ) {
630
631 1
				if( $gv_multi = \GV\GF_Entry::from_entry( $_multi ) ) {
632 1
					$entry_slugs[] = $gv_multi->get_slug();
633
				} else {
634
					// TODO: This path isn't covered by unit tests
635
					$entry_slugs[] = \GravityView_API::get_entry_slug( $_multi['id'], $_multi );
636
				}
637
638 1
				unset( $gv_multi );
639
640 1
				$forms[] = $_multi['form_id'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$forms was never initialized. Although not strictly required by PHP, it is generally a good practice to add $forms = 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...
641
			}
642
643 1
			$entry_slug = implode( ',', $entry_slugs );
644
		} else {
645
646
			// Fallback when
647 3
			if( $gv_entry = \GV\GF_Entry::from_entry( $entry ) ) {
648 3
				$entry_slug = $gv_entry->get_slug();
649
			} else {
650
				// TODO: This path isn't covered by unit tests
651
				$entry_slug = \GravityView_API::get_entry_slug( $entry['id'], $entry );
652
			}
653
654 3
			unset( $gv_entry );
655
		}
656
657 3
		if ( get_option('permalink_structure') && !is_preview() ) {
658
659
			$args = array();
660
661
			/**
662
			 * Make sure the $directory_link doesn't contain any query otherwise it will break when adding the entry slug.
663
			 * @since 1.16.5
664
			 */
665
			$link_parts = explode( '?', $directory_link );
666
667
			$query = !empty( $link_parts[1] ) ? '?'.$link_parts[1] : '';
668
669
			$directory_link = trailingslashit( $link_parts[0] ) . $query_arg_name . '/'. $entry_slug .'/' . $query;
670
671
		} else {
672
673 3
			$args = array( $query_arg_name => $entry_slug );
674
		}
675
676
		/**
677
		 * @since 1.7.3
678
		 */
679 3
		if ( $add_directory_args ) {
680
681 3
			if ( ! empty( $_GET['pagenum'] ) ) {
682
				$args['pagenum'] = intval( $_GET['pagenum'] );
683
			}
684
685
			/**
686
			 * @since 1.7
687
			 */
688 3
			if ( $sort = \GV\Utils::_GET( 'sort' ) ) {
689
				$args['sort'] = $sort;
690
				$args['dir'] = \GV\Utils::_GET( 'dir' );
691
			}
692
693
		}
694
695 3
		if( $post_id ) {
696 3
			$passed_post = get_post( $post_id );
697 3
			$views       = \GV\View_Collection::from_post( $passed_post );
698 3
			$has_multiple_views = $views->count() > 1;
699
		} else {
700
			$has_multiple_views = class_exists( 'GravityView_View_Data' ) && GravityView_View_Data::getInstance()->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...
701
		}
702
703 3
		if ( $has_multiple_views ) {
704 1
			$args['gvid'] = $view_id ? $view_id : gravityview_get_view_id();
705
		}
706
707 3
		return add_query_arg( $args, $directory_link );
708
709
	}
710
711
712
}
713
714
715
// inside loop functions
716
717
/**
718
 * @deprecated Use \GV\Field::get_label()
719
 */
720
function gv_label( $field, $entry = NULL ) {
721 1
	return GravityView_API::field_label( $field, $entry );
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_API::field_label() has been deprecated with message: Use \GV\Field::get_label()

This method 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 method will be removed from the class and what other method or class to use instead.

Loading history...
722
}
723
724
function gv_class( $field, $form = NULL, $entry = array() ) {
725 22
	return GravityView_API::field_class( $field, $form, $entry  );
726
}
727
728
/**
729
 * Generate a CSS class to be added to the wrapper <div> of a View
730
 *
731
 * @since 1.5.4
732
 * @since 1.16 Added $echo parameter.
733
 * @since 2.0 Added $context parameter.
734
 *
735
 * @param string $passed_css_class Default: `gv-container gv-container-{view id}`. If View is hidden until search, adds ` hidden`
736
 * @param boolean $echo Whether to echo the output. Default: true
737
 * @param \GV\Template_Context $context The template context.
738
 *
739
 * @return string CSS class, sanitized by gravityview_sanitize_html_class()
740
 */
741
function gv_container_class( $passed_css_class = '', $echo = true, $context = null ) {
742 25
	if ( $context instanceof \GV\Template_Context ) {
743 23
		$hide_until_searched = false;
744 23
		$total_entries = 0;
745 23
		$view_id = 0;
746 23
		if ( $context->view ) {
747 23
			$view_id = $context->view->ID;
748 23
			if( $context->view->settings->get( 'hide_until_searched' ) ) {
749 2
				$hide_until_searched = ( empty( $context->entry ) && ! $context->request->is_search() );
750
			}
751
		}
752 23
		if ( $context->entries ) {
753 17
			$total_entries = $context->entries->total();
754 6
		} else if ( $context->entry ) {
755 23
			$total_entries = 1;
756
		}
757
	} else {
758
		/** @deprecated legacy execution path */
759 3
		$view_id = GravityView_View::getInstance()->getViewId();
760 3
		$hide_until_searched = GravityView_View::getInstance()->isHideUntilSearched();
761 3
		$total_entries = GravityView_View::getInstance()->getTotalEntries();
762
	}
763
764 25
	$passed_css_class = trim( $passed_css_class );
765
766 25
	$default_css_class = ! empty( $view_id ) ? sprintf( 'gv-container gv-container-%d', $view_id ) : 'gv-container';
767
768 25
	if ( $hide_until_searched ) {
769 2
		$default_css_class .= ' hidden';
770
	}
771
772 25
	if ( 0 === $total_entries ) {
773 19
		$default_css_class .= ' gv-container-no-results';
774
	}
775
776 25
	$css_class = trim( $passed_css_class . ' '. $default_css_class );
777
778
	/**
779
	 * @filter `gravityview/render/container/class` Modify the CSS class to be added to the wrapper <div> of a View
780
	 * @since 1.5.4
781
	 * @param[in,out] string $css_class Default: `gv-container gv-container-{view id}`. If View is hidden until search, adds ` hidden`. If the View has no results, adds `gv-container-no-results`
782
	 * @since 2.0
783
	 * @param \GV\Template_Context $context The context.
784
	 */
785 25
	$css_class = apply_filters( 'gravityview/render/container/class', $css_class, $context );
786
787 25
	$css_class = gravityview_sanitize_html_class( $css_class );
788
789 25
	if ( $echo ) {
790 25
		echo $css_class;
791
	}
792
793 25
	return $css_class;
794
}
795
796
/**
797
 * @deprecated Use \GV\Field_Template::render()
798
 */
799
function gv_value( $entry, $field ) {
800
801 1
	$value = GravityView_API::field_value( $entry, $field );
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_API::field_value() has been deprecated with message: Use \GV\Field_Template::render() or the more low-level \GV\Field::get_value()

This method 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 method will be removed from the class and what other method or class to use instead.

Loading history...
802
803 1
	if( $value === '' ) {
804
		/**
805
		 * @filter `gravityview_empty_value` What to display when a field is empty
806
		 * @param string $value (empty string)
807
		 */
808
		$value = apply_filters( 'gravityview_empty_value', '' );
809
	}
810
811 1
	return $value;
812
}
813
814
function gv_directory_link( $post = NULL, $add_pagination = true, $context = null ) {
815 7
	return GravityView_API::directory_link( $post, $add_pagination, $context );
816
}
817
818
function gv_entry_link( $entry, $post_id = NULL ) {
819 2
	return GravityView_API::entry_link( $entry, $post_id );
820
}
821
822
function gv_no_results( $wpautop = true, $context = null ) {
823 19
	return GravityView_API::no_results( $wpautop, $context );
824
}
825
826
/**
827
 * Generate HTML for the back link from single entry view
828
 * @since 1.0.1
829
 * @since 2.0
830
 * @param \GV\Template_Context $context The context this link is being displayed from.
831
 * @return string|null      If no GV post exists, null. Otherwise, HTML string of back link.
832
 */
833
function gravityview_back_link( $context = null ) {
834
835 6
	$href = gv_directory_link( null, true, $context );
836
837
	/**
838
	 * @filter `gravityview_go_back_url` Modify the back link URL
839
	 * @since 1.17.5
840
	 * @see gv_directory_link() Generated the original back link
841
	 * @param string $href Existing label URL
842
	 * @deprecated Use `gravityview/template/links/back/url`
843
	 */
844 6
	$href = apply_filters( 'gravityview_go_back_url', $href );
845
846
	/**
847
	 * @filter `gravityview/template/links/back/url` Modify the back link URL
848
	 * @since 2.0
849
	 * @see gv_directory_link() Generated the original back link
850
	 * @param string $href Existing label URL
851
	 * @param \GV\Template_Context The context.
852
	 */
853 6
	$href = apply_filters( 'gravityview/template/links/back/url', $href, $context );
854
855 6
	if ( empty( $href ) ) {
856 1
		return NULL;
857
	}
858
859 5
	if ( $context instanceof \GV\Template_Context ) {
860 5
		$view_id = $context->view->ID;
861 5
		$view_label = $context->template->get_back_label();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class GV\Template as the method get_back_label() does only exist in the following sub-classes of GV\Template: GV\Entry_Legacy_Template, GV\Entry_List_Template, GV\Entry_Table_Template, GV\Entry_Template. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
862
	} else {
863
		/** @deprecated legacy path */
864
		$gravityview_view = GravityView_View::getInstance();
865
		$view_id = $gravityview_view->getViewId();
866
		$view_label = $gravityview_view->getBackLinkLabel() ? $gravityview_view->getBackLinkLabel() : false;
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_View::getBackLinkLabel() has been deprecated with message: Use $template->get_back_label();

This method 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 method will be removed from the class and what other method or class to use instead.

Loading history...
867
	}
868
869
	/** Default */
870 5
	$label = $view_label ? $view_label : __( '&larr; Go back', 'gravityview' );
871
872
	/**
873
	 * @filter `gravityview_go_back_label` Modify the back link text
874
	 * @since 1.0.9
875
	 * @param string $label Existing label text
876
	 * @deprecated Use `gravityview/template/links/back/label`
877
	 */
878 5
	$label = apply_filters( 'gravityview_go_back_label', $label );
879
880
	/**
881
	 * @filter `gravityview/template/links/back/label` Modify the back link text
882
	 * @since 2.0
883
	 * @see gv_directory_link() Generated the original back link
884
	 * @param string $label Existing label text
885
	 * @param \GV\Template_Context The context.
886
	 */
887 5
	$label = apply_filters( 'gravityview/template/links/back/label', $label, $context );
888
889
	/**
890
	 * @filter `gravityview/template/links/back/atts` Modify the attributes used on the back link anchor tag
891
	 * @since 2.1
892
	 * @param array $atts Original attributes, default: [ data-viewid => $view_id ]
893
	 * @param \GV\Template_Context The context.
894
	 */
895 5
	$atts = apply_filters( 'gravityview/template/links/back/atts', array( 'data-viewid' => $view_id ), $context );
896
897 5
	$link = gravityview_get_link( $href, esc_html( $label ), $atts );
898
899 5
	return $link;
900
}
901
902
/**
903
 * Handle getting values for complex Gravity Forms fields
904
 *
905
 * If the field is complex, like a product, the field ID, for example, 11, won't exist. Instead,
906
 * it will be 11.1, 11.2, and 11.3. This handles being passed 11 and 11.2 with the same function.
907
 *
908
 * @since 1.0.4
909
 * @param  array      $entry    GF entry array
910
 * @param  string      $field_id [description]
911
 * @param  string 	$display_value The value generated by Gravity Forms
912
 * @return string                Value
913
 */
914
function gravityview_get_field_value( $entry, $field_id, $display_value ) {
915
916 6
	if( floatval( $field_id ) === floor( floatval( $field_id ) ) ) {
917
918
		// For the complete field value as generated by Gravity Forms
919 3
		return $display_value;
920
921
	} else {
922
923
		// For one part of the address (City, ZIP, etc.)
924 6
		return isset( $entry[ $field_id ] ) ? $entry[ $field_id ] : '';
925
926
	}
927
928
}
929
930
/**
931
 * Take a passed CSV of terms and generate a linked list of terms
932
 *
933
 * Gravity Forms passes categories as "Name:ID" so we handle that using the ID, which
934
 * is more accurate than checking the name, which is more likely to change.
935
 *
936
 * @param  string      $value    Existing value
937
 * @param  string      $taxonomy Type of term (`post_tag` or `category`)
938
 * @return string                CSV of linked terms
939
 */
940
function gravityview_convert_value_to_term_list( $value, $taxonomy = 'post_tag' ) {
941
942 1
	$output = array();
943
944 1
	if ( is_array( $value ) ) {
945 1
		$terms = array_filter( array_values( $value ), 'strlen' );
946
	} else {
947 1
		$terms = explode( ', ', $value );
948
	}
949
950 1
	foreach ($terms as $term_name ) {
951
952
		// If we're processing a category,
953 1
		if( $taxonomy === 'category' ) {
954
955
			// Use rgexplode to prevent errors if : doesn't exist
956 1
			list( $term_name, $term_id ) = rgexplode( ':', $term_name, 2 );
957
958
			// The explode was succesful; we have the category ID
959 1
			if( !empty( $term_id )) {
960 1
				$term = get_term_by( 'id', $term_id, $taxonomy );
961
			} else {
962
			// We have to fall back to the name
963 1
				$term = get_term_by( 'name', $term_name, $taxonomy );
964
			}
965
966
		} else {
967
			// Use the name of the tag to get the full term information
968 1
			$term = get_term_by( 'name', $term_name, $taxonomy );
969
		}
970
971
		// There's still a tag/category here.
972 1
		if( $term ) {
973
974 1
			$term_link = get_term_link( $term, $taxonomy );
975
976
			// If there was an error, continue to the next term.
977 1
			if ( is_wp_error( $term_link ) ) {
978
			    continue;
979
			}
980
981 1
			$output[] = gravityview_get_link( $term_link, esc_html( $term->name ) );
982
		}
983
	}
984
985 1
	return implode(', ', $output );
986
}
987
988
/**
989
 * Get the links for post_tags and post_category output based on post ID
990
 * @param  int      $post_id  The ID of the post
991
 * @param  boolean     $link     Add links or no?
992
 * @param  string      $taxonomy Taxonomy of term to fetch.
993
 * @return string                String with terms
994
 */
995
function gravityview_get_the_term_list( $post_id, $link = true, $taxonomy = 'post_tag' ) {
996
997 1
	$output = get_the_term_list( $post_id, $taxonomy, NULL, ', ' );
998
999 1
	if( empty( $link ) ) {
1000 1
		return strip_tags( $output);
1001
	}
1002
1003 1
	return $output;
1004
1005
}
1006
1007
1008
/**
1009
 * Get all views processed so far for the current page load
1010
 *
1011
 * @see  GravityView_View_Data::add_view()
1012
 * @return array Array of View data, each View data with `id`, `view_id`, `form_id`, `template_id`, `atts`, `fields`, `widgets`, `form` keys.
1013
 */
1014
function gravityview_get_current_views() {
1015
1016 1
	$fe = GravityView_frontend::getInstance();
1017
1018
	// Solve problem when loading content via admin-ajax.php
1019 1
	if( ! $fe->getGvOutputData() ) {
1020
1021 1
		gravityview()->log->debug( 'gv_output_data not defined; parsing content.' );
1022
1023 1
		$fe->parse_content();
1024
	}
1025
1026
	// Make 100% sure that we're dealing with a properly called situation
1027 1
	if( !is_a( $fe->getGvOutputData(), 'GravityView_View_Data' ) ) {
1028
1029
		gravityview()->log->debug( 'gv_output_data not an object or get_view not callable.', array( 'data' => $fe->getGvOutputData() ) );
1030
1031
		return array();
1032
	}
1033
1034 1
	return $fe->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...
1035
}
1036
1037
/**
1038
 * Get data for a specific view
1039
 *
1040
 * @deprecated use \GV\View API instead
1041
 * @since 2.5
1042
 *
1043
 * @see  GravityView_View_Data::get_view()
1044
 * @return array View data with `id`, `view_id`, `form_id`, `template_id`, `atts`, `fields`, `widgets`, `form` keys.
1045
 */
1046
function gravityview_get_current_view_data( $view_id = 0 ) {
1047
	if ( $view_id ) {
1048
		if ( $view = \GV\View::by_id( $view_id ) ) {
1049
			return $view; // implements ArrayAccess
1050
		}
1051
		return array();
1052
	}
1053
1054
	$fe = GravityView_frontend::getInstance();
1055
1056
	// If not set, grab the current view ID
1057
	if ( empty( $view_id ) ) {
1058
		$view_id = $fe->get_context_view_id();
1059
	}
1060
1061
	if ( ! $fe->getGvOutputData() ) { return array(); }
1062
1063
	return $fe->getGvOutputData()->get_view( $view_id );
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_View_Data::get_view() has been deprecated.

This method has been deprecated.

Loading history...
1064
}
1065
1066
// Templates' hooks
1067
function gravityview_before() {
1068
	/**
1069
	 * @action `gravityview/template/before` Append content to the view.
1070
	 * @param object $gravityview The $gravityview object available in templates.
1071
	 */
1072 33
	if ( count( $args = func_get_args() ) ) {
1073 31
		$gravityview = reset( $args );
1074 31
		if ( $gravityview instanceof \GV\Template_Context ) {
1075
			/**
1076
			 * @action `gravityview/template/before` Prepend content to the view.
1077
			 * @param \GV\Template_Context $gravityview The $gravityview object available in templates.
1078
			 */
1079 31
			do_action( 'gravityview/template/before', $gravityview );
1080
1081
			/**
1082
			 * @deprecated Use `gravityview/template/before`
1083
			 */
1084 22
			return do_action( 'gravityview_before', $gravityview->view->ID );
1085
		}
1086
	}
1087
1088
	/**
1089
	 * @action `gravityview_before` Prepend content to the View container `<div>`
1090
	 * @deprecated Use `gravityview/template/before`.
1091
	 * @param int $view_id The ID of the View being displayed
1092
	 */
1093 2
	do_action( 'gravityview_before', gravityview_get_view_id() );
1094 2
}
1095
1096
function gravityview_header() {
1097
	/**
1098
	 * @action `gravityview/template/header` Append content to the view.
1099
	 * @param object $gravityview The $gravityview object available in templates.
1100
	 */
1101 21
	if ( count( $args = func_get_args() ) ) {
1102 19
		$gravityview = reset( $args );
1103 19
		if ( $gravityview instanceof \GV\Template_Context ) {
1104
			/**
1105
			 * @action `gravityview/template/header` Prepend content to the view container <div>.
1106
			 * @param \GV\Template_Context $gravityview The $gravityview object available in templates.
1107
			 */
1108 19
			do_action( 'gravityview/template/header', $gravityview );
1109
1110
			/**
1111
			 * @deprecated Use `gravityview/template/header`
1112
			 */
1113 19
			return do_action( 'gravityview_header', $gravityview->view->ID );
1114
		}
1115
	}
1116
1117
	/**
1118
	 * @action `gravityview_header` Prepend content to the View container `<div>`
1119
	 * @deprecated Use `gravityview/template/header`.
1120
	 * @param int $view_id The ID of the View being displayed
1121
	 */
1122 2
	do_action( 'gravityview_header', gravityview_get_view_id() );
1123 2
}
1124
1125
function gravityview_footer() {
1126
	/**
1127
	 * @action `gravityview/template/footer` Append content to the view.
1128
	 * @param object $gravityview The $gravityview object available in templates.
1129
	 */
1130 21
	if ( count( $args = func_get_args() ) ) {
1131 19
		$gravityview = reset( $args );
1132 19
		if ( $gravityview instanceof \GV\Template_Context ) {
1133
			/**
1134
			 * @action `gravityview/template/footer` Prepend outside of the view container <div>.
1135
			 * @param \GV\Template_Context $gravityview The $gravityview object available in templates.
1136
			 */
1137 19
			do_action( 'gravityview/template/footer', $gravityview );
1138
1139
			/**
1140
			 * @deprecated Use `gravityview/template/footer`
1141
			 */
1142 19
			return do_action( 'gravityview_footer', $gravityview->view->ID );
1143
		}
1144
	}
1145
1146
	/**
1147
	 * @action `gravityview_after` Display content after a View. Used to render footer widget areas. Rendered outside the View container `<div>`
1148
	 * @deprecated Use `gravityview/template/footer`.
1149
	 * @param int $view_id The ID of the View being displayed
1150
	 */
1151 2
	do_action( 'gravityview_footer', gravityview_get_view_id() );
1152 2
}
1153
1154
function gravityview_after() {
1155 24
	if ( count( $args = func_get_args() ) ) {
1156 22
		$gravityview = reset( $args );
1157 22
		if ( $gravityview instanceof \GV\Template_Context ) {
1158
			/**
1159
			 * @action `gravityview/template/after` Append content to the view.
1160
			 * @param \GV\Template_Context $gravityview The $gravityview object available in templates.
1161
			 */
1162 22
			do_action( 'gravityview/template/after', $gravityview );
1163
1164
			/**
1165
			 * @deprecated Use `gravityview/template/after`
1166
			 */
1167 22
			do_action( 'gravityview_after', $gravityview->view->ID );
1168
1169 22
			return;
1170
		}
1171
	}
1172
1173
	/**
1174
	 * @action `gravityview_after` Append content to the View container `<div>`
1175
	 * @deprecated Use `gravityview/template/after`
1176
	 * @param int $view_id The ID of the View being displayed
1177
	 */
1178 2
	do_action( 'gravityview_after', gravityview_get_view_id() );
1179 2
}
1180
1181
/**
1182
 * Get the current View ID being rendered
1183
 *
1184
 * @global GravityView_View $gravityview_view
1185
 *
1186
 * @return int View ID, if exists. `0` if `GravityView_View` doesn't exist, like in the admin, or no View is set.
1187
 */
1188
function gravityview_get_view_id() {
1189
1190 2
	if ( ! class_exists( 'GravityView_View' ) ) {
1191
		return 0;
1192
	}
1193
1194 2
	return GravityView_View::getInstance()->getViewId();
1195
}
1196
1197
/**
1198
 * Returns the current GravityView context, or empty string if not GravityView
1199
 *
1200
 * - Returns empty string on GravityView archive pages
1201
 * - Returns empty string on archive pages containing embedded Views
1202
 * - Returns empty string for embedded Views, not 'directory'
1203
 * - Returns empty string for embedded entries (oEmbed or [gventry]), not 'single'
1204
 * - Returns 'single' when viewing a [gravityview] shortcode-embedded single entry
1205
 *
1206
 * @global GravityView_View $gravityview_view
1207
 * @deprecated since 2.0.6.2 Use `gravityview()->request`
1208
 * @return string View context "directory", "single", "edit", or empty string if not GravityView
1209
 */
1210
function gravityview_get_context() {
1211 4
	global $wp_query;
1212
1213 4
	if ( isset( $wp_query ) && $wp_query->post_count > 1 ) {
1214
		return '';
1215
	}
1216
1217
	/**
1218
	 * @filter `gravityview_is_edit_entry` Whether we're currently on the Edit Entry screen \n
1219
	 * The Edit Entry functionality overrides this value.
1220
	 * @param boolean $is_edit_entry
1221
	 */
1222 4
	$is_edit_entry = apply_filters( 'gravityview_is_edit_entry', false );
1223
1224 4
	if ( $is_edit_entry ) {
1225
		return 'edit';
1226 4
	} else if ( gravityview()->request->is_entry() ) {
1227
		return 'single';
1228 4
	} else if ( gravityview()->request->is_view() ) {
1229 4
		return 'directory';
1230
	}
1231
1232
	return '';
1233
}
1234
1235
1236
/**
1237
 * Return an array of files prepared for output. Wrapper for GravityView_Field_FileUpload::get_files_array()
1238
 *
1239
 * Processes files by file type and generates unique output for each.
1240
 *
1241
 * Returns array for each file, with the following keys:
1242
 *
1243
 * `file_path` => The file path of the file, with a line break
1244
 * `html` => The file output HTML formatted
1245
 *
1246
 * @see GravityView_Field_FileUpload::get_files_array()
1247
 *
1248
 * @since  1.2
1249
 * @param  string $value    Field value passed by Gravity Forms. String of file URL, or serialized string of file URL array
1250
 * @param  string $gv_class Field class to add to the output HTML
1251
 * @since  2.0
1252
 * @param  \GV\Template_Context $context The context
1253
 * @return array           Array of file output, with `file_path` and `html` keys (see comments above)
1254
 */
1255
function gravityview_get_files_array( $value, $gv_class = '', $context = null ) {
1256
	/** @define "GRAVITYVIEW_DIR" "../" */
1257
1258 3
	if( !class_exists( 'GravityView_Field' ) ) {
1259
		include_once( GRAVITYVIEW_DIR .'includes/fields/class-gravityview-field.php' );
1260
	}
1261
1262 3
	if( !class_exists( 'GravityView_Field_FileUpload' ) ) {
1263
		include_once( GRAVITYVIEW_DIR .'includes/fields/class-gravityview-field-fileupload.php' );
1264
	}
1265
1266 3
	if ( is_null( $context ) ) {
1267
		_doing_it_wrong( __FUNCTION__, '2.0', 'Please pass an \GV\Template_Context object as the 3rd parameter' );
1268
	}
1269
1270 3
	return GravityView_Field_FileUpload::get_files_array( $value, $gv_class, $context );
1271
}
1272
1273
/**
1274
 * Generate a mapping link from an address
1275
 *
1276
 * The address should be plain text with new line (`\n`) or `<br />` line breaks separating sections
1277
 *
1278
 * @todo use GF's field get_export_value() instead
1279
 *
1280
 * @see https://gravityview.co/support/documentation/201608159 Read how to modify the link
1281
 * @param  string $address Address
1282
 * @return string          URL of link to map of address
1283
 */
1284
function gravityview_get_map_link( $address ) {
1285
1286 1
	$address_qs = str_replace( array( '<br />', "\n" ), ' ', $address ); // Replace \n with spaces
1287 1
	$address_qs = urlencode( $address_qs );
1288
1289 1
	$url = "https://maps.google.com/maps?q={$address_qs}";
1290
1291 1
	$link_text = esc_html__( 'Map It', 'gravityview' );
1292
1293 1
	$link = gravityview_get_link( $url, $link_text, 'class=map-it-link' );
1294
1295
	/**
1296
	 * @filter `gravityview_map_link` Modify the map link generated. You can use a different mapping service, for example.
1297
	 * @param[in,out]  string $link Map link
1298
	 * @param[in] string $address Address to generate link for
1299
	 * @param[in] string $url URL generated by the function
1300
	 */
1301 1
	$link = apply_filters( 'gravityview_map_link', $link, $address, $url );
1302
1303 1
	return $link;
1304
}
1305
1306
1307
/**
1308
 * Output field based on a certain html markup
1309
 *
1310
 *   markup - string to be used on a sprintf statement.
1311
 *      Use:
1312
 *         {{label}} - field label
1313
 *         {{value}} - entry field value
1314
 *         {{class}} - field class
1315
 *
1316
 *   wpautop - true will filter the value using wpautop function
1317
 *
1318
 * @since  1.1.5
1319
 * @param  array $passed_args Associative array with field data. `field` and `form` are required.
1320
 * @since  2.0
1321
 * @param  \GV\Template_Context The template context.
1322
 * @return string Field output. If empty value and hide empty is true, return empty.
1323
 */
1324
function gravityview_field_output( $passed_args, $context = null ) {
1325
	$defaults = array(
1326 19
		'entry' => null,
1327
		'field' => null,
1328
		'form' => null,
1329
		'hide_empty' => true,
1330
		'markup' => '<div id="{{ field_id }}" class="{{ class }}">{{ label }}{{ value }}</div>',
1331
		'label_markup' => '',
1332
		'wpautop' => false,
1333
		'zone_id' => null,
1334
	);
1335
1336 19
	$args = wp_parse_args( $passed_args, $defaults );
1337
1338
	/**
1339
	 * @filter `gravityview/field_output/args` Modify the args before generation begins
1340
	 * @since 1.7
1341
	 * @param array $args Associative array; `field` and `form` is required.
1342
	 * @param array $passed_args Original associative array with field data. `field` and `form` are required.
1343
	 * @since 2.0
1344
	 * @param \GV\Template_Context $context The context.
1345
	 * @deprecated
1346
	 */
1347 19
	$args = apply_filters( 'gravityview/field_output/args', $args, $passed_args, $context );
1348
1349
	/**
1350
	 * @filter `gravityview/template/field_output/context` Modify the context before generation begins.
1351
	 * @since 2.0
1352
	 * @param[in,out] \GV\Template_Context $context The context.
1353
	 * @param array $args The sanitized arguments, these should not be trusted any longer.
1354
	 * @param array $passed_args The passed arguments, these should not be trusted any longer.
1355
	 */
1356 19
	$context = apply_filters( 'gravityview/template/field_output/context', $context, $args, $passed_args );
1357
1358 19
	if ( $context instanceof \GV\Template_Context ) {
1359 18
		if ( ! $context->field || ! $context->view || ! $context->view->form ) {
1360
			gravityview()->log->error( 'Field or form are empty.', array( 'data' => array( $context->field, $context->view->form ) ) );
1361 18
			return '';
1362
		}
1363
	} else {
1364
		// @deprecated path
1365
		// Required fields.
1366 1
		if ( empty( $args['field'] ) || empty( $args['form'] ) ) {
1367
			gravityview()->log->error( 'Field or form are empty.', array( 'data' => $args ) );
1368
			return '';
1369
		}
1370
	}
1371
1372 19
	if ( $context instanceof \GV\Template_Context ) {
1373 18
		$entry = $args['entry'] ? : ( $context->entry ? $context->entry->as_entry() : array() );
1374 18
		$field = $args['field'] ? : ( $context->field ? $context->field->as_configuration() : array() );
1375 18
		$form = $args['form'] ? : ( $context->view->form ? $context->view->form->form : array() );
0 ignored issues
show
Documentation introduced by
The property $form is declared private in GV\Form. 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...
1376
	} else {
1377
		// @deprecated path
1378 1
		$entry = empty( $args['entry'] ) ? array() : $args['entry'];
1379 1
		$field = $args['field'];
1380 1
		$form = $args['form'];
1381
	}
1382
1383
	/**
1384
	 * Create the content variables for replacing.
1385
	 * @since 1.11
1386
	 */
1387
	$placeholders = array(
1388 19
		'value' => '',
1389
		'width' => '',
1390
		'width:style' => '',
1391
		'label' => '',
1392
		'label_value' => '',
1393
		'label_value:esc_attr' => '',
1394
		'label_value:data-label' => '',
1395
		'class' => '',
1396
		'field_id' => '',
1397
	);
1398
1399 19
	if ( $context instanceof \GV\Template_Context ) {
1400 18
		$placeholders['value'] = \GV\Utils::get( $args, 'value', '' );
1401
	} else {
1402
		// @deprecated path
1403 1
		$placeholders['value'] = gv_value( $entry, $field );
0 ignored issues
show
Deprecated Code introduced by
The function gv_value() has been deprecated with message: Use \GV\Field_Template::render()

This function has been deprecated. The supplier of the file has supplied an explanatory message.

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

Loading history...
1404
	}
1405
1406
	// If the value is empty and we're hiding empty, return empty.
1407 19
	if ( $placeholders['value'] === '' && ! empty( $args['hide_empty'] ) ) {
1408 1
		return '';
1409
	}
1410
1411 19
	if ( $placeholders['value'] !== '' && ! empty( $args['wpautop'] ) ) {
1412
		$placeholders['value'] = wpautop( $placeholders['value'] );
1413
	}
1414
1415
	// Get width setting, if exists
1416 19
	$placeholders['width'] = GravityView_API::field_width( $field );
1417
1418
	// If replacing with CSS inline formatting, let's do it.
1419 19
	$placeholders['width:style'] = GravityView_API::field_width( $field, 'width:' . $placeholders['width'] . '%;' );
1420
1421
	// Grab the Class using `gv_class`
1422 19
	$placeholders['class'] = gv_class( $field, $form, $entry );
1423 19
	$placeholders['field_id'] = GravityView_API::field_html_attr_id( $field, $form, $entry );
1424
1425 19
	if ( $context instanceof \GV\Template_Context ) {
1426 18
		$placeholders['label_value'] = \GV\Utils::get( $args, 'label' );
1427
	} else {
1428
		// Default Label value
1429 1
		$placeholders['label_value'] = gv_label( $field, $entry );
0 ignored issues
show
Deprecated Code introduced by
The function gv_label() has been deprecated with message: Use \GV\Field::get_label()

This function has been deprecated. The supplier of the file has supplied an explanatory message.

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

Loading history...
1430
	}
1431
1432 19
	$placeholders['label_value:data-label'] = trim( esc_attr( strip_tags( str_replace( '>&nbsp;', '>', $placeholders['label_value'] ) ) ) );
1433 19
	$placeholders['label_value:esc_attr'] = esc_attr( $placeholders['label_value'] );
1434
1435 19
	if ( empty( $placeholders['label'] ) && ! empty( $placeholders['label_value'] ) ){
1436 19
		$placeholders['label'] = '<span class="gv-field-label">{{ label_value }}</span>';
1437
	}
1438
1439
	/**
1440
	 * @filter `gravityview/field_output/pre_html` Allow Pre filtering of the HTML
1441
	 * @since 1.11
1442
	 * @param string $markup The HTML for the markup
1443
	 * @param array $args All args for the field output
1444
	 * @since 2.0
1445
	 * @param \GV\Template_Context $context The context.
1446
	 */
1447 19
	$html = apply_filters( 'gravityview/field_output/pre_html', $args['markup'], $args, $context );
1448
1449
	/**
1450
	 * @filter `gravityview/field_output/open_tag` Modify the opening tags for the template content placeholders
1451
	 * @since 1.11
1452
	 * @param string $open_tag Open tag for template content placeholders. Default: `{{`
1453
	 * @since 2.0
1454
	 * @param \GV\Template_Context $context The context.
1455
	 */
1456 19
	$open_tag = apply_filters( 'gravityview/field_output/open_tag', '{{', $args, $context );
1457
1458
	/**
1459
	 * @filter `gravityview/field_output/close_tag` Modify the closing tags for the template content placeholders
1460
	 * @since 1.11
1461
	 * @param string $close_tag Close tag for template content placeholders. Default: `}}`
1462
	 * @since 2.0
1463
	 * @param \GV\Template_Context $context The context.
1464
	 */
1465 19
	$close_tag = apply_filters( 'gravityview/field_output/close_tag', '}}', $args, $context );
1466
1467
	/**
1468
	 * Loop through each of the tags to replace and replace both `{{tag}}` and `{{ tag }}` with the values
1469
	 * @since 1.11
1470
	 */
1471 19
	foreach ( $placeholders as $tag => $value ) {
1472
1473
		// If the tag doesn't exist just skip it
1474 19
		if ( false === strpos( $html, $open_tag . $tag . $close_tag ) && false === strpos( $html, $open_tag . ' ' . $tag . ' ' . $close_tag ) ){
1475 19
			continue;
1476
		}
1477
1478
		// Array to search
1479
		$search = array(
1480 19
			$open_tag . $tag . $close_tag,
1481 19
			$open_tag . ' ' . $tag . ' ' . $close_tag,
1482
		);
1483
1484
		/**
1485
		 * `gravityview/field_output/context/{$tag}` Allow users to filter content on context
1486
		 * @since 1.11
1487
		 * @param string $value The content to be shown instead of the {{tag}} placeholder
1488
		 * @param array $args Arguments passed to the function
1489
		 * @since 2.0
1490
		 * @param \GV\Template_Context $context The context.
1491
		 */
1492 19
		$value = apply_filters( 'gravityview/field_output/context/' . $tag, $value, $args, $context );
1493
1494
		// Finally do the replace
1495 19
		$html = str_replace( $search, $value, $html );
1496
	}
1497
1498
	/**
1499
	 * @filter `gravityview_field_output` Modify field HTML output
1500
	 * @param string $html Existing HTML output
1501
	 * @param array $args Arguments passed to the function
1502
	 * @since 2.0
1503
	 * @param \GV\Template_Context $context The context.
1504
	 */
1505 19
	$html = apply_filters( 'gravityview_field_output', $html, $args, $context );
1506
1507
	/**
1508
	 * @filter `gravityview/field_output/html` Modify field HTML output
1509
	 * @param string $html Existing HTML output
1510
	 * @param array $args Arguments passed to the function
1511
	 * @since 2.0
1512
	 * @param \GV\Template_Context $context The context.
1513
	 */
1514 19
	$html = apply_filters( 'gravityview/field_output/html', $html, $args, $context );
1515
1516
	/** @since 2.0.8 Remove unused atts */
1517 19
	$html = str_replace( array( ' style=""', ' class=""', ' id=""' ), '', $html );
1518
1519 19
	return $html;
1520
}
1521