Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/Moodle/mod/print/lib.php
blob: 6bcc38cbbfbf671491078a9ae9dacfa100f3ca10 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
<?php  // $Id: lib.php,v 1.7.2.5 2009/04/22 21:30:57 skodak Exp $

/**
 * Library of functions and constants for module print
 * This file should have two well differenced parts:
 *   - All the core Moodle functions, neeeded to allow
 *     the module to work integrated in Moodle.
 *   - All the print specific functions, needed
 *     to implement all the module logic. Please, note
 *     that, if the module become complex and this lib
 *     grows a lot, it's HIGHLY recommended to move all
 *     these module specific functions to a new php file,
 *     called "locallib.php" (see forum, quiz...). This will
 *     help to save some memory when Moodle is performing
 *     actions across all modules.
 */



/**
 * Given an object containing all the necessary data,
 * (defined by the form in mod_form.php) this function
 * will create a new instance and return the id number
 * of the new instance.
 *
 * @param object $print An object from the form in mod_form.php
 * @return int The id of the newly inserted print record
 */


class print_base {
    
    var $cm;
    var $course;
    var $printconfig;
    var $submission;

    function print_base($cmid='staticonly', $printconfig=NULL, $cm=NULL, $course=NULL) {

        if ($cmid == 'staticonly') {
            //use static functions only!
            return;
        }

        global $CFG;

        if ($cm) {
            $this->cm = $cm;
        } else if (! $this->cm = get_coursemodule_from_id('print', $cmid)) {
            error('Course Module ID was incorrect');
        }
        $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);

        if ($course) {
            $this->course = $course;
        } else if ($this->cm->course == $COURSE->id) {
            $this->course = $COURSE;
        } else if (! $this->course = get_record('course', 'id', $this->cm->course)) {
            error('Course is misconfigured');
        }

        if ($printconfig) {
            $this->printconfig = $printconfig;
        } else if (! $this->printconfig = get_record('print', 'id', $this->cm->instance)) {
            error('print ID was incorrect');
        }
        
        #$this->submissions = $this->check_database("print_submissions");
        $this->printconfig->cmidnumber = $this->cm->id;     // compatibility with modedit assignment obj
        $this->printconfig->courseid   = $this->course->id; // compatibility with modedit assignment obj
        $this->printconfig->maxbytes = 2097152;
}
function check_database($table) {
           global $CFG,$USER;
           $sql = "SELECT *
                   FROM {$CFG->prefix}$table
                   WHERE userid = '$USER->id'
                   AND assignment = '{$this->printconfig->id}'";       
            
           return $sql;

}

