Completed
Push — master ( 1b32e3...e32e6e )
by Zack
06:12 queued 14s
created

GravityView_API::entry_link()   D

Complexity

Conditions 14
Paths 186

Size

Total Lines 75
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

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