Completed
Pull Request — 2.x (#3632)
by Phil
04:46
created

PodsField_File::input()   C

Complexity

Conditions 31
Paths 6

Size

Total Lines 51
Code Lines 34

Duplication

Lines 24
Ratio 47.06 %

Importance

Changes 0
Metric Value
cc 31
eloc 34
c 0
b 0
f 0
nc 6
nop 5
dl 24
loc 51
rs 5.4631

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
 * @package Pods\Fields
4
 */
5
class PodsField_File extends PodsField {
6
7
    /**
8
     * Field Type Group
9
     *
10
     * @var string
11
     * @since 2.0
12
     */
13
    public static $group = 'Relationships / Media';
14
15
    /**
16
     * Field Type Identifier
17
     *
18
     * @var string
19
     * @since 2.0
20
     */
21
    public static $type = 'file';
22
23
    /**
24
     * Field Type Label
25
     *
26
     * @var string
27
     * @since 2.0
28
     */
29
    public static $label = 'File / Image / Video';
30
31
    /**
32
     * API caching for fields that need it during validate/save
33
     *
34
     * @var \PodsAPI
35
     * @since 2.3
36
     */
37
    protected static $api = false;
38
39
    /**
40
     * Do things like register/enqueue scripts and stylesheets
41
     *
42
     * @since 2.0
43
     */
44
    public function __construct () {
45
        self::$label = __( 'File / Image / Video', 'pods' );
46
    }
47
48
    /**
49
     * Add admin_init actions
50
     *
51
     * @since 2.3
52
     */
53
    public function admin_init() {
54
        // AJAX for Uploads
55
        add_action( 'wp_ajax_pods_upload', array( $this, 'admin_ajax_upload' ) );
56
        add_action( 'wp_ajax_nopriv_pods_upload', array( $this, 'admin_ajax_upload' ) );
57
    }
58
59
    /**
60
     * Add options and set defaults to
61
     *
62
     * @param array $options
0 ignored issues
show
Bug introduced by
There is no parameter named $options. 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...
63
     *
64
     * @since 2.0
65
     */
66
    public function options () {
67
        $sizes = get_intermediate_image_sizes();
68
69
        $image_sizes = array();
70
71
        foreach ( $sizes as $size ) {
72
            $image_sizes[ $size ] = ucwords( str_replace( '-', ' ', $size ) );
73
        }
74
75
        $options = array(
76
            self::$type . '_format_type' => array(
77
                'label' => __( 'Upload Limit', 'pods' ),
78
                'default' => 'single',
79
                'type' => 'pick',
80
                'data' => array(
81
                    'single' => __( 'Single File', 'pods' ),
82
                    'multi' => __( 'Multiple Files', 'pods' )
83
                ),
84
                'dependency' => true
85
            ),
86
            self::$type . '_uploader' => array(
87
                'label' => __( 'File Uploader', 'pods' ),
88
                'default' => 'attachment',
89
                'type' => 'pick',
90
                'data' => apply_filters(
91
                    'pods_form_ui_field_' . self::$type . '_uploader_options',
92
                    array(
93
                        'attachment' => __( 'Attachments (WP Media Library)', 'pods' ),
94
                        'plupload'   => __( 'Plupload', 'pods' )
95
                    )
96
                ),
97
                'dependency' => true
98
            ),
99
            self::$type . '_attachment_tab' => array(
100
                'label' => __( 'Attachments Default Tab', 'pods' ),
101
                'depends-on' => array( self::$type . '_uploader' => 'attachment' ),
102
                'default' => 'upload',
103
                'type' => 'pick',
104
                'data' => array(
105
                    // keys MUST match WP's router names
106
                    'upload' => __( 'Upload File', 'pods' ),
107
                    'browse' => __( 'Media Library', 'pods' )
108
                )
109
            ),
110
            self::$type . '_edit_title' => array(
111
                'label' => __( 'Editable Title', 'pods' ),
112
                'default' => 1,
113
                'type' => 'boolean'
114
            ),
115
            self::$type . '_show_edit_link' => array(
116
                'label' => __( 'Show Edit Link', 'pods' ),
117
                'default' => 0,
118
                'type' => 'boolean'
119
            ),
120
            self::$type . '_linked' => array(
121
                'label' => __( 'Show Download Link', 'pods' ),
122
                'default' => 0,
123
                'type' => 'boolean'
124
            ),
125
            self::$type . '_limit' => array(
126
                'label' => __( 'Max Number of Files', 'pods' ),
127
                'depends-on' => array( self::$type . '_format_type' => 'multi' ),
128
                'default' => 0,
129
                'type' => 'number'
130
            ),
131
            self::$type . '_restrict_filesize' => array(
132
                'label' => __( 'Restrict File Size', 'pods' ),
133
                'depends-on' => array( self::$type . '_uploader' => 'plupload' ),
134
                'default' => '10MB',
135
                'type' => 'text'
136
            ),
137
            self::$type . '_type' => array(
138
                'label' => __( 'Restrict File Types', 'pods' ),
139
                'default' => apply_filters( 'pods_form_ui_field_' . self::$type . '_type_default', 'images' ),
140
                'type' => 'pick',
141
                'data' => apply_filters(
142
                    'pods_form_ui_field_' . self::$type . '_type_options',
143
                    array(
144
                        'images' => __( 'Images (jpg, jpeg, png, gif)', 'pods' ),
145
                        'video' => __( 'Video (mpg, mov, flv, mp4, etc..)', 'pods' ),
146
                        'audio' => __( 'Audio (mp3, m4a, wav, wma, etc..)', 'pods' ),
147
                        'text' => __( 'Text (txt, csv, tsv, rtx, etc..)', 'pods' ),
148
                        'any' => __( 'Any Type (no restriction)', 'pods' ),
149
                        'other' => __( 'Other (customize allowed extensions)', 'pods' )
150
                    )
151
                ),
152
                'dependency' => true
153
            ),
154
            self::$type . '_allowed_extensions' => array(
155
                'label' => __( 'Allowed File Extensions', 'pods' ),
156
                'description' => __( 'Separate file extensions with a comma (ex. jpg,png,mp4,mov)', 'pods' ),
157
                'depends-on' => array( self::$type . '_type' => 'other' ),
158
                'default' => apply_filters( 'pods_form_ui_field_' . self::$type . '_extensions_default', '' ),
159
                'type' => 'text'
160
            ),
161
            self::$type . '_field_template' => array(
162
                'label' => __( 'List Style', 'pods' ),
163
                'help' => __( 'You can choose which style you would like the files to appear within the form.', 'pods' ),
164
                'depends-on' => array( self::$type . '_type' => 'images' ),
165
                'default' => apply_filters( 'pods_form_ui_field_' . self::$type . '_template_default', 'rows' ),
166
                'type' => 'pick',
167
                'data' => apply_filters(
168
                    'pods_form_ui_field_' . self::$type . '_type_templates',
169
                    array(
170
                        'rows' => __( 'Rows', 'pods' ),
171
                        'tiles' => __( 'Tiles', 'pods' ),
172
                    )
173
                ),
174
            ),/*
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% 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...
175
            self::$type . '_image_size' => array(
176
                'label' => __( 'Excluded Image Sizes', 'pods' ),
177
                'description' => __( 'Image sizes not to generate when processing the image', 'pods' ),
178
                'depends-on' => array( self::$type . '_type' => 'images' ),
179
                'default' => 'images',
180
                'type' => 'pick',
181
                'pick_format_type' => 'multi',
182
                'pick_format_multi' => 'checkbox',
183
                'data' => apply_filters(
184
                    'pods_form_ui_field_' . self::$type . '_image_size_options',
185
                    $image_sizes
186
                )
187
            ),*/
188
            self::$type . '_add_button' => array(
189
                'label' => __( 'Add Button Text', 'pods' ),
190
                'default' => __( 'Add File', 'pods' ),
191
                'type' => 'text'
192
            ),
193
            self::$type . '_modal_title' => array(
194
                'label' => __( 'Modal Title', 'pods' ),
195
                'depends-on' => array( self::$type . '_uploader' => 'attachment' ),
196
                'default' => __( 'Attach a file', 'pods' ),
197
                'type' => 'text'
198
            ),
199
            self::$type . '_modal_add_button' => array(
200
                'label' => __( 'Modal Add Button Text', 'pods' ),
201
                'depends-on' => array( self::$type . '_uploader' => 'attachment' ),
202
                'default' => __( 'Add File', 'pods' ),
203
                'type' => 'text'
204
            ),
205
206
            /* WP GALLERY OUTPUT */
207
            self::$type . '_wp_gallery_output' => array(
208
	            'label' => __( 'Output as a WP Gallery', 'pods' ),
209
	            'help' => sprintf(
210
	            	__( '<a href="%s" target="_blank">Click here for more info</a>', 'pods' ),
211
					'https://codex.wordpress.org/The_WordPress_Gallery'
212
				),
213
	            'depends-on' => array( self::$type . '_type' => 'images' ),
214
	            'dependency' => true,
215
	            'type' => 'boolean'
216
            ),
217
            self::$type . '_wp_gallery_link' => array(
218
	            'label' => __( 'Gallery image links', 'pods' ),
219
	            'depends-on' => array( self::$type . '_wp_gallery_output' => 1 ),
220
	            'type' => 'pick',
221
	            'data' => array(
222
		            'post' => __( 'Attachment Page', 'pods' ),
223
		            'file' => __( 'Media File', 'pods' ),
224
		            'none' => __( 'None', 'pods' )
225
	            )
226
            ),
227
            self::$type . '_wp_gallery_columns' => array(
228
	            'label' => __( 'Gallery image columns', 'pods' ),
229
	            'depends-on' => array( self::$type . '_wp_gallery_output' => 1 ),
230
	            'type' => 'pick',
231
	            'data' => array(
232
		            '1' => 1,
233
			    '2' => 2,
234
			    '3' => 3,
235
			    '4' => 4,
236
			    '5' => 5,
237
			    '6' => 6,
238
			    '7' => 7,
239
			    '8' => 8,
240
			    '9' => 9,
241
	            )
242
            ),
243
            self::$type . '_wp_gallery_random_sort' => array(
244
	            'label' => __( 'Gallery randomized order', 'pods' ),
245
	            'depends-on' => array( self::$type . '_wp_gallery_output' => 1 ),
246
	            'type' => 'boolean'
247
            ),
248
            self::$type . '_wp_gallery_size' => array(
249
	            'label' => __( 'Gallery image size', 'pods' ),
250
	            'depends-on' => array( self::$type . '_wp_gallery_output' => 1 ),
251
	            'type' => 'pick',
252
	            'data' => $this->data_image_sizes(),
253
            )
254
        );
255
256 View Code Duplication
        if ( !pods_version_check( 'wp', '3.5' ) ) {
257
            unset( $options[ self::$type . '_linked' ] );
258
            unset( $options[ self::$type . '_modal_title' ] );
259
            unset( $options[ self::$type . '_modal_add_button' ] );
260
261
            $options[ self::$type . '_attachment_tab' ][ 'default' ] = 'type';
262
            $options[ self::$type . '_attachment_tab' ][ 'data' ] = array(
263
                'type' => __( 'Upload File', 'pods' ),
264
                'library' => __( 'Media Library', 'pods' )
265
            );
266
        }
267
268
        return $options;
269
    }
270
271
    /**
272
     * Define the current field's schema for DB table storage
273
     *
274
     * @param array $options
275
     *
276
     * @return array
277
     * @since 2.0
278
     */
279
    public function schema ( $options = null ) {
280
        $schema = false;
281
282
        return $schema;
283
    }
284
285
    /**
286
     * Change the way the value of the field is displayed with Pods::get
287
     *
288
     * @param mixed $value
289
     * @param string $name
290
     * @param array $options
291
     * @param array $pod
292
     * @param int $id
293
     *
294
     * @return mixed|null
295
     * @since 2.0
296
     */
297
    public function display ( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
298
    	if ( 1 == $options[ self::$type . '_wp_gallery_output' ] ) {
299
    		return $this->do_wp_gallery( $value, $options );
300
		}
301
302
        if ( is_array( $value ) && !empty( $value ) ) {
303
            if ( isset( $value[ 'ID' ] ) )
304
                $value = wp_get_attachment_url( $value[ 'ID' ] );
305
            else {
306
                $attachments = $value;
307
                $value = array();
308
309 View Code Duplication
                foreach ( $attachments as $v ) {
310
                    if ( !is_array( $v ) )
311
                        $value[] = $v;
312
                    elseif ( isset( $v[ 'ID' ] ) )
313
                        $value[] = wp_get_attachment_url( $v[ 'ID' ] );
314
                }
315
316
                $value = implode( ' ', $value );
317
            }
318
        }
319
320
        return $value;
321
    }
322
323
    /**
324
     * Customize output of the form field
325
     *
326
     * @param string $name
327
     * @param mixed $value
328
     * @param array $options
329
     * @param array $pod
330
     * @param int $id
331
     *
332
     * @since 2.0
333
     */
334
    public function input ( $name, $value = null, $options = null, $pod = null, $id = null ) {
335
        $options = (array) $options;
336
        $form_field_type = PodsForm::$field_type;
0 ignored issues
show
Bug introduced by
The property field_type cannot be accessed from this context as it is declared private in class PodsForm.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
337
338 View Code Duplication
        if ( !is_admin() ) {
339
            include_once( ABSPATH . '/wp-admin/includes/template.php' );
340
341
            if ( is_multisite() )
342
                include_once( ABSPATH . '/wp-admin/includes/ms.php' );
343
        }
344
345 View Code Duplication
        if ( ( ( defined( 'PODS_DISABLE_FILE_UPLOAD' ) && true === PODS_DISABLE_FILE_UPLOAD )
346
               || ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && true === PODS_UPLOAD_REQUIRE_LOGIN && !is_user_logged_in() )
347
               || ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && !is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_UPLOAD_REQUIRE_LOGIN ) ) ) )
