forked from jkuchar/MultipleFileUpload
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultipleFileUpload.php
More file actions
492 lines (411 loc) · 12.9 KB
/
MultipleFileUpload.php
File metadata and controls
492 lines (411 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
<?php
/**
* MultipleFileUpload (https://github.com/jkuchar/MultipleFileUpload/)
*
* Copyright (c) 2013 Jan Kuchař (http://www.jankuchar.cz)
*
* For the full copyright and license information, please view
* the file license.txt that was distributed with this source code.
*/
namespace MultipleFileUpload;
use Nette\Environment;
use Nette\Utils\Html;
use Nette\Forms;
use Nette\InvalidStateException;
use Nette\NotSupportedException;
class MultipleFileUpload extends Forms\Controls\UploadControl {
const NAME = "Multiple File Uploader";
const VERSION = 'Unknown';
/**
* Is files handle uploads called?
* @var bool
* @see self::handleUploads()
*/
private static $handleUploadsCalled = false;
/**
* Model
* @var Model\IQueues
* @see self::init()
*/
protected static $queuesModel;
/**
* Validate file callback
* @var Callback
* @return bool
* @param \Nette\Http\FileUpload File to be checked
*/
public static $validateFileCallback;
/**
* Interface registrator instance
* @var UI\Registrator
*/
public static $interfaceRegistrator;
/**
* Root of mfu directory in public folder (used for serving js, css, ...)
* @var type string
*/
public static $baseWWWRoot = null;
/**
* Initialize MFU
*/
public static function init() {
// Init UI registrator
$uiReg = self::$interfaceRegistrator = new UI\Registrator();
$uiReg->register("MultipleFileUpload\\UI\\HTML4SingleUpload");
$uiReg->register("MultipleFileUpload\\UI\\Plupload");
// Set default check callback
self::$validateFileCallback = callback(__CLASS__, "validateFile");
// TODO: remove this magic
self::$baseWWWRoot = Environment::getHttpRequest()->url->baseUrl . "MultipleFileUpload/";
}
/**
* Register MFU into Nette
*/
public static function register() {
self::init();
$application = Environment::getApplication();
$application->onStartup[] = callback(__CLASS__, "handleUploads");
$application->onShutdown[] = callback(__CLASS__, "cleanCache");
}
/* ########## HANDLING UPLOADS ########### */
/**
* Setts life time of files in queue (shortcut for self::getQueuesModel()->setLifeTime)
* @param int $lifeTime Time in seconds
*/
static function setLifeTime($lifeTime) {
self::getQueuesModel()
->setLifeTime((int) $lifeTime);
}
protected static function _doSetLifetime() {
// Auto cofing of lifeTime
$maxInputTime = (int) ini_get("max_input_time");
if ($maxInputTime < 0) { // Pokud není žádný maximální čas vstupu (-1)
$lifeTime = 3600;
} else {
$lifeTime = $maxInputTime + 5; // Maximální čas vstupu + pár sekund
}
self::setLifeTime($lifeTime);
}
/**
* Handles uploading files
*/
public static function handleUploads() {
// Pokud už bylo voláno handleUploads -> skonči
if (self::$handleUploadsCalled === true) {
return;
} else {
self::$handleUploadsCalled = true;
}
$req = Environment::getHttpRequest();
// Workaround for: http://forum.nettephp.com/cs/3680-httprequest-getheaders-a-content-type
$contentType = $req->getHeader("content-type");
if (!$contentType and isset($_SERVER["CONTENT_TYPE"])) {
$contentType = $_SERVER["CONTENT_TYPE"];
}
if ($req->getMethod() !== "POST") {
return;
}
self::getQueuesModel()->initialize();
foreach (self::getUIRegistrator()->getInterfaces() AS $interface) {
// \Nette\Diagnostics\Debugger::log($interface->getReflection()->getName().": is this your upload? ".$interface->isThisYourUpload());
if ($interface->isThisYourUpload()) {
$ret = $interface->handleUploads();
if ($ret === true)
break;
}
}
}
/**
* Checks file if is ok and can be processed
* @param \Nette\Http\FileUpload $file
* @return bool
*/
public static function validateFile(\Nette\Http\FileUpload $file) {
return $file->isOk();
}
/**
* Cleans cache
*/
public static function cleanCache() {
if (!Environment::isProduction() or rand(1, 100) < 5) {
self::getQueuesModel()->cleanup();
}
}
/**
*
* @return type
* @throws \Nette\InvalidStateException
*/
public static function getQueuesModel() {
if (!self::$queuesModel) { // if nothing is set, setup sqlite model, which should work on all systems with SQLite
self::setQueuesModel(new Model\SQLite\Queues());
}
if (!self::$queuesModel instanceof Model\IQueues) {
throw new \Nette\InvalidStateException("Queues model is not instance of Model\IQueues!");
}
return self::$queu
8000
esModel;
}
/**
* Setts new queues model
* @param \MultipleFileUpload\Model\IQueues $model
*/
public static function setQueuesModel(Model\IQueues $model) {
self::$queuesModel = $model;
self::_doSetLifetime();
}
/**
* @return UI\Registrator
*/
public static function getUIRegistrator() {
if (!self::$interfaceRegistrator instanceof UI\Registrator) {
throw new InvalidStateException("Interface registrator is not instance of MFUUIRegistrator!");
}
return self::$interfaceRegistrator;
}
public static function getHead() {
// TODO: Add MFUFallbackController?
$out = "";
foreach (self::getUIRegistrator()->getInterfaces() AS $interface) {
$out .= $interface->renderHeadSection();
}
return $out;
}
/* *****************************************************************************
* ************************* Form Control **************************************
* ***************************************************************************** */
/**
* Unique identifier
* @var string
*/
public $token;
/**
* Maximum selected files in one input
* @var int
*/
public $maxFiles;
/**
* Maximum file size of single uploaded file
* @var int
*/
public $maxFileSize;
/**
* How many threads will be used to upload files
* @var int
*/
public $simUploadThreads;
/**
* Constructor
* @param string $label Label
*/
public function __construct($label = NULL, $maxSelectedFiles = 25) {
parent::__construct($label);
if (!self::$handleUploadsCalled) {
throw new InvalidStateException("MultipleFileUpload::handleUpload() has not been called. Call `MultipleFileUpload::register();` from your bootstrap before you call Applicaton::run();");
};
$this->maxFiles = $maxSelectedFiles;
$this->control = Html::el("div"); // TODO: support for prototype
$this->maxFileSize = self::parseIniSize(ini_get('upload_max_filesize'));
$this->simUploadThreads = 5;
}
/**
* Generates control
* @return Html
*/
public function getControl() {
$this->setOption('rendered', TRUE);
// Create control
$control = Html::el('div class=MultipleFileUpload')->id($this->getHtmlId());
// <section token field>
$tokenField = Html::el('input type=hidden')->name($this->getHtmlName() . '[token]')->value($this->getToken());
$control->add($tokenField);
// </section token field>
$fallbacks = array();
$interfaces = self::getUIRegistrator()->getInterfaces();
$num = count($interfaces);
$cnt = 1;
foreach ($interfaces AS $interface) {
$html = $interface->render($this);
// remove wrapping <script> tags
$init = \Nette\Utils\Strings::replace($interface->renderInitJavaScript($this), '/\s*<\/?script>\s*/');
$desctruct = $interface->renderDestructJavaScript($this);
$id = $this->getHtmlId() . "-MFUInterface-" . \Nette\Utils\Strings::webalize($interface->reflection->name);
$fallback = (object) array(
"id" => $id,
"init" => $init,
"destruct" => $desctruct
);
$fallbacks[] = $fallback;
$container = Html::el("div");
$container->setHtml($html);
$container->id = $id;
if ($cnt == $num) { // Last (will be rendered as JavaScript-disabled capable)
$container->style["display"] = "block";
} else {
$container->style["display"] = "none";
}
$cnt++;
$control->add($container);
}
$template = new UI\Template();
$template->setFile(dirname(__FILE__) . DIRECTORY_SEPARATOR . "RegisterJS.latte");
$template->id = $this->getHtmlId();
$template->fallbacks = $fallbacks;
$control->add($tem
8000
plate->__toString(TRUE));
/*
// <section without JavaScript>
$withoutJS = Html::el("div class=withoutJS");
$standardFileInput = Html::el("input type=file")
->name($this->getHtmlName() . '[files][]');
$withoutJS->add($this->createSectionWithoutJS($standardFileInput));
$control->add($withoutJS);
// </section without JavaScript>
// <section with JavaScript>
$withJS = Html::el("div class=withJS");
$uploadifyID = $this->getHtmlId() . "-uploadifyBox";
$withJS->add($this->createSectionWithJS($uploadifyID, $this->getToken()));
$control->add($withJS);
// </section with JavaScript>
*/
// Pokud už byla volána metoda handleUploads -
/* if(self::$handleUploadsCheck){
$control->add(Html::el('script type=text/javascript')->add(
'jQuery("#' . $uploadifyID . '").uploadify(' . json_encode($this->uploaderOptions) . ');'
));
}; */
return $control;
}
/**
* Loads and process STANDARD http request. NOT uploadify requests!
*/
public function loadHttpData() {
$name = $this->getHtmlName() . '[token]';
$data = $this->getForm()->getHttpData();
// Zjistí token fronty souborů, kterou jsou soubory doručeny
// -> Jak JS tak bez JS (akorát s JS už dorazí pouze token - nic jiného)
if (!empty($data)) {
$token = Forms\Helpers::extractHttpData($data, $name, Forms\Form::DATA_LINE);
if ($token) {
$this->token = $token;
} else {
throw new InvalidStateException("Token has not been received! Without token MultipleFileUploader can't identify which files has been received.");
}
}
}
/**
* Setts value
* @param mixed $value
*/
public function setValue($value) {
if ($value === null) {
// pole se vymaže samo v destructoru
} else {
throw new NotSupportedException('Value of MultiFileUpload component cannot be directly set.');
}
}
/**
* Getts value
* @return array
*/
public function getValue() {
$data = $this->getQueue()->getFiles();
// Ořízneme soubory, kterých je více než maximální *počet* souborů
// TODO: Nepřesunout jako validační pravidlo?
$pocetPolozek = count($data);
if ($pocetPolozek > $this->maxFiles) {
$rozdil = $pocetPolozek - $this->maxFiles;
for ($rozdil = $pocetPolozek - $this->maxFiles; $rozdil > 0; $rozdil--) {
array_pop($data);
}
}
return $data;
}
/**
* Returns token
* @return string|null
*/
public function getToken($need = true) {
// Load token from request
if (!$this->token) {
$this->loadHttpData();
}
// If upload do not start, generate queueID
if (!$this->token and !$this->form->isSubmitted()) {
$this->token = uniqid(rand());
}
if (!$this->token AND $need) {
throw new InvalidStateException("Can't get a token!");
}
return $this->token;
}
/**
* Getts queue model
* @return Model\IQueue
*/
public function getQueue() {
return self::getQueuesModel()->getQueue($this->getToken());
}
/**
* Destructors: makes fast cleanup
*/
public function __destruct() {
if ($this->getForm()->isSubmitted()) {
// comment out if you want to keep files after form submission as well, for cases of server errors so F5 can be used to refresh
$this->getQueue()->delete();
}
}
/* *****************************************************************************
* *************************** Validators **************************************
* ***************************************************************************** */
/**
* Filled validator: has been any file uploaded?
* @param Forms\IControl
* @return bool
*/
public static function validateFilled(Forms\IControl $control) {
$files = $control->getValue();
return (count($files) > 0);
}
/**
* FileSize validator: is file size in limit?
* @param Forms\Controls\UploadControl
* @param int file size limit
* @return bool
*/
public static function validateFileSize(Forms\Controls\UploadControl $control, $limit) {
$files = $control->getValue();
$size = 0;
foreach ($files AS $file) {
$size += $file->getSize();
}
return $size <= $limit;
}
/**
* MimeType validator: has file specified mime type?
* @param FileUpload
* @param array|string mime type
* @return bool
*/
public static function validateMimeType(Forms\Controls\UploadControl $control, $mimeType) {
throw new NotSupportedException("Can't validate mime type! This is MULTIPLE file upload control.");
}
/* * ******************* Helpers ******************** */
/**
* Parses ini size
* @param string $value
* @return int
*/
public static function parseIniSize($value) {
$units = array('k' => 1024, 'm' => 1048576, 'g' => 1073741824);
$unit = strtolower(substr($value, -1));
if (is_numeric($unit) || !isset($units[$unit]))
return $value;
return ((int) $value) * $units[$unit];
}
}
/**
* Extension method for FormContainer
*/
function FormContainer_addMultipleFileUpload(Forms\Container $_this, $name, $label = NULL, $maxFiles = 25) {
return $_this[$name] = new MultipleFileUpload($label, $maxFiles);
}
\Nette\Forms\Container::extensionMethod("\Nette\Forms\Container::addMultipleFileUpload", "MultipleFileUpload\FormContainer_addMultipleFileUpload");