tce_functions_omr.php 14.1 KB
Newer Older
Nick's avatar
11.2  
Nick committed
1
2
3
4
<?php
//============================================================+
// File name   : tce_functions_omr.php
// Begin       : 2011-05-17
tecnickcom's avatar
tecnickcom committed
5
// Last Update : 2014-06-11
Nick's avatar
11.2  
Nick committed
6
7
8
9
10
11
12
13
//
// Description : Functions to import test data from scanned
//               OMR (Optical Mark Recognition) sheets.
//
// Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
Nick's avatar
Nick committed
14
//               Tecnick.com LTD
Nick's avatar
11.2  
Nick committed
15
16
17
18
//               www.tecnick.com
//               info@tecnick.com
//
// License:
tecnickcom's avatar
tecnickcom committed
19
//    Copyright (C) 2004-2014 Nicola Asuni - Tecnick.com LTD
Nick's avatar
11.2  
Nick committed
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
//    See LICENSE.TXT file for more information.
//============================================================+

/**
 * @file
 * Functions to import test data from scanned OMR (Optical Mark Recognition) sheets.
 * @package com.tecnick.tcexam.shared
 * @author Nicola Asuni
 * @since 2011-05-17
 */

/**
 * Encode OMR test data array as a string to be printed on QR-Code.
 * @param $data (array) array to be encoded
 * @return encoded string.
 */
function F_encodeOMRTestData($data) {
	$str = serialize($data);
	$str = gzcompress($str, 9); // requires php-zlib extension
	$str = base64_encode($str);
	$str = urlencode($str);
	return $str;
}

/**
 * Decode OMR test data string (read from QR-Code) as array.
 * @param $str (string) string to be decoded.
 * @return array with test data (0 => test_id, n => array(0 => question_n_ID, 1 => array(answers_IDs)), or false in case of error.
 */
function F_decodeOMRTestData($str) {
	if (empty($str)) {
		return false;
	}
	$data = $str;
	$data = urldecode($data);
	$data = base64_decode($data);
	$data = gzuncompress($data);
	$data = unserialize($data);
	return $data;
}

/**
 * Read QR-Code from OMR page and return Test data.
 * This function uses the external application zbarimg (http://zbar.sourceforge.net/).
 * @param $image (string) image file to be decoded (scanned OMR page).
 * @return array with test data or false in case o error
 */
function F_decodeOMRTestDataQRCode($image) {
	require_once('../config/tce_config.php');
	if (empty($image)) {
		return false;
	}
	$command = K_OMR_PATH_ZBARIMG.' --raw -Sdisable -Sqrcode.enable -q '.escapeshellarg($image);
	$str = exec($command);
	return F_decodeOMRTestData($str);
}

/**
Nick's avatar
Nick committed
78
 * Decode a single OMR Page and return data array.
Nick's avatar
11.2  
Nick committed
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
 * This function requires ImageMagick library and zbarimg (http://zbar.sourceforge.net/).
 * @param $image (string) image file to be decoded (scanned OMR page at 200 DPI with full color range).
 * @return array of answers data or false in case of error.
 */
