Test Failed
Push — 1.0.0-dev ( 740ad8...b2bddd )
by nguereza
02:44
created

Upload::setDestinationDirectory()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 13
nc 5
nop 2
dl 0
loc 17
rs 9.5222
c 2
b 0
f 0
1
<?php
2
    defined('ROOT_PATH') or exit('Access denied');
3
    /**
4
     * TNH Framework
5
     *
6
     * A simple PHP framework using HMVC architecture
7
     *
8
     * This content is released under the MIT License (MIT)
9
     *
10
     * Copyright (c) 2017 TNH Framework
11
     *
12
     * Permission is hereby granted, free of charge, to any person obtaining a copy
13
     * of this software and associated documentation files (the "Software"), to deal
14
     * in the Software without restriction, including without limitation the rights
15
     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
     * copies of the Software, and to permit persons to whom the Software is
17
     * furnished to do so, subject to the following conditions:
18
     *
19
     * The above copyright notice and this permission notice shall be included in all
20
     * copies or substantial portions of the Software.
21
     *
22
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
     * SOFTWARE.
29
     */
30
31
    /**
32
     *    Upload
33
     *
34
     *    A complete class to upload files with php 5 or higher, but the best: very simple to use.
35
     *
36
     *    @author Olaf Erlandsen <[email protected]>
37
     *    @author http://www.webdevfreelance.com/
38
     *
39
     *    @package FileUpload
40
     *    @version 1.5
41
     */