348
             && ( ( defined( 'PODS_DISABLE_FILE_BROWSER' ) && true === PODS_DISABLE_FILE_BROWSER )
349
                  || ( defined( 'PODS_FILES_REQUIRE_LOGIN' ) && is_bool( PODS_FILES_REQUIRE_LOGIN ) && true === PODS_FILES_REQUIRE_LOGIN && !is_user_logged_in() )
350
                  || ( defined( 'PODS_FILES_REQUIRE_LOGIN' ) && !is_bool( PODS_FILES_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_FILES_REQUIRE_LOGIN ) ) ) )
351
        ) {
352
            ?>
353
        <p>You do not have access to upload / browse files. Contact your website admin to resolve.</p>
354
        <?php
355
            return;
356
        }
357
358
        // @todo: Now One Field to Rule Them All
359
        $field_type = 'file-upload';
360
        pods_view( PODS_DIR . 'ui/fields-mv/file-upload.php', compact( array_keys( get_defined_vars() ) ) );
361
        return;
362
363
        // @todo: we're short-circuiting for prototyping above.  The actions below will need to be woven in
364
365
        // Use plupload if attachment isn't available
366
        if ( 'attachment' == pods_var( self::$type . '_uploader', $options ) && ( !is_user_logged_in() || ( !current_user_can( 'upload_files' ) && !current_user_can( 'edit_files' ) ) ) )
