Completed
Pull Request — 2.x (#3397)
by Scott Kingsley
06:40
created

PodsField_File::input()   C

Complexity

Conditions 31
Paths 6

Size

Total Lines 51
Code Lines 34

Duplication

Lines 30
Ratio 58.82 %

Importance

Changes 0
Metric Value
cc 31
eloc 34
nc 6
nop 5
dl 30
loc 51
rs 5.4631
c 0
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_file_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 . '_linked' => array(
116
                'label' => __( 'Link to File in editor', 'pods' ),
117
                'default' => 0,
118
                'type' => 'boolean'
119
            ),
120
            self::$type . '_limit' => array(
121
                'label' => __( 'Max Number of Files', 'pods' ),
122
                'depends-on' => array( self::$type . '_format_type' => 'multi' ),
123
                'default' => 0,
124
                'type' => 'number'
125
            ),
126
            self::$type . '_restrict_filesize' => array(
127
                'label' => __( 'Restrict File Size', 'pods' ),
128
                'depends-on' => array( self::$type . '_uploader' => 'plupload' ),
129
                'default' => '10MB',
130
                'type' => 'text'
131
            ),
132
            self::$type . '_type' => array(
133
                'label' => __( 'Restrict File Types', 'pods' ),
134
                'default' => apply_filters( 'pods_form_ui_field_file_type_default', 'images' ),
135
                'type' => 'pick',
136
                'data' => apply_filters(
137
                    'pods_form_ui_field_file_type_options',
138
                    array(
139
                        'images' => __( 'Images (jpg, jpeg, png, gif)', 'pods' ),
140
                        'video' => __( 'Video (mpg, mov, flv, mp4, etc..)', 'pods' ),
141
                        'audio' => __( 'Audio (mp3, m4a, wav, wma, etc..)', 'pods' ),
142
                        'text' => __( 'Text (txt, csv, tsv, rtx, etc..)', 'pods' ),
143
                        'any' => __( 'Any Type (no restriction)', 'pods' ),
144
                        'other' => __( 'Other (customize allowed extensions)', 'pods' )
145
                    )
146
                ),
147
                'dependency' => true
148
            ),
149
            self::$type . '_allowed_extensions' => array(
150
                'label' => __( 'Allowed File Extensions', 'pods' ),
151
                'description' => __( 'Separate file extensions with a comma (ex. jpg,png,mp4,mov)', 'pods' ),
152
                'depends-on' => array( self::$type . '_type' => 'other' ),
153
                'default' => apply_filters( 'pods_form_ui_field_file_extensions_default', '' ),
154
                'type' => 'text'
155
            ),/*
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
156
            self::$type . '_image_size' => array(
157
                'label' => __( 'Excluded Image Sizes', 'pods' ),
158
                'description' => __( 'Image sizes not to generate when processing the image', 'pods' ),
159
                'depends-on' => array( self::$type . '_type' => 'images' ),
160
                'default' => 'images',
161
                'type' => 'pick',
162
                'pick_format_type' => 'multi',
163
                'pick_format_multi' => 'checkbox',
164
                'data' => apply_filters(
165
                    'pods_form_ui_field_file_image_size_options',
166
                    $image_sizes
167
                )
168
            ),*/
169
            self::$type . '_add_button' => array(
170
                'label' => __( 'Add Button Text', 'pods' ),
171
                'default' => __( 'Add File', 'pods' ),
172
                'type' => 'text'
173
            ),
174
            self::$type . '_modal_title' => array(
175
                'label' => __( 'Modal Title', 'pods' ),
176
                'depends-on' => array( self::$type . '_uploader' => 'attachment' ),
177
                'default' => __( 'Attach a file', 'pods' ),
178
                'type' => 'text'
179
            ),
180
            self::$type . '_modal_add_button' => array(
181
                'label' => __( 'Modal Add Button Text', 'pods' ),
182
                'depends-on' => array( self::$type . '_uploader' => 'attachment' ),
183
                'default' => __( 'Add File', 'pods' ),
184
                'type' => 'text'
185
            )
186
        );
