Completed
Pull Request — 2.x (#3397)
by Scott Kingsley
07:47 queued 58s
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 1
Bugs 0 Features 0
Metric Value
cc 31
eloc 34
nc 6
nop 5
dl 24
loc 51
rs 5.4631
c 1
b 0
f 0

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
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
207 View Code Duplication
        if ( !pods_version_check( 'wp', '3.5' ) ) {
208
            unset( $options[ self::$type . '_linked' ] );
209
            unset( $options[ self::$type . '_modal_title' ] );
210
            unset( $options[ self::$type . '_modal_add_button' ] );
211
212
            $options[ self::$type . '_attachment_tab' ][ 'default' ] = 'type';
213
            $options[ self::$type . '_attachment_tab' ][ 'data' ] = array(
214
                'type' => __( 'Upload File', 'pods' ),
215
                'library' => __( 'Media Library', 'pods' )
216
            );
217
        }
218
219
        return $options;
220
    }
221
222
    /**
223
     * Define the current field's schema for DB table storage
224
     *
225
     * @param array $options
226
     *
227
     * @return array
228
     * @since 2.0
229
     */
230
    public function schema ( $options = null ) {
231
        $schema = false;
232
233
        return $schema;
234
    }
235
236
    /**
237
     * Change the way the value of the field is displayed with Pods::get
238
     *
239
     * @param mixed $value
240
     * @param string $name
241
     * @param array $options
242
     * @param array $pod
243
     * @param int $id
244
     *
245
     * @return mixed|null
246
     * @since 2.0
247
     */
248
    public function display ( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
249
        if ( is_array( $value ) && !empty( $value ) ) {
250
            if ( isset( $value[ 'ID' ] ) )
251
                $value = wp_get_attachment_url( $value[ 'ID' ] );
252
            else {
253
                $attachments = $value;
254
                $value = array();
255
256
                foreach ( $attachments as $v ) {
257
                    if ( !is_array( $v ) )
258
                        $value[] = $v;
259
                    elseif ( isset( $v[ 'ID' ] ) )
260
                        $value[] = wp_get_attachment_url( $v[ 'ID' ] );
261
                }
262
263
                $value = implode( ' ', $value );
264
            }
265
        }
266
267
        return $value;
268
    }
269
270
    /**
271
     * Customize output of the form field
272
     *
273
     * @param string $name
274
     * @param mixed $value
275
     * @param array $options
276
     * @param array $pod
277
     * @param int $id
278
     *
279
     * @since 2.0
280
     */
281
    public function input ( $name, $value = null, $options = null, $pod = null, $id = null ) {
282
        $options = (array) $options;
283
        $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...
284
285 View Code Duplication
        if ( !is_admin() ) {
286
            include_once( ABSPATH . '/wp-admin/includes/template.php' );
287
288
            if ( is_multisite() )
289
                include_once( ABSPATH . '/wp-admin/includes/ms.php' );
290
        }
291
292 View Code Duplication
        if ( ( ( defined( 'PODS_DISABLE_FILE_UPLOAD' ) && true === PODS_DISABLE_FILE_UPLOAD )
293
               || ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && true === PODS_UPLOAD_REQUIRE_LOGIN && !is_user_logged_in() )
294
               || ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && !is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_UPLOAD_REQUIRE_LOGIN ) ) ) )
295
             && ( ( defined( 'PODS_DISABLE_FILE_BROWSER' ) && true === PODS_DISABLE_FILE_BROWSER )
296
                  || ( defined( 'PODS_FILES_REQUIRE_LOGIN' ) && is_bool( PODS_FILES_REQUIRE_LOGIN ) && true === PODS_FILES_REQUIRE_LOGIN && !is_user_logged_in() )
297
                  || ( defined( 'PODS_FILES_REQUIRE_LOGIN' ) && !is_bool( PODS_FILES_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_FILES_REQUIRE_LOGIN ) ) ) )
