Completed
Push — master ( 79e63b...a5181c )
by Daniel
05:26 queued 02:19
created
code/MimeUploadValidator.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@
 block discarded – undo
28 28
      * Check if the temporary file has a valid MIME type for it's extension.
29 29
      *
30 30
      * @uses finfo php extension
31
-     * @return boolean|null
31
+     * @return boolean
32 32
      */
33 33
     public function isValidMime()
34 34
     {
Please login to merge, or discard this patch.
Indentation   +138 added lines, -138 removed lines patch added patch discarded remove patch
@@ -6,144 +6,144 @@
 block discarded – undo
6 6
  */
7 7
 class MimeUploadValidator extends Upload_Validator
8 8
 {
9
-    /**
10
-     * The preg_replace() pattern to use against MIME types. Used to strip out
11
-     * useless characters so matching of MIME types can be fuzzy.
12
-     *
13
-     * @var string Regexp pattern
14
-     */
15
-    protected $filterPattern = '/.*[\/\.\-\+]/i';
16
-
17
-    public function setFilterPattern($pattern)
18
-    {
19
-        $this->filterPattern = $pattern;
20
-    }
21
-
22
-    public function getFilterPattern()
23
-    {
24
-        return $this->filterPattern;
25
-    }
26
-
27
-    /**
28
-     * Check if the temporary file has a valid MIME type for it's extension.
29
-     *
30
-     * @uses finfo php extension
31
-     * @return boolean|null
32
-     */
33
-    public function isValidMime()
34
-    {
35
-        $extension = strtolower(pathinfo($this->tmpFile['name'], PATHINFO_EXTENSION));
36
-
37
-                // we can't check filenames without an extension or no temp file path, let them pass validation.
38
-                if (!$extension || !$this->tmpFile['tmp_name']) {
39
-                    return true;
40
-                }
41
-
42
-        $expectedMimes = $this->getExpectedMimeTypes($this->tmpFile);
43
-        if (empty($expectedMimes)) {
44
-            throw new MimeUploadValidator_Exception(
45
-                sprintf('Could not find a MIME type for extension %s', $extension)
46
-            );
47
-        }
48
-
49
-        $finfo = new finfo(FILEINFO_MIME_TYPE);
50
-        $foundMime = $finfo->file($this->tmpFile['tmp_name']);
51
-        if (!$foundMime) {
52
-            throw new MimeUploadValidator_Exception(
53
-                sprintf('Could not find a MIME type for file %s', $this->tmpFile['tmp_name'])
54
-            );
55
-        }
56
-
57
-        foreach ($expectedMimes as $expected) {
58
-            if ($this->compareMime($foundMime, $expected)) {
59
-                return true;
60
-            }
61
-        }
62
-        return false;
63
-    }
64
-
65
-    /**
66
-     * Fetches an array of valid mimetypes.
67
-     *
68
-     * @return array
69
-     */
70
-    public function getExpectedMimeTypes($tmpFile)
71
-    {
72
-        $extension = strtolower(pathinfo($tmpFile['name'], PATHINFO_EXTENSION));
73
-
74
-        // if the finfo php extension isn't loaded, we can't complete this check.
75
-        if (!class_exists('finfo')) {
76
-            throw new MimeUploadValidator_Exception('PHP extension finfo is not loaded');
77
-        }
78
-
79
-        // Attempt to figure out which mime types are expected/acceptable here.
80
-        $expectedMimes = array();
81
-
82
-        // Get the mime types set in framework core
83
-        $knownMimes = Config::inst()->get('HTTP', 'MimeTypes');
84
-        if (isset($knownMimes[$extension])) {
85
-            $expectedMimes[] = $knownMimes[$extension];
86
-        }
87
-
88
-        // Get the mime types and their variations from mimevalidator
89
-        $knownMimes = Config::inst()->get(get_class($this), 'MimeTypes');
90
-        if (isset($knownMimes[$extension])) {
91
-            if (is_array($knownMimes[$extension])) {
92
-                $expectedMimes += $knownMimes[$extension];
93
-            } else {
94
-                $expectedMimes[] = $knownMimes[$extension];
95
-            }
96
-        }
97
-        return $expectedMimes;
98
-    }
99
-
100
-    /**
101
-     * Check two MIME types roughly match eachother.
102
-     *
103
-     * Before we check MIME types, remove known prefixes "vnd.", "x-" etc.
104
-     * If there is a suffix, we'll use that to compare. Examples:
105
-     *
106
-     * application/x-json = json
107
-     * application/json = json
108
-     * application/xhtml+xml = xml
109
-     * application/xml = xml
110
-     *
111
-     * @param string $first The first MIME type to compare to the second
112
-     * @param string $second The second MIME type to compare to the first
113
-     * @return boolean
114
-     */
115
-    public function compareMime($first, $second)
116
-    {
117
-        return preg_replace($this->filterPattern, '', $first) === preg_replace($this->filterPattern, '', $second);
118
-    }
119
-
120
-    public function validate()
121
-    {
122
-        if (parent::validate() === false) {
123
-            return false;
124
-        }
125
-
126
-        try {
127
-            $result = $this->isValidMime();
128
-            if ($result === false) {
129
-                $this->errors[] = _t(
130
-                    'File.INVALIDMIME',
131
-                    'File extension does not match known MIME type'
132
-                );
133
-                return false;
134
-            }
135
-        } catch (MimeUploadValidator_Exception $e) {
136
-            $this->errors[] = _t(
137
-                'File.FAILEDMIMECHECK',
138
-                'MIME validation failed: {message}',
139
-                'Argument 1: Message about why MIME type detection failed',
140
-                array('message' => $e->getMessage())
141
-            );
142
-            return false;
143
-        }
144
-
145
-        return true;
146
-    }
9
+	/**
10
+	 * The preg_replace() pattern to use against MIME types. Used to strip out
11
+	 * useless characters so matching of MIME types can be fuzzy.
12
+	 *
13
+	 * @var string Regexp pattern
14
+	 */
15
+	protected $filterPattern = '/.*[\/\.\-\+]/i';
16
+
17
+	public function setFilterPattern($pattern)
18
+	{
19
+		$this->filterPattern = $pattern;
20
+	}
21
+
22
+	public function getFilterPattern()
23
+	{
24
+		return $this->filterPattern;
25
+	}
26
+
27
+	/**
28
+	 * Check if the temporary file has a valid MIME type for it's extension.
29
+	 *
30
+	 * @uses finfo php extension
31
+	 * @return boolean|null
32
+	 */
33
+	public function isValidMime()
34
+	{
35
+		$extension = strtolower(pathinfo($this->tmpFile['name'], PATHINFO_EXTENSION));
36
+
37
+				// we can't check filenames without an extension or no temp file path, let them pass validation.
38
+				if (!$extension || !$this->tmpFile['tmp_name']) {
39
+					return true;
40
+				}
41
+
42
+		$expectedMimes = $this->getExpectedMimeTypes($this->tmpFile);
43
+		if (empty($expectedMimes)) {
44
+			throw new MimeUploadValidator_Exception(
45
+				sprintf('Could not find a MIME type for extension %s', $extension)
46
+			);
47
+		}
48
+
49
+		$finfo = new finfo(FILEINFO_MIME_TYPE);
50
+		$foundMime = $finfo->file($this->tmpFile['tmp_name']);
51
+		if (!$foundMime) {
52
+			throw new MimeUploadValidator_Exception(
53
+				sprintf('Could not find a MIME type for file %s', $this->tmpFile['tmp_name'])
54
+			);
55
+		}
56
+
57
+		foreach ($expectedMimes as $expected) {
58
+			if ($this->compareMime($foundMime, $expected)) {
59
+				return true;
60
+			}
61
+		}
62
+		return false;
63
+	}
64
+
65
+	/**
66
+	 * Fetches an array of valid mimetypes.
67
+	 *
68
+	 * @return array
69
+	 */
70
+	public function getExpectedMimeTypes($tmpFile)
71
+	{
72
+		$extension = strtolower(pathinfo($tmpFile['name'], PATHINFO_EXTENSION));
73
+
74
+		// if the finfo php extension isn't loaded, we can't complete this check.
75
+		if (!class_exists('finfo')) {
76
+			throw new MimeUploadValidator_Exception('PHP extension finfo is not loaded');
77
+		}
78
+
79
+		// Attempt to figure out which mime types are expected/acceptable here.
80
+		$expectedMimes = array();
81
+
82
+		// Get the mime types set in framework core
83
+		$knownMimes = Config::inst()->get('HTTP', 'MimeTypes');
84
+		if (isset($knownMimes[$extension])) {
85
+			$expectedMimes[] = $knownMimes[$extension];
86
+		}
87
+
88
+		// Get the mime types and their variations from mimevalidator
89
+		$knownMimes = Config::inst()->get(get_class($this), 'MimeTypes');
90
+		if (isset($knownMimes[$extension])) {
91
+			if (is_array($knownMimes[$extension])) {
92
+				$expectedMimes += $knownMimes[$extension];
93
+			} else {
94
+				$expectedMimes[] = $knownMimes[$extension];
95
+			}
96
+		}
97
+		return $expectedMimes;
98
+	}
99
+
100
+	/**
101
+	 * Check two MIME types roughly match eachother.
102
+	 *
103
+	 * Before we check MIME types, remove known prefixes "vnd.", "x-" etc.
104
+	 * If there is a suffix, we'll use that to compare. Examples:
105
+	 *
106
+	 * application/x-json = json
107
+	 * application/json = json
108
+	 * application/xhtml+xml = xml
109
+	 * application/xml = xml
110
+	 *
111
+	 * @param string $first The first MIME type to compare to the second
112
+	 * @param string $second The second MIME type to compare to the first
113
+	 * @return boolean
114
+	 */
115
+	public function compareMime($first, $second)
116
+	{
117
+		return preg_replace($this->filterPattern, '', $first) === preg_replace($this->filterPattern, '', $second);
118
+	}
119
+
120
+	public function validate()
121
+	{
122
+		if (parent::validate() === false) {
123
+			return false;
124
+		}
125
+
126
+		try {
127
+			$result = $this->isValidMime();
128
+			if ($result === false) {
129
+				$this->errors[] = _t(
130
+					'File.INVALIDMIME',
131
+					'File extension does not match known MIME type'
132
+				);
133
+				return false;
134
+			}
135
+		} catch (MimeUploadValidator_Exception $e) {
136
+			$this->errors[] = _t(
137
+				'File.FAILEDMIMECHECK',
138
+				'MIME validation failed: {message}',
139
+				'Argument 1: Message about why MIME type detection failed',
140
+				array('message' => $e->getMessage())
141
+			);
142
+			return false;
143
+		}
144
+
145
+		return true;
146
+	}
147 147
 }
148 148
 
149 149
 class MimeUploadValidator_Exception extends Exception
Please login to merge, or discard this patch.
tests/MimeUploadValidatorTest.php 2 patches
Indentation   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -1,79 +1,79 @@
 block discarded – undo
1 1
 <?php
2 2
 class MimeUploadValidatorTest extends SapphireTest
3 3
 {
4
-    public function testInvalidFileExtensionValidatingMimeType()
5
-    {
6
-        // setup plaintext file with invalid extension
7
-        $tmpFileName = 'UploadTest-testUpload.jpg';
8
-        $tmpFilePath = TEMP_FOLDER . '/' . $tmpFileName;
9
-        $tmpFileContent = '';
10
-        for ($i=0; $i<10000; $i++) {
11
-            $tmpFileContent .= '0';
12
-        }
13
-        file_put_contents($tmpFilePath, $tmpFileContent);
4
+	public function testInvalidFileExtensionValidatingMimeType()
5
+	{
6
+		// setup plaintext file with invalid extension
7
+		$tmpFileName = 'UploadTest-testUpload.jpg';
8
+		$tmpFilePath = TEMP_FOLDER . '/' . $tmpFileName;
9
+		$tmpFileContent = '';
10
+		for ($i=0; $i<10000; $i++) {
11
+			$tmpFileContent .= '0';
12
+		}
13
+		file_put_contents($tmpFilePath, $tmpFileContent);
14 14
 
15
-        // emulates the $_FILES array
16
-        $tmpFile = array(
17
-            'name' => $tmpFileName,
18
-            'size' => filesize($tmpFilePath),
19
-            'tmp_name' => $tmpFilePath,
20
-            'extension' => 'jpg',
21
-            'error' => UPLOAD_ERR_OK,
22
-        );
15
+		// emulates the $_FILES array
16
+		$tmpFile = array(
17
+			'name' => $tmpFileName,
18
+			'size' => filesize($tmpFilePath),
19
+			'tmp_name' => $tmpFilePath,
20
+			'extension' => 'jpg',
21
+			'error' => UPLOAD_ERR_OK,
22
+		);
23 23
 
24
-        $u = new Upload();
25
-        $u->setValidator(new MimeUploadValidator());
26
-        $result = $u->load($tmpFile);
27
-        $errors = $u->getErrors();
28
-        $this->assertFalse($result, 'Load failed because file extension does not match excepted MIME type');
29
-        $this->assertEquals('File extension does not match known MIME type', $errors[0]);
24
+		$u = new Upload();
25
+		$u->setValidator(new MimeUploadValidator());
26
+		$result = $u->load($tmpFile);
27
+		$errors = $u->getErrors();
28
+		$this->assertFalse($result, 'Load failed because file extension does not match excepted MIME type');
29
+		$this->assertEquals('File extension does not match known MIME type', $errors[0]);
30 30
 
31
-        unlink($tmpFilePath);
32
-    }
31
+		unlink($tmpFilePath);
32
+	}
33 33
 
34 34
 
35
-    public function testGetExpectedMimeTypes()
36
-    {
37
-        // Setup a file with a capitalised extension and try to match it against a lowercase file.
38
-        $tmpFileName = 'text.TXT';
39
-        $tmpFilePath = TEMP_FOLDER . '/' . $tmpFileName;
40
-        $tmpFileContent = '';
41
-        for ($i=0; $i<10000; $i++) {
42
-            $tmpFileContent .= '0';
43
-        }
44
-        file_put_contents($tmpFilePath, $tmpFileContent);
35
+	public function testGetExpectedMimeTypes()
36
+	{
37
+		// Setup a file with a capitalised extension and try to match it against a lowercase file.
38
+		$tmpFileName = 'text.TXT';
39
+		$tmpFilePath = TEMP_FOLDER . '/' . $tmpFileName;
40
+		$tmpFileContent = '';
41
+		for ($i=0; $i<10000; $i++) {
42
+			$tmpFileContent .= '0';
43
+		}
44
+		file_put_contents($tmpFilePath, $tmpFileContent);
45 45
 
46
-        $validator = new MimeUploadValidator();
47
-        $tmpFile = array(
48
-            'name' => $tmpFileName,
49
-            'tmp_name' => $tmpFilePath,
50
-        );
51
-        $expected = $validator->getExpectedMimeTypes($tmpFile);
52
-        $this->assertCount(1, $expected);
53
-        $this->assertContains('text/plain', $expected);
46
+		$validator = new MimeUploadValidator();
47
+		$tmpFile = array(
48
+			'name' => $tmpFileName,
49
+			'tmp_name' => $tmpFilePath,
50
+		);
51
+		$expected = $validator->getExpectedMimeTypes($tmpFile);
52
+		$this->assertCount(1, $expected);
53
+		$this->assertContains('text/plain', $expected);
54 54
 
55
-        unlink($tmpFilePath);
55
+		unlink($tmpFilePath);
56 56
 
57
-        // Test a physical ico file with capitalised extension
58
-        $tmpFile = array(
59
-            'name' => 'favicon.ICO',
60
-            'tmp_name' => 'assets/favicon.ICO',
61
-        );
62
-        $expected = $validator->getExpectedMimeTypes($tmpFile);
63
-        $this->assertCount(3, $expected);
64
-    }
57
+		// Test a physical ico file with capitalised extension
58
+		$tmpFile = array(
59
+			'name' => 'favicon.ICO',
60
+			'tmp_name' => 'assets/favicon.ICO',
61
+		);
62
+		$expected = $validator->getExpectedMimeTypes($tmpFile);
63
+		$this->assertCount(3, $expected);
64
+	}
65 65
 
66
-    public function testMimeComparison()
67
-    {
68
-        $validator = new MimeUploadValidator();
66
+	public function testMimeComparison()
67
+	{
68
+		$validator = new MimeUploadValidator();
69 69
 
70
-        $this->assertTrue($validator->compareMime('application/xhtml+xml', 'application/xml'));
71
-        $this->assertTrue($validator->compareMime('application/vnd.text', 'application/text'));
72
-        $this->assertTrue($validator->compareMime('application/vnd.vnd.text', 'application/text'));
73
-        $this->assertTrue($validator->compareMime('application/x-text', 'application/text'));
74
-        $this->assertTrue($validator->compareMime('application/gzip', 'application/gzip'));
75
-        $this->assertTrue($validator->compareMime('application/x-gzip', 'application/gzip'));
76
-        $this->assertFalse($validator->compareMime('application/png', 'application/json'));
77
-        $this->assertFalse($validator->compareMime('text/plain', 'text/json'));
78
-    }
70
+		$this->assertTrue($validator->compareMime('application/xhtml+xml', 'application/xml'));
71
+		$this->assertTrue($validator->compareMime('application/vnd.text', 'application/text'));
72
+		$this->assertTrue($validator->compareMime('application/vnd.vnd.text', 'application/text'));
73
+		$this->assertTrue($validator->compareMime('application/x-text', 'application/text'));
74
+		$this->assertTrue($validator->compareMime('application/gzip', 'application/gzip'));
75
+		$this->assertTrue($validator->compareMime('application/x-gzip', 'application/gzip'));
76
+		$this->assertFalse($validator->compareMime('application/png', 'application/json'));
77
+		$this->assertFalse($validator->compareMime('text/plain', 'text/json'));
78
+	}
79 79
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -7,7 +7,7 @@  discard block
 block discarded – undo
7 7
         $tmpFileName = 'UploadTest-testUpload.jpg';
8 8
         $tmpFilePath = TEMP_FOLDER . '/' . $tmpFileName;
9 9
         $tmpFileContent = '';
10
-        for ($i=0; $i<10000; $i++) {
10
+        for ($i = 0; $i < 10000; $i++) {
11 11
             $tmpFileContent .= '0';
12 12
         }
13 13
         file_put_contents($tmpFilePath, $tmpFileContent);
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
         $tmpFileName = 'text.TXT';
39 39
         $tmpFilePath = TEMP_FOLDER . '/' . $tmpFileName;
40 40
         $tmpFileContent = '';
41
-        for ($i=0; $i<10000; $i++) {
41
+        for ($i = 0; $i < 10000; $i++) {
42 42
             $tmpFileContent .= '0';
43 43
         }
44 44
         file_put_contents($tmpFilePath, $tmpFileContent);
Please login to merge, or discard this patch.