187
188 View Code Duplication
        if ( !pods_version_check( 'wp', '3.5' ) ) {
189
            unset( $options[ self::$type . '_linked' ] );
190
            unset( $options[ self::$type . '_modal_title' ] );
191
            unset( $options[ self::$type . '_modal_add_button' ] );
192
193
            $options[ self::$type . '_attachment_tab' ][ 'default' ] = 'type';
194
            $options[ self::$type . '_attachment_tab' ][ 'data' ] = array(
195
                'type' => __( 'Upload File', 'pods' ),
196
                'library' => __( 'Media Library', 'pods' )
197
            );
198
        }
199
200
        return $options;
201
    }
202
203
    /**
204
     * Define the current field's schema for DB table storage
205
     *
206
     * @param array $options
207
     *
208
     * @return array
209
     * @since 2.0
210
     */
211
    public function schema ( $options = null ) {
212
        $schema = false;
213
214
        return $schema;
215
    }
216
217
    /**
218
     * Change the way the value of the field is displayed with Pods::get
219
     *
220
     * @param mixed $value
221
     * @param string $name
222
     * @param array $options
223
     * @param array $pod
224
     * @param int $id
225
     *
226
     * @return mixed|null
227
     * @since 2.0
228
     */
229
    public function display ( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
230
        if ( is_array( $value ) && !empty( $value ) ) {
231
            if ( isset( $value[ 'ID' ] ) )
232
                $value = wp_get_attachment_url( $value[ 'ID' ] );
233
            else {
234
                $attachments = $value;
235
                $value = array();
236
237
                foreach ( $attachments as $v ) {
238
                    if ( !is_array( $v ) )
239
                        $value[] = $v;
240
                    elseif ( isset( $v[ 'ID' ] ) )
241
                        $value[] = wp_get_attachment_url( $v[ 'ID' ] );
242
                }
243
244
                $value = implode( ' ', $value );
245
            }
246
        }
247
248
        return $value;
249
    }
250
251
    /**
252
     * Customize output of the form field
253
     *
254
     * @param string $name
255
     * @param mixed $value
256
     * @param array $options
257
     * @param array $pod
258
     * @param int $id
259
     *
260
     * @since 2.0
261
     */
262
    public function input ( $name, $value = null, $options = null, $pod = null, $id = null ) {
263
        $options = (array) $options;
264
        $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...
265
266 View Code Duplication
        if ( !is_admin() ) {
267
            include_once( ABSPATH . '/wp-admin/includes/template.php' );
268
269
            if ( is_multisite() )
270
                include_once( ABSPATH . '/wp-admin/includes/ms.php' );
271
        }
272
273 View Code Duplication
        if ( ( ( defined( 'PODS_DISABLE_FILE_UPLOAD' ) && true === PODS_DISABLE_FILE_UPLOAD )
274
               || ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && true === PODS_UPLOAD_REQUIRE_LOGIN && !is_user_logged_in() )
275
               || ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && !is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_UPLOAD_REQUIRE_LOGIN ) ) ) )
276
             && ( ( defined( 'PODS_DISABLE_FILE_BROWSER' ) && true === PODS_DISABLE_FILE_BROWSER )
277
                  || ( defined( 'PODS_FILES_REQUIRE_LOGIN' ) && is_bool( PODS_FILES_REQUIRE_LOGIN ) && true === PODS_FILES_REQUIRE_LOGIN && !is_user_logged_in() )
278
                  || ( defined( 'PODS_FILES_REQUIRE_LOGIN' ) && !is_bool( PODS_FILES_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_FILES_REQUIRE_LOGIN ) ) ) )