0 ignored issues
show
Unused Code introduced by
// @todo: we're short-ci...od, $id); return; } does not seem to be reachable.

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

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

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

    return false;
}

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

Loading history...
367
            $field_type = 'plupload';
368
        elseif ( 'plupload' == pods_var( self::$type . '_uploader', $options ) )
369
            $field_type = 'plupload';
370 View Code Duplication
        elseif ( 'attachment' == pods_var( self::$type . '_uploader', $options ) ) {
371
            if ( !pods_version_check( 'wp', '3.5' ) || !is_admin() ) // @todo test frontend media modal
372
                $field_type = 'attachment';
373
            else
374
                $field_type = 'media';
375
        }
376
        else {
377
            // Support custom File Uploader integration
378
            do_action( 'pods_form_ui_field_' . self::$type . '_uploader_' . pods_var( self::$type . '_uploader', $options ), $name, $value, $options, $pod, $id );
379
            do_action( 'pods_form_ui_field_' . self::$type . '_uploader', pods_var( self::$type . '_uploader', $options ), $name, $value, $options, $pod, $id );
380
            return;
381
        }
382
383
        pods_view( PODS_DIR . 'ui/fields/' . $field_type . '.php', compact( array_keys( get_defined_vars() ) ) );
384
    }
385
386
    /**
387
     * Build regex necessary for JS validation
388
     *
389
     * @param mixed $value
390
     * @param string $name
391
     * @param array $options
392
     * @param string $pod
393
     * @param int $id
394
     *
395
     * @return bool
396
     * @since 2.0
397
     */
