Passed
Push — master ( 76abd2...ab5d59 )
by Julito
10:01
created

HotpotatoesExerciseResult   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 315
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 183
dl 0
loc 315
rs 9.68
c 0
b 0
f 0
wmc 34

3 Methods

Rating   Name   Duplication   Size   Complexity  
B getExercisesReporting() 0 73 9
C exportCompleteReportCSV() 0 72 11
D exportCompleteReportXLS() 0 130 14
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class HotpotatoesExerciseResult
6
 * Allows you to export exercises results in multiple presentation forms.
7
 *
8
 * @package chamilo.exercise
9
 */
10
class HotpotatoesExerciseResult
11
{
12
    //stores the list of exercises
13
    private $exercises_list = [];
0 ignored issues
show
introduced by
The private property $exercises_list is not used, and could be removed.
Loading history...
14
15
    //stores the results
16
    private $results = [];
17
18
    /**
19
     * Gets the results of all students (or just one student if access is limited).
20
     *
21
     * @param string $document_path The document path (for HotPotatoes retrieval)
22
     * @param    int        User ID. Optional. If no user ID is provided, we take all the results. Defauts to null
23
     *
24
     * @return bool
25
     */
26
    public function getExercisesReporting($document_path, $hotpotato_name)
27
    {
28
        $return = [];
29
        $TBL_USER = Database::get_main_table(TABLE_MAIN_USER);
30
        $TBL_TRACK_HOTPOTATOES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
31
        $course_id = api_get_course_int_id();
32
        $user_id = null;
33
        $session_id_and = ' AND te.session_id = '.api_get_session_id().' ';
34
        $hotpotato_name = Database::escape_string($hotpotato_name);
35
36
        if (!empty($exercise_id)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $exercise_id seems to never exist and therefore empty should always be true.
Loading history...
37
            $session_id_and .= " AND exe_exo_id = $exercise_id ";
38
        }
39
40
        if (empty($user_id)) {
41
            $sql = "SELECT firstname as userpart1, lastname as userpart2 ,
42
                    email,
43
                    tth.exe_name,
44
                    tth.score,
45
                    tth.max_score,
46
                    tth.exe_date
47
                    FROM $TBL_TRACK_HOTPOTATOES tth, $TBL_USER tu
48
                    WHERE   tu.user_id=tth.exe_user_id AND
49
                            tth.c_id = $course_id AND
50
                            tth.exe_name = '$hotpotato_name'
51
                    ORDER BY tth.c_id ASC, tth.exe_date ASC";
52
        } else {
53
            // get only this user's results
54
            $sql = "SELECT '', exe_name, score, max_score, exe_date
55
                    FROM $TBL_TRACK_HOTPOTATOES
56
                    WHERE
57
                        exe_user_id = '".$user_id."' AND
58
                        c_id = $course_id AND
59
                        tth.exe_name = '$hotpotato_name'
60
                    ORDER BY c_id ASC, exe_date ASC";
61
        }
62
63
        $results = [];
64
65
        $resx = Database::query($sql);
66
        while ($rowx = Database::fetch_array($resx, 'ASSOC')) {
67
            $results[] = $rowx;
68
        }
69
70
        $hpresults = [];
71
        $resx = Database::query($sql);
72
        while ($rowx = Database::fetch_array($resx, 'ASSOC')) {
73
            $hpresults[] = $rowx;
74
        }
75
76
        // Print the Result of Hotpotatoes Tests
77
        if (is_array($hpresults)) {
78
            for ($i = 0; $i < sizeof($hpresults); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function sizeof() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
79
                $return[$i] = [];
80
                $title = GetQuizName($hpresults[$i]['exe_name'], $document_path);
81
                if ($title == '') {
82
                    $title = basename($hpresults[$i]['exe_name']);
83
                }
84
                if (empty($user_id)) {
85
                    $return[$i]['email'] = $hpresults[$i]['email'];
86
                    $return[$i]['first_name'] = $hpresults[$i]['userpart1'];
87
                    $return[$i]['last_name'] = $hpresults[$i]['userpart2'];
88
                }
89
                $return[$i]['title'] = $title;
90
                $return[$i]['exe_date'] = $hpresults[$i]['exe_date'];
91
92
                $return[$i]['result'] = $hpresults[$i]['score'];
93
                $return[$i]['max'] = $hpresults[$i]['max_score'];
94
            }
95
        }
96
        $this->results = $return;
97
98
        return true;
99
    }
100
101
    /**
102
     * Exports the complete report as a CSV file.
103
     *
104
     * @param string $document_path  Document path inside the document tool
105
     * @param string $hotpotato_name
106
     *
107
     * @return bool False on error
108
     */
109
    public function exportCompleteReportCSV($document_path = '', $hotpotato_name = '')
110
    {
111
        global $charset;
112
        $this->getExercisesReporting($document_path, $hotpotato_name);
113
        $filename = 'exercise_results_'.date('YmdGis').'.csv';
114
        if (!empty($user_id)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $user_id seems to never exist and therefore empty should always be true.
Loading history...
115
            $filename = 'exercise_results_user_'.$user_id.'_'.date('YmdGis').'.csv';
116
        }
117
        $data = '';
118
119
        if (api_is_western_name_order()) {
120
            if (!empty($this->results[0]['first_name'])) {
121
                $data .= get_lang('FirstName').';';
122
            }
123
            if (!empty($this->results[0]['last_name'])) {
124
                $data .= get_lang('LastName').';';
125
            }
126
        } else {
127
            if (!empty($this->results[0]['last_name'])) {
128
                $data .= get_lang('LastName').';';
129
            }
130
            if (!empty($this->results[0]['first_name'])) {
131
                $data .= get_lang('FirstName').';';
132
            }
133
        }
134
        $data .= get_lang('Email').';';
135
        $data .= get_lang('Title').';';
136
        $data .= get_lang('StartDate').';';
137
        $data .= get_lang('Score').';';
138
        $data .= get_lang('Total').';';
139
        $data .= "\n";
140
141
        // Results
142
        foreach ($this->results as $row) {
143
            if (api_is_western_name_order()) {
144
                $data .= str_replace("\r\n", '  ', api_html_entity_decode(strip_tags($row['first_name']), ENT_QUOTES, $charset)).';';
145
                $data .= str_replace("\r\n", '  ', api_html_entity_decode(strip_tags($row['last_name']), ENT_QUOTES, $charset)).';';
146
            } else {
147
                $data .= str_replace("\r\n", '  ', api_html_entity_decode(strip_tags($row['last_name']), ENT_QUOTES, $charset)).';';
148
                $data .= str_replace("\r\n", '  ', api_html_entity_decode(strip_tags($row['first_name']), ENT_QUOTES, $charset)).';';
149
            }
150
151
            $data .= str_replace("\r\n", '  ', api_html_entity_decode(strip_tags($row['email']), ENT_QUOTES, $charset)).';';
152
            $data .= str_replace("\r\n", '  ', api_html_entity_decode(strip_tags($row['title']), ENT_QUOTES, $charset)).';';
153
            $data .= str_replace("\r\n", '  ', $row['exe_date']).';';
154
            $data .= str_replace("\r\n", '  ', $row['result']).';';
155
            $data .= str_replace("\r\n", '  ', $row['max']).';';
156
            $data .= "\n";
157
        }
158
159
        //output the results
160
        $len = strlen($data);
161
        header('Content-type: application/octet-stream');
162
        header('Content-Type: application/force-download');
163
        header('Content-length: '.$len);
164
        if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT'])) {
165
            header('Content-Disposition: filename= '.$filename);
166
        } else {
167
            header('Content-Disposition: attachment; filename= '.$filename);
168
        }
169
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
170
            header('Pragma: ');
171
            header('Cache-Control: ');
172
            header('Cache-Control: public'); // IE cannot download from sessions without a cache
173
        }