298
        ) {
299
            ?>
300
        <p>You do not have access to upload / browse files. Contact your website admin to resolve.</p>
301
        <?php
302
            return;
303
        }
304
305
        // @todo: Now One Field to Rule Them All
306
        $field_type = 'file-upload';
307
        pods_view( PODS_DIR . 'ui/fields-mv/file-upload.php', compact( array_keys( get_defined_vars() ) ) );
308
        return;
309
310
        // @todo: we're short-circuiting for prototyping above.  The actions below will need to be woven in
311
312
        // Use plupload if attachment isn't available
313
        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
Bug introduced by
The variable $options seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
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...
314
            $field_type = 'plupload';
315
        elseif ( 'plupload' == pods_var( self::$type . '_uploader', $options ) )
0 ignored issues
show
Bug introduced by
The variable $options seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
316
            $field_type = 'plupload';
317 View Code Duplication
        elseif ( 'attachment' == pods_var( self::$type . '_uploader', $options ) ) {
0 ignored issues
show
Bug introduced by
The variable $options seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
318
            if ( !pods_version_check( 'wp', '3.5' ) || !is_admin() ) // @todo test frontend media modal
319
                $field_type = 'attachment';
320
            else
321
                $field_type = 'media';
322
        }
323
        else {
324
            // Support custom File Uploader integration
325
            do_action( 'pods_form_ui_field_' . self::$type . '_uploader_' . pods_var( self::$type . '_uploader', $options ), $name, $value, $options, $pod, $id );
326
            do_action( 'pods_form_ui_field_' . self::$type . '_uploader', pods_var( self::$type . '_uploader', $options ), $name, $value, $options, $pod, $id );
327
            return;
328
        }
329
330
        pods_view( PODS_DIR . 'ui/fields/' . $field_type . '.php', compact( array_keys( get_defined_vars() ) ) );
331
    }
332
333
    /**
334
     * Build regex necessary for JS validation
335
     *
336
     * @param mixed $value
337
     * @param string $name
338
     * @param array $options
339
     * @param string $pod
340
     * @param int $id
341
     *
342
     * @return bool
343
     * @since 2.0
344
     */
345
    public function regex ( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
346
        return false;
347
    }
348
349
    /**
350
     * Validate a value before it's saved
351
     *
352
     * @param mixed $value
353
     * @param string $name
354
     * @param array $options
355
     * @param array $fields
356
     * @param array $pod
357
     * @param int $id
358
     * @param null $params
359
     *
360
     * @return bool
361
     * @since 2.0
362
     */
363
    public function validate ( $value, $name = null, $options = null, $fields = null, $pod = null, $id = null, $params = null ) {
364
        // check file size
365
        // check file extensions
366
        return true;
367
    }
368
369
    /**
370
     * Change the value or perform actions after validation but before saving to the DB
371
     *
372
     * @param mixed $value
373
     * @param int $id
374
     * @param string $name
375
     * @param array $options
376
     * @param array $fields
377
     * @param array $pod
378
     * @param object $params
379
     *
380
     * @return mixed
381
     * @since 2.0
382
     */
383
    public function pre_save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
384
        return $value;
385
    }
386
387
    /**
388
     * Save the value to the DB
389
     *
390
     * @param mixed $value
391
     * @param int $id
392
     * @param string $name
393
     * @param array $options
394
     * @param array $fields
395
     * @param array $pod
396
     * @param object $params
397
     *
398
     * @since 2.3
399
     */
400
    public function save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
401
        if ( empty( self::$api ) )
402
            self::$api = pods_api();
403
404
        // File title / field handling