398
    public function regex ( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
399
        return false;
400
    }
401
402
    /**
403
     * Validate a value before it's saved
404
     *
405
     * @param mixed $value
406
     * @param string $name
407
     * @param array $options
408
     * @param array $fields
409
     * @param array $pod
410
     * @param int $id
411
     * @param null $params
412
     *
413
     * @return bool
414
     * @since 2.0
415
     */
416
    public function validate ( $value, $name = null, $options = null, $fields = null, $pod = null, $id = null, $params = null ) {
417
        // check file size
418
        // check file extensions
419
        return true;
420
    }
421
422
    /**
423
     * Change the value or perform actions after validation but before saving to the DB
424
     *
425
     * @param mixed $value
426
     * @param int $id
427
     * @param string $name
428
     * @param array $options
429
     * @param array $fields
430
     * @param array $pod
431
     * @param object $params
432
     *
433
     * @return mixed
434
     * @since 2.0
435
     */
436
    public function pre_save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
437
        return $value;
438
    }
439
440
    /**
441
     * Save the value to the DB
442
     *
443
     * @param mixed $value
444
     * @param int $id
445
     * @param string $name
446
     * @param array $options
447
     * @param array $fields
448
     * @param array $pod
449
     * @param object $params
450
     *
451
     * @since 2.3
452
     */
453
    public function save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
454
        if ( empty( self::$api ) )
455
            self::$api = pods_api();
456
457
        // File title / field handling
458
        foreach ( $value as $id ) {
459
            $title = false;
460
461
            if ( is_array( $id ) ) {
462 View Code Duplication
                if ( isset( $id[ 'title' ] ) && 0 < strlen( trim( $id[ 'title' ] ) ) )
463
                    $title = trim( $id[ 'title' ] );
464
465
                if ( isset( $id[ 'id' ] ) )
466
                    $id = (int) $id[ 'id' ];
467
                else
468
                    $id = 0;
469
            }
470
471
            if ( empty( $id ) )
472
                continue;
473
474
            $attachment_data = array();
475
476
            // Update the title if set
477
            if ( false !== $title && 1 == pods_var( self::$type . '_edit_title', $options, 0 ) ) {
478
                $attachment_data['post_title'] = $title;
479
            }
480
481
            // Update attachment parent if it's not set yet and we're updating a post
482
            if ( ! empty( $params->id ) && ! empty( $pod['type'] ) && 'post_type' == $pod['type'] ) {
483
                $attachment = get_post( $id );
484
                if ( isset( $attachment->post_parent ) && 0 === (int) $attachment->post_parent ) {
485
                    $attachment_data['post_parent'] = (int) $params->id;
486
                }
487
            }
488
489
            // Update the attachment if it the data array is not still empty
490
            if ( ! empty( $attachment_data ) ) {
491
                $attachment_data['ID'] = $id;
492
                self::$api->save_wp_object( 'media', $attachment_data );
493
            }
494
        }
495
    }
