Completed
Push — master ( 2f347b...82694e )
by Haralan
12s
created

Kohana_Upload_Util   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 234
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 97.75%

Importance

Changes 0
Metric Value
wmc 29
lcom 1
cbo 9
dl 0
loc 234
ccs 87
cts 89
cp 0.9775
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A sanitize() 0 16 1
A is_filename() 0 4 1
A filenames_candidates_from_url() 0 13 1
A combine() 0 11 3
A filename_from_url() 0 17 3
A transform_image() 0 21 4
A filename_from_content_disposition() 0 7 2
C download() 0 47 8
A stream_copy_to_file() 0 13 2
B rmdir() 0 22 4
1
<?php defined('SYSPATH') OR die('No direct script access.');
2
3
/**
4
 * This class is what the upload field accually returns
5
 * and has all the nesessary info and manipulation abilities to save / delete / validate itself
6
 *
7
 * @package    Jam
8
 * @author     Ivan Kerin
9
 * @copyright  (c) 2011-2012 Despark Ltd.
10
 * @license    http://creativecommons.org/licenses/by-sa/3.0/legalcode
11
*/
12
class Kohana_Upload_Util {
13
14 4
	public static function download($url, $directory, $filename = NULL)
15
	{
16 4
		$url = str_replace(' ', '%20', $url);
17
18 4
		if ( ! Valid::url($url))
19
			return FALSE;
20
21 4
		$curl = curl_init($url);
22 4
		$file = Upload_Util::combine($directory, uniqid());
23
24 4
		$handle = fopen($file, 'w');
25 4
		$headers = new HTTP_Header();
26
27 4
		curl_setopt($curl, CURLOPT_FILE, $handle);
28 4
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
29 4
		curl_setopt($curl, CURLOPT_HEADERFUNCTION, array($headers, 'parse_header_string'));
30
31 4
		if (curl_exec($curl) === FALSE OR curl_getinfo($curl, CURLINFO_HTTP_CODE) !== 200)
32
		{
33 1
			fclose($handle);
34 1
			unlink($file);
35
36 1
			throw new Kohana_Exception('Curl: Download Error: :error, status :status on url :url', array(':url' => $url, ':status' => curl_getinfo($curl, CURLINFO_HTTP_CODE), ':error' => curl_error($curl)));
37
		}
38
39 3
		fclose($handle);
40
41 3
		if ($filename === NULL)
42
		{
43 3
			if ( ! isset($headers['content-disposition'])
44 3
			 OR ! ($filename = Upload_Util::filename_from_content_disposition($headers['content-disposition'])))
45
			{
46 2
				$mime_type = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
47 2
				$url = urldecode(curl_getinfo($curl, CURLINFO_EFFECTIVE_URL));
48
49 2
				$filename = Upload_Util::filename_from_url($url, $mime_type);
50
			}
51
		}
52
53 3
		$filename = substr(pathinfo($filename, PATHINFO_FILENAME), 0, 60).'.'.pathinfo($filename, PATHINFO_EXTENSION);
54
55 3
		$result_file = Upload_Util::combine($directory, $filename);
56
57 3
		rename($file, $result_file);
58
59 3
		return is_file($result_file) ? $filename : FALSE;
60
	}
61
62
	/**
63
	 * Move the contents of the stream to a specified directory with a given name
64
	 *
65
	 * @param  string $stream
66
	 * @param  string $directory
0 ignored issues
show
Bug introduced by
There is no parameter named $directory. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
67
	 * @param  string $filename
0 ignored issues
show
Bug introduced by
There is no parameter named $filename. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
68
	 */
69 1
	public static function stream_copy_to_file($stream, $file)
70
	{
71 1
		$stream_handle = fopen($stream, "r");
72 1
		$result_handle = fopen($file, 'w');
73
74 1
		$transfered_bytes = stream_copy_to_stream($stream_handle,  $result_handle);
75
76 1
		if ( (int) $transfered_bytes <= 0)
77
			throw new Kohana_Exception('No data was transfered from :stream to :file ', array(':stream' => $stream, ':file' => Debug::path($file)));
78
79 1
		fclose($stream_handle);
80 1
		fclose($result_handle);
81 1
	}
82
83
	/**
84
	 * recursively delete directory
85
	 *
86
	 * @param  string  $directory
87
	 * @return boolean
88
	 */
89 17
	public static function rmdir($directory)
90
	{
91 17
		if ( ! is_dir($directory))
92 1
			return FALSE;
93
94 16
		$files = array_diff(scandir($directory), array('.', '..'));
95
96 16
		foreach ($files as $file)
97
		{
98 15
			$current = $directory.DIRECTORY_SEPARATOR.$file;
99
100 15
			if (is_dir($current))
101
			{
102 2
				Upload_Util::rmdir($current);
103
			}
104
			else
105
			{
106 15
				unlink($current);
107
			}
108
		}
109 16
		return rmdir($directory);
110
	}
111
112
	/**
113
	 * Method to make a filename safe for writing on the filesystem, removing all strange characters
114
	 * @param  string $filename
115
	 * @return string
116
	 */
117 13
	static public function sanitize($filename, $separator = '-')
118
	{
119
		// Transliterate strange chars
120 13
		$filename = UTF8::transliterate_to_ascii($filename);
121
122
		// Sanitize the filename
123 13
		$filename = preg_replace('/[^a-z0-9-\.]/', $separator, strtolower($filename));
124
125
		// Remove spaces
126 13
		$filename = preg_replace('/\s+/u', $separator, $filename);
127
128
		// Strip multiple dashes
129 13
		$filename = preg_replace('/-{2,}/', $separator, $filename);
130
131 13
		return $filename;
132
	}
133
134
	/**
135
	 * Check if a file looks like a filename ("file.ext")
136
	 * @param  string  $filename
137
	 * @return boolean
138
	 */
139 16
	public static function is_filename($filename)
140
	{
141 16
		return (bool) pathinfo($filename, PATHINFO_EXTENSION);
142
	}
143
144
	/**
145
	 * Return possible filenames from a given url.
146
	 * Filenames can be in the query or the url of the file itself
147
	 *
148
	 * @param  string $url
149
	 * @return array
150
	 */
151 14
	public static function filenames_candidates_from_url($url)
152
	{
153 14
		$query = parse_url($url, PHP_URL_QUERY);
154 14
		parse_str($query, $query);
155
156 14
		$filename_candidates = array_values( (array) $query);
157
158 14
		$url_filename = basename(parse_url($url, PHP_URL_PATH));
159
160 14
		$filename_candidates[] = $url_filename;
161
162 14
		return $filename_candidates;
163
	}
164
165
	/**
166
	 * Create a filename path from function arguments with / based on the operating system
167
	 * @code
168
	 * $filename = file::combine('usr','local','bin'); // will be "user/local/bin"
169
	 * @endcode
170
	 * @return string
171
	 * @author Ivan Kerin
172
	 */
173 31
	public static function combine()
174
	{
175 31
		$args = func_get_args();
176
177 31
		foreach ($args as $i => & $arg)
178
		{
179 31
			$arg = $i == 0 ? rtrim($arg, DIRECTORY_SEPARATOR) : trim($arg, DIRECTORY_SEPARATOR);
180
		}
181
182 31
		return join(DIRECTORY_SEPARATOR, array_filter($args));
183
	}
184
185
	/**
186
	 * Detirmine the filename from the url
187
	 * @param  string $url
188
	 * @param  string $mime_type
189
	 * @return string
190
	 */
191 9
	public static function filename_from_url($url, $mime_type = NULL)
192
	{
193 9
		$filename_candidates = Upload_Util::filenames_candidates_from_url($url);
194 9
		$filename_candidates = array_filter($filename_candidates, 'Upload_Util::is_filename');
195 9
		$file = count($filename_candidates) ? reset($filename_candidates) : uniqid();
196 9
		$extensions = File::exts_by_mime($mime_type);
197
198
		$extension_candiates = array(
199 9
			(is_array($extensions) ? end($extensions) : $extensions),
200 9
			pathinfo($file, PATHINFO_EXTENSION),
201 9
			'jpg',
202
		);
203 9
		$extension_candiates = array_filter($extension_candiates);
204 9
		$extension = reset($extension_candiates);
205
206 9
		return Upload_Util::sanitize(pathinfo($file, PATHINFO_FILENAME)).'.'.$extension;
207
	}
208
209 9
	public static function filename_from_content_disposition($content_disposition)
210
	{
211 9
		if (preg_match('/filename="?(.*?)"?$/', $content_disposition, $matches))
212 7
			return $matches[1];
213
214 2
		return NULL;
215
	}
216
217
	/**
218
	 * Perform transformations on an image and store it at a different location (or overwrite existing)
219
	 *
220
	 * @param  string $from
221
	 * @param  string $to
222
	 * @param  array  $transformations
223
	 */
224 3
	public static function transform_image($from, $to, array $transformations = array())
225
	{
226 3
		$image = Image::factory($from, Kohana::$config->load('jam.upload.image_driver'));
227
228
		// Process tranformations
229 3
		foreach ($transformations as $transformation => $params)
230
		{
231 3
			if ( ! in_array($transformation, array('factory', 'save', 'render')))
232
			{
233
				// Call the method excluding the factory, save and render methods
234 3
				call_user_func_array(array($image, $transformation), $params);
235
			}
236
		}
237
238 3
		if ( ! file_exists(dirname($to)))
239
		{
240 1
			mkdir(dirname($to), 0777, TRUE);
241
		}
242
243 3
		$image->save($to, 95);
244 3
	}
245
}
246