279
        ) {
280
            ?>
281
        <p>You do not have access to upload / browse files. Contact your website admin to resolve.</p>
282
        <?php
283
            return;
284
        }
285
286
        // @todo: Now One Field to Rule Them All
287
        $field_type = 'file-upload';
288
        pods_view( PODS_DIR . 'ui/fields-mv/file-upload.php', compact( array_keys( get_defined_vars() ) ) );
289
        return;
290
291
        // @todo: we're short-circuiting for prototyping above.  The actions below will need to be woven in
292
293
        // Use plupload if attachment isn't available
294
        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...
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...
295
            $field_type = 'plupload';
296
        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...
297
            $field_type = 'plupload';
298 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...
299
            if ( !pods_version_check( 'wp', '3.5' ) || !is_admin() ) // @todo test frontend media modal
300
                $field_type = 'attachment';
301
            else
302
                $field_type = 'media';
303
        }
304 View Code Duplication
        else {
305
            // Support custom File Uploader integration
306
            do_action( 'pods_form_ui_field_file_uploader_' . pods_var( self::$type . '_uploader', $options ), $name, $value, $options, $pod, $id );
307
            do_action( 'pods_form_ui_field_file_uploader', pods_var( self::$type . '_uploader', $options ), $name, $value, $options, $pod, $id );
308
            return;
309
        }
310
311
        pods_view( PODS_DIR . 'ui/fields/' . $field_type . '.php', compact( array_keys( get_defined_vars() ) ) );
312
    }
313
314
    /**
315
     * Build regex necessary for JS validation
316
     *
317
     * @param mixed $value
318
     * @param string $name
319
     * @param array $options
320
     * @param string $pod
321
     * @param int $id
322
     *
323
     * @return bool
324
     * @since 2.0
325
     */
326
    public function regex ( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
327
        return false;
328
    }
329
330
    /**
331
     * Validate a value before it's saved
332
     *
333
     * @param mixed $value
334
     * @param string $name
335
     * @param array $options
336
     * @param array $fields
337
     * @param array $pod
338
     * @param int $id
339
     * @param null $params
340
     *
341
     * @return bool
342
     * @since 2.0
343
     */
344
    public function validate ( $value, $name = null, $options = null, $fields = null, $pod = null, $id = null, $params = null ) {
345
        // check file size
346
        // check file extensions
347
        return true;
348
    }
349
350
    /**
351
     * Change the value or perform actions after validation but before saving to the DB
352
     *
353
     * @param mixed $value
354
     * @param int $id
355
     * @param string $name
356
     * @param array $options
357
     * @param array $fields
358
     * @param array $pod
359
     * @param object $params
360
     *
361
     * @return mixed
362
     * @since 2.0
363
     */
364
    public function pre_save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
365
        return $value;
366
    }
367
368
    /**
369
     * Save the value to the DB
370
     *
371
     * @param mixed $value
372
     * @param int $id
373
     * @param string $name
374
     * @param array $options
375
     * @param array $fields
376
     * @param array $pod
377
     * @param object $params
378
     *
379
     * @since 2.3
380
     */
381
    public function save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
382
        if ( empty( self::$api ) )
383
            self::$api = pods_api();
384
385
        // File title / field handling
386
        foreach ( $value as $id ) {
387
            $title = false;
388
389
            if ( is_array( $id ) ) {
390 View Code Duplication
                if ( isset( $id[ 'title' ] ) && 0 < strlen( trim( $id[ 'title' ] ) ) )
391
                    $title = trim( $id[ 'title' ] );
392
393
                if ( isset( $id[ 'id' ] ) )
394
                    $id = (int) $id[ 'id' ];
395
                else
396
                    $id = 0;
397
            }
398
399
            if ( empty( $id ) )
400
                continue;
401
402
            // Update the title if set
403
            if ( false !== $title && 1 == pods_var( self::$type . '_edit_title', $options, 0 ) ) {
404
                $attachment_data = array(
405
                    'ID' => $id,
406
                    'post_title' => $title
407
                );
408
409
                self::$api->save_wp_object( 'media', $attachment_data );
410
            }
411
        }