496
497
    /**
498
     * Customize the Pods UI manage table column output
499
     *
500
     * @param int $id
501
     * @param mixed $value
502
     * @param string $name
503
     * @param array $options
504
     * @param array $fields
505
     * @param array $pod
506
     *
507
     * @return mixed|void
508
     * @since 2.0
509
     */
510
    public function ui ( $id, $value, $name = null, $options = null, $fields = null, $pod = null ) {
511
        if ( empty( $value ) )
512
            return;
513
514
        if ( !empty( $value ) && isset( $value[ 'ID' ] ) )
515
            $value = array( $value );
516
517
        $image_size = apply_filters( 'pods_form_ui_field_' . self::$type . '_ui_image_size', 'thumbnail', $id, $value, $name, $options, $pod );
518
519
        return $this->images( $id, $value, $name, $options, $pod, $image_size );
520
    }
521
522
    /**
523
     * Return image(s) markup
524
     *
525
     * @param int $id
526
     * @param mixed $value
527
     * @param string $name
528
     * @param array $options
529
     * @param array $pod
530
     * @param string $image_size
531
     *
532
     * @return string
533
     * @since 2.3
534
     */
535
    public function images ( $id, $value, $name = null, $options = null, $pod = null, $image_size = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $id 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...
Unused Code introduced by
The parameter $name 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...
Unused Code introduced by
The parameter $options 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...
Unused Code introduced by
The parameter $pod 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...
536
        $images = '';
537
538
        if ( empty( $value ) || !is_array( $value ) )
539
            return $images;
540
541
        foreach ( $value as $v ) {
542
            $images .= pods_image( $v, $image_size );
543
        }
544
545
        return $images;
546
    }
547
548
	/**
549
	 * Data callback for Image Sizes
550
	 *
551
	 * @param string $name The name of the field
552
	 * @param string|array $value The value of the field
553
	 * @param array $options Field options
554
	 * @param array $pod Pod data
555
	 * @param int $id Item ID
556
	 *
557
	 * @return array
558
	 *
559
	 * @since 2.3
560
	 */
561 View Code Duplication
	public function data_image_sizes ( $name = null, $value = null, $options = null, $pod = null, $id = null ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
562
		$data = array();
563
564
		$image_sizes = get_intermediate_image_sizes();
565
566
		foreach ( $image_sizes as $image_size ) {
567
			$data[ $image_size ] = ucwords( str_replace( '-', ' ', $image_size ) );
568
		}
569
570
		return apply_filters( 'pods_form_ui_field_pick_' . __FUNCTION__, $data, $name, $value, $options, $pod, $id );
571
	}
572
573
	/**
574
	 * Create a WP Gallery from the passed values (need to be attachments)
575
	 *
576
	 * @since  2.7
577
	 * @param  string|array  $value    The value(s)
578
	 * @param  array         $options  The field options
579
	 * @return string
580
	 */
581
	public function do_wp_gallery( $value, $options ) {
582
		$args = array();
583
		if ( ! empty( $options[ self::$type . '_wp_gallery_columns' ] ) ) {
584
			$args['columns'] = $options[ self::$type . '_wp_gallery_columns' ];
585
		}
586
		if ( ! empty( $options[ self::$type . '_wp_gallery_random_sort' ] ) ) {
587
			$args['orderby'] = 'rand';
588
		}
589
		if ( ! empty( $options[ self::$type . '_wp_gallery_link' ] ) ) {
590
			$args['link'] = $options[ self::$type . '_wp_gallery_link' ];
591
		}
592
		if ( ! empty( $options[ self::$type . '_wp_gallery_size' ] ) ) {
593
			$args['size'] = $options[ self::$type . '_wp_gallery_size' ];
594
		}
595
596
		if ( isset( $value[ 'ID' ] ) ) {
597
			$args['ids'] = $value[ 'ID' ];
598
		} else {
599
			$images = array();
600 View Code Duplication
			foreach ( $value as $v ) {
0 ignored issues
show
Bug introduced by
The expression $value of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
601
				if ( ! is_array( $v ) ) {
602
					$images[] = (int) $v;
603
				} elseif ( isset( $v[ 'ID' ] ) ) {
604
					$images[] = (int) $v[ 'ID' ];
605
				}
606
			}
607
			$args['ids'] = implode( ',', $images );
608
		}
609
610
		if ( is_callable( 'gallery_shortcode' ) ) {
611
			return gallery_shortcode( $args );
612
		} else {
613
			$shortcode = '[gallery';
614
			foreach ( $args as $key => $value ) {
615
				$shortcode .= ' ' . $key . '="' . $value . '"';
616
			}
617
			$shortcode .= ']';
618
			return do_shortcode( $shortcode );
619
		}
620
	}
621
622
    /**
623
     * Handle file row output for uploaders
624
     *
625
     * @param array $attributes
626
     * @param int $limit
627
     * @param bool $editable
628
     * @param int $id
629
     * @param string $icon
630
     * @param string $name
631
     *
632
     * @return string
633
     * @since 2.0
634
     */
