GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — integration ( a3ab80...7a98f7 )
by Brendan
06:22
created

FieldUpload::processRawFieldData()   D

Complexity

Conditions 25
Paths 64

Size

Total Lines 159
Code Lines 86

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 25
eloc 86
c 5
b 0
f 0
nc 64
nop 5
dl 0
loc 159
rs 4.5682

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
    /**
4
     * @package toolkit
5
     */
6
7
    /**
8
     * A simple Upload field that essentially maps to HTML's `<input type='file '/>`.
9
     */
10
    class FieldUpload extends Field implements ExportableField, ImportableField
11
    {
12
        protected static $imageMimeTypes = array(
13
            'image/gif',
14
            'image/jpg',
15
            'image/jpeg',
16
            'image/pjpeg',
17
            'image/png',
18
            'image/x-png'
19
        );
20
21 View Code Duplication
        public function __construct()
22
        {
23
            parent::__construct();
24
25
            $this->_name = __('File Upload');
0 ignored issues
show
Bug introduced by
The property _name does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
26
            $this->_required = true;
27
28
            $this->set('location', 'sidebar');
29
            $this->set('required', 'no');
30
        }
31
32
        /*-------------------------------------------------------------------------
33
            Definition:
34
        -------------------------------------------------------------------------*/
35
36
        public function canFilter()
37
        {
38
            return true;
39
        }
40
41
        public function canPrePopulate()
42
        {
43
            return true;
44
        }
45
46
        public function isSortable()
47
        {
48
            return true;
49
        }
50
51
        public function fetchFilterableOperators()
52
        {
53
            return array(
54
                array(
55
                    'title' => 'is',
56
                    'filter' => ' ',
57
                    'help' => __('Find files that are an exact match for the given string.')
58
                ),
59
                array(
60
                    'title' => 'contains',
61
                    'filter' => 'regexp: ',
62
                    'help' => __('Find files that match the given <a href="%s">MySQL regular expressions</a>.', array(
63
                        'http://dev.mysql.com/doc/mysql/en/Regexp.html'
64
                    ))
65
                ),
66
                array(
67
                    'title' => 'does not contain',
68
                    'filter' => 'not-regexp: ',
69
                    'help' => __('Find files that do not match the given <a href="%s">MySQL regular expressions</a>.',
70
                        array(
71
                            'http://dev.mysql.com/doc/mysql/en/Regexp.html'
72
                        ))
73
                ),
74
                array(
75
                    'title' => 'file type is',
76
                    'filter' => 'mimetype: ',
77
                    'help' => __('Find files that match the given mimetype.')
78
                ),
79
                array(
80
                    'title' => 'size is',
81
                    'filter' => 'size: ',
82
                    'help' => __('Find files that match the given size.')
83
                )
84
            );
85
        }
86
87
        /*-------------------------------------------------------------------------
88
            Setup:
89
        -------------------------------------------------------------------------*/
90
91
        public function createTable()
92
        {
93
            return Symphony::Database()->query(
94
                "CREATE TABLE IF NOT EXISTS `tbl_entries_data_" . $this->get('id') . "` (
95
              `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
96
              `entry_id` INT(11) UNSIGNED NOT NULL,
97
              `file` VARCHAR(255) DEFAULT NULL,
98
              `size` INT(11) UNSIGNED NULL,
99
              `mimetype` VARCHAR(100) DEFAULT NULL,
100
              `meta` VARCHAR(255) DEFAULT NULL,
101
              PRIMARY KEY  (`id`),
102
              UNIQUE KEY `entry_id` (`entry_id`),
103
              KEY `file` (`file`),
104
              KEY `mimetype` (`mimetype`)
105
            )"
106
            );
107
        }
108
109
        /*-------------------------------------------------------------------------
110
            Utilities:
111
        -------------------------------------------------------------------------*/
112
113
        public function entryDataCleanup($entry_id, $data = null)
114
        {
115
            $file_location = $this->getFilePath($data['file']);
116
117
            if (is_file($file_location)) {
118
                General::deleteFile($file_location);
119
            }
120
121
            parent::entryDataCleanup($entry_id);
122
123
            return true;
124
        }
125
126
        public function getFilePath($filename)
127
        {
128
            /**
129
             * Ensure the file exists in the `WORKSPACE` directory
130
             *
131
             * @link http://getsymphony.com/discuss/issues/view/610/
132
             */
133
            $file = WORKSPACE . preg_replace(array('%/+%', '%(^|/)\.\./%', '%\/workspace\/%'), '/',
134
                    $this->get('destination') . '/' . $filename);
135
136
            return $file;
137
        }
138
139
        public function displaySettingsPanel(XMLElement &$wrapper, $errors = null)
140
        {
141
            parent::displaySettingsPanel($wrapper, $errors);
142
143
            // Destination Folder
144
            $ignore = array(
145
                '/workspace/events',
146
                '/workspace/data-sources',
147
                '/workspace/text-formatters',
148
                '/workspace/pages',
149
                '/workspace/utilities'
150
            );
151
            $directories = General::listDirStructure(WORKSPACE, null, true, DOCROOT, $ignore);
152
153
            $label = Widget::Label(__('Destination Directory'));
154
155
            $options = array();
156
            $options[] = array('/workspace', false, '/workspace');
157
158
            if (!empty($directories) && is_array($directories)) {
159
                foreach ($directories as $d) {
160
                    $d = '/' . trim($d, '/');
161
162
                    if (!in_array($d, $ignore)) {
163
                        $options[] = array($d, ($this->get('destination') === $d), $d);
164
                    }
165
                }
166
            }
167
168
            $label->appendChild(Widget::Select('fields[' . $this->get('sortorder') . '][destination]', $options));
169
170 View Code Duplication
            if (isset($errors['destination'])) {
171
                $wrapper->appendChild(Widget::Error($label, $errors['destination']));
172
            } else {
173
                $wrapper->appendChild($label);
174
            }
175
176
            // Validation rule
177
            $this->buildValidationSelect($wrapper, $this->get('validator'),
178
                'fields[' . $this->get('sortorder') . '][validator]', 'upload', $errors);
179
180
            // Requirements and table display
181
            $this->appendStatusFooter($wrapper);
182
        }
183
184
        /*-------------------------------------------------------------------------
185
            Settings:
186
        -------------------------------------------------------------------------*/
187
188
        public function checkFields(array &$errors, $checkForDuplicates = true)
189
        {
190
            if (is_dir(DOCROOT . $this->get('destination') . '/') === false) {
191
                $errors['destination'] = __('The destination directory, %s, does not exist.', array(
192
                    '<code>' . $this->get('destination') . '</code>'
193
                ));
194 View Code Duplication
            } elseif (is_writable(DOCROOT . $this->get('destination') . '/') === false) {
195
                $errors['destination'] = __('The destination directory is not writable.')
196
                    . ' '
197
                    . __('Please check permissions on %s.', array(
198
                        '<code>' . $this->get('destination') . '</code>'
199
                    ));
200
            }
201
202
            parent::checkFields($errors, $checkForDuplicates);
203
        }
204
205 View Code Duplication
        public function commit()
206
        {
207
            if (!parent::commit()) {
208
                return false;
209
            }
210
211
            $id = $this->get('id');
212
213
            if ($id === false) {
214
                return false;
215
            }
216
217
            $fields = array();
218
219
            $fields['destination'] = $this->get('destination');
220
            $fields['validator'] = ($fields['validator'] === 'custom' ? null : $this->get('validator'));
221
222
            return FieldManager::saveSettings($id, $fields);
223
        }
224
225
        public function displayPublishPanel(
226
            XMLElement &$wrapper,
227
            $data = null,
228
            $flagWithError = null,
229
            $fieldnamePrefix = null,
230
            $fieldnamePostfix = null,
231
            $entry_id = null
232
        ) {
233
            if (is_dir(DOCROOT . $this->get('destination') . '/') === false) {
234
                $flagWithError = __('The destination directory, %s, does not exist.', array(
235
                    '<code>' . $this->get('destination') . '</code>'
236
                ));
237 View Code Duplication
            } elseif ($flagWithError && is_writable(DOCROOT . $this->get('destination') . '/') === false) {
238
                $flagWithError = __('Destination folder is not writable.')
239
                    . ' '
240
                    . __('Please check permissions on %s.', array(
241
                        '<code>' . $this->get('destination') . '</code>'
242
                    ));
243
            }
244
245
            $label = Widget::Label($this->get('label'));
246
            $label->setAttribute('class', 'file');
247
248
            if ($this->get('required') !== 'yes') {
249
                $label->appendChild(new XMLElement('i', __('Optional')));
250
            }
251
252
            $span = new XMLElement('span', null, array('class' => 'frame'));
253
254
            if (isset($data['file'])) {
255
                $filename = $this->get('destination') . '/' . basename($data['file']);
256
                $file = $this->getFilePath($data['file']);
257
                if (file_exists($file) === false || !is_readable($file)) {
258
                    $flagWithError = __('The file uploaded is no longer available. Please check that it exists, and is readable.');
259
                }
260
261
                $span->appendChild(new XMLElement('span',
262
                    Widget::Anchor(preg_replace("![^a-z0-9]+!i", "$0&#8203;", $filename), URL . $filename)));
263
            } else {
264
                $filename = null;
265
            }
266
267
            $span->appendChild(Widget::Input('fields' . $fieldnamePrefix . '[' . $this->get('element_name') . ']' . $fieldnamePostfix,
268
                $filename, ($filename ? 'hidden' : 'file')));
269
270
            $label->appendChild($span);
271
272
            if ($flagWithError !== null) {
273
                $wrapper->appendChild(Widget::Error($label, $flagWithError));
274
            } else {
275
                $wrapper->appendChild($label);
276
            }
277
        }
278
279
        /*-------------------------------------------------------------------------
280
            Publish:
281
        -------------------------------------------------------------------------*/
282
283
        public function checkPostFieldData($data, &$message, $entry_id = null)
0 ignored issues
show
Coding Style introduced by
checkPostFieldData uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
284
        {
285
            /**
286
             * For information about PHPs upload error constants see:
287
             *
288
             * @link http://php.net/manual/en/features.file-upload.errors.php
289
             */
290
            $message = null;
291
292
            if (
293
                empty($data)
294
                || (
295
                    is_array($data)
296
                    && isset($data['error'])
297
                    && $data['error'] === UPLOAD_ERR_NO_FILE
298
                )
299
            ) {
300 View Code Duplication
                if ($this->get('required') === 'yes') {
301
                    $message = __('‘%s’ is a required field.', array($this->get('label')));
302
303
                    return self::__MISSING_FIELDS__;
304
                }
305
306
                return self::__OK__;
307
            }
308
309
            // Its not an array, so just retain the current data and return
310
            if (is_array($data) === false) {
311
                $file = $this->getFilePath(basename($data));
312
                if (file_exists($file) === false || !is_readable($file)) {
313
                    $message = __('The file uploaded is no longer available. Please check that it exists, and is readable.');
314
315
                    return self::__INVALID_FIELDS__;
316
                }
317
318
                // Ensure that the file still matches the validator and hasn't
319
                // changed since it was uploaded.
320
                return $this->validateFilename($file, $message);
321
            }
322
323
            if (is_dir(DOCROOT . $this->get('destination') . '/') === false) {
324
                $message = __('The destination directory, %s, does not exist.', array(
325
                    '<code>' . $this->get('destination') . '</code>'
326
                ));
327
328
                return self::__ERROR__;
329 View Code Duplication
            } elseif (is_writable(DOCROOT . $this->get('destination') . '/') === false) {
330
                $message = __('Destination folder is not writable.')
331
                    . ' '
332
                    . __('Please check permissions on %s.', array(
333
                        '<code>' . $this->get('destination') . '</code>'
334
                    ));
335
336
                return self::__ERROR__;
337
            }
338
339
            if ($data['error'] !== UPLOAD_ERR_NO_FILE && $data['error'] !== UPLOAD_ERR_OK) {
340
                switch ($data['error']) {
341
                    case UPLOAD_ERR_INI_SIZE:
342
                        $message = __('File chosen in ‘%1$s’ exceeds the maximum allowed upload size of %2$s specified by your host.',
343
                            array(
344
                                $this->get('label'),
345
                                (is_numeric(ini_get('upload_max_filesize')) ? General::formatFilesize(ini_get('upload_max_filesize')) : ini_get('upload_max_filesize'))
346
                            ));
347
                        break;
348
                    case UPLOAD_ERR_FORM_SIZE:
349
                        $message = __('File chosen in ‘%1$s’ exceeds the maximum allowed upload size of %2$s, specified by Symphony.',
350
                            array($this->get('label'), General::formatFilesize($_POST['MAX_FILE_SIZE'])));
351
                        break;
352
                    case UPLOAD_ERR_PARTIAL:
353
                    case UPLOAD_ERR_NO_TMP_DIR:
354
                        $message = __('File chosen in ‘%s’ was only partially uploaded due to an error.',
355
                            array($this->get('label')));
356
                        break;
357
                    case UPLOAD_ERR_CANT_WRITE:
358
                        $message = __('Uploading ‘%s’ failed. Could not write temporary file to disk.',
359
                            array($this->get('label')));
360
                        break;
361
                    case UPLOAD_ERR_EXTENSION:
362
                        $message = __('Uploading ‘%s’ failed. File upload stopped by extension.',
363
                            array($this->get('label')));
364
                        break;
365
                }
366
367
                return self::__ERROR_CUSTOM__;
368
            }
369
370
            // Sanitize the filename
371
            $data['name'] = Lang::createFilename($data['name']);
372
373
            // Validate the filename
374
            return $this->validateFilename($data['name'], $message);
375
        }
376
377
        public function validateFilename($file, &$message)
378
        {
379
            if ($this->get('validator') !== null) {
380
                $rule = $this->get('validator');
381
382 View Code Duplication
                if (General::validateString($file, $rule) === false) {
383
                    $message = __('File chosen in ‘%s’ does not match allowable file types for that field.', array(
384
                        $this->get('label')
385
                    ));
386
387
                    return self::__INVALID_FIELDS__;
388
                }
389
            }
390
            // If the developer did not specified any validator, check for the
391
            // blacklisted file types instead
392
            else {
393
                $blacklist = Symphony::Configuration()->get('upload_blacklist', 'admin');
394
395 View Code Duplication
                if (!empty($blacklist) && General::validateString($file, $blacklist)) {
396
                    $message = __('File chosen in ‘%s’ is blacklisted for that field.', array(
397
                        $this->get('label')
398
                    ));
399
400
                    return self::__INVALID_FIELDS__;
401
                }
402
            }
403
404
            return self::__OK__;
405
        }
406
407
        public function appendFormattedElement(
408
            XMLElement &$wrapper,
409
            $data,
410
            $encode = false,
411
            $mode = null,
412
            $entry_id = null
413
        ) {
414
            // It is possible an array of null data will be passed in. Check for this.
415
            if (!is_array($data) || !isset($data['file']) || is_null($data['file'])) {
416
                return;
417
            }
418
419
            $file = $this->getFilePath($data['file']);
420
            $filesize = (file_exists($file) && is_readable($file)) ? filesize($file) : null;
421
            $item = new XMLElement($this->get('element_name'));
422
            $item->setAttributeArray(array(
423
                'size' => !is_null($filesize) ? General::formatFilesize($filesize) : 'unknown',
424
                'bytes' => !is_null($filesize) ? $filesize : 'unknown',
425
                'path' => General::sanitize(
426
                    str_replace(WORKSPACE, null, dirname($file))
427
                ),
428
                'type' => $data['mimetype']
429
            ));
430
431
            $item->appendChild(new XMLElement('filename', General::sanitize(basename($file))));
432
433
            $m = unserialize($data['meta']);
434
435
            if (is_array($m) && !empty($m)) {
436
                $item->appendChild(new XMLElement('meta', null, $m));
437
            }
438
439
            $wrapper->appendChild($item);
440
        }
441
442
        public function prepareTableValue($data, XMLElement $link = null, $entry_id = null)
443
        {
444
            if (isset($data['file']) === false || !$file = $data['file']) {
445
                return parent::prepareTableValue(null, $link, $entry_id);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
446
            }
447
448
            if ($link) {
449
                $link->setValue(basename($file));
450
                $link->setAttribute('data-path', $this->get('destination'));
451
452
                return $link->generate();
453
            } else {
454
                $link = Widget::Anchor(basename($file), URL . $this->get('destination') . '/' . $file);
455
                $link->setAttribute('data-path', $this->get('destination'));
456
457
                return $link->generate();
458
            }
459
        }
460
461
        /*-------------------------------------------------------------------------
462
            Output:
463
        -------------------------------------------------------------------------*/
464
465
        public function prepareTextValue($data, $entry_id = null)
466
        {
467
            if (isset($data['file'])) {
468
                return $data['file'];
469
            }
470
471
            return null;
472
        }
473
474
        public function prepareAssociationsDrawerXMLElement(Entry $e, array $parent_association, $prepopulate = '')
475
        {
476
            $li = parent::prepareAssociationsDrawerXMLElement($e, $parent_association);
477
            $a = $li->getChild(0);
478
            $a->setAttribute('data-path', $this->get('destination'));
479
480
            return $li;
481
        }
482
483 View Code Duplication
        public function prepareImportValue($data, $mode, $entry_id = null)
484
        {
485
            $message = $status = null;
486
            $modes = (object)$this->getImportModes();
487
488
            if ($mode === $modes->getValue) {
489
                return $data;
490
            } elseif ($mode === $modes->getPostdata) {
491
                return $this->processRawFieldData($data, $status, $message, true, $entry_id);
492
            }
493
494
            return null;
495
        }
496
497
        public function getImportModes()
498
        {
499
            return array(
500
                'getValue' => ImportableField::STRING_VALUE,
501
                'getPostdata' => ImportableField::ARRAY_VALUE
502
            );
503
        }
504
505
        /*-------------------------------------------------------------------------
506
            Import:
507
        -------------------------------------------------------------------------*/
508
509
        public function processRawFieldData($data, &$status, &$message = null, $simulate = false, $entry_id = null)
510
        {
511
            $status = self::__OK__;
512
513
            // No file given, save empty data:
514
            if ($data === null) {
515
                return array(
516
                    'file' => null,
517
                    'mimetype' => null,
518
                    'size' => null,
519
                    'meta' => null
520
                );
521
            }
522
523
            // Its not an array, so just retain the current data and return:
524
            if (is_array($data) === false) {
525
                $file = $this->getFilePath(basename($data));
526
527
                $result = array(
528
                    'file' => $data,
529
                    'mimetype' => null,
530
                    'size' => null,
531
                    'meta' => null
532
                );
533
534
                // Grab the existing entry data to preserve the MIME type and size information
535
                if (isset($entry_id)) {
536
                    $row = Symphony::Database()->fetchRow(0, sprintf(
537
                        "SELECT `file`, `mimetype`, `size`, `meta` FROM `tbl_entries_data_%d` WHERE `entry_id` = ?",
538
                        $this->get('id')
539
                    ),
540
                        array($entry_id)
541
                    );
542
543
                    if (empty($row) === false) {
544
                        $result = $row;
545
                    }
546
                }
547
548
                // Found the file, add any missing meta information:
549
                if (file_exists($file) && is_readable($file)) {
550
                    if (empty($result['mimetype'])) {
551
                        $result['mimetype'] = General::getMimeType($file);
552
                    }
553
554
                    if (empty($result['size'])) {
555
                        $result['size'] = filesize($file);
556
                    }
557
558
                    if (empty($result['meta'])) {
559
                        $result['meta'] = serialize(static::getMetaInfo($file, $result['mimetype']));
560
                    }
561
562
                    // The file was not found, or is unreadable:
563
                } else {
564
                    $message = __('The file uploaded is no longer available. Please check that it exists, and is readable.');
565
                    $status = self::__INVALID_FIELDS__;
566
                }
567
568
                return $result;
569
            }
570
571
            if ($simulate && is_null($entry_id)) {
572
                return $data;
573
            }
574
575
            // Check to see if the entry already has a file associated with it:
576
            if (is_null($entry_id) === false) {
577
                $row = Symphony::Database()->fetchRow(0, sprintf(
578
                    "SELECT * FROM `tbl_entries_data_%s` WHERE `entry_id` = ? LIMIT 1",
579
                    $this->get('id')
580
                ),
581
                    array($entry_id)
582
                );
583
584
                $existing_file = isset($row['file']) ? $this->getFilePath($row['file']) : null;
585
586
                // File was removed:
587
                if (
588
                    $data['error'] === UPLOAD_ERR_NO_FILE
589
                    && !is_null($existing_file)
590
                    && is_file($existing_file)
591
                ) {
592
                    General::deleteFile($existing_file);
593
                }
594
            }
595
596
            // Do not continue on upload error:
597
            if ($data['error'] === UPLOAD_ERR_NO_FILE || $data['error'] !== UPLOAD_ERR_OK) {
598
                return false;
599
            }
600
601
            // Where to upload the new file?
602
            $abs_path = DOCROOT . '/' . trim($this->get('destination'), '/');
603
            $rel_path = str_replace('/workspace', '', $this->get('destination'));
604
605
            // Sanitize the filename
606
            $data['name'] = Lang::createFilename($data['name']);
607
608
            // If a file already exists, then rename the file being uploaded by
609
            // adding `_1` to the filename. If `_1` already exists, the logic
610
            // will keep adding 1 until a filename is available (#672)
611
            if (file_exists($abs_path . '/' . $data['name'])) {
612
                $extension = General::getExtension($data['name']);
613
                $new_file = substr($abs_path . '/' . $data['name'], 0, -1 - strlen($extension));
614
                $renamed_file = $new_file;
0 ignored issues
show
Unused Code introduced by
$renamed_file is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
615
                $count = 1;
616
617
                do {
618
                    $renamed_file = $new_file . '_' . $count . '.' . $extension;
619
                    $count++;
620
                } while (file_exists($renamed_file));
621
622
                // Extract the name filename from `$renamed_file`.
623
                $data['name'] = str_replace($abs_path . '/', '', $renamed_file);
624
            }
625
626
            $file = $this->getFilePath($data['name']);
627
628
            // Attempt to upload the file:
629
            $uploaded = General::uploadFile(
630
                $abs_path,
631
                $data['name'],
632
                $data['tmp_name'],
633
                Symphony::Configuration()->get('write_mode', 'file')
0 ignored issues
show
Documentation introduced by
\Symphony::Configuration...t('write_mode', 'file') is of type array|string, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
634
            );
635
636
            if ($uploaded === false) {
637
                $message = __(
638
                    __('There was an error while trying to upload the file %1$s to the target directory %2$s.'),
639
                    array(
640
                        '<code>' . $data['name'] . '</code>',
641
                        '<code>workspace/' . ltrim($rel_path, '/') . '</code>'
642
                    )
643
                );
644
                $status = self::__ERROR_CUSTOM__;
645
646
                return false;
647
            }
648
649
            // File has been replaced:
650
            if (
651
                isset($existing_file)
652
                && $existing_file !== $file
653
                && is_file($existing_file)
654
            ) {
655
                General::deleteFile($existing_file);
656
            }
657
658
            // Get the mimetype, don't trust the browser. RE: #1609
659
            $data['type'] = General::getMimeType($file);
660
661
            return array(
662
                'file' => basename($file),
663
                'size' => $data['size'],
664
                'mimetype' => $data['type'],
665
                'meta' => serialize(static::getMetaInfo($file, $data['type']))
666
            );
667
        }
668
669
        public static function getMetaInfo($file, $type)
670
        {
671
            $meta = array();
672
673
            if (!file_exists($file) || !is_readable($file)) {
674
                return $meta;
675
            }
676
677
            $meta['creation'] = DateTimeObj::get('c', filemtime($file));
678
679
            if (General::in_iarray($type, FieldUpload::$imageMimeTypes) && $array = @getimagesize($file)) {
680
                $meta['width'] = $array[0];
681
                $meta['height'] = $array[1];
682
            }
683
684
            return $meta;
685
        }
686
687
        /*-------------------------------------------------------------------------
688
            Export:
689
        -------------------------------------------------------------------------*/
690
691
        /**
692
         * Give the field some data and ask it to return a value using one of many
693
         * possible modes.
694
         *
695
         * @param mixed $data
696
         * @param integer $mode
697
         * @param integer $entry_id
698
         * @return array|string|null
699
         */
700
        public function prepareExportValue($data, $mode, $entry_id = null)
701
        {
702
            $modes = (object)$this->getExportModes();
703
704
            $filepath = $this->getFilePath($data['file']);
705
706
            // No file, or the file that the entry is meant to have no
707
            // longer exists.
708
            if (!isset($data['file']) || !is_file($filepath)) {
709
                return null;
710
            }
711
712
            if ($mode === $modes->getFilename) {
713
                return $data['file'];
714
            }
715
716
            if ($mode === $modes->getObject) {
717
                $object = (object)$data;
718
719
                if (isset($object->meta)) {
720
                    $object->meta = unserialize($object->meta);
721
                }
722
723
                return $object;
724
            }
725
726
            if ($mode === $modes->getPostdata) {
727
                return $data['file'];
728
            }
729
        }
730
731
        /**
732
         * Return a list of supported export modes for use with `prepareExportValue`.
733
         *
734
         * @return array
735
         */
736
        public function getExportModes()
737
        {
738
            return array(
739
                'getFilename' => ExportableField::VALUE,
740
                'getObject' => ExportableField::OBJECT,
741
                'getPostdata' => ExportableField::POSTDATA
742
            );
743
        }
744
745
        /*-------------------------------------------------------------------------
746
            Filtering:
747
        -------------------------------------------------------------------------*/
748
749
        public function buildDSRetrievalSQL($data, &$joins, &$where, $andOperation = false)
750
        {
751
            $field_id = $this->get('id');
752
753
            if (preg_match('/^mimetype:/', $data[0])) {
754
                $data[0] = str_replace('mimetype:', '', $data[0]);
755
                $column = 'mimetype';
756
            } elseif (preg_match('/^size:/', $data[0])) {
757
                $data[0] = str_replace('size:', '', $data[0]);
758
                $column = 'size';
759
            } else {
760
                $column = 'file';
761
            }
762
763
            if (self::isFilterRegex($data[0])) {
764
                $this->buildRegexSQL($data[0], array($column), $joins, $where);
765
            } elseif ($andOperation) {
766
                foreach ($data as $value) {
767
                    $this->_key++;
768
                    $value = $this->cleanValue($value);
769
                    $joins .= "
770
                    LEFT JOIN
771
                        `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}
772
                        ON (e.id = t{$field_id}_{$this->_key}.entry_id)
773
                ";
774
                    $where .= "
775
                    AND t{$field_id}_{$this->_key}.{$column} = '{$value}'
776
                ";
777
                }
778
            } else {
779
                if (!is_array($data)) {
780
                    $data = array($data);
781
                }
782
783
                foreach ($data as &$value) {
784
                    $value = $this->cleanValue($value);
785
                }
786
787
                $this->_key++;
788
                $data = implode("', '", $data);
789
                $joins .= "
790
                LEFT JOIN
791
                    `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}
792
                    ON (e.id = t{$field_id}_{$this->_key}.entry_id)
793
            ";
794
                $where .= "
795
                AND t{$field_id}_{$this->_key}.{$column} IN ('{$data}')
796
            ";
797
            }
798
799
            return true;
800
        }
801
802
        /*-------------------------------------------------------------------------
803
            Sorting:
804
        -------------------------------------------------------------------------*/
805
806
        public function buildSortingSQL(&$joins, &$where, &$sort, $order = 'ASC')
807
        {
808
            if (in_array(strtolower($order), array('random', 'rand'))) {
809
                $sort = 'ORDER BY RAND()';
810
            } else {
811
                $sort = sprintf(
812
                    'ORDER BY (
813
                    SELECT %s
814
                    FROM tbl_entries_data_%d AS `ed`
815
                    WHERE entry_id = e.id
816
                ) %s',
817
                    '`ed`.file',
818
                    $this->get('id'),
819
                    $order
820
                );
821
            }
822
        }
823
824
        /*-------------------------------------------------------------------------
825
            Events:
826
        -------------------------------------------------------------------------*/
827
828 View Code Duplication
        public function getExampleFormMarkup()
829
        {
830
            $label = Widget::Label($this->get('label'));
831
            $label->appendChild(Widget::Input('fields[' . $this->get('element_name') . ']', null, 'file'));
832
833
            return $label;
834
        }
835
    }
836