function F_decodeOMRPage($image) {
	require_once('../config/tce_config.php');
	// decode barcode containing first question number
	$command = K_OMR_PATH_ZBARIMG.' --raw -Sdisable -Scode128.enable -q '.escapeshellarg($image);
	$qstart = exec($command);
	$qstart = intval($qstart);
	if ($qstart == 0) {
		return false;
	}
	$img = new Imagick();
	$img->readImage($image);
	$imginfo = $img->identifyImage();
	if ($imginfo['type'] == 'TrueColor') {
		// remove red color
		$img->separateImageChannel(Imagick::CHANNEL_RED);
	} else {
		// desaturate image
		$img->modulateImage(100, 0, 100);
	}
	// get image width and height
	$w = $imginfo['geometry']['width'];
	$h = $imginfo['geometry']['height'];
	if ($h > $w) {
		// crop header and footer
		$y = round(($h - $w) / 2);
		$img->cropImage($w, $w, 0, $y);
		$img->setImagePage(0, 0, 0, 0);
	}
	$img->normalizeImage(Imagick::CHANNEL_ALL);
	$img->enhanceImage();
	$img->despeckleImage();
tecnickcom's avatar
tecnickcom committed
114
115
116
117
	$img->blackthresholdImage('#808080');
	$img->whitethresholdImage('#808080');
	$img->trimImage(85);
	$img->deskewImage(15);
Nick's avatar
Nick committed
118
119
120
	$img->trimImage(85);
	$img->resizeImage(1028, 1052, Imagick::FILTER_CUBIC, 1);
	$img->setImagePage(0, 0, 0, 0);
tecnickcom's avatar
tecnickcom committed
121
	//$img->writeImage(K_PATH_CACHE.'_DEBUG_OMR_.PNG'); // DEBUG
Nick's avatar
11.2  
Nick committed
122
123
124
125
126
127
128
129
130
131
132
133
134
	// scan block width
	$blkw = 16;
	// starting column in pixels
	$scol = 106;
	// starting row in pixels
	$srow = 49;
	// column distance in pixels between two answers
	$dcol = 75.364;
	// column distance in pixels between True/false circles
	$dtf = 25;
	// row distance in pixels between two questions
	$drow = 32.38;
	// verify image pattern
nick's avatar
nick committed
135
	$imgtmp = clone $img;
Nick's avatar
11.2  
Nick committed
136
137
138
139
140
141
142
143
144
145
146
147
148
	$imgtmp->cropImage(1028, 10, 0, 10);
	$imgtmp->setImagePage(0, 0, 0, 0);
	// create reference block pattern
	$impref = new Imagick();
	$impref->newImage(3, 10, new ImagickPixel('black'));
	$psum = 0;
	for ($c = 0; $c < 12; ++$c) {
		$x = round(112 + ($c * $dcol));
		// get square region inside the current grid position
		$imreg = $img->getImageRegion(3, 10, $x, 0);
		$imreg->setImagePage(0, 0, 0, 0);
		// get root-mean-square-error with reference image
		$rmse = $imreg->compareImages($impref, Imagick::METRIC_ROOTMEANSQUAREDERROR);
nick's avatar
nick committed
149
150
		// count reference blocks
		$psum += round(1.25 - $rmse[1]);
Nick's avatar
11.2  
Nick committed
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
	}
	$imreg->clear();
	$impref->clear();
	if ($psum != 12) {
		return false;
	}
	// create reference block
	$imref = new Imagick();
	$imref->newImage($blkw, $blkw, new ImagickPixel('black'));
	// array to be returned
	$omrdata = array();
	// for each row (question)
	for ($r = 0; $r < 30; ++$r) {
		$omrdata[($r + $qstart)] = array();
		$y = round($srow + ($r * $drow));
		// for each column (answer)
		for ($c = 0; $c < 12; ++$c) {
			// read true option
			$x = round($scol + ($c * $dcol));
			// get square region inside the current grid position
			$imreg = $img->getImageRegion($blkw, $blkw, $x, $y);
			$imreg->setImagePage(0, 0, 0, 0);
			// get root-mean-square-error with reference image
			$rmse = $imreg->compareImages($imref, Imagick::METRIC_ROOTMEANSQUAREDERROR);
			// true option
			$opt_true = (2 * round(1.25 - $rmse[1]));
			// read false option
			$x += $dtf;
			// get square region inside the current grid position
			$imreg = $img->getImageRegion($blkw, $blkw, $x, $y);
			$imreg->setImagePage(0, 0, 0, 0);
			// get root-mean-square-error with reference image
			$rmse = $imreg->compareImages($imref, Imagick::METRIC_ROOTMEANSQUAREDERROR);
			// false option
			$opt_false = round(1.25 - $rmse[1]);
			// set array to be returned (-1 = unset, 0 = false, 1 = true)
			$val = ($opt_true + $opt_false - 1);
			if ($val > 1) {
				$val = 1;
			}
			$omrdata[($r + $qstart)][($c + 1)] = $val;
		}
	}
	$imreg->clear();
	$imref->clear();
	return $omrdata;
}

/**
 * Import user's test data from OMR.
 * @param $user_id (int) user ID.
 * @param $date (string) date-time field.
 * @param $omr_testdata (array) Array containing test data.
 * @param $omr_answers (array) Array containing test answers (from OMR).
tecnickcom's avatar
tecnickcom committed
205
 * @param $overwrite (boolean) If true overwrites the previous answers on non-repeatable tests.
Nick's avatar
11.2  
Nick committed
206
207
 * @return boolean TRUE in case of success, FALSE otherwise.
 */