function view1() {
          global $USER;

        require_capability('mod/print:view', $this->context);

        add_to_log($this->course->id, 'print', 'view', "view.php?id={$this->cm->id}", $this->printconfig->id, $this->cm->id);

        $this->view_header();


        if (has_capability('mod/print:submit', $this->context)) {
            
            if ($this->submissions = get_records_sql($this->check_database("print_submissions"))) {
               
               
            } else {
               $substring = "No Submissions yet";
               print_simple_box(get_string('nofilesyet', 'assignment'), 'center');
            }

            
            $filecount = $this->count_user_files($USER->id);
            $submission = $this->get_submissions1($USER->id);

           # $this->view_feedback();

                print_heading(get_string('submissiondraft', 'assignment'), '', 3);
            

            if ($filecount and $submission) {
                print_simple_box($this->print_user_files($USER->id, true), 'center');
            } else {
                   print_simple_box(get_string('nofilesyet', 'assignment'), 'center');
                }
            
           
            $this->view_upload_form();

            
       }
   }
      function view_header($subpage='') {

        global $CFG;


        if ($subpage) {
            $navigation = build_navigation($subpage, $this->cm);
        } else {
            $navigation = build_navigation('', $this->cm);
        }

        print_header('Print Uploads', $this->course->fullname, $navigation, '', '',
                     true, update_module_button($this->cm->id, $this->course->id, ''),
                     navmenu($this->course, $this->cm));

        groups_print_activity_menu($this->cm, 'view.php?id=' . $this->cm->id);
        
        echo '<div class="reportlink">'.$this->submittedlink().'</div>';
        echo '<div class="clearer"></div>';
    }
    
        function submissions($mode) {
        ///The main switch is changed to facilitate
        ///1) Batch fast grading
        ///2) Skip to the next one on the popup
        ///3) Save and Skip to the next one on the popup

        //make user global so we can use the id
        global $USER;

        
        switch ($mode) {
            case 'single':                        // We are in a popup window displaying submission
                $this->display_submission();
                break;

            case 'all':                          // Main window, display everything
                $this->display_submissions();
                break;

        
                foreach ($_POST[$col] as $id => $unusedvalue){

                    $id = (int)$id; //clean parameter name

                    $this->process_outcomes($id);

                    if (!$submission = $this->get_submission($id)) {
                        $submission = $this->prepare_new_submission($id);
                        $newsubmission = true;
                    } else {
                        $newsubmission = false;
                    }
                    unset($submission->data1);  // Don't need to update this.
                    unset($submission->data2);  // Don't need to update this.

                    //for fast grade, we need to check if any changes take place
                    $updatedb = false;
       
                   if ($commenting) {
                        $commentvalue = trim($_POST['submissioncomment'][$id]);
                        $updatedb = $updatedb || ($submission->submissioncomment != stripslashes($commentvalue));
                        $submission->submissioncomment = $commentvalue;
                    } else {
                        unset($submission->submissioncomment);  // Don't need to update this.
                    }

                    $submission->teacher    = $USER->id;
                    if ($updatedb) {
                        $submission->mailed = (int)(!$mailinfo);
                    }

                    $submission->timemarked = time();

                    //if it is not an update, we don't change the last modified time etc.
                    //this will also not write into database if no submissioncomment and grade is entered.

                    if ($updatedb){
                        if ($newsubmission) {
                            if (!isset($submission->submissioncomment)) {
                                $submission->submissioncomment = '';
                            }
                            if (!$sid = insert_record('print_submissions', $submission)) {
                                return false;
                            }
                            $submission->id = $sid;
                        } else {
                            if (!update_record('print_submissions', $submission)) {
                                return false;
                            }
                        }

                        // triger grade event
                        $this->update_grade($submission);

                        //add to log only if updating
                        add_to_log($this->course->id, 'print', 'update grades',
                                   'submissions.php?id='.$this->printconfig->id.'&user='.$submission->userid,
                                   $submission->userid, $this->cm->id);
                    }

                }

                $message = notify(get_string('changessaved'), 'notifysuccess', 'center', true);

                $this->display_submissions($message);
                break;


            case 'next':
                /// We are currently in pop up, but we want to skip to next one without saving.
                ///    This turns out to be similar to a single case
                /// The URL used is for the next submission.

                $this->display_submission();
                break;

            case 'saveandnext':
                ///We are in pop up. save the current one and go to the next one.
                //first we save the current changes
                if ($submission = $this->process_feedback()) {
                    //print_heading(get_string('changessaved'));
                    $extra_javascript = $this->update_main_listing($submission);
                }

                //then we display the next submission
                $this->display_submission($extra_javascript);
                break;

            default:
                echo "something seriously is wrong!!";
                break;
        }
    
}
    function display_submissions($message='') {
        global $CFG, $db, $USER;
        require_once($CFG->libdir.'/gradelib.php');

        /* first we check to see if the form has just been submitted
         * to request user_preference updates
         */

        if (isset($_POST['updatepref'])){
            $perpage = optional_param('perpage', 10, PARAM_INT);
            $perpage = ($perpage <= 0) ? 10 : $perpage ;
            set_user_preference('assignment_perpage', $perpage);
            set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
        }

        /* next we get perpage and quickgrade (allow quick grade) params
         * from database
         */
        $perpage    = get_user_preferences('assignment_perpage', 10);

              
        if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
            $uses_outcomes = true;
        } else {
            $uses_outcomes = false;
        }

        $page    = optional_param('page', 0, PARAM_INT);
        $strsaveallfeedback = get_string('saveallfeedback', 'assignment');

    /// Some shortcuts to make the code read better

        $course     = $this->course;
        $assignment = $this->printconfig;
        $cm         = $this->cm;

        $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
        add_to_log($course->id, 'print', 'view submission', 'submissions.php?id='.$this->cm->id, $this->printconfig->id, $this->cm->id);
        $navigation = build_navigation('submissions', $this->cm);
        print_header_simple(format_string($this->printconfig->name,true), "", $navigation,
                '', '', true, update_module_button($cm->id, $course->id, 'print'), navmenu($course, $cm));

        $course_context = get_context_instance(CONTEXT_COURSE, $course->id);


        if (!empty($message)) {
            echo $message;   // display messages here if any
        }

        $context = get_context_instance(CONTEXT_MODULE, $cm->id);

    /// Check to see if groups are being used in this assignment

        /// find out current groups mode
        $groupmode = groups_get_activity_groupmode($cm);
        $currentgroup = groups_get_activity_group($cm, true);
        groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);

        /// Get all ppl that are allowed to submit assignments
        if ($users = get_users_by_capability($context, 'mod/print:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
            $users = array_keys($users);
        }

        // if groupmembersonly used, remove users who are not in any group
        if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
            if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
                $users = array_intersect($users, array_keys($groupingusers));
            }
        }

        $tablecolumns = array('picture', 'fullname', 'status', 'submissions');
      

        $tableheaders = array('',
                              get_string('fullname'),
                              get_string('status'),
                              'submissions');
        
        require_once($CFG->libdir.'/tablelib.php');
        $table = new flexible_table('mod-print-submissions');

        $table->define_columns($tablecolumns);
        $table->define_headers($tableheaders);
        $table->define_baseurl($CFG->wwwroot.'/mod/print/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);

        $table->sortable(true, 'lastname');//sorted by lastname by default
        $table->collapsible(true);
        $table->initialbars(true);

        $table->column_suppress('picture');
        $table->column_suppress('fullname');

        $table->column_class('picture', 'picture');
        $table->column_class('fullname', 'fullname');
        $table->column_class('status', 'status');
        $table->column_class('submissions','submissions');
        
        $table->set_attribute('cellspacing', '0');
        $table->set_attribute('id', 'attempts');
        $table->set_attribute('class', 'submissions');
        $table->set_attribute('width', '100%');
        $table->set_attribute('align', 'center');

        $table->no_sorting('outcome');

        // Start working -- this is necessary as soon as the niceties are over
        $table->setup();

        if (empty($users)) {
            print_heading(get_string('nosubmitusers','assignment'));
            return true;
        }

    /// Construct the SQL

        if ($where = $table->get_sql_where()) {
            $where .= ' AND ';
        }

        if ($sort = $table->get_sql_sort()) {
            $sort = ' ORDER BY '.$sort;
        }

        $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
                          s.id AS submissionid, 
                          COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
        $sql = 'FROM '.$CFG->prefix.'user u '.
               'LEFT JOIN '.$CFG->prefix.'print_submissions s ON u.id = s.userid
                                                                  AND s.assignment = '.$this->printconfig->id.' '.
               'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';

        $table->pagesize($perpage, count($users));

        ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
        $offset = $page * $perpage;

        $strupdate = get_string('update');
        $strgrade  = get_string('grade');
        #$grademenu = make_grades_menu($this->printconfig->grade);

        if (($ausers = get_records_sql($select.$sql.$sort, $table->get_page_start(), $table->get_page_size())) !== false) {
            foreach ($ausers as $auser) {

            /// Calculate user status
                $picture = print_user_picture($auser, $course->id, $auser->picture, false, true);


                if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
                    $auser->status = 0;
                } else {
                    $auser->status = 1;
                }

                $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;

                ///No more buttons, we use popups ;-).
                $popup_url = '/mod/print/submissions.php?id='.$this->cm->id
                           . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;offset='.$offset++;
                $button = link_to_popup_window ($popup_url, 'grade'.$auser->id, $buttontext, 600, 780,
                                                $buttontext, 'none', true, 'button'.$auser->id);

                $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
                $url = $this->print_user_files($auser->id,true,true);
                $submissions = '<div id="down'.$auser->id.'" class="s'.$auser->status.'">'.$url.'</div>';
              
		$userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
                $row = array($picture, $userlink, $status, $submissions);
                if ($uses_outcomes) {
                    $row[] = $outcomes;
                }

                $table->add_data($row);
            }
        }


        /// Print quickgrade form around the table
            echo '<form action="submissions.php" id="fastg" method="post">';
            echo '<div>';
            echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
            echo '<input type="hidden" name="mode" value="fastgrade" />';
            echo '<input type="hidden" name="page" value="'.$page.'" />';
            echo '</div>';
        
        $table->print_html();  /// Print the whole table

            $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
            echo '<div class="fgcontrols">';
            echo '<div class="emailnotification">';
            echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
            echo '<input type="hidden" name="mailinfo" value="0" />';
            echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
            helpbutton('emailnotification', get_string('enableemailnotification', 'assignment'), 'assignment').'</p></div>';
            echo '</div>';
            echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
            echo '</div>';
            echo '</form>';
        /// End of fast grading form

        /// Mini form for setting user preference
        echo '<div class="qgprefs">';
        echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
        echo '<input type="hidden" name="updatepref" value="1" />';
        echo '<table id="optiontable">';
        echo '<tr><td>';
        echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
        echo '</td>';
        echo '<td>';
        echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
        helpbutton('pagesize', get_string('pagesize','assignment'), 'assignment');
        echo '</td></tr>';
        echo '<tr><td>';
        echo '</td>';
        echo '<td>';
        echo '</td></tr>';
        echo '<tr><td colspan="2">';
        echo '<input type="submit" value="'.get_string('savepreferences').'" />';
        echo '</td></tr></table>';
        echo '</div></form></div>';
        ///End of mini form
