Project

General

Profile

Bug #5376 » hotpotatoes_exercise_report.php

Yoselyn Castillo, 15/10/2012 18:26

 
1
<?php
2
/* For licensing terms, see /license.txt */
3
/**
4
 *	Exercise list: This script shows the list of exercises for administrators and students.
5
 *	@package chamilo.exercise
6
 *	@author hubert.borderiou 
7
 *
8
 */
9
/**
10
 * Code
11
 */
12
// name of the language file that needs to be included
13
$language_file = array('exercice');
14

    
15
// including the global library
16
require_once '../inc/global.inc.php';
17
require_once '../gradebook/lib/be.inc.php';
18

    
19
// Setting the tabs
20
$this_section = SECTION_COURSES;
21

    
22
$htmlHeadXtra[] = api_get_jqgrid_js();
23

    
24
// Access control
25
api_protect_course_script(true, false, true);
26

    
27

    
28
// including additional libraries
29
require_once 'exercise.class.php';
30
require_once 'exercise.lib.php';
31
require_once 'question.class.php';
32
require_once 'answer.class.php';
33
require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
34
require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
35
require_once 'hotpotatoes.lib.php';
36
require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
37

    
38
// need functions of statsutils lib to display previous exercices scores
39
require_once api_get_path(LIBRARY_PATH) . 'statsUtils.lib.inc.php';
40

    
41
// document path
42
$documentPath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . "/document";
43

    
44
/*	Constants and variables */
45
$is_allowedToEdit           = api_is_allowed_to_edit(null, true) || api_is_drh();
46
$is_tutor                   = api_is_allowed_to_edit(true);
47

    
48
$TBL_QUESTIONS              = Database :: get_course_table(TABLE_QUIZ_QUESTION);
49
$TBL_TRACK_EXERCICES        = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
50
$TBL_TRACK_HOTPOTATOES_EXERCICES        = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
51
$TBL_LP_ITEM_VIEW           = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
52

    
53
$course_id            = api_get_course_int_id();
54
$hotpotatoes_path     = isset($_REQUEST['path']) ? $_REQUEST['path'] : null;
55
$filter_user          = isset($_REQUEST['filter_by_user']) ? intval($_REQUEST['filter_by_user']) : null;
56

    
57
$locked = api_resource_is_locked_by_gradebook($exercise_id, LINK_EXERCISE);
58

    
59

    
60
if (empty($hotpotatoes_path)) {
61
    api_not_allowed();
62
}
63

    
64
if (!$is_allowedToEdit) {
65
   // api_not_allowed();
66
}
67

    
68
if (!empty($_REQUEST['path'])) {
69
    $parameters['path'] = Security::remove_XSS($_REQUEST['path']);
70
}
71

    
72

    
73

    
74

    
75
if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') {
76
    if (api_is_platform_admin() || api_is_course_admin() || api_is_course_tutor() || api_is_course_coach()) {
77
        $load_extra_data = false;
78
        if (isset($_REQUEST['extra_data']) && $_REQUEST['extra_data'] == 1) {
79
            $load_extra_data = true;
80
        }
81
        
82
        require_once 'hotpotatoes_exercise_result.class.php';
83
        // @todo make xls export work
84
//        switch ($_GET['export_format']) {
85
//            case 'xls' :
86
//                $export = new ExerciseResult();
87
//                $export->exportCompleteReportXLS($documentPath, null, $load_extra_data, null, $_GET['exerciseId'], $_GET['hotpotato_name']);
88
//                exit;
89
//                break;
90
//            case 'csv' :
91
//            default :
92
                $export = new HotpotatoesExerciseResult();
93
                $export->exportCompleteReportCSV($documentPath, $hotpotatoes_path);
94
                exit;
95
//                break;
96
//        }
97
    } else {
98
        api_not_allowed(true);
99
    }