405
        foreach ( $value as $id ) {
406
            $title = false;
407
408
            if ( is_array( $id ) ) {
409 View Code Duplication
                if ( isset( $id[ 'title' ] ) && 0 < strlen( trim( $id[ 'title' ] ) ) )
410
                    $title = trim( $id[ 'title' ] );
411
412
                if ( isset( $id[ 'id' ] ) )
413
                    $id = (int) $id[ 'id' ];
414
                else
415
                    $id = 0;
416
            }
417
418
            if ( empty( $id ) )
419
                continue;
420
421
            // Update the title if set
422
            if ( false !== $title && 1 == pods_var( self::$type . '_edit_title', $options, 0 ) ) {
423
                $attachment_data = array(
424
                    'ID' => $id,
425
                    'post_title' => $title
426
                );
427
428
                self::$api->save_wp_object( 'media', $attachment_data );
429
            }
430
        }
431
    }
432
433
    /**
434
     * Customize the Pods UI manage table column output
435
     *
436
     * @param int $id
437
     * @param mixed $value
438
     * @param string $name
439
     * @param array $options
440
     * @param array $fields
441
     * @param array $pod
442
     *
443
     * @return mixed|void
444
     * @since 2.0
445
     */
446
    public function ui ( $id, $value, $name = null, $options = null, $fields = null, $pod = null ) {
447
        if ( empty( $value ) )
448
            return;
449
450
        if ( !empty( $value ) && isset( $value[ 'ID' ] ) )
451
            $value = array( $value );
452
453
        $image_size = apply_filters( 'pods_form_ui_field_' . self::$type . '_ui_image_size', 'thumbnail', $id, $value, $name, $options, $pod );
454
455
        return $this->images( $id, $value, $name, $options, $pod, $image_size );
456
    }
457
458
    /**
459
     * Return image(s) markup
460
     *
461
     * @param int $id
462
     * @param mixed $value
463
     * @param string $name
464
     * @param array $options
465
     * @param array $pod
466
     * @param string $image_size
467
     *
468
     * @return string
469
     * @since 2.3
470
     */
471
    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...
472
        $images = '';
473
474
        if ( empty( $value ) || !is_array( $value ) )
475
            return $images;
476
477
        foreach ( $value as $v ) {
478
            $images .= pods_image( $v, $image_size );
479
        }
480
481
        return $images;
482
    }
483
484
    /**
485
     * Handle file row output for uploaders
486
     *
487
     * @param array $attributes
488
     * @param int $limit
489
     * @param bool $editable
490
     * @param int $id
491
     * @param string $icon
492
     * @param string $name
493
     *
494
     * @return string
495
     * @since 2.0
496
     */
497
    public function markup ( $attributes, $limit = 1, $editable = true, $id = null, $icon = null, $name = null, $linked = false, $link = null ) {
498
        // Preserve current file type
499
        $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...
500
501
        ob_start();
502
503
        if ( empty( $id ) )
504
            $id = '{{id}}';
505
506
        if ( empty( $icon ) ) {
507
	        $icon = '{{icon}}';
508
        }else{
509
	        $icon = esc_url( $icon );
510
        }
511
512
513
        if ( empty( $name ) )
514
            $name = '{{name}}';
515
516
        if ( empty( $link ) )
517
            $link = '{{link}}';
518
519
        $editable = (boolean) $editable;
520
        $linked = (boolean) $linked;
521
        ?>
522
    <li class="pods-file hidden" id="pods-file-<?php echo esc_attr( $id ); ?>">
523
        <?php echo PodsForm::field( $attributes[ 'name' ] . '[' . $id . '][id]', $id, 'hidden' ); ?>
524
525
        <ul class="pods-file-meta media-item">
526
            <?php if ( 1 != $limit ) { ?>
527
                <li class="pods-file-col pods-file-handle">Handle</li>
528
            <?php } ?>
529
530
            <li class="pods-file-col pods-file-icon">
531
                <img class="pinkynail" src="<?php echo $icon; ?>" alt="Icon" />
532
            </li>
533
534
            <li class="pods-file-col pods-file-name">
535
                <?php
536
                if ( $editable )
537
                    echo PodsForm::field( $attributes[ 'name' ] . '[' . $id . '][title]', $name, 'text' );
538
                else
539
                    echo ( empty( $name ) ? '{{name}}' : $name );
540
                ?>
541
            </li>
542
543
            <li class="pods-file-col pods-file-delete"><a href="#delete">Delete</a></li>
544
545
			<?php
546
				if ( $linked ) {
547
			?>
548
            	<li class="pods-file-col pods-file-download"><a href="<?php echo esc_url( $link ); ?>" target="_blank">Download</a></li>
549
			<?php
550
				}
551
			?>
552
        </ul>
553
    </li>
554
    <?php
555
        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...
556
557
        return ob_get_clean();
558
    }