42
    class Upload extends BaseClass {
43
44
        /**
45
         *   Version
46
         *
47
         *   @since      1.5
48
         *   @version    1.0
49
         */
50
        const VERSION = '1.5';
51
52
        /**
53
         *    Upload function name
54
         *    Remember:
55
         *        Default function: move_uploaded_file
56
         *        Native options:
57
         *            - move_uploaded_file (Default and best option)
58
         *            - copy
59
         *
60
         *    @since        1.0
61
         *    @version    1.0
62
         *    @var        string
63
         */
64
        private $uploadFunction = 'move_uploaded_file';
65
66
        /**
67
         *    Array with the information obtained from the
68
         *    variable $_FILES or $HTTP_POST_FILES.
69
         *
70
         *    @since        1.0
71
         *    @version    1.0
72
         *    @var        array
73
         */
74
        private $uploadedFileData = array();
75
76
        /**
77
         *    If the file you are trying to upload already exists it will
78
         *    be overwritten if you set the variable to true.
79
         *
80
         *    @since        1.0
81
         *    @version    1.0
82
         *    @var        boolean
83
         */
84
        private $overwriteFile = false;
85
86
        /**
87
         *    Input element
88
         *    Example:
89
         *        <input type="file" name="file" />
90
         *    Result:
91
         *        FileUpload::$input = file
92
         *
93
         *    @since        1.0
94
         *    @version    1.0
95
         *    @var        string
96
         */
97
        private $input;
98
99
        /**
100
         *    Path output
101
         *
102
         *    @since        1.0
103
         *    @version    1.0
104
         *    @var        string
105
         */
106
        private $destinationDirectory;
107
108
        /**
109
         *    Output filename
110
         *
111
         *    @since        1.0
112
         *    @version    1.0
113
         *    @var        string
114
         */
115
        private $filename;
116
117
        /**
118
         *    Max file size
119
         *
120
         *    @since        1.0
121
         *    @version    1.0
122
         *    @var        float
123
         */
124
        private $maxFileSize = 0.0;
125
126
        /**
127
         *    List of allowed mime types
128
         *
129
         *    @since        1.0
130
         *    @version    1.0
131
         *    @var        array
132
         */
133
        private $allowedMimeTypes = array();
134
135
        /**
136
         *    Callbacks
137
         *
138
         *    @since        1.0
139
         *    @version    1.0
140
         *    @var        array
141
         */
142
        private $callbacks = array();
143
144
        /**
145
         *    File object
146
         *
147
         *    @since        1.0
148
         *    @version    1.0
149
         *    @var        object
150
         */
151
        private $file;
152
153
        /**
154
         *    Helping mime types
155
         *
156
         *    @since        1.0
157
         *    @version    1.0
158
         *    @var        array
159
         */
160
        private $mimeHelping = array(
161
            'text'      =>    array('text/plain',),
162
            'image'     =>    array(
163
                'image/jpeg',
164
                'image/jpg',
165
                'image/pjpeg',
166
                'image/png',
167
                'image/gif',
168
            ),
169
            'document'  =>    array(
170
                'application/pdf',
171
                'application/msword',
172
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
173
                'application/vnd.openxmlformats-officedocument.presentationml.presentation',
174
                'application/vnd.ms-powerpoint',
175
                'application/vnd.ms-excel',
176
                'application/vnd.oasis.opendocument.spreadsheet',
177
                'application/vnd.oasis.opendocument.presentation',
178
            ),
179
            'video'    =>    array(
180
                'video/3gpp',
181
                'video/3gpp',
182
                'video/x-msvideo',
183
                'video/avi',
184
                'video/mpeg4',
185
                'video/mp4',
186
                'video/mpeg',
187
                'video/mpg',
188
                'video/quicktime',
189
                'video/x-sgi-movie',
190
                'video/x-ms-wmv',
191
                'video/x-flv',
192
            ),
193
        );
194
195
        /**
196
         * The upload error message
197
         * @var array
198
         */
199
        public $errorMessages = array();
200
201
        /**
202
         * The upload error message
203
         * @var string
204
         */
205
        protected $error = null;
206
207
208
        /**
209
         *    Construct
210
         *
211
         *    @since     0.1
212
         *    @version   1.0.1
213
         *    @return    object
214
         *    @method    object    __construct
215
         */
216
        public function __construct() {
217
            parent::__construct();
218
219
            //Load language messages
220
            $this->loadLangMessages();
221
222
            $this->file = array(
223
                'status'                =>    false, // True: success upload
224
                'mime'                  =>    '', // Empty string
225
                'filename'              =>    '', // Empty string
226
                'original'              =>    '', // Empty string
227
                'size'                  =>    0, // 0 Bytes
228
                'sizeFormated'          =>    '0B', // 0 Bytes
229
                'destination'           =>    './', // Default: ./
230
                'allowed_mime_types'    =>    array(), // Allowed mime types
231
                'error'                 =>    null, // File error
232
            );
233
234
            // Change dir to current dir
235
            $this->destinationDirectory = dirname(__FILE__) . DIRECTORY_SEPARATOR;
236
237
            // Set file array
238
            $this->uploadedFileData = get_instance()->globalvar->files();
239
            $this->logger->info('The upload file information are : ' . stringfy_vars($this->uploadedFileData));
240
        }
241
242
        
243
        /**
244
         *    Set input.
245
         *    If you have $_FILES["file"], you must use the key "file"
246
         *    Example:
247
         *        $object->setInput("file");
248
         *
249
         *    @since     1.0
250
         *    @version   1.0
251
         *    @param     string      $input
252
         *    @return    object
253
         *    @method    boolean     setInput
254
         */
255
        public function setInput($input) {
256
            $this->input = $input;
257
            return $this;
258
        }
259
260
        /**
261
         *    Get the file input name
262
         *    @return    string
263
         */
264
        public function getInput() {
265
            return $this->input;
266
        }
267
268
        /**
269
         * Set the file array data generally in constructor this is already set using $_FILES 
270
         * super global
271
         * @param array $fileData the new value
272
         *
273
         * @return object the current instance
274
         */
275
        public function setUploadedFileData(array $fileData){
276
            $this->uploadedFileData = $fileData;
277
            return $this;
278
        }
279
280
         /**
281
         *    Get the uploade file array
282
         *    @return    array
283
         */
284
        public function getUploadedFileData() {
285
            return $this->uploadedFileData;
286
        }
287
288
289
        /**
290
         *    Set new filename
291
         *    Example:
292
         *        FileUpload::setFilename("new file.txt")
293
         *    Remember:
294
         *        Use %s to retrive file extension
295
         *
296
         *    @since     1.0
297
         *    @version   1.0
298
         *    @param     string      $filename
299
         *    @return    object
300
         *    @method    boolean     setFilename
301
         */
302
        public function setFilename($filename) {
303
            if ($this->isFilename($filename)) {
304
                $this->filename = $filename;
305
            }
306
            return $this;
307
        }
308
309
        /**
310
         *    Set automatic filename
311
         *
312
         *    @since     1.0
313
         *    @version   1.5
314
         *    @param     string      $extension
315
         *    @return    object
316
         *    @method    boolean     setAutoFilename
317
         */
318
        public function setAutoFilename() {
319
            $this->filename = sha1(mt_rand(1, 9999) . uniqid()) . time();
320
            return $this;
321
        }
322
323
         /**
324
         *    Get the filename
325
         *    @return    string
326
         */
327
        public function getFilename() {
328
            return $this->filename;
329
        }
330
331
        /**
332
         *    Set file size limit
333
         *
334
         *    @since     1.0
335
         *    @version   1.0
336
         *    @param     double     $fileSize
337
         *    @return    object
338
         *    @method    boolean     setMaxFileSize
339
         */
340
        public function setMaxFileSize($fileSize) {
341
            $size = $this->sizeInBytes($fileSize);
342
            if (is_numeric($size) && $size > -1) {
343
                // Get PHP upload max file size config
344
                $phpMaxUploadSize = ini_get('upload_max_filesize');
345
                // check difference
346
                if ($this->sizeInBytes((int) $phpMaxUploadSize) < $size) {
347
                    $this->logger->warning('The upload max file size you set [' . $fileSize . '] '
348
                            . 'is greather than the PHP configuration for upload max file size [' . $phpMaxUploadSize . ']');
349
                }
350
                $this->maxFileSize = $size;
351
            }
352
            return $this;
353
        }
354
355
         /**
356
         *    Get the max file size
357
         *    @return    double|int
358
         */
359
        public function getMaxFileSize() {
360
            return $this->maxFileSize;
361
        }
362
363
         /**
364
         *    Append a mime type to allowed mime types
365
         *
366
         *    @since     1.0
367
         *    @version   1.0.1
368
         *    @param     string      $mime
369
         *    @return    object
370
         *    @method    boolean     setAllowMimeType
371
         */
372
        public function setAllowMimeType($mime) {
373
            $this->allowedMimeTypes[] = strtolower($mime);
374
            $this->file['allowed_mime_types'][] = strtolower($mime); 
375
            return $this;
376
        }
377
378
        /**
379
         *    Set array mime types
380
         *
381
         *    @since     1.0
382
         *    @version   1.0
383
         *    @param     array       $mimes
384
         *    @return    object
385
         *    @method    boolean     setAllowedMimeTypes
386
         */
387
        public function setAllowedMimeTypes(array $mimes) {
388
            array_map(array($this, 'setAllowMimeType'), $mimes);
389
            return $this;
390
        }
391
392
        /**
393
         *    Set allowed mime types from mime helping
394
         *
395
         *    @since     1.0.1
396
         *    @version   1.0.1
397
         *    @return    object
398
         *    @method    boolean    setMimeHelping
399
         */
400
        public function setMimeHelping($name) {
401
            if (array_key_exists($name, $this->mimeHelping)) {
402
                return $this->setAllowedMimeTypes($this->mimeHelping[$name]);
403
            }
404
            return $this;
405
        }
406
407
        /**
408
         *    Clear allowed mime types cache
409
         *
410
         *    @since     1.0
411
         *    @version   1.0
412
         *    @return    object
413
         *    @method    boolean    clearAllowedMimeTypes
414
         */
415
        public function clearAllowedMimeTypes() {
416
            $this->allowedMimeTypes = array();
417
            $this->file['allowed_mime_types'] = array();
418
            return $this;
419
        }
420
421
        /**
422
         *    Get the list of mimes type allowed
423
         *    @return    array
424
         */
425
        public function getAllowMimeType() {
426
            return $this->allowedMimeTypes;
427
        }
428
429
        /**
430
         *    Set input callback
431
         *
432
         *    @since     1.0
433
         *    @version   1.0
434
         *    @param     mixed       $callback
435
         *    @return    object
436
         *    @method    boolean     setCallbackInput
437
         */
438
        public function setCallbackInput($callback) {
439
            if (is_callable($callback, false)) {
440
                $this->callbacks['input'] = $callback;
441
            }
442
            return $this;
443
        }
444
445
        /**
446
         *    Set output callback
447
         *
448
         *    @since     1.0
449
         *    @version   1.0
450
         *    @param     mixed       $callback
451
         *    @return    object
452
         *    @method    boolean     setCallbackOutput
453
         */
454
        public function setCallbackOutput($callback) {
455
            if (is_callable($callback, false)) {
456
                $this->callbacks['output'] = $callback;
457
            }
458
            return $this;
459
        }
460
461
        /**
462
         *    Get the list of callbacks for "input" and "output"
463
         *    @return    array
464
         */
465
        public function getCallbacks() {
466
            return $this->callbacks;
467
        }
468
469
        /**
470
         *    Set function to upload file
471
         *    Examples:
472
         *        1.- FileUpload::setUploadFunction("move_uploaded_file");
473
         *        2.- FileUpload::setUploadFunction("copy");
474
         *
475
         *    @since     1.0
476
         *    @version   1.0
477
         *    @param     string      $function
478
         *    @return    object
479
         *    @method    boolean     setUploadFunction
480
         */
481
        public function setUploadFunction($function) {
482
            if (is_callable($function)) {
483
                $this->uploadFunction = $function;
484
            }
485
            return $this;
486
        }
487
488
         /**
489
         *    Get the upload function name like "copy", "move_uploaded_file"
490
         *    @return    string
491
         */
492
        public function getUploadFunction() {
493
            return $this->uploadFunction;
494
        }
495
496
        /**
497
         *    Allow overwriting files
498
         *
499
         *    @since      1.0
500
         *    @version    1.0
501
         *    @return     object
502
         *    @method     boolean    allowOverwriting
503
         */
504
        public function allowOverwriting($status = true) {
505
            $this->overwriteFile = $status;
506
            return $this;
507
        }
508
509
         /**
510
         *    Get the allow overwriting
511
         *    @return    boolean
512
         */
513
        public function isAllowOverwriting() {
514
            return $this->overwriteFile ;
515
        }
516
517
        /**
518
         *    Set destination output
519
         *
520
         *    @since     1.0
521
         *    @version   1.0
522
         *    @param     string      $directory      Destination path
523
         *    @param     boolean     $autoCreate
524
         *    @return    object
525
         *    @method    boolean     setDestinationDirectory
526
         */
527
        public function setDestinationDirectory($directory, $autoCreate = false) {
528
            $dir = realpath($directory);
529
            $dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
530
            if ($this->isDirpath($dir)) {
531
                if ($this->dirExists($dir)) {
532
                    $this->destinationDirectory = $dir;
533
                    chdir($dir);
534
                } else if ($autoCreate === true) {
535
                    if (mkdir($dir, 0775, true)) {
536
                        $this->destinationDirectory = $dir;
537
                        chdir($dir);
538
                    } else {
539
                        $this->logger->warning('Can not create the upload directory [' . $directory . ']');
540
                    }
541
                }
542
            }
543
            return $this;
544
        }
545
546
        /**
547
         *    Get the destination directory
548
         *    @return    string
549
         */
550
        public function getDestinationDirectory() {
551
            return $this->destinationDirectory ;
552
        }
553
554
        /**
555
         * Check if the file is uploaded
556
         * @return boolean
557
         */
558
        public function isUploaded() {
559
            return isset($this->uploadedFileData[$this->input])
560
                        && is_uploaded_file($this->uploadedFileData[$this->input]['tmp_name']);
561
        }
562
563
        /**
564
         *    Upload file
565
         *
566
         *    @since     1.0
567
         *    @version   1.0.1
568
         *    @return    boolean
569
         *    @method    boolean    save
570
         */
571
        public function save() {
572
            if (!$this->isUploaded()) {
573
                return false;
574
            }
575
            // set original filename if not have a new name
576
            $this->setFilenameUsingUploadedData();
577
578
            // set file info
579
            $this->file['mime']         = $this->uploadedFileData[$this->input]['type'];
580
            $this->file['tmp']          = $this->uploadedFileData[$this->input]['tmp_name'];
581
            $this->file['original']     = $this->uploadedFileData[$this->input]['name'];
582
            $this->file['size']         = $this->uploadedFileData[$this->input]['size'];
583
            $this->file['sizeFormated'] = $this->sizeFormat($this->file['size']);
584
            $this->file['destination']  = $this->destinationDirectory . $this->filename;
585
            $this->file['filename']     = $this->filename;
586
            $this->file['error']        = $this->uploadedFileData[$this->input]['error'];
587
588
            $this->logger->info('The upload file information to process is : ' . stringfy_vars($this->file));
589
590
            if ($this->uploadHasError()) {
591
                return false;
592
            }
593
            // Execute input callback
594
            $this->runCallback('input');
595
596
            $this->file['status'] = call_user_func_array(
597
                $this->uploadFunction, array(
598
                    $this->uploadedFileData[$this->input]['tmp_name'],
599
                    $this->destinationDirectory . $this->filename
600
                )
601
            );
602
603
            // Execute output callback
604
            $this->runCallback('output');
605
606
            return $this->file['status'];
607
        }
608
609
        /**
610
         * Get the upload error message
611
         * @return string
612
         */
613
        public function getError() {
614
            return $this->error;
615
        }
616
617
         /**
618
         *    Retrive status of upload
619
         *
620
         *    @since     1.0
621
         *    @version   1.0
622
         *    @return    boolean
623
         *    @method    boolean    getStatus
624
         */
625
        public function getStatus() {
626
            return $this->file['status'];
627
        }
628
629
        /**
630
         *    File info
631
         *
632
         *    @since      1.0
633
         *    @version    1.0
634
         *    @return     object
635
         *    @method     object    getInfo
636
         */
637
        public function getInfo() {
638
            return (object) $this->file;
639
        }
640
641
642
        /**
643
         *    Check file exists
644
         *
645
         *    @since      1.0
646
         *    @version    1.0.1
647
         *    @param      string     $file
648
         *    @return     boolean
649
         *    @method     boolean    fileExists
650
         */
651
        protected function fileExists($file) {
652
            return $this->isFilename($file) 
653
                                && file_exists($file) 
654
                                && is_file($file);
655
        }
656
657
         /**
658
         * Set the filename if is empty using the uploaded data information
659
         *
660
         * @return object the current instance
661
         */
662
        protected function setFilenameUsingUploadedData() {
663
            // set original filename if not have a new name
664
            if (empty($this->filename)) {
665
                $this->filename = $this->uploadedFileData[$this->input]['name'];
666
            } else {
667
                // Replace %s for extension in filename
668
                // Before: /[\w\d]*(.[\d\w]+)$/i
669
                // After: /^[\s[:alnum:]\-\_\.]*\.([\d\w]+)$/iu
670
                // Support unicode(utf-8) characters
671
                // Example: "русские.jpeg" is valid; "Zhōngguó.jpeg" 
672
                // is valid; "Tønsberg.jpeg" is valid
673
                $extension = preg_replace(
674
                    '/^[\p{L}\d\s\-\_\.\(\)]*\.([\d\w]+)$/iu',
675
                    '$1',
676
                    $this->uploadedFileData[$this->input]['name']
677
                );
678
                $this->filename = $this->filename . '.' . $extension;
679
            }
680
            return $this;
681
        }
682
683
        /**
684
         *    Check dir exists
685
         *
686
         *    @since        1.0
687
         *    @version    1.0.1
688
         *    @param      string     $path
689
         *    @return     boolean
690
         *    @method     boolean    dirExists
691
         */
692
        protected function dirExists($path) {
693
            return $this->isDirpath($path) 
694
                                && file_exists($path) 
695
                                && is_dir($path);
696
        }
697
698
        /**
699
         *    Check valid filename
700
         *
701
         *    @since     1.0
702
         *    @version   1.0.1
703
         *    @param     string      $filename
704
         *    @return    boolean
705
         *    @method    boolean     isFilename
706
         */
707
        protected function isFilename($filename) {
708
            $filename = basename($filename);
709
            return !empty($filename);
710
        }
711
712
        /**
713
         *    Validate mime type with allowed mime types,
714
         *    but if allowed mime types is empty, this method return true
715
         *
716
         *    @since     1.0
717
         *    @version   1.0
718
         *    @param     string      $mime
719
         *    @return    boolean
720
         *    @method    boolean     checkMimeType
721
         */
722
        protected function checkMimeType($mime) {
723
            if (count($this->allowedMimeTypes) === 0) {
724
                return true;
725
            }
726
            return in_array(strtolower($mime), $this->allowedMimeTypes);
727
        }
728
729
        /**
730
         *    Validate max upload file size,
731
         *    but if max size is 0, this method return true
732
         *
733
         *    @since     1.0
734
         *    @version   1.0
735
         *    @param     double|integer      $size
736
         *    @return    boolean
737
         */
738
        protected function checkMaxSize($size) {
739
            if ($this->maxFileSize <= 0) {
740
                return true;
741
            }
742
            if ($this->maxFileSize < $size) {
743
                return false;
744
            }
745
            return true;
746
        }
747
748
         /**
749
         *    Check the file overwritting
750
         *    @since     1.0
751
         *    @version   1.0
752
         *    @return    boolean
753
         */
754
        protected function checkFileOverwritting() {
755
            if ($this->fileExists($this->destinationDirectory . $this->filename)) {
756
                return $this->overwriteFile;
757
            }
758
            return true;
759
        }
760
       
761
       
762
        /**
763
         *    Check valid path
764
         *
765
         *    @since        1.0
766
         *    @version    1.0.1
767
         *    @param        string    $filename
768
         *    @return     boolean
769
         *    @method     boolean    isDirpath
770
         */
771
        protected function isDirpath($path) {
772
            if (DIRECTORY_SEPARATOR == '/') {
773
                return (preg_match('/^[^*?"<>|:]*$/', $path) == 1);
774
            } else {
775
                return (preg_match("/^[^*?\"<>|:]*$/", substr($path, 2)) == 1);
776
            }
777
        }
778
779
        /**
780
         *    File size for humans.
781
         *
782
         *    @since      1.0
783
         *    @version    1.0
784
         *    @param      integer    $bytes
785
         *    @param      integer    $precision
786
         *    @return     string
787
         *    @method     string     sizeFormat
788
         */
789
        protected function sizeFormat($size, $precision = 2) {
790
            if ($size > 0) {
791
                $base     = log($size) / log(1024);
792
                $suffixes = array('B', 'K', 'M', 'G', 'T');
793
                $suffixe = '';
794
                if (isset($suffixes[floor($base)])) {
795
                    $suffixe = $suffixes[floor($base)];
796
                }
797
                return round(pow(1024, $base - floor($base)), $precision) . $suffixe;
798
            }
799
            return null;
800
        }
801
802
        
803
        /**
804
         *    Convert human file size to bytes
805
         *
806
         *    @since      1.0
807
         *    @version    1.0.1
808
         *    @param      integer|double    $size
809
         *    @return     integer|double
810
         *    @method     string     sizeInBytes
811
         */
812
        protected function sizeInBytes($size) {
813
            $unit = 'B';
814
            $units = array('B' => 0, 'K' => 1, 'M' => 2, 'G' => 3, 'T' => 4);
815
            $matches = array();
816
            preg_match('/(?<size>[\d\.]+)\s*(?<unit>b|k|m|g|t)?/i', $size, $matches);
817
            if (array_key_exists('unit', $matches)) {
818
                $unit = strtoupper($matches['unit']);
819
            }
820
            return (floatval($matches['size']) * pow(1024, $units[$unit]));
821
        }
822
823
        /**
824
         * Set the upload error message
825
         * @param string $message the upload error message to set
826
         *
827
         * @return object the current instance
828
         */
829
        protected function setError($message) {
830
            $this->logger->info('The file upload got error : ' . $message);
831
            $this->error = $message;
832
            return $this;
833
        }
834
835
        /**
836
         * Run the callbacks in the file uploaded
837
         * @param string $type the type of callback "input" or "output"
838
         * @return void 
839
         */
840
        protected function runCallback($type) {
841
            if (!empty($this->callbacks[$type])) {
842
                call_user_func($this->callbacks[$type], (object) $this->file);
843
            }
844
        }
845
846
        /**
847
         * Check if file upload has error
848
         * @return boolean
849
         */
850
        protected function uploadHasError() {
851
            //check if file upload is  allowed in the configuration
852
            if (!ini_get('file_uploads')) {
853
                $this->setError($this->errorMessages['file_uploads']);
854
                return true;
855
            }
856
857
            //check for php upload error
858
            $error = $this->getPhpUploadErrorMessageByCode($this->file['error']);
859
            if ($error !== null) {
0 ignored issues
show
introduced by
The condition $error !== null is always true.
Loading history...
860
                $this->setError($error);
861
                return true;
862
            }
863
            
864
            //check for mime type
865
            if (!$this->checkMimeType($this->file['mime'])) {
866
                $this->setError($this->errorMessages['accept_file_types']);
867
                return true;
868
            }
869
870
            // Check file size
871
            if (!$this->checkMaxSize($this->file['size'])) {
872
                $this->setError(sprintf($this->errorMessages['max_file_size'], $this->sizeFormat($this->maxFileSize)));
873
                return true;
874
            }
875
876
            // Check if exists file
877
            if (!$this->checkFileOverwritting()) {
878
                $this->setError($this->errorMessages['overwritten_not_allowed']);
879
                return true;
880
            }
881
            return false;
882
        }
883
884
        /**
885
         * Get the PHP upload error message for the given code
886
         * @param  int $code the error code
887
         * @return string the error message
888
         */
889
        protected function getPhpUploadErrorMessageByCode($code) {
890
            $error = null;
891
            $codeMessageMaps = array(
892
                1 => $this->errorMessages['upload_err_ini_size'],
893
                2 => $this->errorMessages['upload_err_form_size'],
894
                3 => $this->errorMessages['upload_err_partial'],
895
                4 => $this->errorMessages['upload_err_no_file'],
896
                6 => $this->errorMessages['upload_err_no_tmp_dir'],
897
                7 => $this->errorMessages['upload_err_cant_write'],
898
                8 => $this->errorMessages['upload_err_extension'],
899
            );
900
            if (isset($codeMessageMaps[$code])) {
901
                $error = $codeMessageMaps[$code];
902
            }
903
            return $error;
904
        }
905
906
        /**
907
         * Load the language messages for upload
908
         */
909
        protected function loadLangMessages() {
910
            get_instance()->loader->lang('file_upload');
911
            $this->errorMessages = array(
912
                                    'upload_err_ini_size'     => get_instance()->lang->get('fu_upload_err_ini_size'),
913
                                    'upload_err_form_size'    => get_instance()->lang->get('fu_upload_err_form_size'),
914
                                    'upload_err_partial'      => get_instance()->lang->get('fu_upload_err_partial'),
915
                                    'upload_err_no_file'      => get_instance()->lang->get('fu_upload_err_no_file'),
916
                                    'upload_err_no_tmp_dir'   => get_instance()->lang->get('fu_upload_err_no_tmp_dir'),
917
                                    'upload_err_cant_write'   => get_instance()->lang->get('fu_upload_err_cant_write'),
918
                                    'upload_err_extension'    => get_instance()->lang->get('fu_upload_err_extension'),
919
                                    'accept_file_types'       => get_instance()->lang->get('fu_accept_file_types'),
920
                                    'file_uploads'            => get_instance()->lang->get('fu_file_uploads_disabled'),
921
                                    'max_file_size'           => get_instance()->lang->get('fu_max_file_size'),
922
                                    'overwritten_not_allowed' => get_instance()->lang->get('fu_overwritten_not_allowed'),
923
                                );
924
        }
925
926
    }
927