This repository has been archived by the owner on Jun 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docviewer.module
818 lines (755 loc) · 25.7 KB
/
docviewer.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
<?php
require_once('docviewer.cfg');
//определяет список возможных прав
function docviewer_perm() {
return array(t("read books"), t("download books"), t("add books"), t("delete own books"), t("administer docviewer"));
}
//вывод справки
function docviewer_help($path, $arg) {
$output = '';
switch ($path) {
case "admin/help#docviewer":
$output = '<p>'. t("Display interface for viewing docs (now only pdf)") .'</p>';
break;
}
return $output;
}
//ссылка в меню
function docviewer_menu() {
$items = array();
$items['books'] = array(
'title' => t('Documents'),
'description' => t('Documents list'),
'page callback' => 'docviewer_list',
'page arguments' => array(),
'type' => MENU_NORMAL_ITEM,
'access callback' => '_docviewer_list_perm',
);
$items['books/%user_uid_optional'] = array(
'page callback' => 'docviewer_list',
'page arguments' => array(1),
'type' => MENU_CALLBACK,
'access callback' => '_docviewer_list_perm',
);
$items['books/%user_uid_optional/%docviewer_document/%'] = array(
'page callback' => 'docviewer_get_page',
'page arguments' => array(1, 2, 3),
'type' => MENU_CALLBACK,
'access arguments' => array(t('read books')),
);
$items['books/%user_uid_optional/%docviewer_document'] = array(
'page callback' => 'docviewer_read_book',
'page arguments' => array(1, 2),
'type' => MENU_CALLBACK,
'access arguments' => array(t('read books')),
);
$items['docviewer/%docviewer_document/delete'] = array(
'title' => t('Delete document'),
'page callback' => 'drupal_get_form',
'page arguments' => array('docviewer_delete_confirm', 1),
'access callback' => 'docviewer_delete_document',
'type' => MENU_CALLBACK,
);
$items['books/%user_uid_optional/%docviewer_document/get'] = array(
'page callback' => 'docviewer_get_document',
'page arguments' => array(1, 2),
'type' => MENU_CALLBACK,
'access callback' => '_perm_get_book',
'access arguments' => array(1, 2),
);
$items['admin/content/docviewer_clear'] = array(
'title' => t('Delete failed documents'),
'description' => t('Delete failed documents.'),
'page callback' => 'drupal_get_form',
'page arguments' => array('docviewer_clear_form'),
'access arguments' => array(t('administer docviewer')),
'type' => MENU_NORMAL_ITEM,
);
$items['books/%user_uid_optional/%docviewer_document/edit'] = array(
'page callback' => 'drupal_get_form',
'page arguments' => array('docviewer_edit_form', 2),
'type' => MENU_NORMAL_ITEM,
'access callback' => 'docviewer_edit_access',
'access arguments' => array(2),
);
return $items;
}
//формы
//загрузка файла на сервер
function docviewer_upload_form() {
global $user;
//Администратор может загружать любые файлы. Проверки отключаются
if ($user->uid === 1) {
drupal_set_message("You are login as admin. File validation off.", "warning");
}
$objects = array();
$objects = docviewer_get_objects_select();
$objects[t('Add own section...')] = t('Add own section...');
$form = array();
//если условие выполняется значит была попытка загрузить файл больше разрешенного размера
if (($_SERVER['CONTENT_LENGTH'])&&(parse_size(ini_get("post_max_size")) < $_SERVER['CONTENT_LENGTH'])) {
drupal_set_message(t("File size is larger than allowed."), 'error');
}
$form['subj'] = array(
'#type' => 'fieldset',
'#title' => t('Upload file'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['#attributes'] = array('enctype' => "multipart/form-data");
$form['subj']['name'] = array(
'#type' => 'textfield',
'#title' => t('Document name'),
);
$form['subj']['notify'] = array(
'#type' => 'markup',
'#value' => '<div>'. t('If document name not write, document save with file name') .'</div>',
);
$form['subj']['section'] = array(
'#type' => 'fieldset',
'#collapsible' => FALSE,
'#collapsed' => FALSE,
'#prefix' => "<div class='container-inline'>",
'#suffix' => '</div>',
'#element_validate' => array('_subject_validate'),
);
$form['subj']['section']['subject'] = array(
'#type' => 'select',
'#title' => t('Section'),
'#required' => TRUE,
'#options' => $objects,
'#default_value' => t('Add own section...'),
);
$form['subj']['section']['own_subject'] = array(
'#type' => 'textfield',
'#title' => t(''),
);
$form['subj']['upload'] = array(
'#type' => 'file',
'#title' => t('Upload file'),
'#size' => 22,
);
$form['subj']['max_filesize'] = array(
'#type' => 'markup',
'#value' => "<div><b>Max file size:</b> ". (file_upload_max_size()/1024/1024) .'mB</div>',
);
$form['subj']['download'] = array(
'#type' => 'checkbox',
'#title' => t('Allow to download'),
'#default_value' => TRUE,
);
$form['subj']['submit'] = array(
'#type' => 'submit',
'#value' => t('Upload document'),
);
return $form;
}
//обработка данных из формы docviewer_upload
//TODO:AJAX, перенаправление на страницу с прогрессбаром
//TODO:learn drupal path build function, and rewrite function
//TODO:check mimetype
function docviewer_upload_form_submit($form, &$form_state) {
$file = _docviewer_upload_doc($form, $form_state);
switch ($file['error']) {
case 0:
db_query("UPDATE {docviewer_documents} SET active=1 WHERE md5sum='%s'", $file['md5sum']);
break;
case 1: break;
case 4:
unlink($file['source_by_id']);
db_query("DELETE FROM {docviewer_documents} WHERE md5sum='%s'", $file['md5sum']);
case 3:
_rm($file['cache_dir']);
case 2:
unlink($file['source_file']);
}
}
//TODO: move all variables in array 'status'
//upload document
//return:
//0 - succesfull
//1 - error without actions
//2 - save file
//3 - create cash-folder
//4 - rename document
function _docviewer_upload_doc($form, &$form_state) {
global $_source_dir;
global $_cache_dir;
global $user;
$status = array();
$validators = array(
"file_validate_extensions" => array('pdf'),
);
$dest = file_directory_path() .'/'. $_source_dir;
$cache = file_directory_path() .'/'. $_cache_dir;
//проверка директории для сохранения
if (!file_check_directory($dest, FILE_CREATE_DIRECTORY)) {
form_set_error('upload', t("Can't create directory for file"));
$status['error'] = 1;
return $status;
}
if (!file_check_directory($cache, FILE_CREATE_DIRECTORY)) {
form_set_error('upload', t("Can't create directory for file"));
$status['error'] = 1;
return $status;
}
//костыль: не вставляется значение напрямую из формы
if ($form_state['values']['download'] == "1") {
$is_download = 1;
}
else {
$is_download = 0;
}
$file = file_save_upload('upload', $validators, $dest);
if (empty($form_state['values']['name'])) $form_state['values']['name'] = $file->filename;
//не удалось сохранить файл
if ($file == 0) {
form_set_error('upload', t("File saving fail."));
$status['error'] = 1;
return $status;
}
$status['source_file'] = $file->filepath;
$md5sum = md5_file($file->filepath);
$status['md5sum'] = $md5sum;
$result = db_query("SELECT * FROM {docviewer_documents} WHERE md5sum='%s'", $md5sum);
if ($result->num_rows) {
form_set_error('upload', t("File already exists"));
$status['error'] = 2;
return $status;
}
$cache_folder = file_directory_path() ."/". $_cache_dir ."/". $md5sum;
$status['cache_dir'] = $cache_folder;
//не удалось создать папку для кэша
if (!file_check_directory($cache_folder, FILE_CREATE_DIRECTORY)) {
form_set_error('upload', "Failed create cache files folder.");
return 2;
}
$pages = _docviewer_caching_document($file->filepath, $cache_folder);
//Изображений не создано
if ($pages <= 0) {
form_set_error('upload', t("Document reading fail."));
$status['error'] = 3;
return $status;
}
$subject = ($form_state['values']['subject'] === t('Add own section...')) ? $form_state['values']['own_subject'] : $form_state['values']['subject'];
//Не удалось добавить информацию о файле в базу
if (!db_query("INSERT INTO {docviewer_documents} (name, pages, md5sum, uid, upload_date, filesize, download, filename, subject) VALUES('%s', '%d', '%s', '%d', '%d', '%d', '%d', '%s', '%s')", $form_state['values']['name'], $pages, $md5sum, $user->uid, $file->timestamp, $file->filesize, $is_download, $file->filename, check_plain($subject))) {
form_set_error('upload', t("Insert in database failed."));
$status['error'] = 3;
return $status;
}
$result = db_query("SELECT docid FROM {docviewer_documents} WHERE md5sum='%s'", $md5sum);
//не удалось узнать id только что созданного документа
if (!$result) {
form_set_error('upload', t("Database error."));
$status['error'] = 3;
return $status;
}
$result = db_fetch_object($result);
$source_move = $dest ."/". $result->docid;
//rename doc by id
if (!rename($file->filepath, $source_move)) {
form_set_error('upload', t('Rename document fail.'));
$status['error'] = 4;
return $status;
}
$status['source_by_id'] = $source_move;
$cache_move = file_directory_path() .'/'. $_cache_dir .'/'. $result->docid;
//переименование папки с кэшем
if (!rename($cache_folder, $cache_move)) {
form_set_error('upload', t("Rename cache folder fail. From '$cache_folder' to '$cache_move'. "));
$status['error'] = 3;
return $status;
}
drupal_set_message("File ". check_plain($file->filename) ." succesfull upload.");
$status['error'] = 0;
return $status;
}
//make cache for document. return page count of document
//TODO: add check with "is_dir"
function _docviewer_caching_document($doc, $cache_folder) {
$files = array();
exec("pdftoppm -png '". realpath($doc) ."' '". realpath($cache_folder) ."/page'");
$file = file_scan_directory($cache_folder, "^page{1}-[0-9]+\.png$");
foreach ($file as $value) {
if (_docviewer_resize($value->filename, 750, 0)) drupal_set_message("Resize file $value->basename failed.");
}
return count($file);
}
//рекурсивное удаление папки или файла
function _rm($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir ."/". $object) == "dir") _rm($dir ."/". $object); else unlink($dir ."/". $object);
}
}
reset($objects);
rmdir($dir);
}
if (is_file($dir)) {
unlink($dir);
}
}
//удаление документа
function docviewer_delete_confirm_submit($form, &$form_state) {
global $_source_dir;
global $_cache_dir;
$id = $form_state['values']['docid'];
if (!db_query("DELETE FROM {docviewer_documents} WHERE docid=%d", $id)) {
drupal_set_message(t("Delete document") . check_plain($id) . t("from database failed."), "error");
}
_rm(file_directory_path() ."/". $_source_dir ."/". $id);
_rm(file_directory_path() ."/". $_cache_dir ."/". $id);
drupal_set_message(check_plain(t('Document succesfull delete')));
drupal_goto("books/");
}
//форма подтверждения удаления
function docviewer_delete_confirm(&$form_state, $doc) {
global $user;
$form['docid'] = array(
'#type' => 'value',
'#value' => $doc->docid,
);
if(user_access(t('delete own books'))&&($doc->uid == $user->uid)) {
$own = true;
}
else {
$own = false;
}
if (user_access(t('administer docviewer'))||$own) {
return confirm_form($form, t("Are you sure you want to delete the document <i>") . check_plain($doc->name) . '</i>?', 'books', t('This action cannot be undone.'), t('Delete'), t('Cancel') );
}
else {
drupal_set_message("You haven't permission to delete this document.", "error");
drupal_goto("books");
}
}
//проверка существования документа
function docviewer_document_load($id) {
$result = db_query("SELECT * FROM {docviewer_documents} WHERE docid=%d AND active=1", $id);
return db_fetch_object($result);
}
//return the $page page of document with id=$docid
//TODO:check host of the document
function docviewer_get_page($uid, $doc, $page) {
global $_cache_dir;
if (preg_match("/^page-0*([0-9]+)$/i", $page, $matches) == 1) {
$page = $matches[1];
$zeros_q = 0;
$zeros = "";
for ($i = 0; $i<(strlen($doc->pages)-strlen($page)); $i++) $zeros_q++;
if (strlen($doc->pages) > strlen($doc->pages-1)) $zeros_q--;
for ($i = 0; $i<$zeros_q; $i++) $zeros .= "0";
if (($page <= $doc->pages)&&($page > 0)) {
header("Content-Type: image/png");
readfile(realpath(file_directory_path() ."/". $_cache_dir ."/". $doc->docid ."/page-". $zeros . $page .".png"));
}
}
drupal_goto();
}
//resize image (create only smaller picture) by width.
//0 - succesfull
//1 - error
function _docviewer_resize($path, $width) {
//$test=new Imagick($path);
//$cur_size=$test->getImageGeometry();
//if($width < $cur_size['width']) {
//$test->thumbnailImage($width,0);
//}
//$test->setImageColorspace(imagick::COLORSPACE_SRGB);
//$test->writeImage($path);
////Change quantity of colors
//$src = imagecreatefrompng($path);
//imagetruecolortopalette($src, false, 255);
//imagepng($src, $path);
//imagedestroy($src);
return 0;
}
function docviewer_list($uid = FALSE) {
$output = "";
if (user_access(t('add books'))||user_access(t('administer docviewer'))) $output .= drupal_get_form("docviewer_upload_form");
$output .= drupal_get_form('docviewer_list_filter', $uid);
return $output;
}
//access check documents
function docviewer_delete_document() {
if (user_access(t('administer docviewer'))||user_access(t('delete own books'))) return TRUE;
return FALSE;
}
function docviewer_node_info() {
return array(
'docviewer' => array(
'name' => t('Document viewer'),
'module' => 'docviewer',
'description' =>t("Node with embeded viewer."),
)
);
}
function docviewer_read_book($uid, $document) {
global $user;
$out = "";
$out .= theme('docviewer_viewer', $document, $uid);
return $out;
}
function _docviewer_list_perm() {
return TRUE;
}
function docviewer_theme() {
return array(
'docviewer_viewer' => array(
'template' => 'viewer',
'arguments' => array('document' => NULL, 'uid' => NULL),
),
'docviewer_clear_form' => array(
'file' => 'viewer',
'arguments' => array('form' => NULL),
),
);
}
function docviewer_get_document($uid, $doc) {
global $_source_dir;
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"". $doc->filename ."\";" );
readfile(realpath(file_directory_path() ."/". $_source_dir ."/". $doc->docid));
}
function docviewer_clear_form() {
global $_source_dir;
global $_cache_dir;
$form = array();
$form['header'] = array(
'#type' => 'value',
'#value' => array(
theme('table_select_header_cell'),
t('File'),
t('Warning')
),
);
$files = scandir(file_directory_path() ."/". $_source_dir);
$query = db_query("SELECT docid, pages FROM {docviewer_documents}");
$docs = array();
$options = array();
while ($row = db_fetch_object($query)) {
$docs[$row->docid] = array(
'pages' => $row->pages,
);
}
foreach($files as $file) {
if (($file == ".")||($file == "..")) {
continue;
}
if (!isset($docs[$file])) {
$options[$file] = '';
$form['error'][$file] = array(
'#type' => 'value',
'#value' => 'File not in base',
);
$form[$file] = array(
'#type' => 'value',
'#value' => 'source',
);
continue;
}
}
$files = scandir(file_directory_path() ."/". $_cache_dir);
foreach($files as $file) {
if (($file == ".")||($file == "..")) {
continue;
}
if (!isset($docs[$file])) {
$options[$file] = '';
if (isset($form['error'][$file])) {
$where = "all";
$err = "Record in database not exists";
}
else {
$where = "source";
$err = "File not in base";
}
$form['error'][$file] = array(
'#type' => 'value',
'#value' => $err,
);
$form[$file] = array(
'#type' => 'value',
'#value' => $where,
);
continue;
}
}
$form['chkbox'] = array(
'#type' => 'checkboxes',
'#options' => $options,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Delete'),
);
return $form;
}
function theme_docviewer_clear_form($form) {
$output = "";
$rows = array();
foreach (element_children($form['error']) as $key) {
$rows[] = array(
drupal_render($form['chkbox'][$key]),
'filename' => $key,
'error' => $form['error'][$key]['#value'],
);
}
$output .= theme("table", $form['header']['#value'], $rows);
$output .= drupal_render($form);
return $output;
}
function docviewer_clear_form_submit(&$form, $form_state) {
global $_source_dir;
global $_cache_dir;
$path = "";
foreach(element_children($form_state['values']['chkbox']) as $key) {
if ($form_state['values']['chkbox'][$key] === $key) {
$path = file_directory_path();
if ($form_state['values'][$key] == "source") {
$path = realpath($path ."/". $_source_dir);
}
if ($form_state['values'][$key] == "cache") {
$path = realpath($path ."/". $_cache_dir);
}
if ($form_state['values'][$key] == "all") {
_rm($path ."/". $_cache_dir ."/". $key);
$path = realpath($path ."/". $_source_dir);
}
_rm($path ."/". $key);
}
}
}
function docviewer_edit_form($form, $doc) {
$objects = array();
$objects = docviewer_get_objects_select();
$objects[t('Add own section...')] = t('Add own section...');
$query = db_query("SELECT subject FROM {docviewer_documents} WHERE docid='%d'", $doc->docid);
if ($result = db_fetch_object($query)) {
$default_object = $result->subject;
}else{
$default_object = "";
}
$form = array();
$form['id'] = array(
'#type' => 'hidden',
'#value' => $doc->docid,
);
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Document name'),
'#weight' => 0,
'#required' => TRUE,
'#default_value' => $doc->name,
);
$form['section'] = array(
'#type' => 'fieldset',
'#collapsible' => FALSE,
'#collapsed' => FALSE,
'#prefix' => "<div class='container-inline'>",
'#suffix' => '</div>',
'#element_validate' => array('_subject_validate'),
);
$form['section']['subject'] = array(
'#type' => 'select',
'#title' => t('Section'),
'#required' => TRUE,
'#options' => $objects,
'#default_value' => $default_object,
);
$form['section']['own_subject'] = array(
'#type' => 'textfield',
'#title' => t(''),
);
$form['download'] = array(
'#type' => 'checkbox',
'#title' => t('Allow to download'),
'#weight' => 5,
'#default_value' => $doc->download,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#weight' => 6,
);
return $form;
}
function docviewer_edit_form_submit($form, &$form_state) {
$subject = ($form_state['values']['subject'] === t('Add own section...')) ? $form_state['values']['own_subject'] : $form_state['values']['subject'];
db_query("UPDATE {docviewer_documents} SET name='%s', download='%d', subject='%s' WHERE docid='%d'", $form_state['values']['name'], $form_state['values']['download'], check_plain($subject), $form_state['values']['id']);
drupal_goto("/books");
}
function docviewer_edit_access($doc) {
global $user;
if (($user->uid == $doc->uid)||(user_access(t('administer docviewer')))) return TRUE;
}
function docviewer_viewer_preprocess(&$variables, $hook) {
}
function docviewer_get_objects_select() {
$query = db_query("SELECT subject FROM {docviewer_documents}");
$objects = array();
while ($row = db_fetch_object($query)) {
if (!isset($objects[$row->subject])) $objects[$row->subject] = $row->subject;
}
return $objects;
}
function _subject_validate($element, $form_state) {
if (($element['#post']['subject'] === t('Add own section...'))&&(empty($element['#post']['own_subject']))) {
form_set_error('own_subject', t('Enter section name'));
}
}
function docviewer_list_filter(&$form_state, $uid) {
global $user;
$form = array();
$users = docviewer_get_users_select();
$sections = docviewer_get_objects_select();
$sections['all'] = t('All');
$users['all'] = t('All');
$form['mark'] = array(
'#type' => 'markup',
'#value' => '<style type="text/css">
#edit-section-wrapper {display:inline-block;width:45%}
#edit-user-wrapper {display:inline-block;width:30%}
.submit-filter {display:inline-block;width:23%}
#filter .form-select {width:100%}
</style>',
);
if ($user->uid > 0) {
$form['filter'] = array(
'#type' => 'fieldset',
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#title' => t('Filter'),
);
$form['filter']['fields'] = array(
'#prefix' => '<div class="container-inline" id="filter">',
'#suffix' => '</div>',
);
$form['filter']['fields']['section'] = array(
'#type' => 'select',
'#title' => t('Section'),
'#required' => FALSE,
'#options' => $sections,
'#default_value' => (isset($form_state['storage']['section'])) ? $form_state['storage']['section'] : t('all'),
);
$form['filter']['fields']['user'] = array(
'#type' => 'select',
'#title' => t('User'),
'#required' => FALSE,
'#options' => $users,
'#default_value' => (isset($form_state['storage']['user'])) ? $form_state['storage']['user'] : t('all'),
);
$form['filter']['fields']['submit'] = array(
'#type' => 'submit',
'#attributes' => array("class"=>"submit-filter"),
'#value' => t('Apply'),
'#validate' => array('docviewer_filter_validate'),
);
}
$perpage = 20;
$header = array(
array('data' => 'Id', 'field' => 'docid'),
array('data' => t('Title'), 'field' => 'name'),
array('data' => t('Section'), 'field' => 'subject'),
array('data' => t('User'), 'field' => 'uid'),
array('data' => t('Size'), 'field' => 'filesize'),
array('data' => t('Pages'), 'field' => 'pages'),
t('Actions')
);
//generate table
$list = "";
//build query
$sql_end = "FROM {docviewer_documents} WHERE active=1";
$sql_q = "SELECT COUNT(*) ";
$sql_all = "SELECT * ";
//get user for condition
if(is_numeric($uid->uid)) {
$sql_end .= " AND uid='". $uid->uid ."'";
}elseif(isset($form['filter']['fields']['user']['#default_value']) && ($form['filter']['fields']['user']['#default_value'] != t('all'))){
$sql_end .= " AND uid='". $form['filter']['fields']['user']['#default_value'] ."'";
}
//get section for condition
if(isset($form['filter']['fields']['section']['#default_value']) && ($form['filter']['fields']['section']['#default_value'] != t('all'))){
$sql_end .= " AND subject='". $form['filter']['fields']['section']['#default_value'] ."'";
}
$sql_end .= " ". tablesort_sql($header);
$sql = $sql_all . $sql_middle . $sql_end;
$sql_count = $sql_q . $sql_middle . $sql_end;
$query = pager_query($sql, $perpage, 0, $sql_count);
$data = array();
while ($row = db_fetch_object($query)) {
$actions = "";
if (user_access(t('read books'))||user_access(t('administer docviewer'))) {
$actions .= l(t('view'), 'books/'. $row->uid .'/'. $row->docid);
}
if (($row->download == 1)&&(user_access(t('download books')))) {
$actions .= '<br>';
$actions .= l(t('download'), 'books/'. $row->uid .'/'. $row->docid .'/get');
}
if (docviewer_edit_access($row)) {
$actions .= '<br>';
$actions .= l(t('edit'), 'books/'. $row->uid .'/'. $row->docid .'/edit');
}
if ((($user->uid == $row->uid)&&user_access(t('delete own books')))||user_access(t('administer docviewer'))) {
$actions .= '<br>';
$actions .= l(t('delete'), 'docviewer/'. $row->docid .'/delete', array('alias' => TRUE));
}
$doc_user = user_load($row->uid);
$data[] = array(
$row->docid,
check_plain($row->name),
check_plain($row->subject),
check_plain($doc_user->name),
round($row->filesize/1024, 2) . t(" kB"),
$row->pages,
$actions,
);
}
$list .= theme_table($header, $data);
$list .= theme('pager');
$form['list'] = array(
'#type' => 'markup',
'#value' => $list,
);
return $form;
}
function docviewer_filter_validate($form, &$form_state) {
$form_state['storage'] = $form_state['values'];
$form_state['rebuild'] = TRUE;
}
//hard linked to table profile_values
function docviewer_get_users_select() {
//get surname
$query = db_query("SELECT users.uid, users.name, val.value FROM {users} AS users JOIN {docviewer_documents} AS docs ON users.uid=docs.uid LEFT JOIN {profile_values} AS val ON docs.uid=val.uid LEFT JOIN {profile_fields} AS profile ON val.fid=profile.fid WHERE profile.name='profile_surname' OR profile.name IS NULL AND docs.active=1");
$objects = array();
while ($row = db_fetch_object($query)) {
if (!isset($objects[$row->uid])) {
$objects[$row->uid] = $row->name;
if (!empty($row->value)) $objects[$row->uid] .= " - ". check_plain($row->value);
}
}
////get name
$query = db_query("SELECT docs.uid, val.value FROM {docviewer_documents} AS docs LEFT JOIN {profile_values} AS val ON docs.uid=val.uid LEFT JOIN {profile_fields} AS profile ON val.fid=profile.fid WHERE profile.name='profile_name' AND docs.active=1");
while ($row = db_fetch_object($query)) {
if (!empty($row->value))
$objects[$row->uid] .= " ". check_plain(mb_substr($row->value, 0, 1)) .". ";
}
////get secondname
$query = db_query("SELECT docs.uid, val.value FROM {docviewer_documents} AS docs LEFT JOIN {profile_values} AS val ON docs.uid=val.uid LEFT JOIN {profile_fields} AS profile ON val.fid=profile.fid WHERE profile.name='profile_pname' AND docs.active=1");
while ($row = db_fetch_object($query)) {
if (!empty($row->value))
$objects[$row->uid] .= " ". check_plain(mb_substr($row->value, 0, 1)) .".";
}
return $objects;
}
function _perm_get_book($uid, $doc) {
if (user_access(t('download books'), $uid) && ($doc->download == 1)) {
return TRUE;
}
else{
return FALSE;
}
}