100
}
101

    
102
//Send student email @todo move this code in a class, library
103
//if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_GET['exeid']== strval(intval($_GET['exeid']))) {
104
//    $id         = intval($_GET['exeid']); //filtered by post-condition
105
//    $track_exercise_info = get_exercise_track_exercise_info($id);
106
//    if (empty($track_exercise_info)) {
107
//        api_not_allowed();
108
//    }
109
//    $test              = $track_exercise_info['title'];
110
//    $student_id        = $track_exercise_info['exe_user_id'];
111
//
112
//    $session_id        = $track_exercise_info['session_id'];
113
//    $lp_id             = $track_exercise_info['orig_lp_id'];
114
//    //$lp_item_id        = $track_exercise_info['orig_lp_item_id'];
115
//    $lp_item_view_id   = $track_exercise_info['orig_lp_item_view_id'];
116
//
117
//    // Teacher data
118
//    $teacher_info      = api_get_user_info(api_get_user_id());
119
//    $user_info         = api_get_user_info($student_id);
120
//    $student_email     = $user_info['mail'];
121
//    $from              = $teacher_info['mail'];
122
//    $from_name         = api_get_person_name($teacher_info['firstname'], $teacher_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
123
//
124
//    $url               = api_get_path(WEB_CODE_PATH) . 'exercice/exercise_report.php?' . api_get_cidreq() . '&id_session='.$session_id.'&exerciseId='.$exercise_id;
125
//
126
//    $my_post_info      = array();
127
//    $post_content_id   = array();
128
//    $comments_exist    = false;
129
//
130
//    foreach ($_POST as $key_index => $key_value) {
131
//        $my_post_info  = explode('_',$key_index);
132
//        $post_content_id[]=$my_post_info[1];
133
//        if ($my_post_info[0]=='comments') {
134
//            $comments_exist=true;
135
//        }
136
//    }
137
//
138
//    $loop_in_track=($comments_exist===true) ? (count($_POST)/2) : count($_POST);
139
//
140
//    $array_content_id_exe=array();
141
//    if ($comments_exist===true) {
142
//        $array_content_id_exe = array_slice($post_content_id,$loop_in_track);
143
//    } else {
144
//        $array_content_id_exe = $post_content_id;
145
//    }
146
//
147
//    for ($i=0;$i<$loop_in_track;$i++) {
148
//        $my_marks           = Database::escape_string($_POST['marks_'.$array_content_id_exe[$i]]);
149
//        $contain_comments   = Database::escape_string($_POST['comments_'.$array_content_id_exe[$i]]);
150
//        if (isset($contain_comments)) {
151
//            $my_comments    = Database::escape_string($_POST['comments_'.$array_content_id_exe[$i]]);
152
//        } else {
153
//            $my_comments    = '';
154
//        }
155
//        $my_questionid = intval($array_content_id_exe[$i]);
156
//        $sql = "SELECT question from $TBL_QUESTIONS WHERE c_id = $course_id AND id = '$my_questionid'";
157
//        $result =Database::query($sql);
158
//        Database::result($result,0,"question");
159
//
160
//        $query = "UPDATE $TBL_TRACK_ATTEMPT SET marks = '$my_marks',teacher_comment = '$my_comments' WHERE question_id = ".$my_questionid." AND exe_id=".$id;
161
//        Database::query($query);
162
//
163
//        //Saving results in the track recording table
164
//        $recording_changes = 'INSERT INTO '.$TBL_TRACK_ATTEMPT_RECORDING.' (exe_id, question_id, marks, insert_date, author, teacher_comment)
165
//                              VALUES ('."'$id','".$my_questionid."','$my_marks','".api_get_utc_datetime()."','".api_get_user_id()."'".',"'.$my_comments.'")';
166
//        Database::query($recording_changes);
167
//    }
168
//
169
//    $qry = 'SELECT DISTINCT question_id, marks FROM ' . $TBL_TRACK_ATTEMPT . ' WHERE exe_id = '.$id .' GROUP BY question_id';
170
//    $res = Database::query($qry);
171
//    $tot = 0;
172
//    while ($row = Database :: fetch_array($res, 'ASSOC')) {
173
//        $tot += $row['marks'];
174
//    }
175
//
176
//    $totquery = "UPDATE $TBL_TRACK_EXERCICES SET exe_result = '".floatval($tot)."' WHERE exe_id = ".$id;
177
//    Database::query($totquery);
178
//
179
//    //@todo move this somewhere else
180
//    $subject = get_lang('ExamSheetVCC');
181
//
182
//    $message  = '<p>'.get_lang('DearStudentEmailIntroduction') . '</p><p>'.get_lang('AttemptVCC');
183
//    $message .= '<h3>'.get_lang('CourseName'). '</h3><p>'.Security::remove_XSS($course_info['name']).'';
184
//    $message .= '<h3>'.get_lang('Exercise') . '</h3><p>'.Security::remove_XSS($test);
185
//
186
//    //Only for exercises not in a LP
187
//    if ($lp_id == 0) {
188
//        $message .= '<p>'.get_lang('ClickLinkToViewComment') . ' <a href="#url#">#url#</a><br />';
189
//    }
190
//
191
//    $message .= '<p>'.get_lang('Regards').'</p>';
192
//    $message .= $from_name;
193
//
194
//    $message = str_replace("#test#", Security::remove_XSS($test), $message);
195
//    $message = str_replace("#url#", $url, $message);
196
//
197
//    @api_mail_html($student_email, $student_email, $subject, $message, $from_name, $from, array('charset'=>api_get_system_encoding()));
198
//
199
//    //Updating LP score here
200
//    if (in_array($origin, array ('tracking_course','user_course','correct_exercise_in_lp'))) {
201
//        $sql_update_score = "UPDATE $TBL_LP_ITEM_VIEW SET score = '" . floatval($tot) . "' WHERE c_id = ".$course_id." AND id = " .$lp_item_view_id;
202
//        Database::query($sql_update_score);
203
//        if ($origin == 'tracking_course') {
204
//            //Redirect to the course detail in lp
205
//            header('location: exercice.php?course=' . Security :: remove_XSS($_GET['course']));
206
//            exit;
207
//        } else {
208
//            //Redirect to the reporting
209
//            header('location: ../mySpace/myStudents.php?origin=' . $origin . '&student=' . $student_id . '&details=true&course=' . $course_id.'&session_id='.$session_id);
210
//            exit;
211
//        }
212
//    }
213
//}
214

    
215

    
216
if ($is_allowedToEdit && $origin != 'learnpath') {
217
    // the form
218
    if (api_is_platform_admin() || api_is_course_admin() || api_is_course_tutor() || api_is_course_coach()) {
219
        $actions .= '<a href="admin.php?exerciseId='.intval($_GET['exerciseId']).'">' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
220
        $actions .= '<a id="export_opener" href="'.api_get_self().'?export_report=1&path='.Security::remove_XSS($hotpotatoes_path).' ">'.Display::return_icon('save.png',   get_lang('Export'),'',ICON_SIZE_MEDIUM).'</a>';
221
    }
222
} else {
223
    $actions .= '<a href="exercice.php">' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
224
}
225

    
226
//Deleting an attempt
227
//if ( ($is_allowedToEdit || $is_tutor || api_is_coach()) && $_GET['delete'] == 'delete' && !empty ($_GET['did']) && $locked == false) {
228
//    $exe_id = intval($_GET['did']);
229
//    if (!empty($exe_id)) {
230
//        $sql = 'DELETE FROM '.$TBL_TRACK_EXERCICES.' WHERE exe_id = '.$exe_id;
231
//        Database::query($sql);
232
//        $sql = 'DELETE FROM '.$TBL_TRACK_ATTEMPT.' WHERE exe_id = '.$exe_id;
233
//        Database::query($sql);
234
//        header('Location: exercise_report.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&exerciseId='.$exercise_id);
235
//        exit;
236
//    }
237
//}
238

    
239
if ($is_allowedToEdit || $is_tutor) {
240
    $nameTools = get_lang('StudentScore');
241
    $interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook","name" => get_lang('Exercices'));
242
    $objExerciseTmp = new Exercise();
243
    if ($objExerciseTmp->read($exercise_id)) {
244
        $interbreadcrumb[] = array("url" => "admin.php?exerciseId=".$exercise_id, "name" => $objExerciseTmp->name);
245
    }
246
} else {
247
    $interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook","name" => get_lang('Exercices'));
248
    $objExerciseTmp = new Exercise();
249
    if ($objExerciseTmp->read($exercise_id)) {
250
        $nameTools = get_lang('Results').': '.$objExerciseTmp->name;
251
    }
252
}
253

    
254
Display :: display_header($nameTools);
255

    
256
$actions = Display::div($actions, array('class'=> 'actions'));
257

    
258
$extra =  '<script type="text/javascript">
259
    $(document).ready(function() {
260

    
261
        $( "#dialog:ui-dialog" ).dialog( "destroy" );
262

    
263
        $( "#dialog-confirm" ).dialog({
264
                autoOpen: false,
265
                show: "blind",
266
                resizable: false,
267
                height:300,
268
                modal: true
269
         });
270

    
271
        $("#export_opener").click(function() {
272
            var targetUrl = $(this).attr("href");
273
            $( "#dialog-confirm" ).dialog({
274
                width:400,
275
                height:300,
276
                buttons: {
277
                    "'.addslashes(get_lang('Download')).'": function() {
278
                        var export_format = $("input[name=export_format]:checked").val();
279
                        var extra_data  = $("input[name=load_extra_data]:checked").val();
280
                        location.href = targetUrl+"&export_format="+export_format+"&extra_data="+extra_data;
281
                        $( this ).dialog( "close" );
282
                    },
283
                }
284
            });
285
            $( "#dialog-confirm" ).dialog("open");
286
            return false;
287
        });
288
    });