412
    }
413
414
    /**
415
     * Customize the Pods UI manage table column output
416
     *
417
     * @param int $id
418
     * @param mixed $value
419
     * @param string $name
420
     * @param array $options
421
     * @param array $fields
422
     * @param array $pod
423
     *
424
     * @return mixed|void
425
     * @since 2.0
426
     */
427
    public function ui ( $id, $value, $name = null, $options = null, $fields = null, $pod = null ) {
428
        if ( empty( $value ) )
429
            return;
430
431
        if ( !empty( $value ) && isset( $value[ 'ID' ] ) )
432
            $value = array( $value );
433
434
        $image_size = apply_filters( 'pods_form_ui_field_file_ui_image_size', 'thumbnail', $id, $value, $name, $options, $pod );
435
436
        return $this->images( $id, $value, $name, $options, $pod, $image_size );
437
    }
438
439
    /**
440
     * Return image(s) markup
441
     *
442
     * @param int $id
443
     * @param mixed $value
444
     * @param string $name
445
     * @param array $options
446
     * @param array $pod
447
     * @param string $image_size
448
     *
449
     * @return string
450
     * @since 2.3
451
     */
452
    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...
453
        $images = '';
454
455
        if ( empty( $value ) || !is_array( $value ) )
456
            return $images;
457
458
        foreach ( $value as $v ) {
459
            $images .= pods_image( $v, $image_size );
460
        }
461
462
        return $images;
463
    }
464
465
    /**
466
     * Handle file row output for uploaders
467
     *
468
     * @param array $attributes
469
     * @param int $limit
470
     * @param bool $editable
471
     * @param int $id
472
     * @param string $icon
473
     * @param string $name
474
     *
475
     * @return string
476
     * @since 2.0
477
     */
478
    public function markup ( $attributes, $limit = 1, $editable = true, $id = null, $icon = null, $name = null, $linked = false, $link = null ) {
479
        // Preserve current file type
480
        $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...
481
482
        ob_start();
483
484
        if ( empty( $id ) )
485
            $id = '{{id}}';
486
487
        if ( empty( $icon ) ) {
488
	        $icon = '{{icon}}';
489
        }else{
490
	        $icon = esc_url( $icon );
491
        }
492
493
494
        if ( empty( $name ) )
495
            $name = '{{name}}';
496
497
        if ( empty( $link ) )
498
            $link = '{{link}}';
499
500
        $editable = (boolean) $editable;
501
        $linked = (boolean) $linked;
502
        ?>
503
    <li class="pods-file hidden" id="pods-file-<?php echo esc_attr( $id ); ?>">
504
        <?php echo PodsForm::field( $attributes[ 'name' ] . '[' . $id . '][id]', $id, 'hidden' ); ?>
505
506
        <ul class="pods-file-meta media-item">
507
            <?php if ( 1 != $limit ) { ?>
508
                <li class="pods-file-col pods-file-handle">Handle</li>
509
            <?php } ?>
510
511
            <li class="pods-file-col pods-file-icon">
512
                <img class="pinkynail" src="<?php echo $icon; ?>" alt="Icon" />
513
            </li>
514
515
            <li class="pods-file-col pods-file-name">
516
                <?php
517
                if ( $editable )
518
                    echo PodsForm::field( $attributes[ 'name' ] . '[' . $id . '][title]', $name, 'text' );
519
                else
520
                    echo ( empty( $name ) ? '{{name}}' : $name );
521
                ?>
522
            </li>
523
524
            <li class="pods-file-col pods-file-delete"><a href="#delete">Delete</a></li>
525
526
			<?php
527
				if ( $linked ) {
528
			?>
529
            	<li class="pods-file-col pods-file-download"><a href="<?php echo esc_url( $link ); ?>" target="_blank">Download</a></li>
530
			<?php
531
				}
532
			?>
533
        </ul>
534
    </li>
535
    <?php
536
        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...
537
538
        return ob_get_clean();
539
    }
