-
Notifications
You must be signed in to change notification settings - Fork 0
/
habarisilo.plugin.php
789 lines (706 loc) · 28.9 KB
/
habarisilo.plugin.php
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
<?php
namespace Habari;
if ( !defined( 'HABARI_PATH' ) ) { die( 'No direct access' ); }
/**
* Simple file access silo
*
* @todo Create some helper functions in a superclass to display panel controls more easily, so that you don't need to include 80 lines of code to build a simple upload form every time.
*/
class HabariSilo extends Plugin implements MediaSilo
{
protected $root = null;
protected $url = null;
const SILO_NAME = 'Habari';
const DERIV_DIR = '.deriv';
/**
* Initialize some internal values when plugin initializes
*/
public function action_init()
{
$user_path = HABARI_PATH . '/' . Site::get_path( 'user', true );
$this->root = $user_path . 'files'; //Options::get('simple_file_root');
$this->url = Site::get_url( 'user', true ) . 'files'; //Options::get('simple_file_url');
}
public function filter_activate_plugin( $ok, $file )
{
if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) {
if ( !$this->check_files() ) {
EventLog::log( _t( "Habari Silo activation failed. The web server does not have permission to create the 'files' directory for the Habari Media Silo." ), 'warning', 'plugin' );
Session::error( _t( "Habari Silo activation failed. The web server does not have permission to create the 'files' directory for the Habari Media Silo." ) );
$ok = false;
}
// Don't bother loading if the gd library isn't active
if ( !function_exists( 'imagecreatefromjpeg' ) ) {
EventLog::log( _t( "Habari Silo activation failed. PHP has not loaded the gd imaging library." ), 'warning', 'plugin' );
Session::error( _t( "Habari Silo activation failed. PHP has not loaded the gd imaging library." ) );
$ok = false;
}
}
return $ok;
}
public function action_plugin_activation( $file )
{
// Create required tokens
ACL::create_token( 'create_directories', 'Create media silo directories', 'Administration' );
ACL::create_token( 'delete_directories', 'Delete media silo directories', 'Administration' );
ACL::create_token( 'upload_media', 'Upload files to media silos', 'Administration' );
ACL::create_token( 'delete_media', 'Delete files from media silos', 'Administration' );
}
/**
* function filter_plugin_config
* Add configuration options
*/
public function filter_plugin_config( $actions )
{
$actions['configure'] = _t('Configure');
return $actions;
}
public function action_plugin_ui_configure()
{
$ui = new FormUI( strtolower( get_class( $this ) ) );
$ui->append( FormControlLabel::wrap( _t('Max thumbnail width:'), FormControlText::create( 'max_thumbnail_width', __CLASS__ . '__max_thumbnail_width' ) ) );
$ui->max_thumbnail_width->add_validator('validate_regex', '/^[0-9]*$/', _t('Only numbers may be entered for thumbnail width.'));
$ui->append( FormControlLabel::wrap( _t('Max thumbnail height:'), FormControlText::create( 'max_thumbnail_height', __CLASS__ . '__max_thumbnail_height' ) ) );
$ui->max_thumbnail_height->add_validator('validate_regex', '/^[0-9]*$/', _t('Only numbers may be entered for thumbnail height.'));
$ui->append( FormControlLabel::wrap( _t('Always create square thumbnails (pad with black if not high enough):' ), FormControlCheckbox::create( 'force_square', __CLASS__ . '__force_square_thumbnail' ) ) );
$ui->append(FormControlSubmit::create('save')->set_caption('Save'));
$ui->out();
}
/**
* function filter_token_description_display
* Plugin filter to localize token descriptions
* @param string Token to get the description of
* @return string The localized token description
*/
public function filter_token_description_display( $token )
{
$desc = array(
'create_directories' => _t( 'Create media silo directories' ),
'delete_directories' => _t( 'Delete media silo directories' ),
'upload_media' => _t( 'Upload files to media silos' ),
'delete_media' => _t( 'Delete files from media silos' ),
);
return isset( $desc[$token] ) ? $desc[$token] : $token;
}
/**
*
* @param string $file. The name of the plugin file
*
* Delete the special silo permissions if they're no longer
* being used.
*/
public function action_plugin_deactivation( $file ) {
$silos = Plugins::get_by_interface( 'MediaSilo' );
if ( count( $silos ) <= 1 ) {
ACL::destroy_token( 'upload_media' );
ACL::destroy_token( 'delete_media' );
ACL::destroy_token( 'create_directories' );
ACL::destroy_token( 'delete_directories' );
}
}
/**
*
* Checks if files directory is usable
*/
private function check_files() {
$user_path = HABARI_PATH . '/' . Site::get_path( 'user', true );
$this->root = $user_path . 'files'; //Options::get('simple_file_root');
$this->url = Site::get_url( 'user', true ) . 'files'; //Options::get('simple_file_url');
if ( !is_dir( $this->root ) ) {
if ( is_writable( $user_path ) ) {
mkdir( $this->root, 0755 );
}
else {
return false;
}
}
return true;
}
/**
* Return basic information about this silo
* name- The name of the silo, used as the root directory for media in this silo
**/
public function silo_info()
{
return array(
'name' => self::SILO_NAME,
'icon' => URL::get_from_filesystem( __FILE__ ) . '/icon.png'
);
}
/**
* Return directory contents for the silo path
* @param string $path The path to retrieve the contents of
* @return array An array of MediaAssets describing the contents of the directory
**/
public function silo_dir( $path )
{
if ( !isset( $this->root ) ) {
return array();
}
$path = preg_replace( '%\.{2,}%', '.', $path );
$results = array();
$dir = Utils::glob( $this->root . ( $path == '' ? '' : '/' ) . $path . '/*' );
foreach ( $dir as $item ) {
if ( substr( basename( $item ), 0, 1 ) == '.' ) {
continue;
}
if ( basename( $item ) == 'desktop.ini' ) {
continue;
}
$file = basename( $item );
$props = array(
'title' => basename( $item ),
);
if(is_dir($item)) {
$results[] = new MediaAsset(
self::SILO_NAME . '/' . $path . ($path == '' ? '' : '/') . basename( $item ),
is_dir( $item ),
$props
);
}
else {
$results[] = $this->silo_get( $path . ($path == '' ? '' : '/') . basename( $item ) );
}
}
//print_r($results);
return $results;
}
/**
* Get the file from the specified path
* @param string $path The path of the file to retrieve
* @param array $qualities Qualities that specify the version of the file to retrieve.
* @return MediaAsset The requested asset
**/
public function silo_get( $path, $qualities = null )
{
if ( ! isset( $this->root ) ) {
return false;
}
$path = preg_replace( '%\.{2,}%', '.', $path );
$file = basename( $path );
$props = array(
'title' => basename( $path ),
);
$realfile = $this->root . '/' . $path;
$thumbnail_suffix = HabariSilo::DERIV_DIR . '/' . $file . '.thumbnail.jpg';
$thumbnail_url = $this->url . '/' . dirname( $path ) . ( dirname( $path ) == '' ? '' : '/' ) . $thumbnail_suffix;
$mimetype = preg_replace(' %[^a-z_0-9]%', '_', Utils::mimetype( $realfile ) );
$mtime = '';
if ( !file_exists( dirname( $realfile ) . '/' . $thumbnail_suffix ) ) {
// Attempt to create thumbnail
$max_thumbnail_width = Options::get( __CLASS__ . '__max_thumbnail_width', Media::THUMBNAIL_WIDTH );
$max_thumbnail_height = Options::get( __CLASS__ . '__max_thumbnail_height', Media::THUMBNAIL_HEIGHT );
if ( !$this->create_thumbnail( $realfile, $max_thumbnail_width, $max_thumbnail_height ) ) {
// there is no thumbnail so use icon based on mimetype.
$icon_path = Plugins::filter( 'habarisilo_icon_base_path', dirname( $this->get_file() ) . '/icons' );
$icon_url = Plugins::filter( 'habarisilo_icon_base_url', $this->get_url() . '/icons' );
if ( ( $icons = Utils::glob( $icon_path . '/*.{png,jpg,gif,svg}', GLOB_BRACE ) ) && $mimetype ) {
$icon_keys = array_map( function($a) {return pathinfo($a, PATHINFO_FILENAME);}, $icons );
$icons = array_combine( $icon_keys, $icons );
$icon_filter = function($a, $b) use ($mimetype) {
return (((strpos($mimetype, $a)===0) ? (strlen($a) / strlen($mimetype)) : 0) >= (((strpos($mimetype, $b)===0)) ? (strlen($b) / strlen($mimetype)) : 0)) ? $a : $b;
};
$icon_key = array_reduce( $icon_keys, $icon_filter );
if ($icon_key) {
$icon = basename( $icons[$icon_key] );
$thumbnail_url = $icon_url .'/'. $icon;
}
else {
// couldn't find an icon so use default
$thumbnail_url = $icon_url .'/default.png';
}
}
}
}
// If the asset is an image, obtain the image dimensions
if ( in_array( $mimetype, array( 'image_jpeg', 'image_png', 'image_gif' ) ) ) {
list( $props['width'], $props['height'] ) = getimagesize( $realfile );
$mtime = '?' . filemtime( $realfile );
}
$props = array_merge(
$props,
array(
'url' => $this->url . '/' . dirname( $path ) . ( $path == '' ? '' : '/' ) . $file,
'thumbnail_url' => $thumbnail_url . $mtime,
'filetype' => $mimetype,
)
);
$asset = new MediaAsset( self::SILO_NAME . '/' . $path, false, $props );
if ( file_exists( $realfile ) && is_file( $realfile ) ) {
$asset->content = file_get_contents( $realfile );
}
return $asset;
}
/**
* Create a thumbnail in the derivative directory
*
* @param string $src_filename The source filename
* @param integer $max_width The maximum width of the output image
* @param integer $max_height The maximum height of the output image
* @return boolean true if the thumbnail creation succeeded
*/
private function create_thumbnail( $src_filename, $max_width = Media::THUMBNAIL_WIDTH, $max_height = Media::THUMBNAIL_HEIGHT )
{
// Does derivative directory not exist?
$thumbdir = dirname( $src_filename ) . '/' . HabariSilo::DERIV_DIR . '';
if ( !is_dir( $thumbdir ) ) {
// Create the derivative driectory
if ( !mkdir( $thumbdir, 0755 ) ) {
// Couldn't make derivative directory
return false;
}
}
// Get information about the image
$isize = @getimagesize( $src_filename );
if(is_array($isize)) {
list( $src_width, $src_height, $type, $attr )= $isize;
}
else {
$type = '';
$src_img = '';
}
// Load the image based on filetype
switch ( $type ) {
case IMAGETYPE_JPEG:
$src_img = imagecreatefromjpeg( $src_filename );
break;
case IMAGETYPE_PNG:
$src_img = imagecreatefrompng( $src_filename );
break;
case IMAGETYPE_GIF:
$src_img = imagecreatefromgif ( $src_filename );
break;
default:
return false;
}
// Did the image fail to load?
if ( !$src_img ) {
return false;
}
// Calculate the output size based on the original's aspect ratio
$y_displacement = 0;
$displace = Options::get( __CLASS__ . '__force_square_thumbnail', true );
if ( $src_width / $src_height > $max_width / $max_height ) {
$thumb_w = $max_width;
$thumb_h = $src_height * $max_width / $src_width;
if($displace) {
// thumbnail is not full height, position it down so that it will be padded on the
// top and bottom with black
$y_displacement = ( $max_height - $thumb_h ) / 2;
}
}
else {
$thumb_w = $src_width * $max_height / $src_height;
$thumb_h = $max_height;
}
// Create the output image and copy to source to it
$dst_img = ImageCreateTrueColor( $thumb_w, ($displace) ? $max_height : $thumb_h );
imagecopyresampled( $dst_img, $src_img, 0, $y_displacement, 0, 0, $thumb_w, $thumb_h, $src_width, $src_height );
/* Sharpen before save?
$sharpenMatrix= array( array(-1, -1, -1), array(-1, 16, -1), array(-1, -1, -1) );
$divisor= 8;
$offset= 0;
imageconvolution( $dst_img, $sharpenMatrix, $divisor, $offset );
//*/
// Define the thumbnail filename
$dst_filename = $thumbdir . '/' . basename( $src_filename ) . ".thumbnail.jpg";
// Save the thumbnail as a JPEG
imagejpeg( $dst_img, $dst_filename );
// Clean up memory
imagedestroy( $dst_img );
imagedestroy( $src_img );
return true;
}
/**
* Create a new asset instance for the specified path
* @param string $path The path of the new file to create
* @return MediaAsset The requested asset
**/
public function silo_new( $path )
{
}
/**
* Store the specified media at the specified path
* @param string $path The path of the file to retrieve
* @param MediaAsset $filedata The MediaAsset to store
* @return boolean True on success
**/
public function silo_put( $path, $filedata )
{
$path = preg_replace('%\.{2,}%', '.', $path);
$file = $this->root . '/' . $path;
$result = $filedata->save( $file );
if ( $result ) {
$max_thumbnail_width = Options::get( __CLASS__ . '__max_thumbnail_width', Media::THUMBNAIL_WIDTH );
$max_thumbnail_height = Options::get( __CLASS__ . '__max_thumbnail_height', Media::THUMBNAIL_HEIGHT );
$this->create_thumbnail( $file, $max_thumbnail_width, $max_thumbnail_height );
}
return $result;
}
/**
* Delete the file at the specified path
* @param string $path The path of the file to retrieve
**/
public function silo_delete( $path )
{
$file = $this->root . '/' . $path;
// Delete the file
$result = unlink( $file );
// If it's an image, remove the file in .deriv too
$thumbdir = dirname( $file ) . '/' . HabariSilo::DERIV_DIR . '';
$thumb = $thumbdir . '/' . basename( $file ) . ".thumbnail.jpg";
if ( file_exists( $thumbdir ) && file_exists( $thumb ) ) {
unlink( $thumb );
// if this is the last thumb, delete the .deriv dir too
if ( self::isEmptyDir( $thumbdir ) ) {
rmdir( $thumbdir );
}
}
return $result;
}
/**
* Retrieve a set of highlights from this silo
* This would include things like recently uploaded assets, or top downloads
* @return array An array of MediaAssets to highlihgt from this silo
**/
public function silo_highlights()
{
}
/**
* Retrieve the permissions for the current user to access the specified path
* @param string $path The path to retrieve permissions for
* @return array An array of permissions constants (MediaSilo::PERM_READ, MediaSilo::PERM_WRITE)
**/
public function silo_permissions( $path )
{
}
/**
* Produce a link for the media control bar that causes a specific path to be displayed
*
* @param string $path The path to display
* @param string $title The text to use for the link in the control bar
* @return string The link to create
*/
public function link_path( $path, $title = '' )
{
if ( $title == '' ) {
$title = basename( $path );
}
return '<a href="#" onclick="habari.media.showdir(\''.$path.'\');return false;">' . $title . '</a>';
}
/**
* Produce a link for the media control bar that causes a specific panel to be displayed
*
* @param string $path The path to pass
* @param string $path The panel to display
* @param string $title The text to use for the link in the control bar
* @return string The link to create
*/
public function link_panel( $path, $panel, $title )
{
return '<a href="#" onclick="habari.media.showpanel(\''.$path.'\', \''.$panel.'\');return false;">' . $title . '</a>';
}
/**
* Provide controls for the media control bar
*
* @param array $controls Incoming controls from other plugins
* @param MediaSilo $silo An instance of a MediaSilo
* @param string $path The path to get controls for
* @param string $panelname The name of the requested panel, if none then emptystring
* @return array The altered $controls array with new (or removed) controls
*
* @todo This should really use FormUI, but FormUI needs a way to submit forms via ajax
*/
public function filter_media_controls( $controls, $silo, $path, $panelname )
{
$class = __CLASS__;
if ( $silo instanceof $class ) {
$controls[] = $this->link_path( self::SILO_NAME . '/' . $path, _t( 'Browse' ) );
if ( User::identify()->can( 'upload_media' ) ) {
$controls[] = $this->link_panel( self::SILO_NAME . '/' . $path, 'upload', _t( 'Upload' ) );
}
if ( User::identify()->can( 'create_directories' ) ) {
$controls[] = $this->link_panel( self::SILO_NAME . '/' . $path, 'mkdir', _t( 'Create Directory' ) );
}
if ( User::identify()->can( 'delete_directories' ) && ( $path && self::isEmptyDir( $this->root . '/' . $path ) ) ) {
$controls[] = $this->link_panel( self::SILO_NAME . '/' . $path, 'rmdir', _t( 'Delete Directory' ) );
}
}
return $controls;
}
/**
* Provide requested media panels for this plugin
*
* Regarding Uploading:
* A panel is returned to the media bar that contains a form, an iframe, and a javascript function.
* The form allows the user to select a file, and is submitted back to the same URL that produced this panel in the first place.
* This has the result of submitting the uploaded file to here when the form is submitted.
* To prevent the panel form from reloading the whole publishing page, the form is submitted into the iframe.
* An onload event attached to the iframe calls the function.
* The function accesses the content of the iframe when it loads, which should contain the results of the request to obtain this panel, which are in JSON format.
* The JSON data is passed to the habari.media.jsonpanel() function in media.js to process the data and display the results, just like when displaying a panel normally.
*
* @param string $panel The HTML content of the panel to be output in the media bar
* @param MediaSilo $silo The silo for which the panel was requested
* @param string $path The path within the silo (silo root omitted) for which the panel was requested
* @param string $panelname The name of the requested panel
* @return string The modified $panel to contain the HTML output for the requested panel
*
* @todo Move the uploaded file from the temporary location to the location indicated by the path field.
*/
public function filter_media_panels( $panel, $silo, $path, $panelname)
{
$class = __CLASS__;
if ( $silo instanceof $class ) {
switch ( $panelname ) {
case 'mkdir':
$fullpath = self::SILO_NAME . '/' . $path;
$form = new FormUI( 'habarisilomkdir' );
$form->append( FormControlStatic::create( 'ParentDirectory' )->set_static( '<div style="margin: 10px auto;">' . _t( 'Parent Directory:' ) . " <strong>/{$path}</strong></div>" ) );
// add the parent directory as a hidden input for later validation
$form->append( FormControlData::create( 'path' )->set_value( $path ) );
$form->append( FormControlData::create( 'action' )->set_value( $panelname ) );
$form->append( FormControlLabel::wrap( _t('What would you like to call the new directory?'),
FormControlText::create( 'directory' )->add_validator( array( $this, 'mkdir_validator' ) ) ) );
$form->append( FormControlSubmit::create( 'submit' )->set_caption( _t('Submit') ) );
$form->media_panel($fullpath, $panelname, 'habari.media.forceReload();');
$form->on_success( array( $this, 'dir_success' ) );
$panel = $form->get(); /* form submission magicallly happens here */
return $panel;
break;
case 'rmdir':
$fullpath = self::SILO_NAME . '/' . $path;
$form = new FormUI( 'habarisilormdir' );
$form->append( FormControlStatic::create( 'RmDirectory' )->set_static( '<div style="margin: 10px auto;">' . _t( 'Directory:' ) . " <strong>/{$path}</strong></div>" ) );
// add the parent directory as a hidden input for later validation
$form->append( FormControlData::create( 'path')->set_value( $path ) );
$form->append( FormControlData::create( 'action' )->set_value( $panelname ) );
$form->append( FormControlStatic::create( 'directory' )->set_static( _t( 'Are you sure you want to delete this directory?' ) ) );
$form->append( FormControlSubmit::create( 'submit' )->set_caption( _t('Delete') ) );
$form->media_panel( $fullpath, $panelname, 'habari.media.forceReload();' );
$form->on_success( array( $this, 'dir_success' ) );
$panel = $form->get(); /* form submission magicallly happens here */
return $panel;
break;
case 'delete':
$fullpath = self::SILO_NAME . '/' . $path;
$form = new FormUI( 'habarisilodelete' );
$form->append( FormControlStatic::create( 'RmFile' )->set_static( '<div style="margin: 10px auto;">' . _t( 'File:' ) . " <strong>/{$path}</strong></div>" ) );
// add the parent directory as a hidden input for later validation
$form->append( FormControlData::create( 'path')->set_value( $path ) );
$form->append( FormControlStatic::create( 'directory' )->set_static( '<p>' . _t( 'Are you sure you want to delete this file?' ) . '</p>' ) );
$form->append( FormControlSubmit::create( 'submit' )->set_caption( _t('Delete') ) );
$form->media_panel( $fullpath, $panelname, 'habari.media.forceReload();' );
$form->on_success( array( $this, 'do_delete' ) );
$panel = $form->get(); /* form submission magicallly happens here */
return $panel;
break;
case 'upload':
if ( isset( $_FILES['file'] ) ) {
// quit if tokens missing or time elapsed
if (!isset( $_POST['token'] ) or !isset( $_POST['token_ts'] ) or false === self::verify_token( $_POST['token'], $_POST['token_ts'] )) {
$msg = _t( 'Suspicious behaviour or too much time has elapsed. Please upload your file(s) again.' );
$panel .= '<p><strong>'.$msg.'</strong></p>';
EventLog::log( $msg , 'warn' );
return $panel;
break;
}
// rearrange $_FILES array so foreach loops work, maybe we should put the helper-function into core
$sorted_files = \Habari\HabariSilo::rearrange_files_arr($_FILES['file']);
// store path before we alter it - we need to reset it to make navigation in mediapanel work
$orig_path = $path;
$path = self::SILO_NAME . '/' . preg_replace('%\.{2,}%', '.', $path) . '/';
$panel .= '<ol>';
foreach($sorted_files as $file_to_upload) {
$size = Utils::human_size($file_to_upload['size']);
$path .= $file_to_upload['name'];
$asset = new MediaAsset($path, false);
$asset->upload($file_to_upload);
if ($asset->put()) {
$msg = _t('File uploaded: %s', array($file_to_upload['name']));
$panel .= '<li>' . $msg . ' ('.$size.') </li>';
EventLog::log($msg, 'info');
} else {
$upload_errors = array(
1 => _t('The uploaded file exceeds the upload_max_filesize directive in php.ini.'),
2 => _t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.'),
3 => _t('The uploaded file was only partially uploaded.'),
4 => _t('No file was uploaded.'),
6 => _t('Missing a temporary folder.'),
7 => _t('Failed to write file to disk.'),
8 => _t('A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.'),
);
$msg = _t('File upload failed: %s', array($file_to_upload['name']));
$panel .= '<li>' . $msg . '<strong>' . $upload_errors[$file_to_upload['error']] . '</strong></li>';
EventLog::log($msg . ' ' . $upload_errors[$file_to_upload['error']], 'err');
}
}
// revert to original path to make navigation in media panel work
$panel .= '</ol>';
$panel .= '<p><a href="#" onclick="habari.media.forceReload();habari.media.showdir(\'' . dirname( $path ) . '\');">' . _t( 'Browse the current silo path.' ) . '</a></p>';
$path = $orig_path;
}
else {
$token_ts = time();
$token = self::create_token( $token_ts );
$fullpath = self::SILO_NAME . '/' . $path;
$form_action = URL::get( 'admin_ajax', array( 'context' => 'media_upload' ) );
$panel .= <<< UPLOAD_FORM
<form enctype="multipart/form-data" method="post" id="simple_upload" target="simple_upload_frame" action="{$form_action}" class="span-10" style="margin:0px auto;text-align: center">
<p style="padding-top:30px;">%s <b style="font-weight:normal;color: #e0e0e0;font-size: 1.2em;">/{$path}</b></p>
<p><input type="file" name="file[]" multiple="multiple"><input type="submit" name="upload" value="%s">
<input type="hidden" name="path" value="{$fullpath}">
<input type="hidden" name="panel" value="{$panelname}">
<input type="hidden" name="token" value="{$token}">
<input type="hidden" name="token_ts" value="{$token_ts}">
</p>
</form>
<iframe id="simple_upload_frame" name="simple_upload_frame" style="width:1px;height:1px;" onload="simple_uploaded();"></iframe>
<script type="text/javascript">
var responsedata;
function simple_uploaded() {
if (!$('#simple_upload_frame')[0].contentWindow) return;
var response = $($('#simple_upload_frame')[0].contentWindow.document.body).text();
if (response) {
eval('responsedata = ' + response);
window.setTimeout(simple_uploaded_complete, 500);
}
}
function simple_uploaded_complete() {
habari.media.jsonpanel(responsedata.data);
}
</script>
UPLOAD_FORM;
$panel = sprintf( $panel, _t( "Upload to:" ), _t( "Upload" ) );
}
}
}
return $panel;
}
/**
* A validator for the mkdir form created with FormUI. Checks to see if the
* webserver can write to the parent directory and that the directory does
* not already exist.
* @param $dir The input from the form
* @param $control The FormControl object
* @param $form The FormUI object
*/
public function mkdir_validator( $dir, $control, $form )
{
if ( strpos( $dir, '*' ) !== false || preg_match( '%(?:^|/)\.%', $dir ) ) {
return array( _t( "The directory name contains invalid characters: %s.", array( $dir ) ) );
}
$path = preg_replace( '%\.{2,}%', '.', $form->path->value );
$dir = $this->root . ( $path == '' ? '' : '/' ) . $path . '/'. $dir;
if ( !is_writable( $this->root . '/' . $path ) ) {
return array( _t( "Webserver does not have permission to create directory: %s.", array( $dir ) ) );
}
if ( is_dir( $dir ) ) {
return array( _t( "Directory: %s already exists.", array( $dir ) ) );
}
return array();
}
/**
* This function performs the mkdir and rmdir actions on submission of the form.
* It is called by FormUI's success() method.
* @param FormUI $form
*/
public function dir_success ( $form )
{
$dir = preg_replace( '%\.{2,}%', '.', $form->directory->value );
$path = preg_replace( '%\.{2,}%', '.', $form->path->value );
switch ( $form->action->value ) {
case 'rmdir':
$dir = $this->root . ( $path == '' ? '' : '/' ) . $path;
rmdir( $dir );
$msg = _t( 'Directory deleted: /%s', array( $path ) );
break;
case 'mkdir':
$dir = $this->root . ( $path == '' ? '' : '/' ) . $path . '/'. $dir;
mkdir( $dir, 0755 );
$msg = _t ( 'Directory created: %s', array( $path . '/' . $form->directory->value ) );
break;
}
EventLog::log( $msg, 'info' );
return '<div class="span-18"style="padding-top:30px;color: #e0e0e0;margin: 0px auto;"><p>' . $msg . '</p></div>';
}
/**
* This function takes the path passed from the form and passes it to silo_delete
* to delete the file and it's thumbnail if it's an image.
*
* @param FormUI $form
*/
public function do_delete ( $form )
{
$path = preg_replace( '%\.{2,}%', '.', $form->path->value );
$result = $this->silo_delete($path);
$panel = '<div class="span-18"style="padding-top:30px;color: #e0e0e0;margin: 0px auto;">';
if ( $result ) {
$msg = _t( 'File deleted: /%s', array( $path ) );
} else {
$msg = _t( 'Failed to delete file: /%s', array( $path ) );
}
$panel .= '<p>' . $msg . '</p>';
$panel .= '<p><a href="#" onclick="habari.media.forceReload();habari.media.showdir(\'' . self::SILO_NAME . '/' . dirname( $path ) . '\');">' . _t( 'Browse the current silo path.' ) . '</a></p></div>';
EventLog::log( $msg, 'info' );
return $panel;
}
/**
* This function is used to check if a directory is empty.
*
* @param string $dir
* @return boolean
*/
private static function isEmptyDir( $dir )
{
return ( ( $files = @scandir( $dir ) ) && count( $files ) <= 2 );
}
/**
* Create the upload token based on the time string submitted and the UID for this Habari installation.
*
* @param integer $timestamp
* @return string
*/
private static function create_token( $timestamp )
{
return substr( md5( $timestamp . Options::get( 'public-GUID' ) ), 0, 10 );
}
/**
* Verify that the token and timestamp passed are valid.
*
* @param string $token
* @param integer $timestamp
*
* @TODO By default this gives the user 5 mins to upload a file from the time
* the form is display and the file uploaded. This should be sufficient,
* but do we a) need this timeout and b) should it be configurable?
*/
private static function verify_token( $token, $timestamp )
{
if ( $token == self::create_token( $timestamp ) ) {
if ( ( time() > ( $timestamp ) ) && ( time() < ( $timestamp + 5*60 ) ) ) {
return true;
}
} else {
return false;
}
}
/**
* When uploading multiple files, the FILES array is arranged in a rather strange form like
* FILES['name'][0] but for use in loops a form like FILES[0]['name'] is easier to process
* this functions rearranges the array, see also
* http://php.net/manual/en/features.file-upload.multiple.php#106565
*
* @param $array arr
* @return array $new
*/
private function rearrange_files_arr( $arr ){
foreach( $arr as $key => $all ){
foreach( $all as $i => $val ){
$new[$i][$key] = $val;
}
}
return $new;
}
}
?>