635
    public function markup ( $attributes, $limit = 1, $editable = true, $id = null, $icon = null, $name = null, $linked = false, $link = null ) {
636
        // Preserve current file type
637
        $field_type = PodsForm::$field_type;
0 ignored issues
show
Bug introduced by
The property field_type cannot be accessed from this context as it is declared private in class PodsForm.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
638
639
        ob_start();
640
641
        if ( empty( $id ) )
642
            $id = '{{id}}';
643
644
        if ( empty( $icon ) ) {
645
	        $icon = '{{icon}}';
646
        }else{
647
	        $icon = esc_url( $icon );
648
        }
649
650
651
        if ( empty( $name ) )
652
            $name = '{{name}}';
653
654
        if ( empty( $link ) )
655
            $link = '{{link}}';
656
657
        $editable = (boolean) $editable;
658
        $linked = (boolean) $linked;
659
        ?>
660
    <li class="pods-file hidden" id="pods-file-<?php echo esc_attr( $id ); ?>">
661
        <?php echo PodsForm::field( $attributes[ 'name' ] . '[' . $id . '][id]', $id, 'hidden' ); ?>
662
663
        <ul class="pods-file-meta media-item">
664
            <?php if ( 1 != $limit ) { ?>
665
                <li class="pods-file-col pods-file-handle">Handle</li>
666
            <?php } ?>
667
668
            <li class="pods-file-col pods-file-icon">
669
                <img class="pinkynail" src="<?php echo $icon; ?>" alt="Icon" />
670
            </li>
671
672
            <li class="pods-file-col pods-file-name">
673
                <?php
674
                if ( $editable )
675
                    echo PodsForm::field( $attributes[ 'name' ] . '[' . $id . '][title]', $name, 'text' );
676
                else
677
                    echo ( empty( $name ) ? '{{name}}' : $name );
678
                ?>
679
            </li>
680
681
            <li class="pods-file-col pods-file-actions">
682
                <ul>
683
                    <li class="pods-file-col pods-file-delete"><a href="#delete">Delete</a></li>
684
                    <?php
685
						if ( $linked ) {
686
					?>
687
		                <li class="pods-file-col pods-file-download"><a href="<?php echo esc_url( $link ); ?>" target="_blank">Download</a></li>
688
					<?php
689
						}
690
					?>
691
                </ul>
692
            </li>
693
        </ul>
694
    </li>
695
    <?php
696
        PodsForm::$field_type = $field_type;
0 ignored issues
show
Bug introduced by
The property field_type cannot be accessed from this context as it is declared private in class PodsForm.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
697
698
        return ob_get_clean();
699
    }
700
701
    /**
702
     * Handle plupload AJAX
703
     *
704
     * @since 2.3
705
     */
706
    public function admin_ajax_upload () {
707
		pods_session_start();
708
709
        // Sanitize input
710
        $params = pods_unslash( (array) $_POST );
711
712 View Code Duplication
        foreach ( $params as $key => $value ) {
713
            if ( 'action' == $key )
714
                continue;
715
716
            unset( $params[ $key ] );
717
718
            $params[ str_replace( '_podsfix_', '', $key ) ] = $value;
719
        }
720
721
        $params = (object) $params;
722
723
        $methods = array(
724
            'upload',
725
        );
726
727
        if ( !isset( $params->method ) || !in_array( $params->method, $methods ) || !isset( $params->pod ) || !isset( $params->field ) || !isset( $params->uri ) || empty( $params->uri ) )
728
            pods_error( 'Invalid AJAX request', PodsInit::$admin );
0 ignored issues
show
Bug introduced by
The property admin cannot be accessed from this context as it is declared private in class PodsInit.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
729
        elseif ( !empty( $params->pod ) && empty( $params->field ) )
730
            pods_error( 'Invalid AJAX request', PodsInit::$admin );
0 ignored issues
show
Bug introduced by
The property admin cannot be accessed from this context as it is declared private in class PodsInit.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
731
        elseif ( empty( $params->pod ) && !current_user_can( 'upload_files' ) )
732
            pods_error( 'Invalid AJAX request', PodsInit::$admin );
0 ignored issues
show
Bug introduced by
The property admin cannot be accessed from this context as it is declared private in class PodsInit.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
733
734
        // Flash often fails to send cookies with the POST or upload, so we need to pass it in GET or POST instead
735
        if ( is_ssl() && empty( $_COOKIE[ SECURE_AUTH_COOKIE ] ) && !empty( $_REQUEST[ 'auth_cookie' ] ) )
736
            $_COOKIE[ SECURE_AUTH_COOKIE ] = $_REQUEST[ 'auth_cookie' ];
737
        elseif ( empty( $_COOKIE[ AUTH_COOKIE ] ) && !empty( $_REQUEST[ 'auth_cookie' ] ) )
738
            $_COOKIE[ AUTH_COOKIE ] = $_REQUEST[ 'auth_cookie' ];
739
740
        if ( empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) && !empty( $_REQUEST[ 'logged_in_cookie' ] ) )
741
            $_COOKIE[ LOGGED_IN_COOKIE ] = $_REQUEST[ 'logged_in_cookie' ];
