Completed
Pull Request — master (#664)
by Zack
07:00 queued 03:02
created

GravityView_API::field_value()   C

Complexity

Conditions 12
Paths 61

Size

Total Lines 127
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 3 Features 0
Metric Value
c 3
b 3
f 0
dl 0
loc 127
rs 5.034
cc 12
eloc 51
nc 61
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
	 * @access public
20
	 * @static
21
	 * @param array $field GravityView field array
22
	 * @param array $entry Gravity Forms entry array
23
	 * @param boolean $force_show_label Whether to always show the label, regardless of field settings
24
	 * @return string
25
	 */
26
	public static function field_label( $field, $entry = array(), $force_show_label = false ) {
27
		$gravityview_view = GravityView_View::getInstance();
28
29
		$form = $gravityview_view->getForm();
30
31
		$label = '';
32
33
		if( !empty( $field['show_label'] ) || $force_show_label ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
34
35
			$label = $field['label'];
36
37
			// Support Gravity Forms 1.9+
38
			if( class_exists( 'GF_Field' ) ) {
39
40
				$field_object = RGFormsModel::get_field( $form, $field['id'] );
41
42
				if( $field_object ) {
43
44
					$input = GFFormsModel::get_input( $field_object, $field['id'] );
45
46
					// This is a complex field, with labels on a per-input basis
47
					if( $input ) {
48
49
						// Does the input have a custom label on a per-input basis? Otherwise, default label.
50
						$label = ! empty( $input['customLabel'] ) ? $input['customLabel'] : $input['label'];
51
52
					} else {
53
54
						// This is a field with one label
55
						$label = $field_object->get_field_label( true, $field['label'] );
56
57
					}
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
58
59
				}
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
60
61
			}
62
63
			// Use Gravity Forms label by default, but if a custom label is defined in GV, use it.
64
			if ( !empty( $field['custom_label'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
65
66
				$label = self::replace_variables( $field['custom_label'], $form, $entry );
67
68
			}
69
70
			/**
71
			 * @filter `gravityview_render_after_label` Append content to a field label
72
			 * @param[in,out] string $appended_content Content you can add after a label. Empty by default.
73
			 * @param[in] array $field GravityView field array
74
			 */
75
			$label .= apply_filters( 'gravityview_render_after_label', '', $field );
76
77
		} // End $field['show_label']
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
78
79
		/**
80
		 * @filter `gravityview/template/field_label` Modify field label output
81
		 * @since 1.7
82
		 * @param[in,out] string $label Field label HTML
83
		 * @param[in] array $field GravityView field array
84
		 * @param[in] array $form Gravity Forms form array
85
		 * @param[in] array $entry Gravity Forms entry array
86
		 */
87
		$label = apply_filters( 'gravityview/template/field_label', $label, $field, $form, $entry );
88
89
		return $label;
90
	}
91
92
	/**
93
	 * Alias for GravityView_Merge_Tags::replace_variables()
94
	 *
95
	 * @see GravityView_Merge_Tags::replace_variables() Moved in 1.8.4
96
	 *
97
	 * @param  string      $text       Text to replace variables in
98
	 * @param  array      $form        GF Form array
99
	 * @param  array      $entry        GF Entry array
100
	 * @return string                  Text with variables maybe replaced
101
	 */
102
	public static function replace_variables( $text, $form = array(), $entry = array() ) {
103
		return GravityView_Merge_Tags::replace_variables( $text, $form, $entry );
104
	}
105
106
	/**
107
	 * Get column width from the field setting
108
	 *
109
	 * @since 1.9
110
	 *
111
	 * @param array $field Array of settings for the field
112
	 * @param string $format Format for width. "%" (default) will return
113
	 *
114
	 * @return string|null If not empty, string in $format format. Otherwise, null.
115
	 */
116
	public static function field_width( $field, $format = '%d%%' ) {
117
118
		$width = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
119
120
		if( !empty( $field['width'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
121
			$width = absint( $field['width'] );
122
123
			// If using percentages, limit to 100%
124
			if( '%d%%' === $format && $width > 100 ) {
125
				$width = 100;
126
			}
127
128
			$width = sprintf( $format, $width );
129
		}
130
131
		return $width;
132
	}
133
134
	/**
135
	 * Fetch Field class
136
	 *
137
	 * @access public
138
	 * @static
139
	 * @param mixed $field
140
	 * @return string
141
	 */
142
	public static function field_class( $field, $form = NULL, $entry = NULL ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
143
		$gravityview_view = GravityView_View::getInstance();
144
145
		$classes = array();
146
147
		if( !empty( $field['custom_class'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
148
149
            $custom_class = $field['custom_class'];
150
151
            if( !empty( $entry ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
152
153
                // We want the merge tag to be formatted as a class. The merge tag may be
154
                // replaced by a multiple-word value that should be output as a single class.
155
                // "Office Manager" will be formatted as `.OfficeManager`, not `.Office` and `.Manager`
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
156
                add_filter('gform_merge_tag_filter', 'sanitize_html_class');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
157
158
                $custom_class = self::replace_variables( $custom_class, $form, $entry);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
159
160
                // And then we want life to return to normal
161
                remove_filter('gform_merge_tag_filter', 'sanitize_html_class');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
162
            }
163
164
			// And now we want the spaces to be handled nicely.
165
			$classes[] = gravityview_sanitize_html_class( $custom_class );
166
167
		}
168
169
		if(!empty($field['id'])) {
0 ignored issues
show
introduced by
No space after opening parenthesis is prohibited
Loading history...
introduced by
Expected 1 space before "!"; 0 found
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
170
			if( !empty( $form ) && !empty( $form['id'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
171
				$form_id = '-'.$form['id'];
172
			} else {
173
				$form_id = $gravityview_view->getFormId() ? '-'. $gravityview_view->getFormId() : '';
174
			}
175
176
			$classes[] = 'gv-field'.$form_id.'-'.$field['id'];
177
		}
178
179
		return esc_attr(implode(' ', $classes));
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
180
	}
181
182
	/**
183
	 * Fetch Field HTML ID
184
	 *
185
	 * @since 1.11
186
	 *
187
	 * @access public
188
	 * @static
189
	 * @param array $field GravityView field array passed to gravityview_field_output()
190
	 * @param array $form Gravity Forms form array, if set.
191
	 * @param array $entry Gravity Forms entry array
192
	 * @return string Sanitized unique HTML `id` attribute for the field
193
	 */
194
	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...
195
		$gravityview_view = GravityView_View::getInstance();
196
		$id = $field['id'];
197
198
		if ( ! empty( $id ) ) {
199
			if ( ! empty( $form ) && ! empty( $form['id'] ) ) {
200
				$form_id = '-' . $form['id'];
201
			} else {
202
				$form_id = $gravityview_view->getFormId() ? '-' . $gravityview_view->getFormId() : '';
203
			}
204
205
			$id = 'gv-field' . $form_id . '-' . $field['id'];
206
		}
207
208
		return esc_attr( $id );
209
	}
210
211
212
	/**
213
	 * Given an entry and a form field id, calculate the entry value for that field.
214
	 *
215
	 * @access public
216
	 * @param array $entry
217
	 * @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...
218
	 * @return null|string
219
	 */
220
	public static function field_value( $entry, $field_settings, $format = 'html' ) {
221
222
		if( empty( $entry['form_id'] ) || empty( $field_settings['id'] ) ) {
223
			return NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
224
		}
225
226
		$gravityview_view = GravityView_View::getInstance();
227
228
		$field_id = $field_settings['id'];
229
		$form = $gravityview_view->getForm();
230
		$field = gravityview_get_field( $form, $field_id );
231
232
		// Prevent any PHP warnings that may be generated
233
		ob_start();
234
235
		if( $field && is_numeric( $field_id ) ) {
236
			// Used as file name of field template in GV.
237
			// Don't use RGFormsModel::get_input_type( $field ); we don't care if it's a radio input; we want to know it's a 'quiz' field
238
			$field_type = $field->type;
239
			$value = RGFormsModel::get_lead_field_value( $entry, $field );
240
		} else {
241
			$field = GravityView_Fields::get_associated_field( $field_id );
242
			$field_type = $field_id; // Used as file name of field template in GV
243
		}
244
245
		// If a Gravity Forms Field is found, get the field display
246
		if( $field ) {
247
			$display_value = GFCommon::get_lead_field_display( $field, $value, $entry["currency"], false, $format );
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal currency does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
Bug introduced by
The variable $value does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
248
249
			if ( $errors = ob_get_clean() ) {
250
				do_action( 'gravityview_log_error', 'GravityView_API[field_value] Errors when calling GFCommon::get_lead_field_display()', $errors );
251
			}
252
253
			$display_value = apply_filters( "gform_entry_field_value", $display_value, $field, $entry, $form );
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal gform_entry_field_value does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
254
255
			// prevent the use of merge_tags for non-admin fields
256
			if( !empty( $field->adminOnly ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
257
				$display_value = self::replace_variables( $display_value, $form, $entry );
258
			}
259
		} else {
260
			$value = $display_value = rgar( $entry, $field_id );
261
			$display_value = $value;
262
		}
263
264
		// Check whether the field exists in /includes/fields/{$field_type}.php
265
		// This can be overridden by user template files.
266
		$field_path = $gravityview_view->locate_template("fields/{$field_type}.php");
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
267
268
		// Set the field data to be available in the templates
269
		$gravityview_view->setCurrentField( array(
270
			'form' => $form,
271
			'field_id' => $field_id,
272
			'field' => $field,
273
			'field_settings' => $field_settings,
274
			'value' => $value,
275
			'display_value' => $display_value,
276
			'format' => $format,
277
			'entry' => $entry,
278
			'field_type' => $field_type, /** {@since 1.6} */
279
		    'field_path' => $field_path, /** {@since 1.16} */
280
		));
281
282
		if( ! empty( $field_path ) ) {
283
284
			do_action( 'gravityview_log_debug', sprintf('[field_value] Rendering %s', $field_path ) );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
285
286
			ob_start();
287
288
			load_template( $field_path, false );
289
290
			$output = ob_get_clean();
291
292
		} else {
293
294
			// Backup; the field template doesn't exist.
295
			$output = $display_value;
296
297
		}
298
299
		// Get the field settings again so that the field template can override the settings
300
		$field_settings = $gravityview_view->getCurrentField('field_settings');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
301
302
		/**
303
		 * @filter `gravityview_field_entry_value_{$field_type}_pre_link` Modify the field value output for a field type before Show As Link setting is applied. Example: `gravityview_field_entry_value_number_pre_link`
304
		 * @since 1.16
305
		 * @param string $output HTML value output
306
		 * @param array  $entry The GF entry array
307
		 * @param array  $field_settings Settings for the particular GV field
308
		 * @param array  $field Field array, as fetched from GravityView_View::getCurrentField()
309
		 */
310
		$output = apply_filters( 'gravityview_field_entry_value_' . $field_type . '_pre_link', $output, $entry, $field_settings, $gravityview_view->getCurrentField() );
311
312
		/**
313
		 * Link to the single entry by wrapping the output in an anchor tag
314
		 *
315
		 * Fields can override this by modifying the field data variable inside the field. See /templates/fields/post_image.php for an example.
316
		 *
317
		 */
318
		if( !empty( $field_settings['show_as_link'] ) && ! gv_empty( $output, false, false ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
319
320
			$link_atts = empty( $field_settings['new_window'] ) ? array() : array( 'target' => '_blank' );
321
322
			$output = self::entry_link_html( $entry, $output, $link_atts, $field_settings );
323
324
		}
325
326
		/**
327
		 * @filter `gravityview_field_entry_value_{$field_type}` Modify the field value output for a field type. Example: `gravityview_field_entry_value_number`
328
		 * @since 1.6
329
		 * @param string $output HTML value output
330
		 * @param array  $entry The GF entry array
331
		 * @param  array $field_settings Settings for the particular GV field
332
		 * @param array $field Current field being displayed
333
		 */
334
		$output = apply_filters( 'gravityview_field_entry_value_'.$field_type, $output, $entry, $field_settings, $gravityview_view->getCurrentField() );
335
336
		/**
337
		 * @filter `gravityview_field_entry_value` Modify the field value output for all field types
338
		 * @param string $output HTML value output
339
		 * @param array  $entry The GF entry array
340
		 * @param  array $field_settings Settings for the particular GV field
341
		 * @param array $field_data  {@since 1.6}
342
		 */
343
		$output = apply_filters( 'gravityview_field_entry_value', $output, $entry, $field_settings, $gravityview_view->getCurrentField() );
344
345
		return $output;
346
	}
347
348
	/**
349
	 * Generate an anchor tag that links to an entry.
350
	 *
351
	 * @since 1.6
352
	 * @see GVCommon::get_link_html()
353
	 *
354
	 * @param string $anchor_text The text or HTML inside the link
355
	 * @param array $entry Gravity Forms entry array
356
	 * @param array|string $passed_tag_atts Attributes to be added to the anchor tag, such as `title` or `rel`.
357
	 * @param array $field_settings Array of field settings. Optional, but passed to the `gravityview_field_entry_link` filter
358
	 *
359
	 * @return string|null Returns HTML for an anchor link. Null if $entry isn't defined or is missing an ID.
360
	 */
361
	public static function entry_link_html( $entry = array(), $anchor_text = '', $passed_tag_atts = array(), $field_settings = array() ) {
362
363
		if ( empty( $entry ) || ! is_array( $entry ) || ! isset( $entry['id'] ) ) {
364
			do_action( 'gravityview_log_debug', 'GravityView_API[entry_link_tag] Entry not defined; returning null', $entry );
365
			return NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
366
		}
367
368
		$href = self::entry_link( $entry );
369
370
		if( '' === $href ) {
371
			return NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
372
		}
373
374
		$link = gravityview_get_link( $href, $anchor_text, $passed_tag_atts );
375
376
		/**
377
		 * @filter `gravityview_field_entry_link` Modify the link HTML
378
		 * @param string $link HTML output of the link
379
		 * @param string $href URL of the link
380
		 * @param array  $entry The GF entry array
381
		 * @param  array $field_settings Settings for the particular GV field
382
		 */
383
		$output = apply_filters( 'gravityview_field_entry_link', $link, $href, $entry, $field_settings );
384
385
		return $output;
386
	}
387
388
	/**
389
	 * Get the "No Results" text depending on whether there were results.
390
	 * @param  boolean     $wpautop Apply wpautop() to the output?
391
	 * @return string               HTML of "no results" text
392
	 */
393
	public static function no_results($wpautop = true) {
394
		$gravityview_view = GravityView_View::getInstance();
395
396
		$is_search = false;
397
398
		if( $gravityview_view && ( $gravityview_view->curr_start || $gravityview_view->curr_end || $gravityview_view->curr_search ) ) {
399
			$is_search = true;
400
		}
401
402
		if($is_search) {
0 ignored issues
show
introduced by
No space after opening parenthesis is prohibited
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
403
			$output = __('This search returned no results.', 'gravityview');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
404
		} else {
405
			$output = __('No entries match your request.', 'gravityview');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
406
		}
407
408
		/**
409
		 * @filter `gravitview_no_entries_text` Modify the text displayed when there are no entries.
410
		 * @param string $output The existing "No Entries" text
411
		 * @param boolean $is_search Is the current page a search result, or just a multiple entries screen?
412
		 */
413
		$output = apply_filters( 'gravitview_no_entries_text', $output, $is_search);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
414
415
		return $wpautop ? wpautop($output) : $output;
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
416
	}
417
418
	/**
419
	 * Generate a link to the Directory view
420
	 *
421
	 * 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!
422
	 *
423
	 * @param int $post_id Post ID
424
	 * @param boolean $add_query_args Add pagination and sorting arguments
425
	 * @return string      Permalink to multiple entries view
426
	 */
427
	public static function directory_link( $post_id = NULL, $add_query_args = true ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
428
		global $post;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
429
430
		$gravityview_view = GravityView_View::getInstance();
431
432
		if( empty( $post_id ) ) {
433
434
			$post_id = false;
435
436
			// DataTables passes the Post ID
437
			if( defined('DOING_AJAX') && DOING_AJAX ) {
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
438
439
				$post_id = isset( $_POST['post_id'] ) ? (int)$_POST['post_id'] : false;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
440
441
			} else {
442
443
				// The Post ID has been passed via the shortcode
444
				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...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
445
446
					$post_id = $gravityview_view->getPostId();
447
448
				} else {
449
450
					// This is a GravityView post type
451
					if( GravityView_frontend::getInstance()->isGravityviewPostType() ) {
452
453
						$post_id = isset( $gravityview_view ) ? $gravityview_view->getViewId() : $post->ID;
454
455
					} else {
456
457
						// This is an embedded GravityView; use the embedded post's ID as the base.
458
						if( GravityView_frontend::getInstance()->isPostHasShortcode() && is_a( $post, 'WP_Post' ) ) {
459
460
							$post_id = $post->ID;
461
462
						} elseif( $gravityview_view->getViewId() ) {
463
464
							// The GravityView has been embedded in a widget or in a template, and
465
							// is not in the current content. Thus, we defer to the View's own ID.
466
							$post_id = $gravityview_view->getViewId();
467
468
						}
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
469
470
					}
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
471
472
				}
473
			}
474
		}
475
476
		// No post ID, get outta here.
477
		if( empty( $post_id ) ) {
478
			return NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
479
		}
480
481
		// If we've saved the permalink in memory, use it
482
		// @since 1.3
483
		$link = wp_cache_get( 'gv_directory_link_'.$post_id );
484
485
		if( empty( $link ) ) {
486
487
			$link = get_permalink( $post_id );
488
489
			// If not yet saved, cache the permalink.
490
			// @since 1.3
491
			wp_cache_set( 'gv_directory_link_'.$post_id, $link );
492
493
		}
494
495
		// Deal with returning to proper pagination for embedded views
496
		if( $link && $add_query_args ) {
497
498
			$args = array();
499
500
			if( $pagenum = rgget('pagenum') ) {
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
501
				$args['pagenum'] = intval( $pagenum );
502
			}
503
504
			if( $sort = rgget('sort') ) {
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
505
				$args['sort'] = $sort;
506
				$args['dir'] = rgget('dir');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
507
			}
508
509
			$link = add_query_arg( $args, $link );
510
		}
511
512
		return $link;
513
	}
514
515
	/**
516
	 * Calculate an *unique* hash for an entry based on the entry ID
517
	 *
518
	 * 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.
519
	 *
520
	 * The hashed value MUST be unique, otherwise multiple entries will share the same URL, which leads to obvious problems.
521
	 *
522
	 * @param  int|string $id Entry ID to generate the hash for.
523
	 * @param  array  $entry        Entry data passed to provide additional information when generating the hash. Optional - don't rely on it being available.
524
	 * @return string               Hashed unique value for entry
525
	 */
526
	private static function get_custom_entry_slug( $id, $entry = array() ) {
527
528
		// Generate an unique hash to use as the default value
529
		$slug = substr( wp_hash( $id, 'gravityview'.$id ), 0, 8 );
530
531
		/**
532
		 * @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}`
533
		 * @param string $hash Existing hash generated by GravityView
534
		 * @param  string $id The entry ID
535
		 * @param  array $entry Entry data array. May be empty.
536
		 */
537
		$slug = apply_filters( 'gravityview_entry_slug', $slug, $id, $entry );
538
539
		// Make sure we have something - use the original ID as backup.
540
		if( empty( $slug ) ) {
541
			$slug = $id;
542
		}
543
544
		return sanitize_title( $slug );
545
	}
546
547
	/**
548
	 * Get the entry slug for the entry. By default, it is the entry ID.
549
	 *
550
	 *
551
	 * @see gravityview_get_entry()
552
	 * @uses GravityView_API::get_custom_entry_slug() If using custom slug, gets the custom slug value
553
	 * @since 1.4
554
	 * @param  int|string $id_or_string ID of the entry, or custom slug string
555
	 * @param  array  $entry        Gravity Forms Entry array, optional. Used only to provide data to customize the `gravityview_entry_slug` filter
556
	 * @return string               Unique slug ID, passed through `sanitize_title()`
557
	 */
558
	public static function get_entry_slug( $id_or_string, $entry = array() ) {
559
560
		/**
561
		 * Default: use the entry ID as the unique identifier
562
		 */
563
		$slug = $id_or_string;
564
565
		/**
566
		 * @filter `gravityview_custom_entry_slug` Whether to enable and use custom entry slugs.
567
		 * @param boolean True: Allow for slugs based on entry values. False: always use entry IDs (default)
568
		 */
569
		$custom = apply_filters('gravityview_custom_entry_slug', false );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
570
571
		// If we're using custom slug...
572
		if ( $custom ) {
573
574
			// Get the entry hash
575
			$hash = self::get_custom_entry_slug( $id_or_string, $entry );
576
577
			// See if the entry already has a hash set
578
			$value = gform_get_meta( $id_or_string, 'gravityview_unique_id' );
579
580
			// If it does have a hash set, and the hash is expected, use it.
581
			// This check allows users to change the hash structure using the
582
			// gravityview_entry_hash filter and have the old hashes expire.
583
			if( empty( $value ) || $value !== $hash ) {
584
585
				gform_update_meta( $id_or_string, 'gravityview_unique_id', $hash );
586
587
			}
588
589
			$slug = $hash;
590
591
			unset( $value, $hash );
592
		}
593
594
		return sanitize_title( $slug );
595
	}
596
597
    /**
598
     * If using the entry custom slug feature, make sure the new entries have the custom slug created and saved as meta
599
     *
600
     * Triggered by add_action( 'gform_entry_created', array( 'GravityView_API', 'entry_create_custom_slug' ), 10, 2 );
601
     *
602
     * @param $entry array Gravity Forms entry object
603
     * @param $form array Gravity Forms form object
604
     */
605
    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...
606
        /**
607
         * @filter `gravityview_custom_entry_slug` On entry creation, check if we are using the custom entry slug feature and update the meta
608
         * @param boolean $custom Should we process the custom entry slug?
609
         */
610
        $custom = apply_filters( 'gravityview_custom_entry_slug', false );
611
        if( $custom ) {
612
            // create the gravityview_unique_id and save it
613
614
            // Get the entry hash
615
            $hash = self::get_custom_entry_slug( $entry['id'], $entry );
616
            gform_update_meta( $entry['id'], 'gravityview_unique_id', $hash );
617
618
        }
619
    }
620
621
622
623
624
	/**
625
	 * return href for single entry
626
	 * @param  array|int $entry   Entry array or entry ID
627
	 * @param  int|null $post_id If wanting to define the parent post, pass a post ID
628
	 * @param boolean $add_directory_args True: Add args to help return to directory; False: only include args required to get to entry {@since 1.7.3}
629
	 * @return string          Link to the entry with the directory parent slug
630
	 */
631
	public static function entry_link( $entry, $post_id = NULL, $add_directory_args = true ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
632
633
		if( ! empty( $entry ) && ! is_array( $entry ) ) {
634
			$entry = GVCommon::get_entry( $entry );
635
		} else if( empty( $entry ) ) {
636
			$entry = GravityView_frontend::getInstance()->getEntry();
637
		}
638
639
		// Second parameter used to be passed as $field; this makes sure it's not an array
640
		if( !is_numeric( $post_id ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
641
			$post_id = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
642
		}
643
644
		// Get the permalink to the View
645
		$directory_link = self::directory_link( $post_id, false );
646
647
		// No post ID? Get outta here.
648
		if( empty( $directory_link ) ) {
649
			return '';
650
		}
651
652
		$query_arg_name = GravityView_Post_Types::get_entry_var_name();
653
654
		$entry_slug = self::get_entry_slug( $entry['id'], $entry );
655
656
		if( get_option('permalink_structure') && !is_preview() ) {
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
657
658
			$args = array();
659
660
			$directory_link = trailingslashit( $directory_link ) . $query_arg_name . '/'. $entry_slug .'/';
661
662
		} else {
663
664
			$args = array( $query_arg_name => $entry_slug );
665
		}
666
667
		/**
668
		 * @since 1.7.3
669
		 */
670
		if( $add_directory_args ) {
671
672
			if( !empty( $_GET['pagenum'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
673
				$args['pagenum'] = intval( $_GET['pagenum'] );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
674
			}
675
676
			/**
677
			 * @since 1.7
678
			 */
679
			if( $sort = rgget('sort') ) {
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
680
				$args['sort'] = $sort;
681
				$args['dir'] = rgget('dir');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
682
			}
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
683
684
		}
685
686
		/**
687
		 * Check if we have multiple views embedded in the same page and in that case make sure the single entry link
688
		 * has the view id so that Advanced Filters can be applied correctly when rendering the single view
689
		 * @see GravityView_frontend::get_context_view_id()
690
		 */
691
		if( class_exists( 'GravityView_View_Data' ) && GravityView_View_Data::getInstance()->has_multiple_views() ) {
692
			$args['gvid'] = gravityview_get_view_id();
693
		}
694
695
		return add_query_arg( $args, $directory_link );
696
697
	}
698
699
700
}
701
702
703
// inside loop functions
704
705
function gv_label( $field, $entry = NULL ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
706
	return GravityView_API::field_label( $field, $entry );
707
}
708
709
function gv_class( $field, $form = NULL, $entry = array() ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
710
	return GravityView_API::field_class( $field, $form, $entry  );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 2 found
Loading history...
711
}
712
713
/**
714
 * Generate a CSS class to be added to the wrapper <div> of a View
715
 *
716
 * @since 1.5.4
717
 * @since 1.16 Added $echo param
718
 *
719
 * @param string $passed_css_class Default: `gv-container gv-container-{view id}`. If View is hidden until search, adds ` hidden`
720
 * @param boolean $echo Whether to echo the output. Default: true
721
 *
722
 * @return string CSS class, sanitized by gravityview_sanitize_html_class()
723
 */
724
function gv_container_class( $passed_css_class = '', $echo = true ) {
725
726
	$passed_css_class = trim( $passed_css_class );
727
728
	$view_id = GravityView_View::getInstance()->getViewId();
729
730
	$default_css_class = ! empty( $view_id ) ? sprintf( 'gv-container gv-container-%d', $view_id ) : 'gv-container';
731
732
	if( GravityView_View::getInstance()->isHideUntilSearched() ) {
733
		$default_css_class .= ' hidden';
734
	}
735
736
	if( 0 === GravityView_View::getInstance()->getTotalEntries() ) {
737
		$default_css_class .= ' gv-container-no-results';
738
	}
739
740
	$css_class = trim( $passed_css_class . ' '. $default_css_class );
741
742
	/**
743
	 * @filter `gravityview/render/container/class` Modify the CSS class to be added to the wrapper <div> of a View
744
	 * @since 1.5.4
745
	 * @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`
746
	 */
747
	$css_class = apply_filters( 'gravityview/render/container/class', $css_class );
748
749
	$css_class = gravityview_sanitize_html_class( $css_class );
750
751
	if( $echo ) {
752
		echo $css_class;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$css_class'
Loading history...
753
	}
754
755
	return $css_class;
756
}
757
758
function gv_value( $entry, $field ) {
759
760
	$value = GravityView_API::field_value( $entry, $field );
761
762
	if( $value === '' ) {
763
		/**
764
		 * @filter `gravityview_empty_value` What to display when a field is empty
765
		 * @param string $value (empty string)
766
		 */
767
		$value = apply_filters( 'gravityview_empty_value', '' );
768
	}
769
770
	return $value;
771
}
772
773
function gv_directory_link( $post = NULL, $add_pagination = true ) {
0 ignored issues
show
introduced by
Overridding WordPress globals is prohibited
Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
774
	return GravityView_API::directory_link( $post, $add_pagination );
775
}
776
777
function gv_entry_link( $entry, $post_id = NULL ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
778
	return GravityView_API::entry_link( $entry, $post_id );
779
}
780
781
function gv_no_results($wpautop = true) {
782
	return GravityView_API::no_results( $wpautop );
783
}
784
785
/**
786
 * Generate HTML for the back link from single entry view
787
 * @since 1.0.1
788
 * @return string|null      If no GV post exists, null. Otherwise, HTML string of back link.
789
 */
790
function gravityview_back_link() {
791
792
	$href = gv_directory_link();
793
794
	if( empty( $href ) ) { return NULL; }
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
795
796
	// calculate link label
797
	$gravityview_view = GravityView_View::getInstance();
798
799
	$label = $gravityview_view->getBackLinkLabel() ? $gravityview_view->getBackLinkLabel() : __( '&larr; Go back', 'gravityview' );
800
801
	/**
802
	 * @filter `gravityview_go_back_label` Modify the back link text
803
	 * @since 1.0.9
804
	 * @param string $label Existing label text
805
	 */
806
	$label = apply_filters( 'gravityview_go_back_label', $label );
807
808
	$link = gravityview_get_link( $href, esc_html( $label ), array(
809
		'data-viewid' => $gravityview_view->getViewId()
810
	));
811
812
	return $link;
813
}
814
815
/**
816
 * Handle getting values for complex Gravity Forms fields
817
 *
818
 * If the field is complex, like a product, the field ID, for example, 11, won't exist. Instead,
819
 * it will be 11.1, 11.2, and 11.3. This handles being passed 11 and 11.2 with the same function.
820
 *
821
 * @since 1.0.4
822
 * @param  array      $entry    GF entry array
823
 * @param  string      $field_id [description]
824
 * @param  string 	$display_value The value generated by Gravity Forms
825
 * @return string                Value
826
 */
827
function gravityview_get_field_value( $entry, $field_id, $display_value ) {
828
829
	if( floatval( $field_id ) === floor( floatval( $field_id ) ) ) {
830
831
		// For the complete field value as generated by Gravity Forms
832
		return $display_value;
833
834
	} else {
835
836
		// For one part of the address (City, ZIP, etc.)
837
		return isset( $entry[ $field_id ] ) ? $entry[ $field_id ] : '';
838
839
	}
840
841
}
842
843
/**
844
 * Take a passed CSV of terms and generate a linked list of terms
845
 *
846
 * Gravity Forms passes categories as "Name:ID" so we handle that using the ID, which
847
 * is more accurate than checking the name, which is more likely to change.
848
 *
849
 * @param  string      $value    Existing value
850
 * @param  string      $taxonomy Type of term (`post_tag` or `category`)
851
 * @return string                CSV of linked terms
852
 */
853
function gravityview_convert_value_to_term_list( $value, $taxonomy = 'post_tag' ) {
854
855
	$output = array();
856
857
	$terms = explode( ', ', $value );
858
859
	foreach ($terms as $term_name ) {
0 ignored issues
show
introduced by
No space after opening parenthesis is prohibited
Loading history...
860
861
		// If we're processing a category,
862
		if( $taxonomy === 'category' ) {
0 ignored issues
show
introduced by
Found "=== '". Use Yoda Condition checks, you must
Loading history...
863
864
			// Use rgexplode to prevent errors if : doesn't exist
865
			list( $term_name, $term_id ) = rgexplode( ':', $value, 2 );
866
867
			// The explode was succesful; we have the category ID
868
			if( !empty( $term_id )) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
869
				$term = get_term_by( 'id', $term_id, $taxonomy );
870
			} else {
871
			// We have to fall back to the name
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected at least 4 tabs, found 3
Loading history...
872
				$term = get_term_by( 'name', $term_name, $taxonomy );
873
			}
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
874
875
		} else {
876
			// Use the name of the tag to get the full term information
877
			$term = get_term_by( 'name', $term_name, $taxonomy );
878
		}
879
880
		// There's still a tag/category here.
881
		if( $term ) {
882
883
			$term_link = get_term_link( $term, $taxonomy );
884
885
			// If there was an error, continue to the next term.
886
			if ( is_wp_error( $term_link ) ) {
887
			    continue;
888
			}
889
890
			$output[] = gravityview_get_link( $term_link, esc_html( $term->name ) );
891
		}
892
	}
893
894
	return implode(', ', $output );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
895
}
896
897
/**
898
 * Get the links for post_tags and post_category output based on post ID
899
 * @param  int      $post_id  The ID of the post
900
 * @param  boolean     $link     Add links or no?
901
 * @param  string      $taxonomy Taxonomy of term to fetch.
902
 * @return string                String with terms
903
 */
904
function gravityview_get_the_term_list( $post_id, $link = true, $taxonomy = 'post_tag' ) {
905
906
	$output = get_the_term_list( $post_id, $taxonomy, NULL, ', ' );
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
907
908
	if( empty( $link ) ) {
909
		return strip_tags( $output);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
910
	}
911
912
	return $output;
913
914
}
915
916
917
/**
918
 * Get all views processed so far for the current page load
919
 *
920
 * @see  GravityView_View_Data::add_view()
921
 * @return array Array of View data, each View data with `id`, `view_id`, `form_id`, `template_id`, `atts`, `fields`, `widgets`, `form` keys.
922
 */
923
function gravityview_get_current_views() {
924
925
	$fe = GravityView_frontend::getInstance();
926
927
	// Solve problem when loading content via admin-ajax.php
928
	if( ! $fe->getGvOutputData() ) {
929
930
		do_action( 'gravityview_log_debug', '[gravityview_get_current_views] gv_output_data not defined; parsing content.' );
931
932
		$fe->parse_content();
933
	}
934
935
	// Make 100% sure that we're dealing with a properly called situation
936
	if( !is_a( $fe->getGvOutputData(), 'GravityView_View_Data' ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
937
938
		do_action( 'gravityview_log_debug', '[gravityview_get_current_views] gv_output_data not an object or get_view not callable.', $fe->getGvOutputData() );
939
940
		return array();
941
	}
942
943
	return $fe->getGvOutputData()->get_views();
944
}
945
946
/**
947
 * Get data for a specific view
948
 *
949
 * @see  GravityView_View_Data::get_view()
950
 * @return array View data with `id`, `view_id`, `form_id`, `template_id`, `atts`, `fields`, `widgets`, `form` keys.
951
 */
952
function gravityview_get_current_view_data( $view_id = 0 ) {
953
954
	$fe = GravityView_frontend::getInstance();
955
956
	if( ! $fe->getGvOutputData() ) { return array(); }
957
958
	// If not set, grab the current view ID
959
	if( empty( $view_id ) ) {
960
		$view_id = $fe->get_context_view_id();
961
	}
962
963
	return $fe->getGvOutputData()->get_view( $view_id );
964
}
965
966
// Templates' hooks
967
function gravityview_before() {
968
	/**
969
	 * @action `gravityview_before` Display content before a View. Used to render widget areas. Rendered outside the View container `<div>`
970
	 * @param int $view_id The ID of the View being displayed
971
	 */
972
	do_action( 'gravityview_before', gravityview_get_view_id() );
973
}
974
975
function gravityview_header() {
976
	/**
977
	 * @action `gravityview_header` Prepend content to the View container `<div>`
978
	 * @param int $view_id The ID of the View being displayed
979
	 */
980
	do_action( 'gravityview_header', gravityview_get_view_id() );
981
}
982
983
function gravityview_footer() {
984
	/**
985
	 * @action `gravityview_after` Display content after a View. Used to render footer widget areas. Rendered outside the View container `<div>`
986
	 * @param int $view_id The ID of the View being displayed
987
	 */
988
	do_action( 'gravityview_footer', gravityview_get_view_id() );
989
}
990
991
function gravityview_after() {
992
	/**
993
	 * @action `gravityview_after` Append content to the View container `<div>`
994
	 * @param int $view_id The ID of the View being displayed
995
	 */
996
	do_action( 'gravityview_after', gravityview_get_view_id() );
997
}
998
999
/**
1000
 * Get the current View ID being rendered
1001
 *
1002
 * @global GravityView_View $gravityview_view
1003
 * @return string View context "directory" or "single"
1004
 */
1005
function gravityview_get_view_id() {
1006
	return GravityView_View::getInstance()->getViewId();
1007
}
1008
1009
/**
1010
 * @global GravityView_View $gravityview_view
1011
 * @return string View context "directory", "single", or "edit"
1012
 */
1013
function gravityview_get_context() {
1014
1015
	$context = '';
1016
1017
	/**
1018
	 * @filter `gravityview_is_edit_entry` Whether we're currently on the Edit Entry screen \n
1019
	 * The Edit Entry functionality overrides this value.
1020
	 * @param boolean $is_edit_entry
1021
	 */
1022
	$is_edit_entry = apply_filters( 'gravityview_is_edit_entry', false );
1023
1024
	if( $is_edit_entry ) {
1025
		$context = 'edit';
1026
	} else if( class_exists( 'GravityView_frontend' ) && $single = GravityView_frontend::is_single_entry() ) {
1027
		$context = 'single';
1028
	} else if( class_exists( 'GravityView_View' ) ) {
1029
		$context = GravityView_View::getInstance()->getContext();
1030
	}
1031
1032
	return $context;
1033
}
1034
1035
1036
/**
1037
 * Return an array of files prepared for output. Wrapper for GravityView_Field_FileUpload::get_files_array()
1038
 *
1039
 * Processes files by file type and generates unique output for each.
1040
 *
1041
 * Returns array for each file, with the following keys:
1042
 *
1043
 * `file_path` => The file path of the file, with a line break
1044
 * `html` => The file output HTML formatted
1045
 *
1046
 * @see GravityView_Field_FileUpload::get_files_array()
1047
 *
1048
 * @since  1.2
1049
 * @param  string $value    Field value passed by Gravity Forms. String of file URL, or serialized string of file URL array
1050
 * @param  string $gv_class Field class to add to the output HTML
1051
 * @return array           Array of file output, with `file_path` and `html` keys (see comments above)
1052
 */
1053
function gravityview_get_files_array( $value, $gv_class = '' ) {
1054
	/** @define "GRAVITYVIEW_DIR" "../" */
1055
1056
	if( !class_exists( 'GravityView_Field' ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
1057
		include_once( GRAVITYVIEW_DIR .'includes/fields/class-gravityview-field.php' );
1058
	}
1059
1060
	if( !class_exists( 'GravityView_Field_FileUpload' ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
1061
		include_once( GRAVITYVIEW_DIR .'includes/fields/fileupload.php' );
1062
	}
1063
1064
	return GravityView_Field_FileUpload::get_files_array( $value, $gv_class );
1065
}
1066
1067
/**
1068
 * Generate a mapping link from an address
1069
 *
1070
 * The address should be plain text with new line (`\n`) or `<br />` line breaks separating sections
1071
 *
1072
 * @todo use GF's field get_export_value() instead
1073
 *
1074
 * @see https://gravityview.co/support/documentation/201608159 Read how to modify the link
1075
 * @param  string $address Address
1076
 * @return string          URL of link to map of address
1077
 */
1078
function gravityview_get_map_link( $address ) {
1079
1080
	$address_qs = str_replace( array( '<br />', "\n" ), ' ', $address ); // Replace \n with spaces
1081
	$address_qs = urlencode( $address_qs );
1082
1083
	$url = "https://maps.google.com/maps?q={$address_qs}";
1084
1085
	$link_text = esc_html__( 'Map It', 'gravityview' );
1086
1087
	$link = gravityview_get_link( $url, $link_text, 'class=map-it-link' );
1088
1089
	/**
1090
	 * @filter `gravityview_map_link` Modify the map link generated. You can use a different mapping service, for example.
1091
	 * @param[in,out]  string $link Map link
1092
	 * @param[in] string $address Address to generate link for
1093
	 * @param[in] string $url URL generated by the function
1094
	 */
1095
	$link = apply_filters( 'gravityview_map_link', $link, $address, $url );
1096
1097
	return $link;
1098
}
1099
1100
1101
/**
1102
 * Output field based on a certain html markup
1103
 *
1104
 *   markup - string to be used on a sprintf statement.
1105
 *      Use:
1106
 *         {{label}} - field label
1107
 *         {{value}} - entry field value
1108
 *         {{class}} - field class
1109
 *
1110
 *   wpautop - true will filter the value using wpautop function
1111
 *
1112
 * @since  1.1.5
1113
 * @param  array $passed_args Associative array with field data. `field` and `form` are required.
1114
 * @return string Field output. If empty value and hide empty is true, return empty.
1115
 */
1116
function gravityview_field_output( $passed_args ) {
1117
	$defaults = array(
1118
		'entry' => null,
1119
		'field' => null,
1120
		'form' => null,
1121
		'hide_empty' => true,
1122
		'markup' => '<div id="{{ field_id }}" class="{{ class }}">{{label}}{{value}}</div>',
1123
		'label_markup' => '',
1124
		'wpautop' => false,
1125
		'zone_id' => null,
1126
	);
1127
1128
	$args = wp_parse_args( $passed_args, $defaults );
1129
1130
	/**
1131
	 * @filter `gravityview/field_output/args` Modify the args before generation begins
1132
	 * @since 1.7
1133
	 * @param array $args Associative array; `field` and `form` is required.
1134
	 * @param array $passed_args Original associative array with field data. `field` and `form` are required.
1135
	 */
1136
	$args = apply_filters( 'gravityview/field_output/args', $args, $passed_args );
1137
1138
	// Required fields.
1139
	if ( empty( $args['field'] ) || empty( $args['form'] ) ) {
1140
		do_action( 'gravityview_log_error', '[gravityview_field_output] Field or form are empty.', $args );
1141
		return '';
1142
	}
1143
1144
	$entry = empty( $args['entry'] ) ? array() : $args['entry'];
1145
1146
	/**
1147
	 * Create the content variables for replacing.
1148
	 * @since 1.11
1149
	 */
1150
	$context = array(
1151
		'value' => '',
1152
		'width' => '',
1153
		'width:style' => '',
1154
		'label' => '',
1155
		'label_value' => '',
1156
		'class' => '',
1157
		'field_id' => '',
1158
	);
1159
1160
	$context['value'] = gv_value( $entry, $args['field'] );
1161
1162
	// If the value is empty and we're hiding empty, return empty.
1163
	if ( $context['value'] === '' && ! empty( $args['hide_empty'] ) ) {
1164
		return '';
1165
	}
1166
1167
	if ( $context['value'] !== '' && ! empty( $args['wpautop'] ) ) {
1168
		$context['value'] = wpautop( $context['value'] );
1169
	}
1170
1171
	// Get width setting, if exists
1172
	$context['width'] = GravityView_API::field_width( $args['field'] );
1173
1174
	// If replacing with CSS inline formatting, let's do it.
1175
	$context['width:style'] = GravityView_API::field_width( $args['field'], 'width:' . $context['width'] . '%;' );
1176
1177
	// Grab the Class using `gv_class`
1178
	$context['class'] = gv_class( $args['field'], $args['form'], $entry );
1179
	$context['field_id'] = GravityView_API::field_html_attr_id( $args['field'], $args['form'], $entry );
1180
1181
	// Get field label if needed
1182
	if ( ! empty( $args['label_markup'] ) && ! empty( $args['field']['show_label'] ) ) {
1183
		$context['label'] = str_replace( array( '{{label}}', '{{ label }}' ), '<span class="gv-field-label">{{ label_value }}</span>', $args['label_markup'] );
1184
	}
1185
1186
	// Default Label value
1187
	$context['label_value'] = gv_label( $args['field'], $entry );
1188
1189
	if ( empty( $context['label'] ) && ! empty( $context['label_value'] ) ){
1190
		$context['label'] = '<span class="gv-field-label">{{ label_value }}</span>';
1191
	}
1192
1193
	/**
1194
	 * @filter `gravityview/field_output/pre_html` Allow Pre filtering of the HTML
1195
	 * @since 1.11
1196
	 * @param string $markup The HTML for the markup
1197
	 * @param array $args All args for the field output
1198
	 */
1199
	$html = apply_filters( 'gravityview/field_output/pre_html', $args['markup'], $args );
1200
1201
	/**
1202
	 * @filter `gravityview/field_output/open_tag` Modify the opening tags for the template content placeholders
1203
	 * @since 1.11
1204
	 * @param string $open_tag Open tag for template content placeholders. Default: `{{`
1205
	 */
1206
	$open_tag = apply_filters( 'gravityview/field_output/open_tag', '{{', $args );
1207
1208
	/**
1209
	 * @filter `gravityview/field_output/close_tag` Modify the closing tags for the template content placeholders
1210
	 * @since 1.11
1211
	 * @param string $close_tag Close tag for template content placeholders. Default: `}}`
1212
	 */
1213
	$close_tag = apply_filters( 'gravityview/field_output/close_tag', '}}', $args );
1214
1215
	/**
1216
	 * Loop through each of the tags to replace and replace both `{{tag}}` and `{{ tag }}` with the values
1217
	 * @since 1.11
1218
	 */
1219
	foreach ( $context as $tag => $value ) {
1220
1221
		// If the tag doesn't exist just skip it
1222
		if ( false === strpos( $html, $open_tag . $tag . $close_tag ) && false === strpos( $html, $open_tag . ' ' . $tag . ' ' . $close_tag ) ){
1223
			continue;
1224
		}
1225
1226
		// Array to search
1227
		$search = array(
1228
			$open_tag . $tag . $close_tag,
1229
			$open_tag . ' ' . $tag . ' ' . $close_tag,
1230
		);
1231
1232
		/**
1233
		 * `gravityview/field_output/context/{$tag}` Allow users to filter content on context
1234
		 * @since 1.11
1235
		 * @param string $value The content to be shown instead of the {{tag}} placeholder
1236
		 * @param array $args Arguments passed to the function
1237
		 */
1238
		$value = apply_filters( 'gravityview/field_output/context/' . $tag, $value, $args );
1239
1240
		// Finally do the replace
1241
		$html = str_replace( $search, $value, $html );
1242
	}
1243
1244
	/**
1245
	 * @todo  Depricate `gravityview_field_output`
1246
	 */
1247
	$html = apply_filters( 'gravityview_field_output', $html, $args );
1248
1249
	/**
1250
	 * @filter `gravityview/field_output/html` Modify field HTML output
1251
	 * @param string $html Existing HTML output
1252
	 * @param array $args Arguments passed to the function
1253
	 */
1254
	$html = apply_filters( 'gravityview/field_output/html', $html, $args );
1255
1256
	// Just free up a tiny amount of memory
1257
	unset( $value, $args, $passed_args, $entry, $context, $search, $open_tag, $tag, $close_tag );
1258
1259
	return $html;
1260
}
1261