#        print_footer($this->course);
    }



    function printit($file) {
        printit_real($file);
    }


    function submittedlink($allgroups=false) {
        global $USER;

        $submitted = '';

        $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
        if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
                $group = 0;
            } else {
                $group = groups_get_activity_group($this->cm);
            }
            if (has_capability('moodle/site:accessallgroups', $context)) {
                if ($count = $this->count_real_submissions($group)) {
                    $submitted = '<a href="submissions.php?id='.$this->cm->id.'">'.
                                 get_string('viewsubmissions', 'assignment', $count).'</a>';
                } else {
                    $submitted = '<a href="submissions.php?id='.$this->cm->id.'">'.
                                 get_string('noattempts', 'assignment').'</a>';
                }
            } else {
                    $submitted = '';
            }
        return $submitted;
    }
    function count_real_submissions($groupid=0) {
        return print_count_real_submissions($this->cm, $groupid);
    }
   
    function print_user_files($userid=0, $return=false, $url=false) {
        global $CFG, $USER;

        $mode    = optional_param('mode', '', PARAM_ALPHA);
        $offset  = optional_param('offset', 0, PARAM_INT);

        if (!$userid) {
            if (!isloggedin()) {
                return '';
            }
            $userid = $USER->id;
        }
        $filearea = $this->file_area_name($userid);

        $output = '';

        if ($submissions = $this->get_submissions1($userid)) {
            foreach ($submissions as $submission) {
               $candelete = $this->can_delete_files($submission);
            }
         }
        $strdelete   = get_string('delete');

        $output .= '<strong>'.get_string('draft', 'assignment').':</strong><br />';
        
       
        if ($basedir = $this->file_area($userid)) {
            if ($files = get_directory_list($basedir, 'responses')) {
                require_once($CFG->libdir.'/filelib.php');
                foreach ($files as $key => $file) {

                    $icon = mimeinfo('icon', $file);
                    $ffurl = get_file_url("$filearea/$file");
                    if(!$url) {
                         $output .= '<a href="'.$ffurl.'" ><img src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.$file.'</a>';
                    }
                    if ($url){
                         $path = $basedir.'/'.$file;
                         $output .= '<a href="'.$ffurl.'" ><img src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.$file.'</a>'.
                         '<form action="submissions.php" method="post">'.
                         '<input type="hidden" name="path" value="'.$path.'">'.
                         '<input type="submit" name="SUBMIT" value="Print">'.
                         '</form>';
                         $sql = "SELECT userid 
                                 FROM {$CFG->prefix}print_submissions
                                 WHERE filepath = '$path'
                                 AND assignment = '{$this->printconfig->id}'";
                         $submission = get_record_sql($sql);
                         $candelete = true;
                     }
                    if ($candelete) {
                        $delurl  = "$CFG->wwwroot/mod/print/delete.php?id={$this->cm->id}&amp;file=$file&amp;userid={$submission->userid}&amp;mode=$mode&amp;offset=$offset";

                        $output .= '<a href="'.$delurl.'">&nbsp;'
                                  .'<img title="'.$strdelete.'" src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" alt="" /></a> ';
                    }

                    $output .= '<br />';
                }
            }
        }


        $output = '<div class="files">'.$output.'</div>';
           
        if ($return) {
            return $output;
        }
        echo $output;
    
}
    function print_get_path($userid) {
           global $CFG;
            $sql = "SELECT filepath 
            FROM {$CFG->prefix}print_submissions
            WHERE userid = '$userid'
            AND assignment = '{$this->printconfig->id}'";
            $records = get_records_sql($sql);
            
            return $records;
           
         }
    
    function delete() {
        $action   = optional_param('action', '', PARAM_ALPHA);

        switch ($action) {
            case 'response':
                $this->delete_responsefile();
                break;
            default:
                $this->delete_file();
        }
        die;
    }
    function delete_file() {
        global $CFG;

        $file     = required_param('file', PARAM_FILE);
        $userid   = required_param('userid', PARAM_INT);
        $confirm  = optional_param('confirm', 0, PARAM_BOOL);
        $mode     = optional_param('mode', '', PARAM_ALPHA);
        $offset   = optional_param('offset', 0, PARAM_INT);

        require_login($this->course->id, false, $this->cm);

        if (empty($mode)) {
            $urlreturn = 'view.php';
            $optionsreturn = array('id'=>$this->cm->id);
            $returnurl = 'view.php?id='.$this->cm->id;
        } else {
            $urlreturn = 'submissions.php';
            $optionsreturn = array('id'=>$this->cm->id, 'offset'=>$offset, 'mode'=>$mode, 'userid'=>$userid);
            $returnurl = "submissions.php?id={$this->cm->id}&amp;offset=$offset&amp;mode=$mode&amp;userid=$userid";
        }

        
        $dir = $this->file_area_name($userid);

        if (!data_submitted('nomatch') or !$confirm) {
            $optionsyes = array ('id'=>$this->cm->id, 'file'=>$file, 'userid'=>$userid, 'confirm'=>1, 'sesskey'=>sesskey(), 'mode'=>$mode, 'offset'=>$offset);
            if (empty($mode)) {
                #$this->view_header(get_string('delete'));
            } else {
                print_header(get_string('delete'));
            }
            print_heading(get_string('delete'));
            notice_yesno(get_string('confirmdeletefile', 'assignment', $file), 'delete.php', $urlreturn, $optionsyes, $optionsreturn, 'post', 'get');
            if (empty($mode)) {
                #$this->view_footer();
            } else {
                print_footer('none');
            }
            die;
        }

        $filepath = $CFG->dataroot.'/'.$dir.'/'.$file;
        if (file_exists($filepath)) {
            if (@unlink($filepath)) {
                $sql = "DELETE
                FROM {$CFG->prefix}print_submissions
                WHERE filepath = '$filepath'
                AND assignment = '{$this->printconfig->id}'";  
                get_records_sql($sql);
                redirect($returnurl);
            }
        }

        // print delete error
        if (empty($mode)) {
            #$this->view_header(get_string('delete'));
        } else {
            #print_header(get_string('delete'));
        }
        notify(get_string('deletefilefailed', 'assignment'));
        print_continue($returnurl);
        if (empty($mode)) {
           # $this->view_footer();
        } else {
            #print_footer('none');
        }
        die;
    }

    function can_delete_files($submission) {
        global $USER;

     
        if (has_capability('mod/print:submit', $this->context)
          and $USER->id == $submission->userid) {                 // no deleting after final submission
            return true;
        } else {
            return false;
        }
    }
    function upload() {
        $action = required_param('action', PARAM_ALPHA);

        $this->upload_file();
    }

    function count_user_files($userid) {
        global $CFG;

        $filearea = $this->file_area_name($userid);

        if ( is_dir($CFG->dataroot.'/'.$filearea) && $basedir = $this->file_area($userid)) {
            if ($files = get_directory_list($basedir)) {
                return count($files);
            }
        }
        return 0;
    }
    function setup_elements(&$mform) {
        global $CFG, $COURSE;

        $ynoptions = array( 0 => get_string('no'), 1 => get_string('yes'));

        $choices = get_max_upload_sizes($CFG->print_maxbytes, 0);
        $choices[0] = get_string('courseuploadlimit') . ' ('.display_size($CFG->print_maxbytes).')';
        $mform->addElement('select', 'maxbytes', get_string('maximumsize', 'assignment'), $choices);
        $mform->setDefault('maxbytes', $CFG->print_maxbytes);

        $options = array();
        for($i = 1; $i <= 20; $i++) {
            $options[$i] = $i;
        }
        $mform->addElement('select', 'var1', get_string("allowmaxfiles", "assignment"), $options);
        $mform->setHelpButton('var1', array('allowmaxfiles', get_string('allowmaxfiles', 'assignment'), 'assignment'));
        $mform->setDefault('var1', 3);

      
               
    }

    function view_upload_form() {
        global $CFG, $USER;

        if(!$this->submissions = get_records_sql($this->check_database("print_submissions"))) {
            $this->submission = $this->submissions[1];
        }
        $struploadafile = get_string('uploadafile');
        $maxbytes = $this->printconfig->maxbytes == 0 ? $this->course->maxbytes : $this->printconfig->maxbytes;
        $strmaxsize = get_string('maxsize', '', display_size($maxbytes));

     
        if ($this->can_upload_file($this->submission)) {
            echo '<div style="text-align:center">';
            echo '<form enctype="multipart/form-data" method="post" action="upload.php">';
            echo '<fieldset class="invisiblefieldset">';
            echo "<p>$struploadafile ($strmaxsize)</p>";
            echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
            echo '<input type="hidden" name="action" value="uploadfile" />';
            require_once($CFG->libdir.'/uploadlib.php');
            upload_print_form_fragment(1,array('newfile'),null,false,null,0,$this->printconfig->maxbytes,false);
            echo '<input type="submit" name="save" value="'.get_string('uploadthisfile').'" />';
            echo '</fieldset>';
            echo '</form>';
            echo '</div>';
            echo '<br />';
        }

    }
      function upload_file() {
        global $CFG, $USER;

        $mode   = optional_param('mode', '', PARAM_ALPHA);
        $offset = optional_param('offset', 0, PARAM_INT);

        $returnurl = 'view.php?id='.$this->cm->id;

        $filecount = $this->count_user_files($USER->id);
        $submission = $this->get_submission($USER->id);

        if (!$this->can_upload_file($submission)) {
            $this->view_header(get_string('upload'));
            notify(get_string('uploaderror', 'assignment'));
            print_continue($returnurl);
           # $this->view_footer();
            die;
        }

        $dir = $this->file_area_name($USER->id);
        check_dir_exists($CFG->dataroot.'/'.$dir, true, true); // better to create now so that student submissions do not block it later

        require_once($CFG->dirroot.'/lib/uploadlib.php');
        $um = new upload_manager('newfile',false,true,$this->course,false,$this->printconfig->maxbytes,true);

        if ($um->process_file_uploads($dir)) {
            $updated = new object();
            $updated->assignment = $this->printconfig->id;
            $updated->id           = $submission->id;
            $updated->timemodified = time();
            $updated->filepath = $um->get_new_filepath();
            $updated->userid = $USER->id;

            if (insert_record('print_submissions', $updated)) {
                add_to_log($this->course->id, 'print', 'upload',
                        'view.php?a='.$this->printconfig->id, $this->printconfig->id, $this->cm->id);
                $submission = $this->get_submission($USER->id);
              } else {
                $new_filename = $um->get_new_filename();
                $this->view_header(get_string('upload'));
                notify(get_string('uploadnotregistered', 'assignment', $new_filename));
                print_continue($returnurl);
               # $this->view_footer();
                die;
            }
            redirect('view.php?id='.$this->cm->id);
        }
        $this->view_header(get_string('upload'));
        notify(get_string('uploaderror', 'assignment'));
        echo $um->get_errors();
        print_continue($returnurl);
        #$this->view_footer();
        die;
    }

   function upload_xmlrpc($filepath, $userid, $title, $id) {
        $updated = new object();
        $updated->timemodified = time();
        $updated->filepath = $filepath;
        $updated->userid = $userid;
        $updated->assignment = $id;
        insert_record('print_submissions', $updated);  
        return  1;
  }

   function get_submissions1($userid=0, $createnew=false, $teachermodified=false) {
        global $USER;

        if (empty($userid)) {
            $userid = $USER->id;
        }

        $submission = get_records('print_submissions', 'userid', $userid);
        #print var_dump($submission);
        if ($submission || !$createnew) {
            return $submission;
        }
        $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
        if (!insert_record("print_submissions", $newsubmission)) {
            error("Could not insert a new empty submission");
        }

        return get_record('print_submissions', 'assignment', $this->printconfig->id, 'userid', $userid);
    }
   
    function get_submission($userid=0, $createnew=false, $teachermodified=false) {
        global $USER;

        if (empty($userid)) {
            $userid = $USER->id;
        }

        $submission = get_record('print_submissions', 'userid', $userid);
        #print var_dump($submission);
        if ($submission || !$createnew) {
            return $submission;
        }
        $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
        if (!insert_record("print_submissions", $newsubmission)) {
            error("Could not insert a new empty submission");
        }

        return get_record('print_submissions', 'assignment', $this->printconfig->id, 'userid', $userid);
    }
    
    function prepare_new_submission($userid, $teachermodified=false) {
        $submission = new Object;
        $submission->assignment   = $this->printconfig->id;
        $submission->userid       = $userid;
        //$submission->timecreated  = time();
        $submission->timecreated = '';
        // teachers should not be modifying modified date, except offline assignments
        if ($teachermodified) {
            $submission->timemodified = 0;
        } else {
            $submission->timemodified = $submission->timecreated;
        }
        $submission->numfiles     = 0;
        $submission->data1        = '';
        $submission->data2        = '';
        $submission->grade        = -1;
        $submission->submissioncomment      = '';
        $submission->format       = 0;
        $submission->teacher      = 0;
        $submission->timemarked   = 0;
        $submission->mailed       = 0;
        return $submission;
    }
    function file_area_name($userid) {
        global $CFG;

        return $this->course->id.'/'.$CFG->moddata.'/print/'.$this->printconfig->id.'/'.$userid;
    }

    function file_area($userid) {
        return make_upload_directory( $this->file_area_name($userid) );
    }


    function can_upload_file($submission) {
        global $USER;

        if (has_capability('mod/print:submit', $this->context)           // can submit
                                                // assignment not closed yet
          and (empty($submission) or $submission->userid == $USER->id)) {                            // no uploading after final submission
            return true;
        } else {
            return false;
        }
    }

    
    function get_submissions($sort='', $dir='DESC') {
        return print_get_all_submissions($this->printconfig, $sort, $dir);
    }
}