540
541
    /**
542
     * Handle plupload AJAX
543
     *
544
     * @since 2.3
545
     */
546
    public function admin_ajax_upload () {
547
		pods_session_start();
548
549
        // Sanitize input
550
        $params = pods_unslash( (array) $_POST );
551
552 View Code Duplication
        foreach ( $params as $key => $value ) {
553
            if ( 'action' == $key )
554
                continue;
555
556
            unset( $params[ $key ] );
557
558
            $params[ str_replace( '_podsfix_', '', $key ) ] = $value;
559
        }
560
561
        $params = (object) $params;
562
563
        $methods = array(
564
            'upload',
565
        );
566
567
        if ( !isset( $params->method ) || !in_array( $params->method, $methods ) || !isset( $params->pod ) || !isset( $params->field ) || !isset( $params->uri ) || empty( $params->uri ) )
568
            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...
569
        elseif ( !empty( $params->pod ) && empty( $params->field ) )
570
            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...
571
        elseif ( empty( $params->pod ) && !current_user_can( 'upload_files' ) )
572
            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...
573
574
        // Flash often fails to send cookies with the POST or upload, so we need to pass it in GET or POST instead
575
        if ( is_ssl() && empty( $_COOKIE[ SECURE_AUTH_COOKIE ] ) && !empty( $_REQUEST[ 'auth_cookie' ] ) )
576
            $_COOKIE[ SECURE_AUTH_COOKIE ] = $_REQUEST[ 'auth_cookie' ];
577
        elseif ( empty( $_COOKIE[ AUTH_COOKIE ] ) && !empty( $_REQUEST[ 'auth_cookie' ] ) )
578
            $_COOKIE[ AUTH_COOKIE ] = $_REQUEST[ 'auth_cookie' ];
579
580
        if ( empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) && !empty( $_REQUEST[ 'logged_in_cookie' ] ) )
581
            $_COOKIE[ LOGGED_IN_COOKIE ] = $_REQUEST[ 'logged_in_cookie' ];
582
583
        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...
584
        unset( $current_user );
585
586
        /**
587
         * Access Checking
588
         */
589
        $upload_disabled = false;
590
591
        if ( defined( 'PODS_DISABLE_FILE_UPLOAD' ) && true === PODS_DISABLE_FILE_UPLOAD )
592
            $upload_disabled = true;
593 View Code Duplication
        elseif ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && true === PODS_UPLOAD_REQUIRE_LOGIN && !is_user_logged_in() )
594
            $upload_disabled = true;
595 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 ) ) )
596
            $upload_disabled = true;
597
598
        $uid = @session_id();
599
600
        if ( is_user_logged_in() )
601
            $uid = 'user_' . get_current_user_id();
602
603
        $nonce_check = 'pods_upload_' . (int) $params->pod . '_' . $uid . '_' . $params->uri . '_' . (int) $params->field;
604
605 View Code Duplication
        if ( true === $upload_disabled || !isset( $params->_wpnonce ) || false === wp_verify_nonce( $params->_wpnonce, $nonce_check ) )
606
            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...
607
608
        $pod = array();
609
        $field = array(
610
            'type' => 'file',
611
            'options' => array()
612
        );
613
614
        $api = pods_api();
615
616
	    $api->display_errors = false;
617
618
        if ( !empty( $params->pod ) ) {
619
            $pod = $api->load_pod( array( 'id' => (int) $params->pod ) );
620
            $field = $api->load_field( array( 'id' => (int) $params->field ) );
621
622 View Code Duplication
            if ( empty( $pod ) || empty( $field ) || $pod[ 'id' ] != $field[ 'pod_id' ] || !isset( $pod[ 'fields' ][ $field[ 'name' ] ] ) )
623
                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...
624
625
            if ( !in_array( $field[ 'type' ], PodsForm::file_field_types() ) )
626
                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...
627
        }