tecnickcom's avatar
tecnickcom committed
208
function F_importOMRTestData($user_id, $date, $omr_testdata, $omr_answers, $overwrite=false) {
Nick's avatar
11.2  
Nick committed
209
210
211
212
213
214
215
216
217
218
219
	require_once('../config/tce_config.php');
	require_once('../../shared/code/tce_functions_test.php');
	global $db, $l;
	// check arrays
	if (count($omr_testdata) > (count($omr_answers) + 1)) {
		// arrays must contain the same amount of questions
		return false;
	}
	$test_id = intval($omr_testdata[0]);
	$user_id = intval($user_id);
	$time = strtotime($date);
Nick's avatar
Nick committed
220
	$date = date(K_TIMESTAMP_FORMAT, $time);
Nick's avatar
11.2  
Nick committed
221
222
223
224
225
226
227
	$dateanswers = date(K_TIMESTAMP_FORMAT, ($time + 1));
	// check user's group
	if (F_count_rows(K_TABLE_USERGROUP.', '.K_TABLE_TEST_GROUPS.' WHERE usrgrp_group_id=tstgrp_group_id AND tstgrp_test_id='.$test_id.' AND usrgrp_user_id='.$user_id.' LIMIT 1') == 0) {
		return false;
	}
	// get test data
	$testdata = F_getTestData($test_id);
Nicola Asuni's avatar
Nicola Asuni committed
228
229
230
231
232
	// 1. check if test is repeatable
	$sqls = 'SELECT test_id FROM '.K_TABLE_TESTS.' WHERE test_id='.$test_id.' AND test_repeatable=\'1\' LIMIT 1';
	if ($rs = F_db_query($sqls, $db)) {
		if ($ms = F_db_fetch_array($rs)) {
			// 1a. update previous test data if repeatable
tecnickcom's avatar
tecnickcom committed
233
			$sqld = 'UPDATE '.K_TABLE_TEST_USER.' SET testuser_status=testuser_status+1 WHERE testuser_test_id='.$test_id.' AND testuser_user_id='.$user_id.' AND testuser_status>3';
Nicola Asuni's avatar
Nicola Asuni committed
234
235
236
237
			if (!$rd = F_db_query($sqld, $db)) {
				F_display_db_error();
			}
		} else {
tecnickcom's avatar
tecnickcom committed
238
239
240
241
242
243
244
245
246
247
248
			if ($overwrite) {
				// 1b. delete previous test data if not repeatable
				$sqld = 'DELETE FROM '.K_TABLE_TEST_USER.' WHERE testuser_test_id='.$test_id.' AND testuser_user_id='.$user_id.'';
				if (!$rd = F_db_query($sqld, $db)) {
					F_display_db_error();
				}
			} else {
				// 1c. check if this data already exist
				if (F_count_rows(K_TABLE_TEST_USER, 'WHERE testuser_test_id='.$test_id.' AND testuser_user_id='.$user_id.'') > 0) {
					return false;
				}
Nicola Asuni's avatar
Nicola Asuni committed
249
250
251
			}
		}
	} else {
Nick's avatar
11.2  
Nick committed
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
		F_display_db_error();
	}
	// 2. create new user's test entry
	// ------------------------------
	$sql = 'INSERT INTO '.K_TABLE_TEST_USER.' (
		testuser_test_id,
		testuser_user_id,
		testuser_status,
		testuser_creation_time,
		testuser_comment
		) VALUES (
		'.$test_id.',
		'.$user_id.',
		4,
		\''.$date.'\',
		\'OMR\'
		)';
	if (!$r = F_db_query($sql, $db)) {
		F_display_db_error(false);
		return false;
	} else {
		// get inserted ID
		$testuser_id = F_db_insert_id($db, K_TABLE_TEST_USER, 'testuser_id');
Nicola Asuni's avatar
Nicola Asuni committed
275
		F_updateTestuserStat($date);
Nick's avatar
11.2  
Nick committed
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
	}
	// 3. create test log entries
	$num_questions = count($omr_testdata) - 1;
	// for each question on array
	for ($q = 1; $q <= $num_questions; ++$q) {
		$question_id = intval($omr_testdata[$q][0]);
		$num_answers = count($omr_testdata[$q][1]);
		// get question data
		$sqlq = 'SELECT question_type, question_difficulty FROM '.K_TABLE_QUESTIONS.' WHERE question_id='.$question_id.' LIMIT 1';
		if ($rq = F_db_query($sqlq, $db)) {
			if ($mq = F_db_fetch_array($rq)) {
				// question scores
				$question_right_score = ($testdata['test_score_right'] * $mq['question_difficulty']);
				$question_wrong_score = ($testdata['test_score_wrong'] * $mq['question_difficulty']);
				$question_unanswered_score = ($testdata['test_score_unanswered'] * $mq['question_difficulty']);
				// add question
				$sqll = 'INSERT INTO '.K_TABLE_TESTS_LOGS.' (
					testlog_testuser_id,
					testlog_question_id,
					testlog_score,
					testlog_creation_time,
					testlog_display_time,
					testlog_reaction_time,
					testlog_order,
					testlog_num_answers
					) VALUES (
					'.$testuser_id.',
					'.$question_id.',
					'.$question_unanswered_score.',
					\''.$date.'\',
					\''.$date.'\',
					1,
					'.$q.',
					'.$num_answers.'
					)';
				if (!$rl = F_db_query($sqll, $db)) {
					F_display_db_error(false);
					return false;
				}
				$testlog_id = F_db_insert_id($db, K_TABLE_TESTS_LOGS, 'testlog_id');
				// set initial question score
				if ($mq['question_type'] == 1) { // MCSA
					$qscore = $question_unanswered_score;
				} else { // MCMA
					$qscore = 0;
				}
				$unanswered = true;
tecnickcom's avatar
tecnickcom committed
323
324
				$numselected = 0; // count the number of MCSA selected answers
				// for each answer on array
Nick's avatar
11.2  
Nick committed
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
				for ($a = 1; $a <= $num_answers; ++$a) {
					$answer_id = intval($omr_testdata[$q][1][$a]);
					if (isset($omr_answers[$q][$a])) {
						$answer_selected = $omr_answers[$q][$a]; //-1, 0, 1
					} else {
						$answer_selected = -1;
					}
					// add answer
					$sqli = 'INSERT INTO '.K_TABLE_LOG_ANSWER.' (
						logansw_testlog_id,
						logansw_answer_id,
						logansw_selected,
						logansw_order
						) VALUES (
						'.$testlog_id.',
						'.$answer_id.',
						'.$answer_selected.',
						'.$a.'
						)';
					if (!$ri = F_db_query($sqli, $db)) {
						F_display_db_error(false);
						return false;
					}
					// calculate question score
					if ($mq['question_type'] < 3) { // MCSA or MCMA
						// check if the answer is right
						$answer_isright = false;
						$sqla = 'SELECT answer_isright FROM '.K_TABLE_ANSWERS.' WHERE answer_id='.$answer_id.' LIMIT 1';
						if ($ra = F_db_query($sqla, $db)) {
							if (($ma = F_db_fetch_array($ra))) {
								$answer_isright = F_getBoolean($ma['answer_isright']);
								switch ($mq['question_type']) {
									case 1: { // MCSA - Multiple Choice Single Answer
										if ($answer_selected == 1) {
tecnickcom's avatar
tecnickcom committed
359
360
361
362
363
364
365
366
											++$numselected;
											if ($numselected == 1) {
												$unanswered = false;
												if ($answer_isright) {
													$qscore = $question_right_score;
												} else {
													$qscore = $question_wrong_score;
												}
Nick's avatar
11.2  
Nick committed
367
											} else {
tecnickcom's avatar
tecnickcom committed
368
369
370
												// multiple answer selected
												$unanswered = true;
												$qscore = $question_unanswered_score;
Nick's avatar
11.2  
Nick committed
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
											}
										}
										break;
									}
									case 2: { // MCMA - Multiple Choice Multiple Answer
										if ($answer_selected == -1) {
											$qscore += $question_unanswered_score;
										} elseif ($answer_selected == 0) {
											$unanswered = false;
											if ($answer_isright) {
												$qscore += $question_wrong_score;
											} else {
												$qscore += $question_right_score;
											}
										} elseif ($answer_selected == 1) {
											$unanswered = false;
											if ($answer_isright) {
												$qscore += $question_right_score;
											} else {
												$qscore += $question_wrong_score;
											}
										}
										break;
									}
								}
							}
						} else {
							F_display_db_error(false);
							return false;
						}
					}
				} // end for each answer
				if ($mq['question_type'] == 2) { // MCMA
					// normalize score
					if (F_getBoolean($testdata['test_mcma_partial_score'])) {
						// use partial scoring for MCMA and ORDER questions
						$qscore = round(($qscore / $num_answers), 3);
					} else {
						// all-or-nothing points
						if ($qscore >= ($question_right_score * $num_answers)) {
							// right
							$qscore = $question_right_score;
						} elseif ($qscore == ($question_unanswered_score * $num_answers)) {
							// unanswered
							$qscore = $question_unanswered_score;
						} else {
							// wrong
							$qscore = $question_wrong_score;
						}
					}
				}
				if ($unanswered) {
					$change_time = '';
				} else {
					$change_time = $dateanswers;
				}
				// update question score
Nick's avatar
Nick committed
428
				$sqll = 'UPDATE '.K_TABLE_TESTS_LOGS.' SET
Nick's avatar
11.2  
Nick committed
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
					testlog_score='.$qscore.',
					testlog_change_time='.F_empty_to_null($change_time).',
					testlog_reaction_time=1000
					WHERE testlog_id='.$testlog_id.'';
				if (!$rl = F_db_query($sqll, $db)) {
					F_display_db_error();
					return false;
				}
			}
		} else {
			F_display_db_error(false);
			return false;
		}
	} // end for each question
	return true;
}

//============================================================+
// END OF FILE
//============================================================+