559
560
    /**
561
     * Handle plupload AJAX
562
     *
563
     * @since 2.3
564
     */
565
    public function admin_ajax_upload () {
566
		pods_session_start();
567
568
        // Sanitize input
569
        $params = pods_unslash( (array) $_POST );
570
571 View Code Duplication
        foreach ( $params as $key => $value ) {
572
            if ( 'action' == $key )
573
                continue;
574
575
            unset( $params[ $key ] );
576
577
            $params[ str_replace( '_podsfix_', '', $key ) ] = $value;
578
        }
579
580
        $params = (object) $params;
581
582
        $methods = array(
583
            'upload',
584
        );
585
586
        if ( !isset( $params->method ) || !in_array( $params->method, $methods ) || !isset( $params->pod ) || !isset( $params->field ) || !isset( $params->uri ) || empty( $params->uri ) )
587
            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...
588
        elseif ( !empty( $params->pod ) && empty( $params->field ) )
589
            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...
590
        elseif ( empty( $params->pod ) && !current_user_can( 'upload_files' ) )
591
            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...
592
593
        // Flash often fails to send cookies with the POST or upload, so we need to pass it in GET or POST instead
594
        if ( is_ssl() && empty( $_COOKIE[ SECURE_AUTH_COOKIE ] ) && !empty( $_REQUEST[ 'auth_cookie' ] ) )
595
            $_COOKIE[ SECURE_AUTH_COOKIE ] = $_REQUEST[ 'auth_cookie' ];
596
        elseif ( empty( $_COOKIE[ AUTH_COOKIE ] ) && !empty( $_REQUEST[ 'auth_cookie' ] ) )
597
            $_COOKIE[ AUTH_COOKIE ] = $_REQUEST[ 'auth_cookie' ];
598
599
        if ( empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) && !empty( $_REQUEST[ 'logged_in_cookie' ] ) )
600
            $_COOKIE[ LOGGED_IN_COOKIE ] = $_REQUEST[ 'logged_in_cookie' ];
601
602
        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...
603
        unset( $current_user );
604
605
        /**
606
         * Access Checking
607
         */
608
        $upload_disabled = false;
609
610
        if ( defined( 'PODS_DISABLE_FILE_UPLOAD' ) && true === PODS_DISABLE_FILE_UPLOAD )
611
            $upload_disabled = true;
612 View Code Duplication
        elseif ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && true === PODS_UPLOAD_REQUIRE_LOGIN && !is_user_logged_in() )
613
            $upload_disabled = true;
614 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 ) ) )
615
            $upload_disabled = true;
616
617
        $uid = @session_id();
618
619
        if ( is_user_logged_in() )
620
            $uid = 'user_' . get_current_user_id();
621
622
        $nonce_check = 'pods_upload_' . (int) $params->pod . '_' . $uid . '_' . $params->uri . '_' . (int) $params->field;
623
624 View Code Duplication
        if ( true === $upload_disabled || !isset( $params->_wpnonce ) || false === wp_verify_nonce( $params->_wpnonce, $nonce_check ) )
625
            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...
626
627
        $pod = array();
628
        $field = array(
629
            'type' => 'file',
630
            'options' => array()
631
        );
632
633
        $api = pods_api();
634
635
	    $api->display_errors = false;