628
629
        $method = $params->method;
630
631
        // Cleaning up $params
632
        unset( $params->action );
633
        unset( $params->method );
634
        unset( $params->_wpnonce );
635
636
        $params->post_id = pods_var( 'post_id', $params, 0, null, true );
637
638
        /**
639
         * Upload a new file (advanced - returns URL and ID)
640
         */
641
        if ( 'upload' == $method ) {
642
            $file = $_FILES[ 'Filedata' ];
643
644
            $limit_size = pods_var( $field[ 'type' ] . '_restrict_filesize', $field[ 'options' ] );
645
646
            if ( !empty( $limit_size ) ) {
647
                if ( false !== stripos( $limit_size, 'MB' ) ) {
648
                    $limit_size = (float) trim( str_ireplace( 'MB', '', $limit_size ) );
649
                    $limit_size = $limit_size * 1025 * 1025; // convert to KB to B
650
                }
651 View Code Duplication
                elseif ( false !== stripos( $limit_size, 'KB' ) ) {
652
                    $limit_size = (float) trim( str_ireplace( 'KB', '', $limit_size ) );
653
                    $limit_size = $limit_size * 1025 * 1025; // convert to B
654
                }
655 View Code Duplication
                elseif ( false !== stripos( $limit_size, 'GB' ) ) {
656
                    $limit_size = (float) trim( str_ireplace( 'GB', '', $limit_size ) );
657
                    $limit_size = $limit_size * 1025 * 1025 * 1025; // convert to MB to KB to B
658
                }
659
                elseif ( false !== stripos( $limit_size, 'B' ) )
660
                    $limit_size = (float) trim( str_ireplace( 'B', '', $limit_size ) );
661
                else
662
                    $limit_size = wp_max_upload_size();
663
664
                if ( 0 < $limit_size && $limit_size < $file[ 'size' ] ) {
665
                    $error = __( 'File size too large, max size is %s', 'pods' );
666
                    $error = sprintf( $error, pods_var( $field[ 'type' ] . '_restrict_filesize', $field[ 'options' ] ) );
667
668
                    pods_error( '<div style="color:#FF0000">Error: ' . $error . '</div>' );
669
                }
670
            }
671
672
            $limit_file_type = pods_var( $field[ 'type' ] . '_type', $field[ 'options' ], 'images' );
673
674
            if ( 'images' == $limit_file_type )
675
                $limit_types = 'jpg,jpeg,png,gif';
676
            elseif ( 'video' == $limit_file_type )
677
                $limit_types = 'mpg,mov,flv,mp4';
678
            elseif ( 'audio' == $limit_file_type )
679
                $limit_types = 'mp3,m4a,wav,wma';
680
            elseif ( 'text' == $limit_file_type )
681
                $limit_types = 'txt,rtx,csv,tsv';
682
            elseif ( 'any' == $limit_file_type )
683
                $limit_types = '';
684
            else
685
                $limit_types = pods_var( $field[ 'type' ] . '_allowed_extensions', $field[ 'options' ], '', null, true );
686
687
            $limit_types = trim( str_replace( array( ' ', '.', "\n", "\t", ';' ), array( '', ',', ',', ',' ), $limit_types ), ',' );
688
689 View Code Duplication
            if ( pods_version_check( 'wp', '3.5' ) ) {
690
                $mime_types = wp_get_mime_types();
691
692
                if ( in_array( $limit_file_type, array( 'images', 'audio', 'video' ) ) ) {
693
                    $new_limit_types = array();
694
695
                    foreach ( $mime_types as $type => $mime ) {
696
                        if ( 0 === strpos( $mime, $limit_file_type ) ) {
697
                            $type = explode( '|', $type );
698
699
                            $new_limit_types = array_merge( $new_limit_types, $type );
700
                        }
701
                    }
702
703
                    if ( !empty( $new_limit_types ) )
704
                        $limit_types = implode( ',', $new_limit_types );
705
                }
706
                elseif ( 'any' != $limit_file_type ) {
707
                    $new_limit_types = array();
708
709
                    $limit_types = explode( ',', $limit_types );
710
711
                    foreach ( $limit_types as $k => $limit_type ) {
712
                        $found = false;
713
714
                        foreach ( $mime_types as $type => $mime ) {
715
                            if ( 0 === strpos( $mime, $limit_type ) ) {
716
                                $type = explode( '|', $type );
717
718
                                foreach ( $type as $t ) {
719
                                    if ( !in_array( $t, $new_limit_types ) )
720
                                        $new_limit_types[] = $t;
721
                                }
722
723
                                $found = true;
724
                            }
725
                        }
726
727
                        if ( !$found )
728
                            $new_limit_types[] = $limit_type;
729
                    }
730
731
                    if ( !empty( $new_limit_types ) )
732
                        $limit_types = implode( ',', $new_limit_types );
733
                }
734
            }
735
736
            $limit_types = explode( ',', $limit_types );
737
738
            $limit_types = array_filter( array_unique( $limit_types ) );
739
740
            if ( !empty( $limit_types ) ) {
741
                $ok = false;
742
743
                foreach ( $limit_types as $limit_type ) {
744
                    $limit_type = '.' . trim( $limit_type, ' .' );
745
746
                    $pos = ( strlen( $file[ 'name' ] ) - strlen( $limit_type ) );
747
748
                    if ( $pos === stripos( $file[ 'name' ], $limit_type ) ) {
749
                        $ok = true;
750
751
                        break;
752
                    }
753
                }
754
755
                if ( false === $ok ) {
756
                    $error = __( 'File type not allowed, please use one of the following: %s', 'pods' );
757
                    $error = sprintf( $error, '.' . implode( ', .', $limit_types ) );
758
759
                    pods_error( '<div style="color:#FF0000">Error: ' . $error . '</div>' );
760
                }
761
            }
762
763
            $custom_handler = apply_filters( 'pods_upload_handle', null, 'Filedata', $params->post_id, $params, $field );
764
765
            if ( null === $custom_handler ) {
766
				$linked = pods_var( $field[ 'type' ] . '_linked', $field[ 'options' ], 0 );
767
768
                $attachment_id = media_handle_upload( 'Filedata', $params->post_id );
769
770
                if ( is_object( $attachment_id ) ) {
771
                    $errors = array();
772
773
                    foreach ( $attachment_id->errors[ 'upload_error' ] as $error_code => $error_message ) {
774
                        $errors[] = '[' . $error_code . '] ' . $error_message;
775
                    }
776
777
                    pods_error( '<div style="color:#FF0000">Error: ' . implode( '</div><div>', $errors ) . '</div>' );
778
                }
779
                else {
780
                    $attachment = get_post( $attachment_id, ARRAY_A );
781
782
                    $attachment[ 'filename' ] = basename( $attachment[ 'guid' ] );
783
784
                    $thumb = wp_get_attachment_image_src( $attachment[ 'ID' ], 'thumbnail', true );
785
                    $attachment[ 'thumbnail' ] = $thumb[ 0 ];
786
787
					$attachment[ 'link' ] = '';
788
789
					if ( $linked ) {
790
                    	$attachment[ 'link' ] = wp_get_attachment_url( $attachment[ 'ID' ] );
791
					}
792
793
                    $attachment = apply_filters( 'pods_upload_attachment', $attachment, $params->post_id );
794
795
                    wp_send_json( $attachment );
796
                }
797
            }
798
        }
799
800
        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...
801
    }
802
}
803