Passed
Push — Showing-Posts ( 38793a...f3dee8 )
by Stone
01:53
created

ImageUpload::getFilename()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 2
nop 2
dl 0
loc 16
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace App\Controllers\Ajax;
4
5
use Core\AjaxController;
6
7
class ImageUpload extends AjaxController
8
{
9
    /**
10
     * @var string the image upload folder, must be writable
11
     */
12
    private $imageFolder = "uploaded_images/";
13
    private $configFolder = "config_images/";
14
    private $userFolder = "user_images/";
0 ignored issues
show
introduced by
The private property $userFolder is not used, and could be removed.
Loading history...
15
16
    /**
17
     * check if the image name is valid
18
     * @param $image string filename to check
19
     * @return bool if image name is valid
20
     *
21
     */
22
    private function isimageValid($image):bool
23
    {
24
        // Sanitize input
25
        if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $image)) {
26
            return false;
27
        }
28
29
        // Verify extension
30
        if (!in_array(strtolower(pathinfo($image, PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
31
            return false;
32
        }
33
34
        return true;
35
    }
36
37
    /**
38
     * Check if file exists and add a number to avoid overwrite
39
     * @param string $fileUrl the file name + folder
40
     * @return string the unique file name
41
     */
42
    private function getFilename(string $folder, string $file):string
43
    {
44
45
        $fileUrl = $folder . $file;
46
        $filePath = $_SERVER['DOCUMENT_ROOT']."/public/".$fileUrl;
47
        if(file_exists($filePath) !== 1)
48
        {
49
            $fileNum = 0;
50
            while(file_exists($filePath))
51
            {
52
                $fileUrl = $folder.$fileNum."_".$file;
53
                $filePath = $_SERVER['DOCUMENT_ROOT']."/public/".$fileUrl;
54
                $fileNum += 1;
55
            }
56
        }
57
        return $fileUrl;
58
    }
59
60
    /**
61
     * @param $tempFile array
62
     * @param $folder string
63
     */
64
    private function fileInputUpload(array $tempFile, string $folder)
65
    {
66
        if (is_uploaded_file($tempFile['tmp_name'])) {
67
            if (!$this->isimageValid($tempFile['name'])) {
68
                echo json_encode(array('error' => 'Invalid name or file extension'));
69
                return;
70
            }
71
72
            //$filetowrite = $folder . $tempFile['name'];
73
            $filetowrite = $this->getFilename($folder, $tempFile['name']);
74
            move_uploaded_file($tempFile['tmp_name'], $filetowrite);
75
76
            // Respond to the successful upload with JSON.
77
            echo json_encode(array('location' => $filetowrite));
78
        } else {
79
            // Notify editor that the upload failed
80
            echo json_encode(array('error' => 'Upload failed'));
81
        }
82
83
    }
84
85
    /**
86
     * Upload images from TinyMCE
87
     * grabbed from https://www.codexworld.com/tinymce-upload-image-to-server-using-php/
88
     */
89
    public function tinymceUpload()
90
    {
91
        //security checks, only admins can upload images to posts
92
        $this->onlyAdmin();
93
        if (!$this->container->getRequest()->isPost()) {
94
            throw new \Core\JsonException('Call is not post');
95
        }
96
97
        $tempFile = $this->request->getUploadedFiles();
98
99
        //need to clean up
100
        if (is_uploaded_file($tempFile['tmp_name'])) {
101
            if (!$this->isimageValid($tempFile['name'])) {
102
                header("HTTP/1.1 400 Invalid file name or file extension.");
103
                return;
104
            }
105
106
            //$filetowrite = $this->imageFolder . $tempFile['name'];
107
            $filetowrite = $this->getFilename($folder, $tempFile['name']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $folder seems to be never defined.
Loading history...
108
            move_uploaded_file($tempFile['tmp_name'], $filetowrite);
109
110
            // Respond to the successful upload with JSON.
111
            echo json_encode(array('location' => $filetowrite));
112
        } else {
113
            // Notify editor that the upload failed
114
            header("HTTP/1.1 500 Server Error");
115
        }
116
    }
117
118
119
    /**
120
     * Upload for the file input in the configuration
121
     */
122
    public function fileInputConfigUpload()
123
    {
124
        //security checks, only admins can upload images to config
125
        $this->onlyAdmin();
126
        if (!$this->container->getRequest()->isPost()) {
127
            throw new \Core\JsonException('Call is not post');
128
        }
129
        $tempFile = $this->request->getUploadedFiles();
130
131
        $this->fileInputUpload($tempFile, $this->configFolder);
132
133
    }
134
135
    /**
136
     * Upload for the file input in the configuration
137
     */
138
    public function fileInputPostUpload()
139
    {
140
        //security checks, only admins can upload images to config
141
        $this->onlyAdmin();
142
        if (!$this->container->getRequest()->isPost()) {
143
            throw new \Core\JsonException('Call is not post');
144
        }
145
        $tempFile = $this->request->getUploadedFiles();
146
147
        $this->fileInputUpload($tempFile, $this->imageFolder);
148
    }
149
150
}