636
637
        if ( !empty( $params->pod ) ) {
638
            $pod = $api->load_pod( array( 'id' => (int) $params->pod ) );
639
            $field = $api->load_field( array( 'id' => (int) $params->field ) );
640
641 View Code Duplication
            if ( empty( $pod ) || empty( $field ) || $pod[ 'id' ] != $field[ 'pod_id' ] || !isset( $pod[ 'fields' ][ $field[ 'name' ] ] ) )
642
                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...
643
644
            if ( !in_array( $field[ 'type' ], PodsForm::file_field_types() ) )
645
                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...
646
        }
647
648
        $method = $params->method;
649
650
        // Cleaning up $params
651
        unset( $params->action );
652
        unset( $params->method );
653
        unset( $params->_wpnonce );
654
655
        $params->post_id = pods_var( 'post_id', $params, 0, null, true );
656
657
        /**
658
         * Upload a new file (advanced - returns URL and ID)
659
         */
660
        if ( 'upload' == $method ) {
661
            $file = $_FILES[ 'Filedata' ];
662
663
            $limit_size = pods_var( $field[ 'type' ] . '_restrict_filesize', $field[ 'options' ] );
664
665
            if ( !empty( $limit_size ) ) {
666
                if ( false !== stripos( $limit_size, 'MB' ) ) {
667
                    $limit_size = (float) trim( str_ireplace( 'MB', '', $limit_size ) );
668
                    $limit_size = $limit_size * 1025 * 1025; // convert to KB to B
669
                }
670 View Code Duplication
                elseif ( false !== stripos( $limit_size, 'KB' ) ) {
671
                    $limit_size = (float) trim( str_ireplace( 'KB', '', $limit_size ) );
672
                    $limit_size = $limit_size * 1025 * 1025; // convert to B
673
                }
674 View Code Duplication
                elseif ( false !== stripos( $limit_size, 'GB' ) ) {
675
                    $limit_size = (float) trim( str_ireplace( 'GB', '', $limit_size ) );
676
                    $limit_size = $limit_size * 1025 * 1025 * 1025; // convert to MB to KB to B
677
                }
678
                elseif ( false !== stripos( $limit_size, 'B' ) )
679
                    $limit_size = (float) trim( str_ireplace( 'B', '', $limit_size ) );
680
                else
681
                    $limit_size = wp_max_upload_size();
682
683
                if ( 0 < $limit_size && $limit_size < $file[ 'size' ] ) {
684
                    $error = __( 'File size too large, max size is %s', 'pods' );
685
                    $error = sprintf( $error, pods_var( $field[ 'type' ] . '_restrict_filesize', $field[ 'options' ] ) );
686
687
                    pods_error( '<div style="color:#FF0000">Error: ' . $error . '</div>' );
688
                }
689
            }
690
691
            $limit_file_type = pods_var( $field[ 'type' ] . '_type', $field[ 'options' ], 'images' );
692
693
            if ( 'images' == $limit_file_type )
694
                $limit_types = 'jpg,jpeg,png,gif';
695
            elseif ( 'video' == $limit_file_type )
696
                $limit_types = 'mpg,mov,flv,mp4';
697
            elseif ( 'audio' == $limit_file_type )
698
                $limit_types = 'mp3,m4a,wav,wma';
699
            elseif ( 'text' == $limit_file_type )
700
                $limit_types = 'txt,rtx,csv,tsv';
701
            elseif ( 'any' == $limit_file_type )
702
                $limit_types = '';
703
            else
704
                $limit_types = pods_var( $field[ 'type' ] . '_allowed_extensions', $field[ 'options' ], '', null, true );
705
706
            $limit_types = trim( str_replace( array( ' ', '.', "\n", "\t", ';' ), array( '', ',', ',', ',' ), $limit_types ), ',' );
707
708 View Code Duplication
            if ( pods_version_check( 'wp', '3.5' ) ) {
709
                $mime_types = wp_get_mime_types();
710
711
                if ( in_array( $limit_file_type, array( 'images', 'audio', 'video' ) ) ) {
712
                    $new_limit_types = array();
713
714
                    foreach ( $mime_types as $type => $mime ) {
715
                        if ( 0 === strpos( $mime, $limit_file_type ) ) {
716
                            $type = explode( '|', $type );
717
718
                            $new_limit_types = array_merge( $new_limit_types, $type );
719
                        }
720
                    }
721
722
                    if ( !empty( $new_limit_types ) )
723
                        $limit_types = implode( ',', $new_limit_types );
724
                }
725
                elseif ( 'any' != $limit_file_type ) {
726
                    $new_limit_types = array();
727
728
                    $limit_types = explode( ',', $limit_types );
729
730
                    foreach ( $limit_types as $k => $limit_type ) {
731
                        $found = false;
732
733
                        foreach ( $mime_types as $type => $mime ) {
734
                            if ( 0 === strpos( $mime, $limit_type ) ) {
735
                                $type = explode( '|', $type );
736
737
                                foreach ( $type as $t ) {
738
                                    if ( !in_array( $t, $new_limit_types ) )
739
                                        $new_limit_types[] = $t;
740
                                }
741
742
                                $found = true;
743
                            }
744
                        }
745
746
                        if ( !$found )
747
                            $new_limit_types[] = $limit_type;
748
                    }
749
750
                    if ( !empty( $new_limit_types ) )
751
                        $limit_types = implode( ',', $new_limit_types );
752
                }
753
            }
754
755
            $limit_types = explode( ',', $limit_types );
756
757
            $limit_types = array_filter( array_unique( $limit_types ) );
758
759
            if ( !empty( $limit_types ) ) {
760
                $ok = false;
761
762
                foreach ( $limit_types as $limit_type ) {
763
                    $limit_type = '.' . trim( $limit_type, ' .' );
764
765
                    $pos = ( strlen( $file[ 'name' ] ) - strlen( $limit_type ) );
766
767
                    if ( $pos === stripos( $file[ 'name' ], $limit_type ) ) {
768
                        $ok = true;
769
770
                        break;
771
                    }
772
                }
773
774
                if ( false === $ok ) {
775
                    $error = __( 'File type not allowed, please use one of the following: %s', 'pods' );
776
                    $error = sprintf( $error, '.' . implode( ', .', $limit_types ) );
777
778
                    pods_error( '<div style="color:#FF0000">Error: ' . $error . '</div>' );
779
                }
780
            }
781
782
            $custom_handler = apply_filters( 'pods_upload_handle', null, 'Filedata', $params->post_id, $params, $field );
783
784
            if ( null === $custom_handler ) {
785
                $attachment_id = media_handle_upload( 'Filedata', $params->post_id );
786
787
                if ( is_object( $attachment_id ) ) {
788
                    $errors = array();
789
790
                    foreach ( $attachment_id->errors[ 'upload_error' ] as $error_code => $error_message ) {
791
                        $errors[] = '[' . $error_code . '] ' . $error_message;
792
                    }
793
794
                    pods_error( '<div style="color:#FF0000">Error: ' . implode( '</div><div>', $errors ) . '</div>' );
795
                }
796
                else {
797
                    $attachment = get_post( $attachment_id, ARRAY_A );
798
799
                    $attachment['filename'] = basename( $attachment['guid'] );
800
801
                    $thumb = wp_get_attachment_image_src( $attachment['ID'], 'thumbnail', true );
802
803
                    $attachment['thumbnail'] = '';
804
805
                    if ( ! empty( $thumb[0] ) ) {
806
                        $attachment['thumbnail'] = $thumb[0];
807
                    }
808
809
                    $attachment['link']      = get_permalink( $attachment['ID'] );
810
                    $attachment['edit_link'] = get_edit_post_link( $attachment['ID'] );
811
                    $attachment['download']  = wp_get_attachment_url( $attachment['ID'] );
812
813
                    $attachment = apply_filters( 'pods_upload_attachment', $attachment, $params->post_id );
814
815
                    wp_send_json( $attachment );
816
                }
817
            }
818
        }
819
820
        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...
821
    }
822
}
823