742
743
        global $current_user;
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...
744
        unset( $current_user );
745
746
        /**
747
         * Access Checking
748
         */
749
        $upload_disabled = false;
750
751
        if ( defined( 'PODS_DISABLE_FILE_UPLOAD' ) && true === PODS_DISABLE_FILE_UPLOAD )
752
            $upload_disabled = true;
753 View Code Duplication
        elseif ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && true === PODS_UPLOAD_REQUIRE_LOGIN && !is_user_logged_in() )
754
            $upload_disabled = true;
755 View Code Duplication
        elseif ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && !is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_UPLOAD_REQUIRE_LOGIN ) ) )
756
            $upload_disabled = true;
757
758
        $uid = @session_id();
759
760
        if ( is_user_logged_in() )
761
            $uid = 'user_' . get_current_user_id();
762
763
        $nonce_check = 'pods_upload_' . (int) $params->pod . '_' . $uid . '_' . $params->uri . '_' . (int) $params->field;
764
765 View Code Duplication
        if ( true === $upload_disabled || !isset( $params->_wpnonce ) || false === wp_verify_nonce( $params->_wpnonce, $nonce_check ) )
766
            pods_error( __( 'Unauthorized request', 'pods' ), PodsInit::$admin );
0 ignored issues
show
Bug introduced by
The property admin cannot be accessed from this context as it is declared private in class PodsInit.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
767
768
        $pod = array();
769
        $field = array(
770
            'type' => 'file',
771
            'options' => array()
772
        );
773
774
        $api = pods_api();
775
776
	    $api->display_errors = false;
777
778
        if ( !empty( $params->pod ) ) {
779
            $pod = $api->load_pod( array( 'id' => (int) $params->pod ) );
780
            $field = $api->load_field( array( 'id' => (int) $params->field ) );
781
782 View Code Duplication
            if ( empty( $pod ) || empty( $field ) || $pod[ 'id' ] != $field[ 'pod_id' ] || !isset( $pod[ 'fields' ][ $field[ 'name' ] ] ) )
783
                pods_error( __( 'Invalid field request', 'pods' ), PodsInit::$admin );
0 ignored issues
show
Bug introduced by
The property admin cannot be accessed from this context as it is declared private in class PodsInit.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
784
785
            if ( !in_array( $field[ 'type' ], PodsForm::file_field_types() ) )
786
                pods_error( __( 'Invalid field', 'pods' ), PodsInit::$admin );
0 ignored issues
show
Bug introduced by
The property admin cannot be accessed from this context as it is declared private in class PodsInit.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
787
        }
788
789
        $method = $params->method;
790
791
        // Cleaning up $params
792
        unset( $params->action );
793
        unset( $params->method );
794
        unset( $params->_wpnonce );
795
796
        $params->post_id = pods_var( 'post_id', $params, 0, null, true );
797
798
        /**
799
         * Upload a new file (advanced - returns URL and ID)
800
         */
