-
Notifications
You must be signed in to change notification settings - Fork 1
/
webfm.module
executable file
·1135 lines (1047 loc) · 36.3 KB
/
webfm.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
/**
* @file
* WebFM Module
*/
// Include permissions handling
require_once(drupal_get_path('module', 'webfm') . '/webfm.permissions.inc');
// Include widget
require_once(drupal_get_path('module', 'webfm') . '/webfm.widget.inc');
/**
* Implements hook_menu().
*/
function webfm_menu() {
$items = array();
$items['documents'] = array(
'title' => 'Web Media Library',
'description' => 'Administer Documents for WebFM',
'page callback' => 'webfm_documents_view',
'access callback' => 'webfm_documents_access',
'type' => MENU_NORMAL_ITEM,
);
$items['webfm/browser'] = array(
'title' => 'Web Media Library',
'description' => 'Administer Documents for WebFM',
'page callback' => 'webfm_file_browser',
'access callback' => 'webfm_file_browser_access',
'type' => MENU_CALLBACK,
);
$items['admin/config/media/webfm'] = array(
'title' => 'WebFM',
'description' => 'Administer Documents for WebFM',
'page callback' => 'drupal_get_form',
'page arguments' => array('webfm_settings_form'),
'access arguments' => array('administer webfm'),
'access callback' => 'user_access',
'type' => MENU_NORMAL_ITEM,
);
$items['webfm/%/view'] = array(
'title' => 'File view',
'description' => 'View a WebFM File',
'page callback' => 'webfm_file_view',
'page arguments' => array(1),
'access callback' => 'webfm_document_view_access',
'type' => MENU_CALLBACK,
);
$items['webfm/%'] = array(
'title' => 'File view',
'description' => 'View a WebFM File',
'page callback' => 'webfm_file_view',
'page arguments' => array(1),
'access callback' => 'webfm_document_view_access',
'type' => MENU_CALLBACK,
);
$items['webfm_send/%'] = array(
'title' => 'That file has moved!',
'description' => 'View a missing WebFM File',
'page callback' => 'webfm_migrate_file_view',
'page arguments' => array(1),
'access callback' => 'webfm_document_view_access',
'type' => MENU_CALLBACK,
);
/*$items['webfm/%'] = array(
'title' => 'File download',
'description' => 'Download a WebFM File',
'page callback' => 'webfm_file_download',
'page arguments' => array(1),
'access callback' => 'webfm_document_download_access',
'type' => MENU_CALLBACK,
);*/
$items['webfm/%/download'] = array(
'title' => 'File download',
'description' => 'Download a WebFM File',
'page callback' => 'webfm_file_download',
'page arguments' => array(1),
'access callback' => 'webfm_document_download_access',
'type' => MENU_CALLBACK,
);
$items['webfm_js'] = array(
'title' => 'API Data Request',
'description' => 'Data Request For WebFM',
'page callback' => 'webfm_json',
'access callback' => 'webfm_documents_access',
'type' => MENU_CALLBACK,
);
return $items;
}
function webfm_documents_access() {
return user_access('access webfm');
}
function webfm_file_browser_access() {
return user_access('access webfm');
}
function webfm_document_download_access() {
return user_access('access any webfm document download') || user_access('access own webfm document download');;
}
function webfm_document_view_access() {
return user_access('access any webfm document view') || user_access('access own webfm document view');
}
/**
* Implements hook_info().
*/
function webfm_hook_info() {
$hooks = array();
$hooks['webfm_file_uploaded'] = array('group' => 'webfm');
}
/**
* Implements hook_webfm_file_uploaded().
*
* @todo Standardize parameter and variable names
*/
function webfm_webfm_file_uploaded($fname, $fid, $dest) {
$file = file_load($fid);
if ($file) {
$file->status = FILE_STATUS_PERMANENT;
$file = file_move($file, file_default_scheme() . '://' . $dest . '/' . $fname, FILE_EXISTS_ERROR);
$file->filename = $fname;
$file->uri = file_default_scheme() . '://' . $dest . '/' . $fname;
file_save($file);
$fields = array('fid' => $file->fid, 'modified' => filemtime($file->uri));
db_insert('webfm_file')->fields($fields)->execute();
if (function_exists('apachesolr_entity_update')) {
$fpieces = explode('.', $file->filename);
$ext = array_pop($fpieces);
if (in_array(strtolower($ext),array('pdf','xls','ppt','doc','xlsx','pptx','txt','docx','rtf','xml'))) {
$indexer_table = apachesolr_get_indexer_table('file');
db_merge($indexer_table)
->key(array(
'entity_type' => 'file',
'entity_id' => $file->fid,
))
->fields(array(
'bundle' => 'file',
'status' => $file->status,
'changed' => REQUEST_TIME,
))
->execute();
}
}
}
}
/**
* Implements hook_apachesolr_entity_info_alter()
*
*/
function webfm_apachesolr_entity_info_alter(&$entity_info) {
$entity_info['file']['indexable'] = TRUE;
$entity_info['file']['status callback'][] = 'webfm_apachesolr_status_callback';
$entity_info['file']['document callback'][] = 'webfm_apachesolr_index_solr_document';
$entity_info['file']['reindex callback'] = 'webfm_apachesolr_solr_reindex';
$entity_info['file']['index_table'] = 'webfm_apachesolr_index_entities_file';
$entity_info['file']['result callback'] = 'webfm_apachesolr_result';
}
function webfm_apachesolr_status_callback($entity_id, $entity_type) {
$file = file_load($entity_id);
return $file->status && property_exists($file,'webfm');
}
function webfm_apachesolr_index_solr_document(ApacheSolrDocument $document, $file, $entity_type) {
$document->is_uid = $file->uid;
$document->label = apachesolr_clean_text($file->filename);
$document->timestamp = apachesolr_date_iso($file->timestamp);
$document->ds_created = apachesolr_date_iso($file->timestamp);
$document->ds_changed = apachesolr_date_iso($file->timestamp);
$fpieces = explode('.', $file->filename);
$ext = array_pop($fpieces);
$document->bundle = $ext;
$document->bundle_name = $ext;
$document->ts_uri = $GLOBALS['base_url'] . '/webfm/' . $file->fid;
$document->url = $GLOBALS['base_url'] . '/webfm/' . $file->fid;
$document->path = $GLOBALS['base_url'] . '/webfm/' . $file->fid;
if (function_exists('drupal_get_path_alias')) {
$language = empty($file->language) ? NULL : $node->language;
$path = 'webfm/' . $file->fid;
$output = drupal_get_path_alias($path, $language);
if ($output && $output != $path) {
$document->path_alias = $output;
}
}
$env_id = apachesolr_default_environment();
$data = webfm_apachesolr_extract($env_id, $file);
$text = $data->extracted;
$text = iconv("UTF-8", "UTF-8//IGNORE", $text);
$document->content = trim(apachesolr_clean_text($text));
$documents = array();
$documents[] = $document;
return $documents;
}
function webfm_apachesolr_solr_reindex() {
$indexer_table = apachesolr_get_indexer_table('file');
$transaction = db_transaction();
$env_id = apachesolr_default_environment();
try {
db_delete($indexer_table)
->condition('entity_type', 'file')
->execute();
if (apachesolr_get_index_bundles($env_id, 'file')) {
$select = db_select('file_managed', 'f');
$select->join('webfm_file','w','w.fid = f.fid');
$select->addField('f', 'fid', 'entity_id');
$select->addExpression("'file'", 'bundle');
$select->addField('f', 'status', 'status');
$select->addExpression("'file'", 'entity_type');
$select->addExpression(REQUEST_TIME, 'changed');
$select->where("reverse(left(reverse(f.filename),LOCATE('.',reverse(f.filename))-1)) IN ('".implode('\',\'',array('pdf','xls','ppt','doc','xlsx','pptx','txt','docx','rtf','xml'))."')");
$insert = db_insert($indexer_table)
->fields(array('entity_id', 'status','bundle', 'entity_type', 'changed'))
->from($select)
->execute();
}
}
catch (Exception $e) {
$transaction->rollback();
drupal_set_message($e->getMessage(), 'error');
watchdog_exception('Apache Solr', $e);
return FALSE;
}
return TRUE;
}
function webfm_apachesolr_result($doc, &$result, &$extra) {
$result += array(
'type' => 'File',
'user' => theme('username', array('account' => $doc)),
'date' => isset($doc->created) ? $doc->created : 0,
'uid' => $doc->is_uid,
);
}
function webfm_apachesolr_extract($env_id, $file){
$env = apachesolr_environment_load($env_id);
$solr = apachesolr_get_solr($env_id);
try {
$filename = basename($file->uri);
$params = array(
'extractOnly' => 'true',
'resource.name' => $filename,
'extractFormat' => 'text',
);
$filepath = drupal_realpath($file->uri);
// Construct a multi-part form-data POST body in $data.
$boundary = '--' . md5(uniqid(REQUEST_TIME));
$data = "--{$boundary}\r\n";
// The 'filename' used here becomes the property name in the response.
$data .= 'Content-Disposition: form-data; name="file"; filename="extracted"';
$data .= "\r\nContent-Type: application/octet-stream\r\n\r\n";
$data .= file_get_contents($filepath);
$data .= "\r\n--{$boundary}--\r\n";
$headers = array('Content-Type' => 'multipart/form-data; boundary=' . $boundary);
$options = array(
'method' => 'POST',
'headers' => $headers,
'data' => $data,
);
}
catch (Exception $e) {
watchdog('Apache solr','Failed to open document %file',array('%file'=>$file->uri),WATCHDOG_ERROR);
return "";
}
try {
$response = $solr->makeServletRequest('update/extract',$params,$options);
}
catch (Exception $e) {
watchdog('Apache solr','Failed to index document %file',array('%file'=>$file->uri),WATCHDOG_ERROR);
watchdog_exception("Apache solr", $e);
}
return $response;
}
/**
* Implements hook_file_load().
*
* @todo Adjust/Replace this to make better use of Drupal 7 Entity API
*/
function webfm_file_load($files) {
$result = db_query('SELECT fid, modified FROM {webfm_file} f WHERE f.fid IN (:fids)', array(':fids' => array_keys($files)))->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $record) {
$files[$record['fid']]->webfm = TRUE;
foreach ($record as $key => $value) {
$files[$record['fid']]->$key = $value;
}
}
}
/**
* Implements hook_file_insert().
*
* @todo Adjust/Replace this to make better use of Drupal 7 Entity API
*/
function webfm_file_insert($file) {
if (property_exists($file, 'webfm') && $file->webfm) {
$fields = array('fid' => $file->fid, 'modified' => filemtime($file->uri));
db_insert('webfm_file')->fields($fields)->execute();
file_usage_add($file, 'webfm', 'webfm', 0, 1);
if (function_exists('apachesolr_entity_update')) {
$fpieces = explode('.', $file->filename);
$ext = array_pop($fpieces);
if (in_array(strtolower($ext),array('pdf','xls','ppt','doc','xlsx','pptx','txt','docx','rtf','xml'))) {
$indexer_table = apachesolr_get_indexer_table('file');
db_merge($indexer_table)
->key(array(
'entity_type' => 'file',
'entity_id' => $file->fid,
))
->fields(array(
'bundle' => 'file',
'status' => $file->status,
'changed' => REQUEST_TIME,
))
->execute();
}
}
}
}
/**
* Implements hook_file_update().
*
* @todo Adjust/Replace this to make better use of Drupal 7 Entity API
*/
function webfm_file_update($file) {
if (property_exists($file, 'webfm') && $file->webfm) {
$fields = array('modified' => filemtime($file->uri));
db_update('webfm_file')->fields($fields)->condition('fid', $file->fid, '=')->execute();
$usage = file_usage_list($file);
if (!isset($usage['webfm']))
{
file_usage_add($file, 'webfm', 'webfm', 0, 1);
}
if (function_exists('apachesolr_mark_entity')) {
apachesolr_mark_entity('file',$file->fid);
}
}
}
/**
* Implements hook_permission().
*/
function webfm_permission() {
return array(
'administer webfm' => array(
'title' => t('Administer WebFM'),
'description' => t('Allow users to administer WebFM'),
),
'access webfm' => array(
'title' => t('Access WebFM Document Management Page'),
'description' => t('Allow users to access webfm browser or document viewer'),
),
'access any webfm document view' => array(
'title' => t('View any documents'),
'description' => t('Allow users to access webfm files'),
),
'access any webfm document download' => array(
'title' => t('Download any documents'),
'description' => t('Allow users to access webfm files'),
),
'access own webfm document view' => array(
'title' => t('View own documents'),
'description' => t('Allow users to access webfm files'),
),
'access own webfm document download' => array(
'title' => t('Download own documents'),
'description' => t('Allow users to access webfm files'),
),
'access any webfm directory' => array(
'title' => t('Access any webfm directory'),
'description' => t('Allow users to access webfm files'),
),
'create webfm file' => array(
'title' => t('Upload files to webfm'),
'description' => t('Allow users to access webfm files'),
),
'create webfm directory' => array(
'title' => t('Create directories in webfm'),
'description' => t('Allow users to access webfm files'),
),
'delete any webfm file' => array(
'title' => t('Delete any webfm file'),
'description' => t('Allow users to access webfm files'),
),
'delete any webfm directory' => array(
'title' => t('Delete any webfm directory'),
'description' => t('Allow users to access webfm files'),
),
'delete own webfm files' => array(
'title' => t('Delete own webfm files'),
'description' => t('Allow users to access webfm files'),
),
'delete own webfm directories' => array(
'title' => t('Delete own webfm directories'),
'description' => t('Allow users to access webfm files'),
),
'replace any webfm file' => array(
'title' => t('Replace any webfm file'),
'description' => t('Allow users to access webfm files'),
),
'modify any webfm directory' => array(
'title' => t('Modify any webfm directory'),
'description' => t('Allow user to move or rename webfm directories'),
),
'modify own webfm directories' => array(
'title' => t('Modify own webfm directories'),
'description' => t('Allow users to move or rename their own webfm directories'),
),
'modify any webfm file' => array(
'title' => t('Modify any webfm file'),
'description' => t('Allow users to move or rename webfm files'),
),
'overwrite any webfm file' => array(
'title' => t('Overwrite any webfm file'),
'description' => t('Allow users to overwrite webfm files'),
),
'overwrite own webfm file' => array(
'title' => t('Overwrite own webfm file'),
'description' => t('Allow users to overwrite their own webfm files'),
),
'modify own webfm files' => array(
'title' => t('Modify own webfm files'),
'description' => t('Allow users to move or rename their own webfm files'),
),
);
}
/**
* Implements hook_theme().
*/
function webfm_theme(&$existing, $type, $theme, $path) {
$hooks = array();
$webfm_path = drupal_get_path('module', 'webfm') . '/tpl';
$hooks['webfm-documents'] = array(
'template' => 'webfm.documents',
'path' => $webfm_path,
);
$hooks['webfm-browser'] = array(
'template' => 'webfm.browser',
'path' => $webfm_path,
);
return $hooks;
}
/**
* Handle file download request
*/
function webfm_file_download($fid) {
if (strpos($fid,'public://') == 0) {
if (stripos(request_uri(),'/webfm') === FALSE) {
return array('Content-Type'=>'bin');
}
}
$fid = intval($fid);
if ($fid <= 0) {
drupal_not_found();
exit();
}
$file_obj = file_load($fid);
if (!$file_obj) {
drupal_not_found();
exit();
}
if (!user_access('access any webfm document download')) {
global $user;
if ($user->uid != $file_obj->uid) {
drupal_access_denied();
exit();
}
}
$name = mime_header_encode($file_obj->filename);
$type = mime_header_encode($file_obj->filemime);
$http_headers = array(
'Content-Type' => $type . '; name="' . $name . '"',
'Content-Disposition' => 'attachment; filename="' . $file_obj->filename . '"',
'Content-Length' => filesize($file_obj->uri),
);
$http_headers['Cache-Control'] = 'private';
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
$http_headers['Cache-Control'] = 'must-revalidate, post-check=0, pre-check=0';
$http_headers['Pragma'] = 'public';
}
else {
$http_headers['Pragma'] = 'no-cache';
}
file_transfer($file_obj->uri, $http_headers);
}
/**
* Handle access to old files
*/
function webfm_migrate_file_view($fid) {
$old = db_query('SELECT * FROM migrate_map_webfm_files WHERE sourceid1=:fid', array(':fid'=>$fid));
$record = $old->fetchObject();
if ($record)
{
$new_fid = $record->destid1;
return array('content'=>array(
'#markup'=>'We couldn\'t find the file you were looking for, <strong>but it looks like it might have moved <a href="/webfm/'.$new_fid.'">here</a></strong>!',
));
}
return array('content'=>array(
'#markup'=>'We couldn\'t find the file you were looking for!',
));
}
/**
* Handle file view request
*
* @todo Standarize code between this and down and put shared code into separate function.
*/
function webfm_file_view($fid) {
$fid = intval($fid);
if ($fid <= 0) {
drupal_not_found();
exit();
}
$file_obj = file_load($fid);
if (!$file_obj) {
drupal_not_found();
exit();
}
if (!user_access('access any webfm document view')) {
global $user;
if ($user->uid != $file_obj->uid) {
drupal_access_denied();
exit();
}
}
$name = mime_header_encode($file_obj->filename);
$type = mime_header_encode($file_obj->filemime);
$inline_types = variable_get('file_inline_types', array('^text/', '^image/', 'flash$', '^application/pdf'));
$disposition = 'attachment';
foreach ($inline_types as $inline_type) {
// Exclamation marks are used as delimiters to avoid escaping slashes.
if (preg_match('!' . $inline_type . '!', $file_obj->filemime)) {
$disposition = 'inline';
}
}
$http_headers = array(
'Content-Type' => $type . '; name="' . $name . '"',
'Content-Disposition' => $disposition . '; filename="' . $file_obj->filename . '"',
'Content-Length' => filesize($file_obj->uri),
);
if ($disposition == "attachment") {
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
$http_headers['Cache-Control'] = 'must-revalidate, post-check=0, pre-check=0';
$http_headers['Pragma'] = 'public';
}
else {
$http_headers['Pragma'] = 'no-cache';
}
}
else {
$http_headers['Cache-Control'] = 'private';
}
file_transfer($file_obj->uri, $http_headers);
}
/**
* Implements hook_wysiwyg_plugin().
*
* @todo Investigate supporting other wysiwyg's
*/
function webfm_wysiwyg_plugin($editor, $version) {
if ($editor == 'ckeditor') {
return array('webfm' => array(
'load' => FALSE,
'options' => array('filebrowserBrowseUrl' => '/webfm/browser'),
'extensions' => array('Webfm' => t('WebFM')),
));
}
}
/**
* Implements hook_ckeditor_plugin().
*/
function webfm_ckeditor_plugin() {
return array(
'webfm' => array(
'name' => 'webfm',
'desc' => t('WebFM CKEditor Plugin'),
'path' => drupal_get_path('module', 'webfm') . '/plugins/webfm/',
),
);
}
/**
* Handle viewing of the documents page
*/
function webfm_documents_view() {
// Invoke the webfm_init hook
module_invoke_all('webfm_init');
module_invoke_all('webfm_register_backend');
// Investigate moving this into a hook for webfm_init
webfm_js();
webfm_css();
$form_markup = '';
// Only provide the upload markup if they are allowed to upload files
if (user_access('create webfm file')) {
$form_markup = drupal_get_form('webfm_uploader_form');
}
$webfm_markup = theme('webfm-documents', array());
$page = array('content' => array(
'webfm' => array('#markup' => $webfm_markup),
'webfm_file_upload' => $form_markup,
));
return $page;
}
/**
* Handle webfm file browser page (used for inbedded pages, wyiwyg etc)
*/
function webfm_file_browser() {
// Invoke webfm_init hook
module_invoke_all('webfm_init');
module_invoke_all('webfm_register_backend');
// See comment in documents view
webfm_js();
webfm_css();
$form_markup = '';
// Only provide the upload markup if they have permission to create files
if (user_access('create webfm file')) {
$form_data = drupal_get_form('webfm_uploader_form');
$form_markup = drupal_render($form_data);
}
$webfm_markup = theme('webfm-documents', array());
print theme('webfm-browser', array('content' => $webfm_markup . $form_markup));
module_invoke_all('exit');
exit();
}
/**
* Uploader form
*
* @todo Increase support for third party modules drop in of uploader
* @todo Ensure that a valid uploader exists, provide a simple default if not
*/
function webfm_uploader_form($form, &$form_state) {
$form = array();
$form['#attributes']['class'][] = 'webfm-uploader-form';
$form['webfm_uploader'] = array(
'#title' => t('Upload Files'),
'#type' => 'webfm_managed_file',
'#description' => t('Choose files to upload into WebFM'),
);
return $form;
}
/**
* Helper function to decode utf8 parameters
*/
function webfm_utf8_urldecode($str) {
$str = preg_replace("/%u([0-9a-f]{3,4})/i", "&#x\\1;", urldecode($str));
return html_entity_decode($str, NULL, 'UTF-8');
}
/**
* Handle JSON Requests, this is where any ajax request will come in
*
* @todo Consider renaming this function
*/
function webfm_json() {
// Invoke webfm_init hook
module_invoke_all('webfm_init');
module_invoke_all('webfm_register_backend');
// Include the file backend class definition
require_once(dirname(__FILE__) . '/webfm.filebackend.inc');
// Get a valid file backend
// This will hopefully in the future support things like S3 etc
$backend = webfm_get_active_backend();
// Grab the requestion ajax action from the post arguments
// @ignore Handled with input filtering below
$action = $_POST['action'];
// @todo rethink this code, quick and dirty atm
// It is up to module developers to properly sanitize these values before outputting them
$param0 = (!empty($_POST['param0'])) ? $_POST['param0'] : NULL;
$param1 = (!empty($_POST['param1'])) ? $_POST['param1'] : NULL;
$param2 = (!empty($_POST['param2'])) ? $_POST['param2'] : NULL;
$param3 = (!empty($_POST['param3'])) ? $_POST['param3'] : NULL;
$param4 = (!empty($_POST['param4'])) ? $_POST['param4'] : NULL;
// Set out content type header
// @todo Consider moving this line of code
drupal_add_http_header('Content-type', 'application/json');
// Intialize response array
$response = array();
if (preg_match('/[^a-zA-Z0-9_-]+/', $action)) {
$response['status'] = 'false';
$response['err'] = t('Invalid action');
print json_encode($response);
// Exit
module_invoke_all('exit');
exit();
return;
}
// Ensure a valid backend has been included
if ($backend == NULL) {
watchdog('WebFM', 'Failed to load a WebFM file backend, please make sure the required modules are enabled', array(), WATCHDOG_ERROR);
$response['status'] = 'false';
$response['err'] = t('WebFM is improperly configured');
print json_encode($response);
// Exit
module_invoke_all('exit');
exit();
return;
}
// Set success status to true by default
$response['status'] = "true";
// Invoke webfm_json_action hook
module_invoke_all('webfm_json_action', $backend, $response, $action, $param0, $param1, $param2, $param3, $param4);
// Default handlers of actions
switch ($action) {
// Read all directories for the directory listing
// @todo Consider renaming this action, its name is a relic from WebFM 6
case 'readtrees':
$treeData = new stdClass();
$treeData->trees = array();
// Build the directory listing from the backend
if ($param0)
{
$param0 = trim(webfm_utf8_urldecode($param0));
if (preg_match('/\.\./', $param0) || strpos($param0, variable_get('webfm_root', "SITE")) !== 0) {
$response['status'] = 'false';
$response['err'] = t('Invalid path');
break;
}
$treeData->trees[0] = $backend->buildWebTree($param0);
}
else
{
$treeData->trees[0] = $backend->buildWebTree(variable_get('webfm_root', "SITE"));
}
// Invoke webfm_readtrees hook
module_invoke_all('webfm_readtrees', $backend, $treeData);
$response['tree'] = $treeData->trees;
break;
// Read all files and directories given a provided root
// @Todo Consider renaming this action, its name is a relic from WebFM 6
case 'readfiles':
// Check that they are questing a valid root, provide a default if not
// Look into adding a hook/setting to disable the default root for
// modules like WebFM OG
if ($param0) {
$param0 = trim(webfm_utf8_urldecode($param0));
if (preg_match('/\.\./', $param0)) {
$response['status'] = 'false';
$response['err'] = t('Invalid path');
break;
}
}
else {
$param0 = '/' . variable_get('webfm_root', 'SITE');
}
// Ensure that we are requesting a valid directory
// @todo Evaluate the usefulness of this function...
if (!$backend->pathExists($param0)) {
$response['status'] = 'false';
$response['err'] = t('Directory does not exist');
break;
}
// Set the breadcrumb
$response['bcrumb'] = explode('/', drupal_substr($param0, 1));
// Provide details about the root directory
// @todo Evaluate if this needs to exist
$response['root'] = array('p' => $param0, 'm' => filemtime(file_default_scheme() . '://' . $param0));
// Compose the file/directory data from the backend
$response = array_merge($response, $backend->buildFileData($param0));
break;
// The client uses local caching to minimie data requests
// This action provides file modification times to validate/invalidate cache
case 'updatecheck':
if ($param0) {
$param0 = trim(webfm_utf8_urldecode($param0));
if (preg_match('/\.\./', $param0)) {
$response['status'] = 'false';
$response['err'] = t('Invalid path');
break;
}
}
else {
$param0 = '/' . variable_get('webfm_root', 'SITE');
}
if (!$backend->pathExists($param0)) {
$response['status'] = 'false';
$response['err'] = t('Directory does not exist');
break;
}
// Return the file modified time and patho
$response['root'] = array('p' => $param0, 'm' => filemtime(file_default_scheme() . '://' . $param0));
break;
// Details about files, this utilized by the widget
// to get details about file attachments
case 'fileinfo':
if ($param0) {
$raw_fids = explode(',', $param0);
foreach ($raw_fids as $raw_fid) {
// Ensure we have what appears to be a valid fid
if (intval(trim($raw_fid)) > 0)
$fids[] = intval(trim($raw_fid));
}
// Load the file data
$files = file_load_multiple($fids);
// Build response
foreach ($files as $file) {
$path = file_uri_target($file->uri);
$pathParts = explode('/', $path);
array_pop($pathParts);
$path = implode('/', $pathParts);
$fdata = webfm_getFileData($file, '/' . $path);
$fdata['id'] = $file->fid;
$response['files'][] = $fdata;
}
}
else {
$response['status'] = 'false';
$response['err'] = t('Invalid request');
}
break;
default:
// Any other actions are dispatched out to the
// Action handlers see webfm.handlers.inc
dispatchRequest($action, array($param0, $param1, $param2, $param3), $response);
break;
}
// Return information the current directory
// @todo This may not currently be used, consider its removal
$response['current'] = '/' . variable_get('webfm_root', "SITE");
// @todo Evaluate what this is doing if anything
$response['admin'] = 'true';
// Invoke webfm_json_action_handled hook
module_invoke_all('webfm_json_action_handled', $backend, $response, $action, $param0, $param1, $param2, $param3, $param4);
// Encode and print the reponse;
print json_encode($response);
// Exit
module_invoke_all('exit');
exit();
}
/**
* Handle action request dispatching
*/
function dispatchRequest($action, $params, &$response) {
// Include the action handles file
require_once(dirname(__FILE__) . '/webfm.handlers.inc');
// Invoke webfm_json_action_dispatch hook
module_invoke_all('webfm_json_action_dispatch', $response, $action, $params);
// Check for a handler for this action
if (function_exists("webfm_ajax_" . $action)) {
call_user_func_array("webfm_ajax_" . $action, array($params, &$response));
}
else {
$response['status'] = 'false';
$response['err'] = t('Unknown action');
}
}
/**
* Helper function for file data reponses
*/
function webfm_getFileData($file, $path) {
$fpieces = explode('.', $file->filename);
$ext = array_pop($fpieces);
$fdata = array('n' => $file->filename,
'f' => 'true',
'p' => $path,
'm' => filemtime($file->uri),
'c' => filectime($file->uri),
'e' => $ext,
's' => filesize($file->uri));
module_invoke_all('webfm_getfiledata', $file, $path, $fdata);
return $fdata;
}
/**
* Helper function for file data reponses
*/
function webfm_getFileDataExt($file, $path) {
$fpieces = explode('.', $file->filename);
$ext = array_pop($fpieces);
$fdata = array('n' => $file->filename,
'id' => $file->fid,
'f' => 'true',
'p' => $path,
'm' => filemtime($file->uri),
'c' => filectime($file->uri),
'e' => $ext,
's' => filesize($file->uri));
module_invoke_all('webfm_getfiledata', $file, $path, $fdata);
return $fdata;
}
/**
* Function to remove unnessary CSS files from the browser page
*/
function webfm_browser_css() {
$css = drupal_add_css();
if (module_exists('admin_menu')) {
$strip = array('admin_menu', 'admin_menu_toolbar');
foreach ($strip as $rem) {
$mod_path = drupal_get_path('module', $rem);
if (!empty($mod_path)) {
$rem_items[] = $mod_path;
}
}
foreach (array_keys($css) as $key) {
foreach ($rem_items as $i) {
if (preg_match('|' . $i . '|', $key)) {
unset($css[$k]);
}
}
}
}
return drupal_get_css($css);
}
/**
* Function to remove unnessary JS from the browser page
*/
function webfm_browser_js() {
$js = drupal_add_js(NULL, array('scope' => 'header'));
if (module_exists('admin_menu')) {
$strip = array('admin_menu', 'admin_menu_toolbar');
foreach ($strip as $rem) {
$mod_path = drupal_get_path('module', $rem);
if (!empty($mod_path)) {
$rem_items[] = $mod_path;
}
}
foreach (array_keys($js) as $key) {
foreach ($rem_items as $i) {
if (preg_match('|' . $i . '|', $key)) {
unset($js[$k]);
}
}
}
}
return drupal_get_js('header', $js);
}
/**
* Add WebFM Required JS Files
*/
function webfm_js() {
global $base_root;
//$js = 'var jQuery17 = jQuery.noConflict(true);
$js = 'function getBaseUrl(){return "' . $base_root . '";}';
$js .= 'function getWebfmIconDir(){return "' . $base_root . '/' . drupal_get_path('module', 'webfm') . '/image/icon";}';
$js .= 'function getWebfmPluginDir(){return "' . $base_root . '/' . drupal_get_path('module', 'webfm') . '/plugins";}';
//drupal_add_js(drupal_get_path('module','webfm') . '/js/jquery-1.7.2.js');
drupal_add_js(drupal_get_path('module', 'webfm') . '/js/jquery-ui.js');
drupal_add_js(drupal_get_path('module', 'webfm') . '/js/zeroclipboard.min.js');
drupal_add_js(drupal_get_path('module', 'webfm') . '/js/jquery.contextmenu.js');
drupal_add_js($js, 'inline');
drupal_add_js(drupal_get_path('module', 'webfm') . '/js/webfm.js');
// Invoke webfm_added_js hook
module_invoke_all('webfm_added_js');
}