Completed
Push — master ( 196a0a...af77e8 )
by Zack
11:10 queued 04:43
created

GravityView_Field_FileUpload   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 294
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 4.44%

Importance

Changes 0
Metric Value
dl 0
loc 294
ccs 4
cts 90
cp 0.0444
rs 10
c 0
b 0
f 0
wmc 27
lcom 1
cbo 4

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A field_options() 0 18 2
F get_files_array() 0 224 23
A get_field_input() 0 8 1
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 8 and the first side effect is on line 303.

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

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

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

Loading history...
2
/**
3
 * @file class-gravityview-field-fileupload.php
4
 * @package GravityView
5
 * @subpackage includes\fields
6
 */
7
8
class GravityView_Field_FileUpload extends GravityView_Field {
9
10
	var $name = 'fileupload';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $name.

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

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
11
12
	var $_gf_field_class_name = 'GF_Field_FileUpload';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $_gf_field_class_name.

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

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
13
14
	var $is_searchable = true;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $is_searchable.

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

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
15
16
	var $search_operators = array( 'contains' );
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $search_operators.

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

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
17
18
	var $group = 'advanced';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $group.

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

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
19
20
	public function __construct() {
21
		$this->label = esc_html__( 'File Upload', 'gravityview' );
22
		parent::__construct();
23
	}
24
25
	function field_options( $field_options, $template_id, $field_id, $context, $input_type ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

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

Loading history...
26
27
		unset( $field_options['search_filter'] );
28
29
		if( 'edit' === $context ) {
30
			return $field_options;
31
		}
32
33
		$add_options['link_to_file'] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$add_options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $add_options = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
34
			'type' => 'checkbox',
35
			'label' => __( 'Display as a Link:', 'gravityview' ),
36
			'desc' => __('Display the uploaded files as links, rather than embedded content.', '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...
37
			'value' => false,
38
			'merge_tags' => false,
39
		);
40
41
		return $add_options + $field_options;
42
	}
43
44
	/**
45
	 * Trick the GF fileupload field to render with the proper HTML ID to enable the plupload JS to work properly
46
	 *
47
	 * @param array               $form  The Form Object currently being processed.
48
	 * @param string|array        $value The field value. From default/dynamic population, $_POST, or a resumed incomplete submission.
0 ignored issues
show
Bug introduced by
There is no parameter named $value. 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...
49
	 * @param null|array          $entry Null or the Entry Object currently being edited.
50
	 * @param GF_Field_FileUpload $field Gravity Forms field
51
	 *
52
	 * @return string
53
	 */
54 1
	function get_field_input( $form, $field_value, $entry, $field ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

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

Loading history...
55
56 1
		$field->_is_entry_detail = true;
57
58 1
		$return = $field->get_field_input( $form, $field_value, $entry );
59
60 1
		return $return;
61
	}
62
63
	/**
64
	 * Return an array of files prepared for output.
65
	 *
66
	 * Processes files by file type and generates unique output for each. Returns array for each file, with the following keys:
67
	 * - `file_path` => The file path of the file, with a line break
68
	 * - `html` => The file output HTML formatted
69
	 *
70
	 * @since  1.2
71
	 * @todo  Support `playlist` shortcode for playlist of video/audio
72
	 * @param  string $value    Field value passed by Gravity Forms. String of file URL, or serialized string of file URL array
73
	 * @param  string $gv_class Field class to add to the output HTML
74
	 * @return array           Array of file output, with `file_path` and `html` keys (see comments above)
75
	 */
76
	static function get_files_array( $value, $gv_class ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

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

Loading history...
77
78
		$gravityview_view = GravityView_View::getInstance();
79
80
		$gv_field_array = $gravityview_view->getCurrentField();
81
82
		/** @var GF_Field_FileUpload $field */
83
		$field = rgar( $gv_field_array, 'field' );
84
		$field_settings = rgar( $gv_field_array, 'field_settings' );
85
		$entry = rgar( $gv_field_array, 'entry' );
86
		$field_value = rgar( $gv_field_array, 'value' );
87
88
		$output_arr = array();
89
90
		// Get an array of file paths for the field.
91
		$file_paths = rgar( $field , 'multipleFiles' ) ? json_decode( $value ) : array( $value );
92
93
		// The $value JSON was probably truncated; let's check lead_detail_long.
94
		if ( ! is_array( $file_paths ) ) {
95
			$full_value = RGFormsModel::get_lead_field_value( $entry, $field );
96
			$file_paths = json_decode( $full_value );
97
		}
98
99
		if ( ! is_array( $file_paths ) ) {
100
			do_action( 'gravityview_log_error', __METHOD__ . ': Field does not have a valid image array. JSON decode may have failed.', array( '$value' => $value, '$field_value' => $field_value ) );
101
			return $output_arr;
102
		}
103
104
		// Process each file path
105
		foreach( $file_paths as $file_path ) {
106
107
			// If the site is HTTPS, use HTTPS
108
			if(function_exists('set_url_scheme')) { $file_path = set_url_scheme($file_path); }
0 ignored issues
show
introduced by
No space after opening 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...
introduced by
No space before closing parenthesis is prohibited
Loading history...
109
110
			// This is from Gravity Forms's code
111
			$file_path = esc_attr(str_replace(" ", "%20", $file_path));
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...
Coding Style Comprehensibility introduced by
The string literal 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...
Coding Style Comprehensibility introduced by
The string literal %20 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...
112
113
			// If the field is set to link to the single entry, link to it.
114
			$link = !empty( $field_settings['show_as_link'] ) ? GravityView_API::entry_link( $entry, $field ) : $file_path;
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
115
116
			// Get file path information
117
			$file_path_info = pathinfo($file_path);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
118
119
			$html_format = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
120
121
			$disable_lightbox = false;
122
123
			$disable_wrapped_link = false;
124
125
			// Is this an image?
126
			$image = new GravityView_Image(array(
127
				'src' => $file_path,
128
				'class' => 'gv-image gv-field-id-'.$field_settings['id'],
129
				'alt' => $field_settings['label'],
130
				'width' => (gravityview_get_context() === 'single' ? NULL : 250)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
131
			));
132
133
			$content = $image->html();
134
135
			// The new default content is the image, if it exists. If not, use the file name as the content.
136
			$content = !empty( $content ) ? $content : $file_path_info['basename'];
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
137
138
			// If pathinfo() gave us the extension of the file, run the switch statement using that.
139
			$extension = empty( $file_path_info['extension'] ) ? NULL : strtolower( $file_path_info['extension'] );
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
140
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
141
142
			switch( true ) {
143
144
				// Audio file
145
				case in_array( $extension, wp_get_audio_extensions() ):
146
147
					$disable_lightbox = true;
148
149
					if( shortcode_exists( 'audio' ) ) {
150
151
						$disable_wrapped_link = true;
152
153
						/**
154
						 * @filter `gravityview_audio_settings` Modify the settings passed to the `wp_video_shortcode()` function
155
						 * @since  1.2
156
						 * @param array $audio_settings Array with `src` and `class` keys
157
						 */
158
						$audio_settings = apply_filters( 'gravityview_audio_settings', array(
159
							'src' => $file_path,
160
							'class' => 'wp-audio-shortcode gv-audio gv-field-id-'.$field_settings['id']
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
161
						));
162
163
						/**
164
						 * Generate the audio shortcode
165
						 * @see http://codex.wordpress.org/Audio_Shortcode
166
						 * @see https://developer.wordpress.org/reference/functions/wp_audio_shortcode/
167
						 */
168
						$content = wp_audio_shortcode( $audio_settings );
169
170
					}
171
172
					break;
173
174
				// Video file
175
				case in_array( $extension, wp_get_video_extensions() ):
176
177
					$disable_lightbox = true;
178
179
					if( shortcode_exists( 'video' ) ) {
180
181
						$disable_wrapped_link = true;
182
183
						/**
184
						 * @filter `gravityview_video_settings` Modify the settings passed to the `wp_video_shortcode()` function
185
						 * @since  1.2
186
						 * @param array $video_settings Array with `src` and `class` keys
187
						 */
188
						$video_settings = apply_filters( 'gravityview_video_settings', array(
189
							'src' => $file_path,
190
							'class' => 'wp-video-shortcode gv-video gv-field-id-'.$field_settings['id']
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
191
						));
192
193
						/**
194
						 * Generate the video shortcode
195
						 * @see http://codex.wordpress.org/Video_Shortcode
196
						 * @see https://developer.wordpress.org/reference/functions/wp_video_shortcode/
197
						 */
198
						$content = wp_video_shortcode( $video_settings );
199
200
					}
201
202
					break;
203
204
				// PDF
205
				case $extension === 'pdf':
206
207
					// PDF needs to be displayed in an IFRAME
208
					$link = add_query_arg( array( 'TB_iframe' => 'true' ), $link );
209
210
					break;
211
212
				// if not image, do not set the lightbox (@since 1.5.3)
213
				case !in_array( $extension, array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' ) ):
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
214
215
					$disable_lightbox = true;
216
217
					break;
218
219
			}
220
221
			// If using Link to File, override the content.
222
			// (We do this here so that the $disable_lightbox can be set. Yes, there's a little more processing time, but oh well.)
223
			if( !empty( $field_settings['link_to_file'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
224
225
				// Force the content to be the file name
226
				$content =  $file_path_info["basename"];
0 ignored issues
show
introduced by
Expected 1 space after "="; 2 found
Loading history...
Coding Style Comprehensibility introduced by
The string literal basename 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...
227
228
				// Restore the wrapped link
229
				$disable_wrapped_link = false;
230
231
			}
232
233
			// Whether to use lightbox or not
234
			if( $disable_lightbox || empty( $gravityview_view->atts['lightbox'] ) || !empty( $field_settings['show_as_link'] ) ) {
0 ignored issues
show
Documentation introduced by
The property $atts is declared protected in GravityView_View. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
235
236
				$link_atts = empty( $field_settings['show_as_link'] ) ? array( 'target' => '_blank' ) : array();
237
238
			} else {
239
240
				$entry_slug = GravityView_API::get_entry_slug( $entry['id'], $entry );
241
242
				$link_atts = array(
243
					'rel' => sprintf( "%s-%s", $gv_class, $entry_slug ),
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal %s-%s 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...
244
					'class' => 'thickbox',
245
				);
246
247
			}
248
249
			/**
250
			 * @filter `gravityview/fields/fileupload/link_atts` Modify the link attributes for a file upload field
251
			 * @param array|string $link_atts Array or attributes string
252
			 * @param array $field Current GravityView field array
253
			 */
254
			$link_atts = apply_filters( 'gravityview/fields/fileupload/link_atts', $link_atts, $gravityview_view->getCurrentField() );
255
256
			/**
257
			 * @filter `gravityview/fields/fileupload/disable_link` Filter to alter the default behaviour of wrapping images (or image names) with a link to the content object
258
			 * @since 1.5.1
259
			 * @param bool $disable_wrapped_link whether to wrap the content with a link to the content object.
260
			 * @param array $gravityview_view->field_data
261
			 * @see GravityView_API:field_value() for info about $gravityview_view->field_data
262
			 */
263
			$disable_wrapped_link = apply_filters( 'gravityview/fields/fileupload/disable_link', $disable_wrapped_link, $gravityview_view->getCurrentField() );
264
265
			// If the HTML output hasn't been overridden by the switch statement above, use the default format
266
			if( !empty( $content ) && empty( $disable_wrapped_link ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
267
268
				/**
269
				 * Modify the link text (defaults to the file name)
270
				 *
271
				 * @since 1.7
272
				 *
273
				 * @param string $content The existing anchor content. Could be `<img>` tag, audio/video embed or the file name
274
				 * @param array $field GravityView array of the current field being processed
275
				 */
276
				$content = apply_filters( 'gravityview/fields/fileupload/link_content', $content, $gravityview_view->getCurrentField() );
277
278
                $content = gravityview_get_link( $link, $content, $link_atts );
279
			}
280
281
			$output_arr[] = array(
282
				'file_path' => $file_path,
283
				'content' => $content
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
284
			);
285
286
		} // End foreach loop
287
288
		/**
289
		 * @filter `gravityview/fields/fileupload/files_array` Modify the files array
290
		 * @since 1.7
291
		 * @param array $output_arr Associative array of files \n
292
		 *  @type string $file_path The path to the file as stored in Gravity Forms \n
293
		 *  @type string $content The generated output for the file \n
294
		 * @param array $field GravityView array of the current field being processed
295
		 */
296
		$output_arr = apply_filters( 'gravityview/fields/fileupload/files_array', $output_arr, $gravityview_view->getCurrentField() );
297
298
		return $output_arr;
299
	}
300
301
}
302
303
new GravityView_Field_FileUpload;
304