801
        if ( 'upload' == $method ) {
802
            $file = $_FILES[ 'Filedata' ];
803
804
            $limit_size = pods_var( $field[ 'type' ] . '_restrict_filesize', $field[ 'options' ] );
805
806
            if ( !empty( $limit_size ) ) {
807
                if ( false !== stripos( $limit_size, 'MB' ) ) {
808
                    $limit_size = (float) trim( str_ireplace( 'MB', '', $limit_size ) );
809
                    $limit_size = $limit_size * 1025 * 1025; // convert to KB to B
810
                }
811 View Code Duplication
                elseif ( false !== stripos( $limit_size, 'KB' ) ) {
812
                    $limit_size = (float) trim( str_ireplace( 'KB', '', $limit_size ) );
813
                    $limit_size = $limit_size * 1025 * 1025; // convert to B
814
                }
815 View Code Duplication
                elseif ( false !== stripos( $limit_size, 'GB' ) ) {
816
                    $limit_size = (float) trim( str_ireplace( 'GB', '', $limit_size ) );
817
                    $limit_size = $limit_size * 1025 * 1025 * 1025; // convert to MB to KB to B
818
                }
819
                elseif ( false !== stripos( $limit_size, 'B' ) )
820
                    $limit_size = (float) trim( str_ireplace( 'B', '', $limit_size ) );
821
                else
822
                    $limit_size = wp_max_upload_size();
823
824
                if ( 0 < $limit_size && $limit_size < $file[ 'size' ] ) {
825
                    $error = __( 'File size too large, max size is %s', 'pods' );
826
                    $error = sprintf( $error, pods_var( $field[ 'type' ] . '_restrict_filesize', $field[ 'options' ] ) );
827
828
                    pods_error( '<div style="color:#FF0000">Error: ' . $error . '</div>' );
829
                }
830
            }
831
832
            $limit_file_type = pods_var( $field[ 'type' ] . '_type', $field[ 'options' ], 'images' );
833
834
            if ( 'images' == $limit_file_type )
835
                $limit_types = 'jpg,jpeg,png,gif';
836
            elseif ( 'video' == $limit_file_type )
837
                $limit_types = 'mpg,mov,flv,mp4';
838
            elseif ( 'audio' == $limit_file_type )
839
                $limit_types = 'mp3,m4a,wav,wma';
840
            elseif ( 'text' == $limit_file_type )
841
                $limit_types = 'txt,rtx,csv,tsv';
842
            elseif ( 'any' == $limit_file_type )
843
                $limit_types = '';
844
            else
845
                $limit_types = pods_var( $field[ 'type' ] . '_allowed_extensions', $field[ 'options' ], '', null, true );
846
847
            $limit_types = trim( str_replace( array( ' ', '.', "\n", "\t", ';' ), array( '', ',', ',', ',' ), $limit_types ), ',' );
848
849 View Code Duplication
            if ( pods_version_check( 'wp', '3.5' ) ) {
850
                $mime_types = wp_get_mime_types();
851
852
                if ( in_array( $limit_file_type, array( 'images', 'audio', 'video' ) ) ) {
853
                    $new_limit_types = array();
854
855
                    foreach ( $mime_types as $type => $mime ) {
856
                        if ( 0 === strpos( $mime, $limit_file_type ) ) {
857
                            $type = explode( '|', $type );
858
859
                            $new_limit_types = array_merge( $new_limit_types, $type );
860
                        }
861
                    }
862
863
                    if ( !empty( $new_limit_types ) )
864
                        $limit_types = implode( ',', $new_limit_types );
865
                }
866
                elseif ( 'any' != $limit_file_type ) {
867
                    $new_limit_types = array();
868
869
                    $limit_types = explode( ',', $limit_types );
870
871
                    foreach ( $limit_types as $k => $limit_type ) {
872
                        $found = false;
873
874
                        foreach ( $mime_types as $type => $mime ) {
875
                            if ( 0 === strpos( $mime, $limit_type ) ) {
876
                                $type = explode( '|', $type );
877
878
                                foreach ( $type as $t ) {
879
                                    if ( !in_array( $t, $new_limit_types ) )
880
                                        $new_limit_types[] = $t;
881
                                }
882
883
                                $found = true;
884
                            }
885
                        }
886
887
                        if ( !$found )
888
                            $new_limit_types[] = $limit_type;
889
                    }
890
891
                    if ( !empty( $new_limit_types ) )
892
                        $limit_types = implode( ',', $new_limit_types );
893
                }
894
            }
895
896
            $limit_types = explode( ',', $limit_types );
897
898
            $limit_types = array_filter( array_unique( $limit_types ) );
899
900
            if ( !empty( $limit_types ) ) {
901
                $ok = false;
902
903
                foreach ( $limit_types as $limit_type ) {
904
                    $limit_type = '.' . trim( $limit_type, ' .' );
905
906
                    $pos = ( strlen( $file[ 'name' ] ) - strlen( $limit_type ) );
907
908
                    if ( $pos === stripos( $file[ 'name' ], $limit_type ) ) {
909
                        $ok = true;
910
911
                        break;
912
                    }
913
                }
914
915
                if ( false === $ok ) {
916
                    $error = __( 'File type not allowed, please use one of the following: %s', 'pods' );
917
                    $error = sprintf( $error, '.' . implode( ', .', $limit_types ) );
918
919
                    pods_error( '<div style="color:#FF0000">Error: ' . $error . '</div>' );
920
                }
921
            }
922
923
            $custom_handler = apply_filters( 'pods_upload_handle', null, 'Filedata', $params->post_id, $params, $field );
924
925
            if ( null === $custom_handler ) {
926
                $attachment_id = media_handle_upload( 'Filedata', $params->post_id );
927
928
                if ( is_object( $attachment_id ) ) {
929
                    $errors = array();
930
931
                    foreach ( $attachment_id->errors[ 'upload_error' ] as $error_code => $error_message ) {
932
                        $errors[] = '[' . $error_code . '] ' . $error_message;
933
                    }
934
935
                    pods_error( '<div style="color:#FF0000">Error: ' . implode( '</div><div>', $errors ) . '</div>' );
936
                }
937
                else {
938
                    $attachment = get_post( $attachment_id, ARRAY_A );
939
940
                    $attachment['filename'] = basename( $attachment['guid'] );
941
942
                    $thumb = wp_get_attachment_image_src( $attachment['ID'], 'thumbnail', true );
943
944
                    $attachment['thumbnail'] = '';
945
946
                    if ( ! empty( $thumb[0] ) ) {
947
                        $attachment['thumbnail'] = $thumb[0];
948
                    }
949
950
                    $attachment['link']      = get_permalink( $attachment['ID'] );
951
                    $attachment['edit_link'] = get_edit_post_link( $attachment['ID'] );
952
                    $attachment['download']  = wp_get_attachment_url( $attachment['ID'] );
953
954
                    $attachment = apply_filters( 'pods_upload_attachment', $attachment, $params->post_id );
955
956
                    wp_send_json( $attachment );
957
                }
958
            }
959
        }
960
961
        die(); // KBAI!
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_ajax_upload() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
962
    }
963
}
964