-
Notifications
You must be signed in to change notification settings - Fork 188
/
InputfieldFile.module
1554 lines (1357 loc) · 45.2 KB
/
InputfieldFile.module
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php namespace ProcessWire;
/**
* An Inputfield for handling file uploads
*
* ProcessWire 3.x, Copyright 2022 by Ryan Cramer
* https://processwire.com
*
* @property string $extensions Allowed file extensions, space separated
* @property array $okExtensions File extensions that are whitelisted if any in $extensions are problematic. (3.0.167+)
* @property int $maxFiles Maximum number of files allowed
* @property int $maxFilesize Maximum file size
* @property bool $useTags Whether or not tags are enabled
* @property string $tagsList Predefined tags
* @property bool|int $unzip Whether or not unzip is enabled
* @property bool|int $overwrite Whether or not overwrite mode is enabled
* @property int $descriptionRows Number of rows for description field (default=1, 0=disable)
* @property string $destinationPath Destination path for uploaded file
* @property string $itemClass Class name(s) for each file item (default=InputfieldFileItem ui-widget ui-widget-content)
* @property bool|int $noUpload Set to true or 1 to disable uploading to this field
* @property bool|int $noLang Set to true or 1 to disable multi-language descriptions
* @property bool|int $noAjax Set to true or 1 to disable ajax uploading
* @property int $uploadOnlyMode Set to true or 1 to disable existing file list display, or 2 to also prevent file from having 'temp' status.
* @property bool|int $noCollapseItem Set to true to disable collapsed items (like for LanguageTranslator tool or other things that add tools to files)
* @property bool|int $noShortName Set to true to disable shortened filenames in output
* @property bool|int $noCustomButton Set to true to disable use of the styled <input type='file'>
* @property Pagefiles|Pagefile|null $value
*
* @method string renderItem($pagefile, $id, $n)
* @method string renderList($value)
* @method string renderUpload($value)
* @method void fileAdded(Pagefile $pagefile)
* @method array extractMetadata(Pagefile $pagefile, array $metadata = array())
* @method Pagefile|null processInputAddFile($filename)
* @method void processInputDeleteFile(Pagefile $pagefile)
* @method bool processInputFile(WireInputData $input, Pagefile $pagefile, $n)
* @method bool processItemInputfields(Pagefile $pagefile, InputfieldWrapper $inputfields, $id, WireInputData $input)
*
*/
class InputfieldFile extends Inputfield implements InputfieldItemList, InputfieldHasSortableValue {
public static function getModuleInfo() {
return array(
'title' => __('Files', __FILE__), // Module Title
'summary' => __('One or more file uploads (sortable)', __FILE__), // Module Summary
'version' => 128,
'permanent' => true,
);
}
/**
* Cache of responses we'll be sending on ajax requests
*
*/
protected $ajaxResponses = array();
/**
* Was a file replaced?
*
*/
protected $singleFileReplacement = false;
/**
* Saved instanceof WireUpload in case API retrieval is needed (see getWireUpload() method)
*
*/
protected $wireUpload = null;
/**
* Set to the current Pagefile item when doing iteration
*
* @var Pagefile|null
*
*/
protected $currentItem = null;
/**
* True when field should behave in an upload only mode
*
* @var bool|int
*
*/
protected $uploadOnlyMode = 0;
/**
* This is true when we are only rendering the value rather than the inputs
*
* @var bool
*
*/
protected $renderValueMode = false;
/**
* True when in ajax mode
*
* @var bool
*
*/
protected $isAjax = false;
/**
* Admin theme specific settings
*
* @var array
*
*/
protected $themeSettings = array();
/**
* Commonly used text labels, translated, indexed by label name
*
* @var array
*
*/
protected $labels = array();
/**
* Cached value of Fieldgroup used for Pagefile custom fields, as used by getItemInputfields() method
*
* @var Fieldgroup|null|bool Null when not yet known, false when known not applicable, Fieldgroup when known and in use
*
*/
protected $itemFieldgroup = null;
/**
* Cached result from FieldtypeFile::getValidFileExtension()
*
* @var array
*
*/
protected $extensionsInfo = array();
/**
* Initialize the InputfieldFile
*
*/
public function init() {
parent::init();
// note: these two fields originate from FieldtypeFile.
// Initializing them here ensures this Inputfield has the values set automatically.
$this->set('extensions', '');
$this->set('okExtensions', array()); // manually whitelisted problematic extensions
$this->set('maxFiles', 0);
$this->set('maxFilesize', 0);
$this->set('useTags', 0);
$this->set('tagsList', '');
// native to this Inputfield
$this->set('unzip', 0);
$this->set('overwrite', 0);
$this->set('descriptionRows', 1);
$this->set('destinationPath', '');
$this->set('itemClass', 'InputfieldFileItem ui-widget ui-widget-content');
$this->set('noUpload', 0); // set to 1 to disable uploading to this field
$this->set('noLang', 0);
$this->set('noAjax', 0); // disable ajax uploading
$this->set('noCollapseItem', 0);
$this->set('noShortName', 0);
$this->set('noCustomButton', false);
$this->attr('type', 'file');
$this->labels = array(
'description' => $this->_('Description'),
'tags' => $this->_('Tags'),
'drag-drop' => $this->_('drag and drop files in here'),
'delete' => $this->_('Delete'),
'choose-file' => $this->_('Choose File'),
'choose-files' => $this->_('Choose Files'),
);
$input = $this->wire()->input;
$this->isAjax = $input->get('InputfieldFileAjax')
|| $input->get('reloadInputfieldAjax')
|| $input->get('renderInputfieldAjax');
$this->setMaxFilesize(trim(ini_get('post_max_size')));
$this->uploadOnlyMode = (int) $input->get('uploadOnlyMode');
$this->addClass('InputfieldItemList', 'wrapClass');
$this->addClass('InputfieldHasFileList', 'wrapClass');
$themeDefaults = array(
'error' => "<span class='ui-state-error-text'>{out}</span>",
);
$themeSettings = $this->wire()->config->InputfieldFile;
$this->themeSettings = is_array($themeSettings) ? array_merge($themeDefaults, $themeSettings) : $themeDefaults;
}
public function get($key) {
if($key === 'renderValueMode') return $this->renderValueMode;
if($key === 'singleFileReplacement') return $this->singleFileReplacement;
if($key === 'descriptionFieldLabel') return $this->labels['description'];
if($key === 'tagsFieldLabel') return $this->labels['tags'];
if($key === 'deleteLabel') return $this->labels['delete'];
if($key === 'themeSettings') return $this->themeSettings;
return parent::get($key);
}
public function set($key, $value) {
if($key == 'maxFilesize') return $this->setMaxFilesize($value);
return parent::set($key, $value);
}
/**
* Set the max file size in bytes or use string like "30m", "2g" "500k"
*
* @param int|string $filesize
* @return $this
*
*/
public function setMaxFilesize($filesize) {
$max = $this->strToBytes($filesize);
$phpMax = $this->strToBytes(ini_get('upload_max_filesize'));
if($phpMax < $max) $max = $phpMax;
parent::set('maxFilesize', $max);
return $this;
}
/**
* Convert string like "32M" to bytes (integer)
*
* @param string|int $filesize
* @return int
*
*/
protected function strToBytes($filesize) {
if(ctype_digit("$filesize")) {
$bytes = (int) $filesize;
} else {
$filesize = rtrim($filesize, 'bB'); // convert mb=>m, gb=>g, kb=>k
$last = strtolower(substr($filesize, -1));
if(ctype_alpha($last)) $filesize = rtrim($filesize, $last);
$filesize = (int) $filesize;
if($last == 'g') {
$bytes = (($filesize * 1024) * 1024) * 1024;
} else if($last == 'm') {
$bytes = ($filesize * 1024) * 1024;
} else if($last == 'k') {
$bytes = $filesize * 1024;
} else if($filesize > 0) {
$bytes = $filesize;
} else {
$bytes = (5 * 1024) * 1024;
}
}
return $bytes;
}
/**
* Per Inputfield interface, returns true when this field is empty
*
*/
public function isEmpty() {
return !wireCount($this->value);
}
/**
* Set an attribute
*
* @param array|string $key
* @param array|int|string $value
* @return Inputfield|InputfieldFile
*
*/
public function setAttribute($key, $value) {
if($key == 'value') {
if($value instanceof Pagefile) {
// if given a Pagefile rather than a Pagefiles, use the Pagefiles instead
$value = $value->pagefiles;
}
if($value instanceof Pagefiles) {
$page = $value->page;
if($page && $page->template->noLang) $this->noLang = true;
}
}
return parent::setAttribute($key, $value);
}
/**
* Check to ensure that the containing form as an 'enctype' attr needed for uploading files
*
*/
protected function checkFormEnctype() {
$parent = $this->parent;
while($parent) {
if($parent->attr('method') == 'post') {
if(!$parent->attr('enctype')) $parent->attr('enctype', 'multipart/form-data');
break;
}
$parent = $parent->parent;
}
}
/**
* Set the parent of this Inputfield
*
* @param InputfieldWrapper $parent
* @return $this
*
*/
public function setParent(InputfieldWrapper $parent) {
parent::setParent($parent);
$this->checkFormEnctype();
return $this;
}
/**
* Get the unique 'id' attribute for the given Pagefile
*
* @param Pagefile $pagefile
* @param string $context Optional context string (like for repeaters) 3.0.178+
* @return string
*
*/
protected function pagefileId(Pagefile $pagefile, $context = '') {
return $this->name . "_" . $context . $pagefile->hash;
}
/**
* Render a description input for the given Pagefile
*
* @param Pagefile $pagefile
* @param string $id
* @param int $n
* @return string
*
*/
protected function renderItemDescriptionField(Pagefile $pagefile, $id, $n) {
$sanitizer = $this->wire()->sanitizer;
$languages = $this->wire()->languages;
$user = $this->wire()->user;
if($n) {}
$out = '';
$tabs = '';
static $hasLangTabs = null;
static $langTabSettings = array();
if($this->renderValueMode) {
if($languages) {
$description = $pagefile->description($this->noLang ? $languages->getDefault() : $user->language);
} else {
$description = $pagefile->description;
}
if(strlen($description)) $description =
"<div class='InputfieldFileDescription detail'>" .
$sanitizer->entities1($description) .
"</div>";
return $description;
}
if($this->descriptionRows > 0) {
$userLanguage = $languages ? $user->language : null;
$defaultDescriptionFieldLabel = $sanitizer->entities1($this->labels['description']);
if(!$userLanguage || $languages->count() < 2 || $this->noLang) {
$numLanguages = 0;
$forLanguages = array(null);
} else {
$numLanguages = $languages->count();
$forLanguages = $languages;
if(is_null($hasLangTabs)) {
$modules = $this->wire()->modules;
$hasLangTabs = $modules->isInstalled('LanguageTabs');
if($hasLangTabs) {
/** @var LanguageTabs $languageTabs */
$languageTabs = $modules->getModule('LanguageTabs');
$langTabSettings = $languageTabs->getSettings();
}
}
}
foreach($forLanguages as $language) {
$descriptionFieldName = "description_$id";
$descriptionFieldLabel = $defaultDescriptionFieldLabel;
$labelClass = "detail";
$attrStr = '';
if($language) {
/** @var Language $language */
$tabField = empty($langTabSettings['tabField']) ? 'title' : $langTabSettings['tabField'];
$descriptionFieldLabel = (string) $language->getUnformatted($tabField);
if(empty($descriptionFieldLabel)) $descriptionFieldLabel = $language->get('name');
$descriptionFieldLabel = $sanitizer->entities($descriptionFieldLabel);
if(!$language->isDefault()) $descriptionFieldName = "description{$language->id}_$id";
$labelClass .= ' LanguageSupportLabel';
if(!$languages->editable($language)) {
$labelClass .= ' LanguageNotEditable';
$descriptionFieldLabel = "<s>$descriptionFieldLabel</s>";
}
$tabID = "langTab_{$id}__$language";
$aClass = "langTab$language";
if(!empty($langTabSettings['aClass'])) $aClass .= " " . $langTabSettings['aClass'];
$tabs .= "<li><a data-lang='$language' class='$aClass' href='#$tabID'>$descriptionFieldLabel</a></li>";
$out .= "<div class='InputfieldFileDescription LanguageSupport' data-language='$language' id='$tabID'>"; // open wrapper
} else {
$out .= "<div class='InputfieldFileDescription'>"; // open wrapper
$attrStr = "placeholder='$descriptionFieldLabel…'";
$labelClass = 'detail pw-hidden';
// for the $pagefile->description($language) call further below
if($languages && $this->noLang) $language = $languages->getDefault();
}
$attrStr = "name='$descriptionFieldName' id='$descriptionFieldName' $attrStr";
$out .= "<label for='$descriptionFieldName' class='$labelClass'>$descriptionFieldLabel</label>";
$description = $sanitizer->entities($pagefile->description($language));
if($this->descriptionRows > 1) {
$out .= "<textarea $attrStr rows='$this->descriptionRows'>$description</textarea>";
} else {
$out .= "<input type='text' $attrStr value='$description' />";
}
$out .= "</div>"; // close wrapper
}
if($numLanguages && $hasLangTabs) {
$ulClass = empty($langTabSettings['ulClass']) ? '' : " class='$langTabSettings[ulClass]'";
$ulAttr = empty($langTabSettings['ulAttrs']) ? '' : " $langTabSettings[ulAttrs]";
$out =
"<div class='hasLangTabs langTabsContainer'>" .
"<div class='langTabs'>" .
"<ul $ulAttr$ulClass>$tabs</ul>" .
$out .
"</div>" .
"</div>";
if($this->isAjax) {
$js = 'script';
$out .= "<$js>setupLanguageTabs($('#wrap_" . $this->attr('id') . "'));</$js>";
}
}
}
if($this->useTags) $out .= $this->renderItemTagsField($pagefile, $id, $n);
return $out;
}
/**
* Render the tags input for the given Pagefile
*
* @param Pagefile $pagefile
* @param string $id
* @param int $n
* @return string
*
*/
protected function renderItemTagsField(Pagefile $pagefile, $id, $n) {
$sanitizer = $this->wire()->sanitizer;
if($n) {}
$tagsLabel = $sanitizer->entities($this->labels['tags']) . '…';
$tagsStr = $sanitizer->entities($pagefile->tags);
$tagsAttr = '';
if($this->useTags >= FieldtypeFile::useTagsPredefined) {
// select predefined
$tagsClass = 'InputfieldFileTagsSelect';
$tagsAttr = "data-cfgname='InputfieldFileTags_{$this->hasField->name}' ";
} else {
// text input
$tagsClass = 'InputfieldFileTagsInput';
}
$out =
"<div class='InputfieldFileTags'>" .
"<label for='tags_$id' class='detail pw-hidden'>$tagsLabel</label>" .
"<input type='text' name='tags_$id' id='tags_$id' value='$tagsStr' " .
"placeholder='$tagsLabel' class='$tagsClass' $tagsAttr/>" .
"</div>";
return $out;
}
/**
* Get a basename for the file, possibly shortened, suitable for display in InputfieldFileList
*
* @param Pagefile $pagefile
* @param int $maxLength
* @return string
*
*/
public function getDisplayBasename(Pagefile $pagefile, $maxLength = 25) {
$displayName = $pagefile->basename;
if($this->noShortName) return $displayName;
if(strlen($displayName) > $maxLength) {
$ext = ".$pagefile->ext";
$maxLength -= (strlen($ext) + 1);
$displayName = basename($displayName, $ext);
$displayName = substr($displayName, 0, $maxLength);
$displayName .= "…" . ltrim($ext, '.');
}
return $displayName;
}
/**
* Render markup for a file item
*
* @param Pagefile $pagefile
* @param string $id
* @param int $n
* @return string
*
*/
protected function ___renderItem($pagefile, $id, $n) {
$displayName = $this->getDisplayBasename($pagefile);
$deleteLabel = $this->labels['delete'];
$uploadName = $pagefile->uploadName();
$icon = wireIconMarkupFile($pagefile->basename, "fa-fw HideIfEmpty");
$tooltip = $this->wire()->sanitizer->entities($pagefile->basename);
if($uploadName && $uploadName != $pagefile->basename) {
$uploadName = $this->wire()->sanitizer->entities($uploadName);
$icon = "<span class='pw-tooltip' title='$uploadName'>$icon</span>";
}
$out =
"<p class='InputfieldFileInfo InputfieldItemHeader ui-state-default ui-widget-header'>" .
"$icon " .
"<a class='InputfieldFileName pw-tooltip' title='$tooltip' target='_blank' href='$pagefile->url' download>$displayName</a> " .
"<span class='InputfieldFileStats'>" . str_replace(' ', ' ', $pagefile->filesizeStr) . "</span> ";
if(!$this->renderValueMode) $out .=
"<label class='InputfieldFileDelete'>" .
"<input type='checkbox' name='delete_$id' value='1' title='$deleteLabel' />" .
"<i class='fa fa-fw fa-trash'></i></label>";
$description = $this->renderItemDescriptionField($pagefile, $id, $n);
$class = 'InputfieldFileData ';
$class .= $description ? 'description ui-widget-content' : 'InputfieldFileFields';
$out .= "</p><div class='$class'>" . $description;
$inputfields = $this->getItemInputfields($pagefile);
if($inputfields) $out .= $inputfields->render();
if(!$this->renderValueMode) {
$out .= "<input class='InputfieldFileSort' type='text' name='sort_$id' value='$n' />";
}
$out .= "</div>";
return $out;
}
/**
* Wrap output of files list item
*
* @param string $out
* @return string
*
*/
protected function renderItemWrap($out) {
// note: using currentItem rather than a new argument since there are now a few modules extending
// this one and if they implement their own calls to this method or version of this method then
// they will get strict notices from php if we add a new argument here.
$item = $this->currentItem;
$id = $item && !$this->renderValueMode ? " id='file_$item->hash'" : "";
return "<li$id class='{$this->itemClass}'>$out</li>";
}
/**
* Render files list ready
*
* @param Pagefiles|null $value
* @throws WireException
* @throws WirePermissionException
*
*/
protected function renderListReady($value) {
if(!$this->renderValueMode) {
// if just rendering the files list (as opposed to saving it), delete any temp files that may have accumulated
if(!$this->overwrite && !count($_POST) && !$this->isAjax && !$this->uploadOnlyMode && !$this->wire()->config->ajax) {
$input = $this->wire()->input;
// don't delete files when in render single field or fields mode
if(!$input->get('field') && !$input->get('fields')) {
if($value instanceof Pagefiles) $value->deleteAllTemp();
}
}
}
}
/**
* Render files list
*
* @param Pagefiles|null $value
* @return string
*
*/
protected function ___renderList($value) {
if(!$value) return '';
$out = '';
$n = 0;
$this->renderListReady($value);
if(!$this->uploadOnlyMode && WireArray::iterable($value)) {
foreach($value as $pagefile) {
$id = $this->pagefileId($pagefile);
$this->currentItem = $pagefile;
$out .= $this->renderItemWrap($this->renderItem($pagefile, $id, $n++));
}
}
$class = 'InputfieldFileList ui-helper-clearfix';
if($this->overwrite && !$this->renderValueMode) $class .= " InputfieldFileOverwrite";
if($out) $out = "<ul class='$class'>$out</ul>";
return $out;
}
/**
* Render upload area
*
* @param Pagefiles|null $value
* @return string
*
*/
protected function ___renderUpload($value) {
if($value) {}
if($this->noUpload || $this->renderValueMode) return '';
// enables user to choose more than one file
if($this->maxFiles != 1) $this->setAttribute('multiple', 'multiple');
$attrs = $this->getAttributes();
unset($attrs['value']);
if(substr($attrs['name'], -1) != ']') $attrs['name'] .= '[]';
$extensions = $this->getAllowedExtensions();
$formatExtensions = $this->formatExtensions();
$chooseLabel = $this->labels['choose-file'];
$dragDropLabel = $this->labels['drag-drop'];
$attrStr = $this->getAttributesString($attrs);
$out =
"<div " .
"data-maxfilesize='$this->maxFilesize' " .
"data-extensions='$extensions' " .
"data-fieldname='$attrs[name]' " .
"class='InputfieldFileUpload'>
";
if($this->getSetting('noCustomButton')) {
$out .= "<input $attrStr>";
} else {
$out .= "
<div class='InputMask ui-button ui-state-default'>
<span class='ui-button-text'>
<i class='fa fa-fw fa-folder-open-o'></i>$chooseLabel
</span>
<input $attrStr>
</div>
";
}
$out .= "
<span class='InputfieldFileValidExtensions detail'>$formatExtensions</span>
<input type='hidden' class='InputfieldFileMaxFiles' value='$this->maxFiles' />
";
if(!$this->noAjax) $out .= "
<span class='AjaxUploadDropHere description'>
<span>
<i class='fa fa-cloud-upload'></i> $dragDropLabel
</span>
</span>
";
$out .= "</div>"; // .InputfieldFileUpload
return $out;
}
/**
* Render ready
*
* @param Inputfield|null $parent
* @param bool $renderValueMode
* @return bool
*
*/
public function renderReady(Inputfield $parent = null, $renderValueMode = false) {
$config = $this->wire()->config;
$this->addClass('InputfieldNoFocus', 'wrapClass');
if(!$renderValueMode) $this->addClass('InputfieldHasUpload', 'wrapClass');
if($this->useTags) {
$jQueryUI = $this->wire()->modules->get('JqueryUI'); /** @var JqueryUI $jQueryUI */
$jQueryUI->use('selectize');
$this->addClass('InputfieldFileHasTags', 'wrapClass');
if($this->useTags >= FieldtypeFile::useTagsPredefined && $this->hasField) {
// predefined tags
$fieldName = $this->hasField->name;
$jsName = "InputfieldFileTags_$fieldName";
$allowUserTags = $this->useTags & FieldtypeFile::useTagsNormal;
$data = $config->js($jsName);
if(!is_array($data)) $data = array();
if(empty($data['tags'])) {
$tags = array();
foreach(explode(' ', (string) $this->get('tagsList')) as $tag) {
$tag = trim($tag);
if(!strlen($tag)) continue;
$tags[strtolower($tag)] = $tag;
}
if($allowUserTags) {
$pagefiles = $this->val();
if($pagefiles instanceof Pagefiles) {
$_tags = $pagefiles->tags(true);
if(count($_tags)) $tags = array_merge($tags, $_tags);
}
}
$data['tags'] = array_values($tags);
$data['allowUserTags'] = $allowUserTags;
$config->js($jsName, $data);
}
$this->wrapAttr('data-configName', $jsName);
} else {
// regular tags text input
}
}
$data = $config->js('InputfieldFile');
if(!is_array($data)) $data = array();
if(empty($data['labels'])) $data['labels'] = array();
if(empty($data['labels']['bad-ext'])) {
$data['labels']['bad-ext'] = $this->_('Unsupported file extension, please use only: EXTENSIONS');
$data['labels']['too-big'] = $this->_('File is too big - maximum allowed size is MAX_KB kb');
$config->js('InputfieldFile', $data);
}
$this->getItemInputfields(); // custom fields ready
return parent::renderReady($parent, $renderValueMode);
}
/**
* Render Inputfield input
*
* @return string
*
*/
public function ___render() {
if(!$this->extensions) {
$this->error($this->_('No file extensions are defined for this field.'));
}
if($this->allowCollapsedItems()) {
$this->addClass('InputfieldItemListCollapse', 'wrapClass');
}
$numItems = (int) wireCount($this->value);
if($numItems === 0) {
$this->addClass('InputfieldFileEmpty', 'wrapClass');
} else if($numItems === 1) {
$this->addClass('InputfieldFileSingle', 'wrapClass');
} else {
$this->addClass('InputfieldFileMultiple', 'wrapClass');
}
return $this->renderList($this->value) . $this->renderUpload($this->value);
}
/**
* Render Inputfield value
*
* @return string
*
*/
public function ___renderValue() {
$this->renderValueMode = true;
$out = $this->render();
$this->renderValueMode = false;
return $out;
}
/**
* File added hook
*
* @param Pagefile $pagefile
* @throws WireException
*
*/
protected function ___fileAdded(Pagefile $pagefile) {
if($this->noUpload) return;
$sanitizer = $this->wire()->sanitizer;
$isValid = $sanitizer->validateFile($pagefile->filename(), array(
'pagefile' => $pagefile
));
if($isValid === false) {
$errors = $sanitizer->errors('clear array');
throw new WireException(
"$pagefile->basename - " . $this->_('File failed validation') .
(count($errors) ? ": " . implode(', ', $errors) : "")
);
} else if($isValid === null) {
// there was no validator available for this file type
}
$message = $this->_('Added file:') . " {$pagefile->basename}"; // Label that precedes an added filename
if($this->isAjax && !$this->noAjax) {
$n = count($this->value);
if($n) $n--; // for sorting
$this->currentItem = $pagefile;
$markup = $this->fileAddedGetMarkup($pagefile, $n);
$this->ajaxResponse(false, $message, $pagefile->url, $pagefile->filesize(), $markup);
} else {
$this->message($message);
}
$user = $this->wire()->user;
$pagefile->createdUser = $user;
$pagefile->modifiedUser = $user;
}
/**
* Get markup for added file
*
* @param Pagefile $pagefile
* @param int $n
* @return string
*
*/
protected function fileAddedGetMarkup(Pagefile $pagefile, $n) {
return $this->renderItemWrap($this->renderItem($pagefile, $this->pagefileId($pagefile), $n));
}
/**
* Given a Pagefile return array of meta data pulled from it
*
* @param Pagefile $pagefile
* @param array $metadata Existing metadata, if applicable
* @return array Associative array of meta data (i.e. description and tags)
*
*/
protected function ___extractMetadata(Pagefile $pagefile, array $metadata = array()) {
$languages = $this->wire()->languages;
if($languages) {
$metadata['description'] = $pagefile->description($languages->getDefault());
} else {
$metadata['description'] = $pagefile->description;
}
if($languages && !$this->noLang) {
foreach($languages as $language) {
/** @var Language $language */
if($language->isDefault()) continue;
$metadata["description$language->id"] = $pagefile->description($language);
}
}
$metadata['tags'] = $pagefile->tags;
$filedata = $pagefile->filedata();
if(count($filedata)) {
$metadata['filedata'] = $filedata;
}
return $metadata;
}
/**
* Process input to add a file
*
* @param string $filename
* @return Pagefile|null Returns Pagefile (added 3.0.212+)
* @throws WireException
*
*/
protected function ___processInputAddFile($filename) {
$total = count($this->value);
$metadata = array();
if($this->maxFiles > 1 && $total >= $this->maxFiles) return null;
// allow replacement of file if maxFiles is 1
if($this->maxFiles == 1 && $total) {
/** @var Pagefile $pagefile */
$pagefile = $this->value->first();
$metadata = $this->extractMetadata($pagefile, $metadata);
$rm = true;
if($filename == $pagefile->basename) {
// use overwrite mode rather than replace mode when single file and same filename
if($this->overwrite) $rm = false;
}
if($rm) {
if($this->overwrite) $this->processInputDeleteFile($pagefile);
$this->singleFileReplacement = true;
}
}
if($this->overwrite) {
$pagefile = $this->value->get($filename);
clearstatcache();
if($pagefile) {
// already have a file of the same name
if($pagefile instanceof Pageimage) $pagefile->removeVariations();
$metadata = $this->extractMetadata($pagefile, $metadata);
} else {
// we don't have a file with the same name as the one that was uploaded
// file must be in another files field on the same page, that could be problematic
$ul = $this->getWireUpload();
// see if any files were overwritten that weren't part of our field
// if so, we need to restore them and issue an error
$err = false;
$files = $this->wire()->files;
foreach($ul->getOverwrittenFiles() as $bakFile => $newFile) {
if(basename($newFile) != $filename) continue;
$files->unlink($newFile);
$files->rename($bakFile, $newFile); // restore
$ul->error(sprintf($this->_('Refused file %s because it is already on the file system and owned by a different field.'), $filename));
$err = true;
}
if($err) return null;
}
}
$this->value->add($filename);
/** @var Pagefile $item */
$item = $this->value->last();
try {
foreach($metadata as $key => $val) {
if($val) $item->$key = $val;
}
// items saved in ajax or uploadOnly mode are temporary till saved in non-ajax/non-uploadOnly
if($this->isAjax && !$this->overwrite) {
if($this->wire()->input->get('InputfieldFileAjax') !== 'noTemp') {
$item->isTemp(true);
}
}
$this->fileAdded($item);
} catch(\Exception $e) {
$item->unlink();
$this->value->remove($item);
throw new WireException($e->getMessage());
}
return $item;
}
/**
* Process input to delete a Pagefile item
*
* @param Pagefile $pagefile
*
*/
protected function ___processInputDeleteFile(Pagefile $pagefile) {
$fileLabel = $this->wire()->config->debug ? $pagefile->url() : $pagefile->name;
$this->message($this->_("Deleted file:") . " $fileLabel"); // Label that precedes a deleted filename
$this->value->delete($pagefile);
$this->trackChange('value');
}
/**
* Process input for one Pagefile
*
* @param WireInputData $input
* @param Pagefile $pagefile
* @param int $n
* @return bool
*
*/
protected function ___processInputFile(WireInputData $input, Pagefile $pagefile, $n) {
$saveFields = false; // allow custom Inputfields to be saved?
$changed = false; // are there any changes to this file?
$id = $this->name . '_' . $pagefile->hash;
if($this->uploadOnlyMode) {