174
        header('Content-Description: '.$filename);
175
        header('Content-transfer-encoding: binary');
176
        // @todo add this utf-8 header for all csv files
177
        echo "\xEF\xBB\xBF"; // force utf-8 header of csv file
178
        echo $data;
179
180
        return true;
181
    }
182
183
    /**
184
     * Exports the complete report as an XLS file.
185
     *
186
     * @param string $document_path
187
     * @param null   $user_id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $user_id is correct as it would always require null to be passed?
Loading history...
188
     * @param bool   $export_user_fields
189
     * @param int    $export_filter
190
     * @param int    $exercise_id
191
     * @param null   $hotpotato_name
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $hotpotato_name is correct as it would always require null to be passed?
Loading history...
192
     *
193
     * @return bool
194
     */
195
    public function exportCompleteReportXLS(
196
        $document_path = '',
197
        $user_id = null,
198
        $export_user_fields = false,
199
        $export_filter = 0,
200
        $exercise_id = 0,
201
        $hotpotato_name = null
202
    ) {
203
        global $charset;
204
        $this->getExercisesReporting(
205
            $document_path,
206
            $user_id,
207
            $export_filter,
208
            $exercise_id,
209
            $hotpotato_name
210
        );
211
        $filename = 'exercise_results_'.api_get_local_time();
212
        if (!empty($user_id)) {
213
            $filename = 'exercise_results_user_'.$user_id.'_'.api_get_local_time();
214
        }
215
216
        // check if exists column 'user'
217
        $withColumnUser = false;
218
        foreach ($this->results as $result) {
219
            if (!empty($result['last_name']) && !empty($result['first_name'])) {
220
                $withColumnUser = true;
221
                break;
222
            }
223
        }
224
        $list = [];
225
        if ($withColumnUser) {
226
            $list[0][] = get_lang('Email');
227
            if (api_is_western_name_order()) {
228
                $list[0][] = get_lang('FirstName');
229
                $list[0][] = get_lang('LastName');
230
            } else {
231
                $list[0][] = get_lang('LastName');
232
                $list[0][] = get_lang('FirstName');
233
            }
234
        }
235
236
        if ($export_user_fields) {
237
            //show user fields section with a big th colspan that spans over all fields
238
            $extra_user_fields = UserManager::get_extra_fields(
239
                0,
240
                1000,
241
                5,
242
                'ASC',
243
                false,
244
                1
245
            );
246
247
            //show the fields names for user fields
248
            foreach ($extra_user_fields as $field) {
249
                $list[0][] = api_html_entity_decode(
250
                    strip_tags($field[3]),
251
                    ENT_QUOTES,
252
                    $charset
253
                );
254
            }
255
        }
256
257
        $list[0][] = get_lang('Title');
258
        $list[0][] = get_lang('StartDate');
259
        $list[0][] = get_lang('EndDate');
260
        $list[0][] = get_lang('Duration').' ('.get_lang('MinMinutes').')';
261
        $list[0][] = get_lang('Score');
262
        $list[0][] = get_lang('Total');
263
        $list[0][] = get_lang('Status');
264
265
        $column = 1;
266
        foreach ($this->results as $row) {
267
            if ($withColumnUser) {
268
                $list[$column][] = api_html_entity_decode(
269
                    strip_tags($row['email']),
270
                    ENT_QUOTES,
271
                    $charset
272
                );
273
274
                if (api_is_western_name_order()) {
275
                    $list[$column][] = api_html_entity_decode(
276
                        strip_tags($row['first_name']),
277
                        ENT_QUOTES,
278
                        $charset
279
                    );
280
                    $list[$column][] = api_html_entity_decode(
281
                        strip_tags($row['last_name']),
282
                        ENT_QUOTES,
283
                        $charset
284
                    );
285
                } else {
286
                    $list[$column][] = api_html_entity_decode(
287
                        strip_tags($row['last_name']),
288
                        ENT_QUOTES,
289
                        $charset
290
                    );
291
                    $list[$column][] = api_html_entity_decode(
292
                        strip_tags($row['first_name']),
293
                        ENT_QUOTES,
294
                        $charset
295
                    );
296
                }
297
            }
298
299
            if ($export_user_fields) {
300
                //show user fields data, if any, for this user
301
                $values = UserManager::get_extra_user_data(
302
                    $row['user_id'],
303
                    false,
304
                    false,
305
                    false,
306
                    true
307
                );
308
                foreach ($values as $value) {
309
                    $list[$column][] = api_html_entity_decode(strip_tags($value), ENT_QUOTES, $charset);
310
                }
311
            }
312
313
            $list[$column][] = api_html_entity_decode(strip_tags($row['title']), ENT_QUOTES, $charset);
314
            $list[$column][] = $row['start_date'];
315
            $list[$column][] = $row['end_date'];
316
            $list[$column][] = $row['duration'];
317
            $list[$column][] = $row['result'];
318
            $list[$column][] = $row['max'];
319
            $list[$column][] = $row['status'];
320
        }
321
322
        Export::arrayToXls($list, $filename);
323
324
        return true;
325
    }
326
}
327