289
    </script>';
290

    
291
$extra .= '<div id="dialog-confirm" title="'.get_lang("ConfirmYourChoice").'">';
292
$form = new FormValidator('report', 'post', null, null, array('class' => 'form-vertical'));
293
$form->addElement('radio', 'export_format', null, get_lang('ExportAsCSV'), 'csv', array('id' => 'export_format_csv_label'));
294
//$form->addElement('radio', 'export_format', null, get_lang('ExportAsXLS'), 'xls', array('id' => 'export_format_xls_label'));
295
//$form->addElement('checkbox', 'load_extra_data', null, get_lang('LoadExtraData'), '0', array('id' => 'export_format_xls_label'));
296
$form->setDefaults(array('export_format' => 'csv'));
297
$extra .= $form->return_form();
298
$extra .= '</div>';
299

    
300
if ($is_allowedToEdit)
301
    echo $extra;
302

    
303
echo $actions;
304

    
305
$url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_hotpotatoes_exercise_results&path='.$hotpotatoes_path.'&filter_by_user='.$filter_user;
306

    
307
//$activeurl = '?sidx=session_active';
308
$action_links = '';
309

    
310
//Generating group list
311

    
312
$group_list = GroupManager::get_group_list();
313
$group_parameters = array('group_all:'.get_lang('All'),'group_none:'.get_lang('None'));
314

    
315
foreach ($group_list as $group) {
316
    $group_parameters[] = $group['id'].':'.$group['name'];
317
}
318
if (!empty($group_parameters)) {
319
    $group_parameters = implode(';', $group_parameters);
320
}
321

    
322
if ($is_allowedToEdit || $is_tutor) {
323

    
324
	//The order is important you need to check the the $column variable in the model.ajax.php file
325
	$columns        = array(get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'),
326
                        get_lang('Group'), get_lang('StartDate'),  get_lang('Score'),  get_lang('Actions'));
327

    
328
  //Column config
329
  // @todo fix search firstname/lastname that doesn't work. rmove search for the moment
330
	$column_model   = array(
331
                        array('name'=>'firstname',      'index'=>'firstname',		'width'=>'50',   'align'=>'left', 'search' => 'false'),
332
                        array('name'=>'lastname',		    'index'=>'lastname',		'width'=>'50',   'align'=>'left', 'formatter'=>'action_formatter', 'search' => 'false'),
333
                        array('name'=>'login',          'hidden'=>'true',       'index'=>'username',        'width'=>'40',   'align'=>'left', 'search' => 'false'),
334
                        array('name'=>'group_name',		  'index'=>'group_id',    'width'=>'40',   'align'=>'left', 'search' => 'false'),
335
            						array('name'=>'exe_date',		    'index'=>'exe_date',		'width'=>'60',   'align'=>'left', 'search' => 'false'),
336
            						array('name'=>'score',			    'index'=>'exe_result',	'width'=>'50',   'align'=>'left', 'search' => 'false'),
337
            						array('name'=>'actions',        'index'=>'actions',     'width'=>'60',  'align'=>'left', 'search' => 'false')
338
                       );
339

    
340
    $action_links = '
341
    // add username as title in lastname filed - ref 4226
342
    function action_formatter(cellvalue, options, rowObject) {
343
        // rowObject is firstname,lastname,login,... get the third word
344
        var loginx = "'.api_htmlentities(sprintf(get_lang("LoginX"),":::"), ENT_QUOTES).'";
345
        var tabLoginx = loginx.split(/:::/);
346
        // tabLoginx[0] is before and tabLoginx[1] is after :::
347
        // may be empty string but is defined
348
        return "<span title=\""+tabLoginx[0]+rowObject[2]+tabLoginx[1]+"\">"+cellvalue+"</span>";
349
    }';
350
} else {
351
    //The order is important you need to check the the $column variable in the model.ajax.php file
352
	$columns        = array(get_lang('StartDate'),  get_lang('Score'),  get_lang('Actions'));
353

    
354
  //Column config
355
  // @todo fix search firstname/lastname that doesn't work. rmove search for the moment
356
	$column_model   = array(
357
                        array('name'=>'exe_date',		    'index'=>'exe_date',		'width'=>'60',   'align'=>'left', 'search' => 'false'),
358
            			array('name'=>'score',			    'index'=>'exe_result',	'width'=>'50',   'align'=>'left', 'search' => 'false'),
359
            			array('name'=>'actions',        'index'=>'actions',     'width'=>'60',  'align'=>'left', 'search' => 'false')
360
                       );
361
}
362

    
363
//Autowidth
364
$extra_params['autowidth'] = 'true';
365

    
366
//height auto
367
$extra_params['height'] = 'auto';
368
//$extra_params['excel'] = 'excel';
369
$extra_params['rowList'] = array(20, 50, 100, 500, 1000, 2000, 5000, 10000);
370

    
371
?>
372
<script>
373

    
374
function setSearchSelect(columnName) {
375
    $("#results").jqGrid('setColProp', columnName,
376
    {
377
       searchoptions:{
378
            dataInit:function(el){
379
                $("option[value='1']",el).attr("selected", "selected");
380
                setTimeout(function(){
381
                    $(el).trigger('change');
382
                },1000);
383
            }
384
        }
385
    });
386
}
387

    
388
function exportExcel() {
389
    var mya=new Array();
390
    mya=$("#results").getDataIDs();  // Get All IDs
391
    var data=$("#results").getRowData(mya[0]);     // Get First row to get the labels
392
    var colNames=new Array();
393
    var ii=0;
394
    for (var i in data){colNames[ii++]=i;}    // capture col names
395
    var html="";
396

    
397
    for(i=0;i<mya.length;i++) {
398
        data=$("#results").getRowData(mya[i]); // get each row
399
        for(j=0;j<colNames.length;j++) {
400
            html=html+data[colNames[j]]+","; // output each column as tab delimited
401
        }
402
        html=html+"\n";  // output each row with end of line
403
    }
404
    html = html+"\n";  // end of line at the end
405

    
406
    var form = $("#export_report_form");
407

    
408
    $("#csvBuffer").attr('value', html);
409
    form.target='_blank';
410
    form.submit();
411
}
412

    
413
$(function() {
414
    <?php
415
    echo Display::grid_js('results', $url,$columns,$column_model, $extra_params, array(), $action_links, true);
416

    
417
    if ($is_allowedToEdit || $is_tutor) { ?>
418

    
419
        //setSearchSelect("status");
420
        //
421
        //view:true, del:false, add:false, edit:false, excel:true}
422
        $("#results").jqGrid('navGrid','#results_pager', {view:true, edit:false, add:false, del:false, excel:false},
423
            {height:280, reloadAfterSubmit:false}, // view options
424
            {height:280, reloadAfterSubmit:false}, // edit options
425
            {height:280, reloadAfterSubmit:false}, // add options
426
            {reloadAfterSubmit: false}, // del options
427
            {width:500} // search options
428
        );
429

    
430
        //Adding search options
431
        var options = {
432
            'stringResult': true,
433
            'autosearch' : true,
434
            'searchOnEnter':false
435
        }
436
        jQuery("#results").jqGrid('filterToolbar',options);
437
        var sgrid = $("#results")[0];
438
        sgrid.triggerToolbar();
439

    
440
    <?php } ?>
441
});
442
</script>
443
<form id="export_report_form" method="post" action="hotpotatoes_exercise_report.php">
444
    <input type="hidden" name="csvBuffer" id="csvBuffer" value="" />
445
    <input type="hidden" name="export_report" id="export_report" value="1" />
446
    <input type="hidden" name="path" id="path" value="<?php echo $hotpotatoes_path ?>" />
447
</form>
448
<?php
449

    
450
echo Display::grid_html('results');
451
Display :: display_footer();
(2-2/4)