function print_count_real_submissions($cm, $groupid=0) {
    global $CFG;

    $context = get_context_instance(CONTEXT_MODULE, $cm->id);

    // this is all the users with this capability set, in this context or higher
    if ($users = get_users_by_capability($context, 'mod/print:submit', 'u.id', '', '', '', $groupid, '', false)) {
        $users = array_keys($users);
    }

    // if groupmembersonly used, remove users who are not in any group
    if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
        if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
            $users = array_intersect($users, array_keys($groupingusers));
        }
    }

    if (empty($users)) {
        return 0;
    }

    $userlists = implode(',', $users);

    return count_records_sql("SELECT COUNT('x')
                                FROM {$CFG->prefix}print_submissions
                               WHERE assignment = $cm->instance AND
                                     timemodified > 0 AND
                                     userid IN ($userlists)");
}


function print_get_all_submissions($assignment, $sort="", $dir="DESC") {
/// Return all assignment submissions by ENROLLED students (even empty)
    global $CFG;

    if ($sort == "lastname" or $sort == "firstname") {
        $sort = "u.$sort $dir";
    } else if (empty($sort)) {
        $sort = "a.timemodified DESC";
    } else {
        $sort = "a.$sort $dir";
    }

    /* not sure this is needed at all since assignmenet already has a course define, so this join?
    $select = "s.course = '$assignment->course' AND";
    if ($assignment->course == SITEID) {
        $select = '';
    }*/

    return get_records_sql("SELECT a.*
                              FROM {$CFG->prefix}print_submissions a,
                                   {$CFG->prefix}user u
                             WHERE u.id = a.userid
                               AND a.assignment = '$assignment->id'
                          ORDER BY $sort");

    /* return get_records_sql("SELECT a.*
                              FROM {$CFG->prefix}assignment_submissions a,
                                   {$CFG->prefix}user_students s,
                                   {$CFG->prefix}user u
                             WHERE a.userid = s.userid
                               AND u.id = a.userid
                               AND $select a.assignment = '$assignment->id'
                          ORDER BY $sort");
    */
}

function print_add_instance($print) {

     
        $print->timemodified = time();
        $print->courseid = $print->course;
     
    # You may have to add extra stuff in here #

    return insert_record('print', $print);
}


/**
 * Given an object containing all the necessary data,
 * (defined by the form in mod_form.php) this function
 * will update an existing instance with new data.
 *
 * @param object $print An object from the form in mod_form.php
 * @return boolean Success/Fail
 */
function print_update_instance($print) {

    $print->timemodified = time();
    $print->id = $print->instance;

    # You may have to add extra stuff in here #

    return update_record('print', $print);
}


/**
 * Given an ID of an instance of this module,
 * this function will permanently delete the instance
 * and any data that depends on it.
 *
 * @param int $id Id of the module instance
 * @return boolean Success/Failure
 */
function print_delete_instance($id) {

    if (! $print = get_record('print', 'id', $id)) {
        return false;
    }

    $result = true;

    # Delete any dependent records here #

    if (! delete_records('print', 'id', $print->id)) {
        $result = false;
    }

    return $result;
}


/**
 * Return a small object with summary information about what a
 * user has done with a given particular instance of this module
 * Used for user activity reports.
 * $return->time = the time they did it
 * $return->info = a short text description
 *
 * @return null
 * @todo Finish documenting this function
 */
function print_user_outline($course, $user, $mod, $print) {
    return $return;
}


/**
 * Print a detailed representation of what a user has done with
 * a given particular instance of this module, for user activity reports.
 *
 * @return boolean
 * @todo Finish documenting this function
 */
function print_user_complete($course, $user, $mod, $print) {
    return true;
}


/**
 * Given a course and a time, this module should find recent activity
 * that has occurred in print activities and print it out.
 * Return true if there was output, or false is there was none.
 *
 * @return boolean
 * @todo Finish documenting this function
 */
function print_print_recent_activity($course, $isteacher, $timestart) {
    return false;  //  True if anything was printed, otherwise false
}


/**
 * Function to be run periodically according to the moodle cron
 * This function searches for things that need to be done, such
 * as sending out mail, toggling flags etc ...
 *
 * @return boolean
 * @todo Finish documenting this function
 **/
function print_cron () {
    return true;
}


/**
 * Must return an array of user records (all data) who are participants
 * for a given instance of print. Must include every user involved
 * in the instance, independient of his role (student, teacher, admin...)
 * See other modules as example.
 *
 * @param int $printid ID of an instance of this module
 * @return mixed boolean/array of students
 */
function print_get_participants($printid) {
    return false;
}


/**
 * This function returns if a scale is being used by one print
 * if it has support for grading and scales. Commented code should be
 * modified if necessary. See forum, glossary or journal modules
 * as reference.
 *
 * @param int $printid ID of an instance of this module
 * @return mixed
 * @todo Finish documenting this function
 */
function print_scale_used($printid, $scaleid) {
    $return = false;

    //$rec = get_record("print","id","$printid","scale","-$scaleid");
    //
    //if (!empty($rec) && !empty($scaleid)) {
    //    $return = true;
    //}

    return $return;
}


/**
 * Checks if scale is being used by any instance of print.
 * This function was added in 1.9
 *
 * This is used to find out if scale used anywhere
 * @param $scaleid int
 * @return boolean True if the scale is used by any print
 */
function print_scale_used_anywhere($scaleid) {
    if ($scaleid and record_exists('print', 'grade', -$scaleid)) {
        return true;
    } else {
        return false;
    }
}


/**
 * Execute post-install custom actions for the module
 * This function was added in 1.9
 *
 * @return boolean true if success, false on error
 */
function print_install() {
    return true;
}

function printit_real($file) {
    
    require_once('PrintIPP.php');
    require_once('CupsPrintIPP.php');
    $ipp = new CupsPrintIPP;
    $ipp->getPrinters();
    $uri = $ipp->available_printers[0];
    #$ipp->setUserName($username='iwikiwi@localhost');
    #$ipp->setAuthentication('iwikiwi@localhost','dbzdbz');
    $ipp->setHost("localhost");
    $ipp->setPrinterURI($uri);
    $ipp->setLog('log.txt');
    $ipp->setData($file); // Path to file.
    $ipp->printJob();
  
}


/**
 * Execute post-uninstall custom actions for the module
 * This function was added in 1.9
 *
 * @return boolean true if success, false on error
 */
function print_uninstall() {
    return true;
}


//////////////////////////////////////////////////////////////////////////////////////
/// Any other print functions go here.  Each of them must have a name that
/// starts with print_
/// Remember (see note in first lines) that, if this section grows, it's HIGHLY
/// recommended to move all funcions below to a new "localib.php" file.


?>