Project

General

Profile

Bug #5376 » exercice.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 Olivier Brouckaert, original author
7
*	@author Denes Nagy, HotPotatoes integration
8
*	@author Wolfgang Schneider, code/html cleanup
9
*	@author Julio Montoya <gugli100@gmail.com>, lots of cleanup + several improvements
10
* Modified by hubert.borderiou (question category)
11
*/
12
/**
13
 * Code
14
 */
15
// name of the language file that needs to be included
16

    
17
use \ChamiloSession as Session;
18

    
19
$language_file = array('exercice','tracking');
20

    
21
// including the global library
22
require_once '../inc/global.inc.php';
23
$current_course_tool  = TOOL_QUIZ;
24

    
25
require_once '../gradebook/lib/be.inc.php';
26

    
27
// Setting the tabs
28
$this_section = SECTION_COURSES;
29

    
30
$htmlHeadXtra[] = api_get_js('qtip2/jquery.qtip.min.js');
31
$htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/qtip2/jquery.qtip.min.css');
32

    
33
// Access control
34
api_protect_course_script(true);
35

    
36
// including additional libraries
37
require_once 'exercise.class.php';
38
require_once 'exercise.lib.php';
39
require_once 'question.class.php';
40
require_once 'answer.class.php';
41
require_once 'testcategory.class.php';
42
require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
43
require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
44
require_once 'hotpotatoes.lib.php';
45
require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
46

    
47
/*	Constants and variables */
48
$is_allowedToEdit 			= api_is_allowed_to_edit(null,true);
49
$is_tutor 					= api_is_allowed_to_edit(true);
50
$is_tutor_course 			= api_is_course_tutor();
51

    
52
$TBL_DOCUMENT 				= Database :: get_course_table(TABLE_DOCUMENT);
53
$TBL_ITEM_PROPERTY 			= Database :: get_course_table(TABLE_ITEM_PROPERTY);
54
$TBL_EXERCICE_QUESTION 		= Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
55
$TBL_EXERCICES 				= Database :: get_course_table(TABLE_QUIZ_TEST);
56
$TBL_TRACK_EXERCICES 		= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
57
$table_lp_item              = Database :: get_course_table(TABLE_LP_ITEM);
58

    
59
// document path
60
$documentPath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . "/document";
61
// picture path
62
$picturePath  = $documentPath . '/images';
63
// audio path
64
$audioPath    = $documentPath . '/audio';
65

    
66
// hotpotatoes
67
$uploadPath     = DIR_HOTPOTATOES; //defined in main_api
68
$exercicePath   = api_get_self();
69
$exfile         = explode('/', $exercicePath);
70
$exfile         = strtolower($exfile[sizeof($exfile) - 1]);
71
$exercicePath   = substr($exercicePath, 0, strpos($exercicePath, $exfile));
72
$exercicePath   = $exercicePath . "exercice.php";
73

    
74
// Clear the exercise session
75
if (isset ($_SESSION['objExercise'])) {
76
	Session::erase('objExercise');
77
}
78
if (isset ($_SESSION['objQuestion'])) {
79
	Session::erase('objQuestion');
80
}
81
if (isset ($_SESSION['objAnswer'])) {
82
	Session::erase('objAnswer');
83
}
84
if (isset ($_SESSION['questionList'])) {
85
	Session::erase('questionList');
86
}
87
if (isset ($_SESSION['exerciseResult'])) {
88
	Session::erase('exerciseResult');
89
}
90

    
91
//General POST/GET/SESSION/COOKIES parameters recovery
92
if (empty ($origin)) {
93
	$origin = Security::remove_XSS($_REQUEST['origin']);
94
}
95
if (empty ($choice)) {
96
	$choice = $_REQUEST['choice'];
97
}
98
if (empty ($hpchoice)) {
99
	$hpchoice = $_REQUEST['hpchoice'];
100
}
101
if (empty ($exerciseId)) {
102
	$exerciseId = intval($_REQUEST['exerciseId']);
103
}
104
if (empty ($file)) {
105
	$file = Database :: escape_string($_REQUEST['file']);
106
}
107

    
108
$learnpath_id       = intval($_REQUEST['learnpath_id']);
109
$learnpath_item_id  = intval($_REQUEST['learnpath_item_id']);
110
$page               = intval($_REQUEST['page']);
111

    
112
$course_info        = api_get_course_info();
113
$course_id          = api_get_course_int_id();
114

    
115
if ($page < 0) {
116
    $page = 1;
117
}
118

    
119
if (!empty($_GET['gradebook']) && $_GET['gradebook']=='view' ) {
120
	$_SESSION['gradebook']=Security::remove_XSS($_GET['gradebook']);
121
	$gradebook=	$_SESSION['gradebook'];
122
} elseif (empty($_GET['gradebook'])) {
123
	unset($_SESSION['gradebook']);
124
	$gradebook=	'';
125
}
126

    
127
if (!empty($gradebook) && $gradebook=='view') {
128
	$interbreadcrumb[] = array ('url' => '../gradebook/' . $_SESSION['gradebook_dest'],'name' => get_lang('ToolGradebook'));
129
}
130

    
131
if ($show != 'result') {
132
	$nameTools = get_lang('Exercices');
133
} else {
134
	if ($is_allowedToEdit || $is_tutor) {
135
		$nameTools = get_lang('StudentScore');
136
		$interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook","name" => get_lang('Exercices'));
137
	    $objExerciseTmp = new Exercise();
138
        if ($objExerciseTmp->read($exerciseId)) {
139
            $interbreadcrumb[] = array("url" => "admin.php?exerciseId=".$exerciseId, "name" => $objExerciseTmp->name);
140
        }
141
	} else {
142
		$nameTools = get_lang('YourScore');
143
		$interbreadcrumb[] = array ("url" => "exercice.php?gradebook=$gradebook","name" => get_lang('Exercices'));
144
	}
145
}
146

    
147
if ($is_allowedToEdit && !empty ($choice) && $choice == 'exportqti2') {
148
	require_once 'export/qti2/qti2_export.php';
149
	$export = export_exercise($exerciseId, true);
150

    
151
	require_once api_get_path(LIBRARY_PATH) . 'pclzip/pclzip.lib.php';
152
	$archive_path = api_get_path(SYS_ARCHIVE_PATH);
153
	$temp_dir_short = api_get_unique_id();
154
	$temp_zip_dir = $archive_path . "/" . $temp_dir_short;
155
	if (!is_dir($temp_zip_dir))
156
		mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
157
	$temp_zip_file = $temp_zip_dir . "/" . api_get_unique_id() . ".zip";
158
	$temp_xml_file = $temp_zip_dir . "/qti2export_" . $exerciseId . '.xml';
159
	file_put_contents($temp_xml_file, $export);
160
	$zip_folder = new PclZip($temp_zip_file);
161
	$zip_folder->add($temp_xml_file, PCLZIP_OPT_REMOVE_ALL_PATH);
162
	$name = 'qti2_export_' . $exerciseId . '.zip';
163

    
164
	//DocumentManager::string_send_for_download($export,true,'qti2export_'.$exerciseId.'.xml');
165
	DocumentManager :: file_send_for_download($temp_zip_file, true, $name);
166
	unlink($temp_zip_file);
167
	unlink($temp_xml_file);
168
	rmdir($temp_zip_dir);
169
	exit; //otherwise following clicks may become buggy
170
}
171

    
172
$htmlHeadXtra[] = '<script>
173
    $(document).ready(function() {
174
        //this makes google chrome to crash ...
175
       /* $(".link_tooltip").each(function(){
176
            $(this).qtip({
177
                content: $(this).find(".exercise_tooltip"),
178
                position: { at:"top right", my:"bottom left"},
179
                show: {
180
                   event: false,
181
                   ready: true // ... but show the tooltip when ready
182
                },
183
                hide: true, //
184
            });
185
        });*/
186
    });
187
</script>';
188

    
189
if ($origin != 'learnpath') {
190
	//so we are not in learnpath tool
191
	Display :: display_header($nameTools, get_lang('Exercise'));
192
	if (isset ($_GET['message'])) {
193
		if (in_array($_GET['message'], array ('ExerciseEdited'))) {
194
			Display :: display_confirmation_message(get_lang($_GET['message']));
195
		}
196
	}
197
} else {
198
	//echo '<link rel="stylesheet" type="text/css" href="' . api_get_path(WEB_CODE_PATH) . 'css/default.css"/>';
199
	Display :: display_reduced_header();
200
}
201

    
202
event_access_tool(TOOL_QUIZ);
203

    
204
// Tool introduction
205
Display :: display_introduction_section(TOOL_QUIZ);
206

    
207
HotPotGCt($documentPath, 1, api_get_user_id() );
208

    
209
// only for administrator
210

    
211
if ($is_allowedToEdit) {
212
	if (!empty($choice)) {
213
		// construction of Exercise
214

    
215
		$objExerciseTmp = new Exercise();
216
		$check = Security::check_token('get');
217
        $exercise_action_locked = api_resource_is_locked_by_gradebook($exerciseId, LINK_EXERCISE);
218

    
219
		if ($objExerciseTmp->read($exerciseId)) {
220
			if ($check) {
221
				switch ($choice) {
222
					case 'delete' : // deletes an exercise
223
                        if ($exercise_action_locked == false) {
224
                            $objExerciseTmp->delete();
225
                            require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
226
                            $link_info = is_resource_in_course_gradebook(api_get_course_id(), 1 , $exerciseId, api_get_session_id());
227
                            if ($link_info !== false) {
228
                                remove_resource_from_course_gradebook($link_info['id']);
229
                            }
230
                            Display :: display_confirmation_message(get_lang('ExerciseDeleted'));
231
                        }
232
						break;
233
					case 'enable' : // enables an exercise
234
						$objExerciseTmp->enable();
235
						$objExerciseTmp->save();
236
                        api_item_property_update($course_info, TOOL_QUIZ, $objExerciseTmp->id, 'visible', api_get_user_id());
237
						// "WHAT'S NEW" notification: update table item_property (previously last_tooledit)
238
						Display :: display_confirmation_message(get_lang('VisibilityChanged'));
239
						break;
240
					case 'disable' : // disables an exercise
241
						$objExerciseTmp->disable();
242
						$objExerciseTmp->save();
243
                        api_item_property_update($course_info, TOOL_QUIZ, $objExerciseTmp->id, 'invisible', api_get_user_id());
244
						Display :: display_confirmation_message(get_lang('VisibilityChanged'));
245
						break;
246
					case 'disable_results' : //disable the results for the learners
247
						$objExerciseTmp->disable_results();
248
						$objExerciseTmp->save();
249
						Display :: display_confirmation_message(get_lang('ResultsDisabled'));
250
						break;
251
					case 'enable_results' : //disable the results for the learners
252
						$objExerciseTmp->enable_results();
253
						$objExerciseTmp->save();
254
						Display :: display_confirmation_message(get_lang('ResultsEnabled'));
255
						break;
256
					case 'clean_results' : //clean student results
257
                        if ($exercise_action_locked == false) {
258
                            $quantity_results_deleted= $objExerciseTmp->clean_results();
259
                            Display :: display_confirmation_message(sprintf(get_lang('XResultsCleaned'),$quantity_results_deleted));
260
                        }
261
                        break;
262
					case 'copy_exercise' : //copy an exercise
263
                        $objExerciseTmp->copy_exercise();
264
                        Display :: display_confirmation_message(get_lang('ExerciseCopied'));
265
                        break;
266
				}
267
			}
268
		}
269
		// destruction of Exercise
270
		unset ($objExerciseTmp);
271
		Security::clear_token();
272
	}
273

    
274
	if (!empty($hpchoice)) {
275
		switch($hpchoice) {
276
			case 'delete' : // deletes an exercise
277
				$imgparams = array ();
278
				$imgcount = 0;
279
				GetImgParams($file, $documentPath, $imgparams, $imgcount);
280
				$fld = GetFolderName($file);
281
				for ($i = 0; $i < $imgcount; $i++) {
282
					my_delete($documentPath . $uploadPath . "/" . $fld . "/" . $imgparams[$i]);
283
					update_db_info("delete", $uploadPath . "/" . $fld . "/" . $imgparams[$i]);
284
				}
285

    
286
				if (my_delete($documentPath . $file)) {
287
					update_db_info("delete", $file);
288
				}
289
				// hotpotatoes folder may contains several tests so don't delete folder if not empty : http://support.chamilo.org/issues/2165
290
				if (!(strstr($uploadPath, DIR_HOTPOTATOES) && !folder_is_empty($documentPath . $uploadPath . "/" . $fld . "/"))) {
291
    				my_delete($documentPath . $uploadPath . "/" . $fld . "/");
292
				}				break;
293
			case 'enable' : // enables an exercise
294
				$newVisibilityStatus = "1"; //"visible"
295
				$query = "SELECT id FROM $TBL_DOCUMENT WHERE c_id = $course_id AND path='" . Database :: escape_string($file) . "'";
296
				$res = Database::query($query);
297
				$row = Database :: fetch_array($res, 'ASSOC');
298
				api_item_property_update($_course, TOOL_DOCUMENT, $row['id'], 'visible', $_user['user_id']);
299
				//$dialogBox = get_lang('ViMod');
300

    
301
				break;
302
			case 'disable' : // disables an exercise
303
				$newVisibilityStatus = "0"; //"invisible"
304
				$query = "SELECT id FROM $TBL_DOCUMENT WHERE c_id = $course_id AND path='" . Database :: escape_string($file) . "'";
305
				$res = Database::query($query);
306
				$row = Database :: fetch_array($res, 'ASSOC');
307
				api_item_property_update($_course, TOOL_DOCUMENT, $row['id'], 'invisible', $_user['user_id']);
308
				break;
309
			default :
310
				break;
311
		}
312
	}
313
}
314

    
315
// Actions div bar
316
if ($is_allowedToEdit) {
317
    echo '<div class="actions">';
318
}
319

    
320

    
321
// Selects $limit exercises at the same time
322
// maximum number of exercises on a same page
323
$limit = 50;
324

    
325
// Display the next and previous link if needed
326
$from = $page * $limit;
327
HotPotGCt($documentPath, 1, api_get_user_id());
328

    
329
//condition for the session
330
$course_code        = api_get_course_id();
331
$session_id         = api_get_session_id();
332
$condition_session  = api_get_session_condition($session_id,true,true);
333

    
334

    
335
// Only for administrators
336
if ($is_allowedToEdit) {
337
    $total_sql = "SELECT count(id) as count FROM $TBL_EXERCICES WHERE c_id = $course_id AND active<>'-1' $condition_session ";
338
    $sql = "SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND active<>'-1' $condition_session ORDER BY title LIMIT ".$from."," .$limit;
339
} else {
340
    // Only for students
341
    $total_sql = "SELECT count(id) as count FROM $TBL_EXERCICES WHERE c_id = $course_id AND active = '1' $condition_session ";
342
    $sql = "SELECT id, title, type, description, results_disabled, session_id, start_time, end_time, max_attempt FROM $TBL_EXERCICES
343
            WHERE c_id = $course_id AND
344
                  active='1' $condition_session
345
            ORDER BY title LIMIT ".$from."," .$limit;
346
    
347
}
348

    
349
$result = Database::query($sql);
350
$exercises_count = Database :: num_rows($result);
351

    
352
$result_total = Database::query($total_sql);
353
$total_exercises  = 0;
354

    
355
if (Database :: num_rows($result_total)) {
356
    $result_total = Database::fetch_array($result_total);
357
    $total_exercises = $result_total['count'];
358
}
359

    
360
//get HotPotatoes files (active and inactive)
361
if ($is_allowedToEdit) {
362
    $sql = "SELECT * FROM $TBL_DOCUMENT WHERE c_id = $course_id AND path LIKE '" . Database :: escape_string($uploadPath) . "/%/%'";
363
    $res = Database::query($sql);
364
    $hp_count = Database :: num_rows($res);
365
} else {
366
    $sql = "SELECT * FROM $TBL_DOCUMENT d, $TBL_ITEM_PROPERTY ip
367
            WHERE   d.id = ip.ref AND
368
                    ip.tool = '" . TOOL_DOCUMENT . "' AND
369
                    d.path LIKE '" . Database :: escape_string($uploadPath) . "/%/%' AND
370
                    ip.visibility ='1' AND
371
                    d.c_id      = ".$course_id." AND
372
                    ip.c_id     = ".$course_id;    
373
    $res = Database::query($sql);
374
    $hp_count = Database :: num_rows($res);
375
}
376
$total = $total_exercises + $hp_count;
377

    
378
if ($is_allowedToEdit && $origin != 'learnpath') {
379
	echo '<a href="exercise_admin.php?' . api_get_cidreq() . '">' . Display :: return_icon('new_exercice.png', get_lang('NewEx'),'',ICON_SIZE_MEDIUM).'</a>';
380
	echo '<a href="question_create.php?' . api_get_cidreq() . '">' . Display :: return_icon('new_question.png', get_lang('AddQ'),'',ICON_SIZE_MEDIUM).'</a>';
381
	// Question category
382
	echo '<a href="tests_category.php">';
383
	echo Display::return_icon('question_category_show.gif', get_lang('QuestionCategory'));
384
	echo '</a>';
385
	echo '<a href="question_pool.php">';
386
	echo Display::return_icon('database.png', get_lang('QuestionPool'), array('style'=>'width:32px'));
387
	echo '</a>';
388
	// end question category
389
	echo '<a href="hotpotatoes.php?' . api_get_cidreq() . '">' . Display :: return_icon('import_hotpotatoes.png', get_lang('ImportHotPotatoesQuiz'),'',ICON_SIZE_MEDIUM).'</a>';
390
	// link to import qti2 ...
391
	echo '<a href="qti2.php?' . api_get_cidreq() . '">' . Display :: return_icon('import_qti2.png', get_lang('ImportQtiQuiz'),'',ICON_SIZE_MEDIUM) .'</a>';
392
    echo '<a href="upload_exercise.php?' . api_get_cidreq() . '">' . Display :: return_icon('import_excel.png', get_lang('ImportExcelQuiz'),'',ICON_SIZE_MEDIUM) .'</a>';
393
}
394

    
395
if ($is_allowedToEdit) {
396
    echo '</div>'; // closing the actions div
397
}
398

    
399
if ($total > $limit) {
400
    echo '<div style="float:right;height:20px;">';
401
    //show pages navigation link for previous page
402
    if ($page) {
403
        echo "<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&amp;page=" . ($page -1) . "\">" . Display :: return_icon('action_prev.png', get_lang('PreviousPage'))."</a>";
404
    } elseif ($total_exercises + $hp_count > $limit) {
405
        echo Display :: return_icon('action_prev_na.png', get_lang('PreviousPage'));
406
    }
407

    
408
    //show pages navigation link for previous page
409
    if ($total_exercises > $from + $limit ||  $hp_count > $from + $limit ) {
410
        echo ' '."<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&amp;page=" . ($page +1) . "\">" .Display::return_icon('action_next.png', get_lang('NextPage')) . "</a>";
411
    } elseif ($page) {
412
        echo ' '.Display :: return_icon('action_next_na.png', get_lang('NextPage'));
413
    }
414
    echo '</div>';
415
    }
416

    
417
    $i =1;
418
    $lis = '';
419

    
420
$online_icon  = Display::return_icon('online.png', get_lang('Visible'),array('width'=>'12px'));
421
$offline_icon = Display::return_icon('offline.png',get_lang('Invisible'),array('width'=>'12px'));
422

    
423
$exercise_list = array();
424
while ($row = Database :: fetch_array($result,'ASSOC')) {
425
    $exercise_list[] = $row;
426
}
427

    
428
echo '<table class="'.Display::return_default_table_class().'">';
429

    
430
/*  Listing exercises  */
431
if (!empty($exercise_list)) {
432
    if ($origin != 'learnpath') {
433
        //avoid sending empty parameters
434
        $myorigin     = (empty ($origin)              ? '' : '&origin=' . $origin);
435
        $mylpid       = (empty ($learnpath_id)        ? '' : '&learnpath_id=' . $learnpath_id);
436
        $mylpitemid   = (empty ($learnpath_item_id)   ? '' : '&learnpath_item_id=' . $learnpath_item_id);
437

    
438
        $token = Security::get_token();
439
        $i=1;
440

    
441
        if ($is_allowedToEdit) {
442
            $headers = array(array('name' => get_lang('ExerciseName')),
443
                             array('name' => get_lang('QuantityQuestions'), 'params' => array('width'=>'100px')),
444
                             array('name' => get_lang('Actions'), 'params' => array('width'=>'180px')));
445
        } else {
446
        	$headers = array(array('name' => get_lang('ExerciseName')),
447
                             array('name' => get_lang('Status')),
448
                             );
449
        }
450

    
451
        $header_list = '';
452
        foreach($headers as $header) {
453
            $params = isset($header['params'])? $header['params'] : null;
454
            $header_list .= Display::tag('th', $header['name'], $params);
455
        }
456
        echo Display::tag('tr', $header_list);
457

    
458
        $count = 0;
459
        if (!empty($exercise_list))
460
        foreach ($exercise_list as $row) {
461
            $my_exercise_id = $row['id'];
462

    
463
            $locked = api_resource_is_locked_by_gradebook($my_exercise_id, LINK_EXERCISE);
464

    
465
            //echo '<div  id="tabs-'.$i.'">';
466
            $i++;
467
            //validacion when belongs to a session
468
            $session_img = api_get_session_image($row['session_id'], $_user['status']);
469

    
470
            $time_limits = false;
471
            if ($row['start_time'] != '0000-00-00 00:00:00' || $row['end_time'] != '0000-00-00 00:00:00') {
472
                $time_limits = true;
473
            }
474

    
475
            if ($time_limits) {
476
                // check if start time
477
                $start_time = false;
478
                if ($row['start_time'] != '0000-00-00 00:00:00') {
479
                    $start_time = api_strtotime($row['start_time'],'UTC');
480
                }
481
                $end_time = false;
482
                if ($row['end_time'] != '0000-00-00 00:00:00') {
483
                    $end_time   = api_strtotime($row['end_time'],'UTC');
484
                }
485
                $now             = time();
486
                $is_actived_time = false;
487

    
488
                //If both "clocks" are enable
489
                if ($start_time && $end_time) {
490
                    if ($now > $start_time && $end_time > $now ) {
491
                        $is_actived_time = true;
492
                    }
493
                } else {
494
                    //we check the start and end
495
                    if ($start_time) {
496
                        if ($now > $start_time) {
497
                           $is_actived_time = true;
498
                        }
499
                    }
500
                    if ($end_time) {
501
                        if ($end_time > $now ) {
502
                           $is_actived_time = true;
503
                        }
504
                    }
505
                }
506
            }
507

    
508
			//Blocking empty start times see BT#2800
509
        	global $_custom;
510
			if (isset($_custom['exercises_hidden_when_no_start_date']) && $_custom['exercises_hidden_when_no_start_date']) {
511
                if (empty($row['start_time']) || $row['start_time'] == '0000-00-00 00:00:00') {
512
                	$time_limits = true;
513
                	$is_actived_time = false;
514
                }
515
			}
516

    
517
            $cut_title = cut($row['title'], EXERCISE_MAX_NAME_SIZE);
518
            $alt_title = '';
519
            if ($cut_title != $row['title']) {
520
                $alt_title = ' title = "'.$row['title'].'" ';
521
            }
522

    
523
            // Teacher only
524
            if ($is_allowedToEdit) {
525
                $added_to_lp = false;
526

    
527
                $sql="SELECT max_score FROM $table_lp_item
528
                      WHERE c_id = $course_id AND
529
                            item_type = '".TOOL_QUIZ."' AND
530
                            path ='".Database::escape_string($row['id'])."'";
531
                $result = Database::query($sql);
532
                if (Database::num_rows($result) > 0) {
533
                    $added_to_lp = true;
534
                }
535

    
536
                $lp_blocked = '';
537
                if ($added_to_lp) {
538
                    //$lp_blocked = Display::label(get_lang('AddedToALP'), 'info');
539
                    $lp_blocked = Display::div(get_lang('AddedToLPCannotBeAccessed'), array('class'=> 'lp_content_type_label'));
540
                }
541

    
542
                //Showing exercise title
543

    
544
                if ($session_id == $row['session_id']) {
545
                    //Settings
546
                    //echo Display::url(Display::return_icon('settings.png',get_lang('Edit'), array('width'=>'22px'))." ".get_lang('Edit'), 'exercise_admin.php?'.api_get_cidreq().'&modifyExercise=yes&exerciseId='.$row['id']);
547
                }                
548
                
549
                $visibility = api_get_item_visibility($course_info, TOOL_QUIZ, $my_exercise_id);
550

    
551
                if ($row['active'] == 0 || $visibility == 0) {
552
                    $title = Display::tag('font', $cut_title, array('style'=>'color:grey'));
553
                } else {
554
                    $title = $cut_title;
555
                }
556

    
557
                $count = intval(count_exercise_result_not_validated($my_exercise_id, $course_code, $session_id));
558

    
559
                $class_tip = '';
560
                if (!empty($count)) {
561
                    $results_text = $count == 1 ? get_lang('ResultNotRevised') : get_lang('ResultsNotRevised');
562
                    $title .= '<span class="exercise_tooltip" style="display: none;">'.$count.' '.$results_text.' </span>';
563
                    $class_tip = 'link_tooltip';
564
                }
565

    
566
                if ($added_to_lp) {
567
                    //$title .= Display::div(get_lang('AddedToLPCannotBeAccessed'), array('class'=> 'lp_content_type_label'));
568
                }
569

    
570
                $url = '<a '.$alt_title.' class="'.$class_tip.'" id="tooltip_'.$row['id'].'" href="overview.php?'.api_get_cidreq().$myorigin.$mylpid.$mylpitemid.'&exerciseId='.$row['id'].'"><img src="../img/quiz.gif" /> '.$title.' </a>';
571

    
572
                $item =  Display::tag('td', $url.' '.$session_img.$lp_blocked);
573

    
574
                //count number exercice - teacher
575
                $sqlquery   = "SELECT count(*) FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND exercice_id = $my_exercise_id";
576
                $sqlresult  = Database::query($sqlquery);
577
                $rowi       = Database :: result($sqlresult, 0);
578

    
579
                if ($session_id == $row['session_id']) {
580
                    //Settings
581
                    $actions =  Display::url(Display::return_icon('edit.png',get_lang('Edit'),'',ICON_SIZE_SMALL), 'admin.php?'.api_get_cidreq().'&exerciseId='.$row['id']);
582

    
583
                    //Exercise results
584
                    $actions .='<a href="exercise_report.php?' . api_get_cidreq() . '&exerciseId='.$row['id'].'">'.Display :: return_icon('test_results.png', get_lang('Results'),'',ICON_SIZE_SMALL).'</a>';
585

    
586
                    //Export
587
                    $actions .= Display::url(Display::return_icon('cd.gif', get_lang('CopyExercise')),       '', array('onclick'=>"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToCopy'),ENT_QUOTES,$charset))." ".addslashes($row['title'])."?"."')) return false;",'href'=>'exercice.php?'.api_get_cidreq().'&choice=copy_exercise&sec_token='.$token.'&exerciseId='.$row['id']));
588
                    
589
                    //Clean exercise
590
                    if ($locked == false) {
591
                        $actions .= Display::url(Display::return_icon('clean.png', get_lang('CleanStudentResults'),'',ICON_SIZE_SMALL),'', array('onclick'=>"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToDeleteResults'),ENT_QUOTES,$charset))." ".addslashes($row['title'])."?"."')) return false;",'href'=>'exercice.php?'.api_get_cidreq().'&choice=clean_results&sec_token='.$token.'&exerciseId='.$row['id']));
592
                    } else {
593
                        $actions .= Display::return_icon('clean_na.png', get_lang('ResourceLockedByGradebook'),'',ICON_SIZE_SMALL);
594
                    }
595

    
596
                    //Visible / invisible
597
                    //Check if this exercise was added in a LP
598
                    if ($added_to_lp) {
599
                        $actions .= Display::return_icon('invisible.png', get_lang('AddedToLPCannotBeAccessed'),'',ICON_SIZE_SMALL);
600
                    } else {
601
                        if ($row['active'] == 0 || $visibility == 0) {
602
                            $actions .= Display::url(Display::return_icon('invisible.png', get_lang('Activate'),'',ICON_SIZE_SMALL) , 'exercice.php?'.api_get_cidreq().'&choice=enable&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']);                            
603
                        } else { // else if not active
604
                            $actions .= Display::url(Display::return_icon('visible.png', get_lang('Deactivate'),'',ICON_SIZE_SMALL) , 'exercice.php?'.api_get_cidreq().'&choice=disable&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']);
605
                        }
606
                    }
607
                    // Export qti ...
608
                    $actions .= Display::url(Display::return_icon('export_qti2.png','IMS/QTI','',ICON_SIZE_SMALL),        'exercice.php?choice=exportqti2&exerciseId='.$row['id']);
609
                } else {
610
                    // not session
611
                    $actions = Display::return_icon('edit_na.png', get_lang('ExerciseEditionNotAvailableInSession'));
612
                    $actions .='<a href="exercise_report.php?' . api_get_cidreq() . '&exerciseId='.$row['id'].'">'.Display :: return_icon('test_results.png', get_lang('Results'),'',ICON_SIZE_SMALL).'</a>';
613
                    $actions .= Display::url(Display::return_icon('cd.gif',   get_lang('CopyExercise')),     '',  array('onclick'=>"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToCopy'),ENT_QUOTES,$charset))." ".addslashes($row['title'])."?"."')) return false;",'href'=>'exercice.php?'.api_get_cidreq().'&choice=copy_exercise&sec_token='.$token.'&exerciseId='.$row['id']));
614
                }
615

    
616
                //Delete
617
                if ($session_id == $row['session_id']) {
618
                    if ($locked == false) {
619
                        $actions .= Display::url(Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL), '', array('onclick'=>"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToDelete'),ENT_QUOTES,$charset))." ".addslashes($row['title'])."?"."')) return false;",'href'=>'exercice.php?'.api_get_cidreq().'&choice=delete&sec_token='.$token.'&exerciseId='.$row['id']));
620
                    } else {
621
                        $actions .= Display::return_icon('delete_na.png', get_lang('ResourceLockedByGradebook'),'',ICON_SIZE_SMALL);
622
                    }
623
                }
624

    
625
				// Number of questions
626
                $random_label = '';
627
                if ($row['random'] > 0 || $row['random'] == -1) {
628
               	    // if random == -1 means use random questions with all questions
629
               	    $random_number_of_question = $row['random'];
630
               	    if ($random_number_of_question == -1) {
631
               	        $random_number_of_question = $rowi;
632
               	    }
633
					if ($row['random_by_category'] > 0) {
634
						if (!class_exists("testcategory.class.php")) include_once "testcategory.class.php" ;
635
						$nbQuestionsTotal = Testcategory::getNumberOfQuestionRandomByCategory($my_exercise_id, $random_number_of_question);
636
						$number_of_questions = $nbQuestionsTotal." ";
637
						$number_of_questions .= ($nbQuestionsTotal > 1) ? get_lang("QuestionsLowerCase") : get_lang("QuestionLowerCase") ;
638
						$number_of_questions .= " - ";
639
						//$number_of_questions .= Testcategory::getNumberMaxQuestionByCat($my_exercise_id).' '.get_lang('QuestionByCategory');
640
                        $number_of_questions .= min(Testcategory::getNumberMaxQuestionByCat($my_exercise_id), $random_number_of_question).' '.get_lang('QuestionByCategory');
641
					} else {
642
                   		$random_label = ' ('.get_lang('Random').') ';
643
                   	    $number_of_questions = $random_number_of_question . ' ' .$random_label.' '.$textByCategory;
644
                   	    //Bug if we set a random value bigger than the real number of questions
645
                   	    if ($random_number_of_question > $rowi) {
646
							$number_of_questions = $rowi. ' ' .$random_label;
647
                   	    }
648
                   	}
649
                } else {
650
                    $number_of_questions = $rowi;
651
                }
652
                
653
                //Attempts
654
                //$attempts = get_count_exam_results($row['id']).' '.get_lang('Attempts');
655

    
656
                //$item .=  Display::tag('td',$attempts);
657
                $item .=  Display::tag('td', $number_of_questions);
658

    
659
            } else {
660
                // Student only
661
                
662
                $visibility = api_get_item_visibility($course_info, TOOL_QUIZ, $my_exercise_id);
663
                                
664
                if ($visibility == 0) {
665
                    continue;
666
                }
667

    
668
                // if time is actived show link to exercise
669

    
670
                if ($time_limits) {
671
                    if ($is_actived_time) {
672
                        $url =  '<a '.$alt_title.'  href="overview.php?'.api_get_cidreq().$myorigin.$mylpid.$mylpitemid.'&exerciseId='.$row['id'].'">'.$cut_title.'</a>';
673
                    } else {
674
                        $url = $row['title'];
675
                    }
676
                } else {
677
                    $url = '<a '.$alt_title.'  href="overview.php?'.api_get_cidreq().$myorigin.$mylpid.$mylpitemid.'&exerciseId='.$row['id'].'">'.$cut_title.'</a>';
678
                }
679

    
680
                //Link of the exercise
681
                $item =  Display::tag('td',$url.' '.$session_img);
682

    
683
                //count number exercise questions
684
                $sqlquery   = "SELECT count(*) FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND exercice_id = ".$row['id'];
685
                $sqlresult  = Database::query($sqlquery);
686
                $rowi       = Database::result($sqlresult, 0);
687

    
688
                if ($row['random'] > 0) {
689
                    $row['random'] . ' ' . api_strtolower(get_lang(($row['random'] > 1 ? 'Questions' : 'Question')));
690
                } else {
691
                    //show results student
692
                    $rowi . ' ' . api_strtolower(get_lang(($rowi > 1 ? 'Questions' : 'Question')));
693
                }
694

    
695
                //This query might be improved later on by ordering by the new "tms" field rather than by exe_id
696
                //Don't remove this marker: note-query-exe-results
697
                $qry = "SELECT * FROM $TBL_TRACK_EXERCICES
698
                        WHERE   exe_exo_id      = ".$row['id']." AND
699
                                exe_user_id     = ".api_get_user_id()." AND
700
                                exe_cours_id    = '".api_get_course_id()."' AND
701
                                status          <> 'incomplete' AND
702
                                orig_lp_id      = 0 AND
703
                                orig_lp_item_id = 0 AND
704
                                session_id      =  '" . api_get_session_id() . "'
705
                        ORDER BY exe_id DESC";
706
                $qryres = Database::query($qry);
707
                $num    = Database :: num_rows($qryres);
708

    
709
                //Hide the results
710
                $my_result_disabled = $row['results_disabled'];
711

    
712
                //Time limits are on
713
                if ($time_limits) {
714
                    // Examn is ready to be taken
715
                    if ($is_actived_time) {
716
                        //Show results
717
                        if ($my_result_disabled == 0 || $my_result_disabled == 2) {
718
                            //More than one attempt
719
                            if ($num > 0) {
720
                                $row_track = Database :: fetch_array($qryres);
721
                                $attempt_text =  get_lang('LatestAttempt') . ' : ';
722
                                $attempt_text .= show_score($row_track['exe_result'], $row_track['exe_weighting']);
723
                            } else {
724
                                //No attempts
725
                                $attempt_text =  get_lang('NotAttempted');
726
                            }
727
                        } else {
728
                            $attempt_text =  get_lang('CantShowResults');
729
                        }
730
                    } else {
731
                        //Quiz not ready due to time limits
732

    
733
                        //@todo use the is_visible function
734
                        if ($row['start_time'] != '0000-00-00 00:00:00' && $row['end_time'] != '0000-00-00 00:00:00') {
735
                            $attempt_text =  sprintf(get_lang('ExerciseWillBeActivatedFromXToY'), api_convert_and_format_date($row['start_time']), api_convert_and_format_date($row['end_time']));
736
                        } else {
737
                            //$attempt_text = get_lang('ExamNotAvailableAtThisTime');
738
                            if ($row['start_time'] != '0000-00-00 00:00:00') {
739
                                $attempt_text = sprintf(get_lang('ExerciseAvailableFromX'), api_convert_and_format_date($row['start_time']));
740
                            }
741
                            if ($row['end_time'] != '0000-00-00 00:00:00') {
742
                                $attempt_text = sprintf(get_lang('ExerciseAvailableUntilX'), api_convert_and_format_date($row['end_time']));
743
                            }
744
                        }
745
                    }
746
                } else {
747
                    //Normal behaviour
748
                    //Show results
749
                    if ($my_result_disabled == 0 || $my_result_disabled == 2) {
750
                        if ($num > 0) {
751
                            $row_track = Database :: fetch_array($qryres);
752
                            $attempt_text =  get_lang('LatestAttempt') . ' : ';
753
                            $attempt_text .= show_score($row_track['exe_result'], $row_track['exe_weighting']);
754
                        } else {
755
                            $attempt_text =  get_lang('NotAttempted');
756
                        }
757
                    } else {
758
                        $attempt_text = get_lang('CantShowResults');
759
                    }
760
                }
761

    
762
                $class_tip = '';
763

    
764
                if (empty($num)) {
765
                    $num = '';
766
                } else {
767
                    $class_tip = 'link_tooltip';
768
                    //@todo use sprintf and show the results validated by the teacher
769
                    if ($num == 1 ) {
770
                        $num = $num.' '.get_lang('Result');
771
                    } else {
772
                        $num = $num.' '.get_lang('Results');
773
                    }
774
                    $num = '<span class="tooltip" style="display: none;">'.$num.'</span>';
775
                }
776
                $item .=  Display::tag('td', $attempt_text);
777

    
778
                //See results
779
                //$actions = '<a class="'.$class_tip.'" id="tooltip_'.$row['id'].'" href="exercise_report.php?' . api_get_cidreq() . '&exerciseId='.$row['id'].'">'.$num.Display::return_icon('test_results.png', get_lang('Results'),'',ICON_SIZE_SMALL).' </a>';
780
            }
781
            $class = 'row_even';
782
            if ($count % 2) {
783
                $class = 'row_odd';
784
            }
785

    
786
            if ($is_allowedToEdit) {
787
                $item .=  Display::tag('td', $actions, array('class' => 'td_actions'));
788
            }
789
            echo Display::tag('tr',$item, array('class'=>$class));
790

    
791
            $count++;
792
        } // end foreach()
793
    }
794
}
795
// end exercise list
796

    
797
//Hotpotatoes results
798
$hotpotatoes_exist = false;
799

    
800
if ($is_allowedToEdit) {
801
    $sql = "SELECT d.path as path, d.comment as comment, ip.visibility as visibility
802
            FROM $TBL_DOCUMENT d, $TBL_ITEM_PROPERTY ip
803
            WHERE   d.c_id = $course_id AND
804
                    ip.c_id = $course_id AND
805
                    d.id = ip.ref AND
806
                    ip.tool = '" . TOOL_DOCUMENT . "' AND
807
                    (d.path LIKE '%htm%') AND
808
                    d.path  LIKE '" . Database :: escape_string($uploadPath) . "/%/%'
809
                    LIMIT " .$from . "," .$limit; // only .htm or .html files listed
810
} else {
811
    $sql = "SELECT d.path as path, d.comment as comment, ip.visibility as visibility
812
            FROM $TBL_DOCUMENT d, $TBL_ITEM_PROPERTY ip
813
            WHERE d.c_id = $course_id AND
814
                    ip.c_id = $course_id AND
815
            d.id = ip.ref AND ip.tool = '" . TOOL_DOCUMENT . "' AND (d.path LIKE '%htm%')
816
            AND   d.path  LIKE '" . Database :: escape_string($uploadPath) . "/%/%' AND ip.visibility='1'
817
            LIMIT " .$from . "," .$limit;
818
}
819

    
820
$result = Database::query($sql);
821

    
822
while ($row = Database :: fetch_array($result, 'ASSOC')) {
823
    $attribute['path'][]        = $row['path'];
824
    $attribute['visibility'][]  = $row['visibility'];
825
    $attribute['comment'][]     = $row['comment'];
826
}
827

    
828
$nbrActiveTests = 0;
829
if (isset($attribute['path']) && is_array($attribute['path'])) {
830
    $hotpotatoes_exist = true;
831
    while (list($key, $path) = each($attribute['path'])) {
832
        $item = '';
833
        list ($a, $vis) = each($attribute['visibility']);
834
        if (strcmp($vis, "1") == 0) {
835
            $active = 1;
836
        } else {
837
            $active = 0;
838
        }
839
        $title = GetQuizName($path, $documentPath);
840
        if ($title == '') {
841
            $title = basename($path);
842
        }
843

    
844
        $class = 'row_even';
845
        if ($count % 2) {
846
            $class = 'row_odd';
847
        }
848

    
849
        // prof only
850
        if ($is_allowedToEdit) {
851
            $item  = Display::tag('td','<img src="../img/hotpotatoes_s.png" alt="HotPotatoes" /> <a href="showinframes.php?file='.$path.'&cid='.api_get_course_id().'&uid='.api_get_user_id().'"'.(!$active?'class="invisible"':'').'>'.$title.'</a> ');
852
            $item .= Display::tag('td','-');
853

    
854
            $actions =  Display::url(Display::return_icon('edit.png',get_lang('Edit'),'',ICON_SIZE_SMALL), 'adminhp.php?'.api_get_cidreq().'&hotpotatoesName='.$path);
855
            $actions .='<a href="hotpotatoes_exercise_report.php?' . api_get_cidreq() . '&path='.$path.'">' . Display :: return_icon('test_results.png', get_lang('Results'),'',ICON_SIZE_SMALL).'</a>';
856

    
857
            // if active
858
            if ($active) {
859
                $nbrActiveTests = $nbrActiveTests +1;
860
                $actions .= '      <a href="'.$exercicePath.'?'.api_get_cidreq().'&hpchoice=disable&amp;page='.$page.'&amp;file='.$path.'">'.Display::return_icon('visible.png', get_lang('Deactivate'),'',ICON_SIZE_SMALL).'</a>';
861
            } else { // else if not active
862
                $actions .='    <a href="'.$exercicePath.'?'.api_get_cidreq().'&hpchoice=enable&amp;page='.$page.'&amp;file='.$path.'">'.Display::return_icon('invisible.png', get_lang('Activate'),'',ICON_SIZE_SMALL).'</a>';
863
            }
864
            $actions .= '<a href="'.$exercicePath.'?'.api_get_cidreq().'&amp;hpchoice=delete&amp;file='.$path.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('AreYouSureToDelete'),ENT_QUOTES,$charset).' '.$title."?").'\')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
865

    
866
            //$actions .='<img src="../img/lp_quiz_na.gif" border="0" title="'.get_lang('NotMarkActivity').'" alt="" />';
867
            $item .= Display::tag('td', $actions);
868
            echo Display::tag('tr',$item, array('class'=>$class));
869
        } else { // student only
870
            if ($active == 1) {
871
                $nbrActiveTests = $nbrActiveTests +1;
872
                $item .= Display::tag('td', '<a href="showinframes.php?'.api_get_cidreq().'&file='.$path.'&cid='.api_get_course_id().'&uid='.api_get_user_id().'"'.(!$active?'class="invisible"':'').'">'.$title.'</a>');
873
                //$item .= Display::tag('td', '');
874
                $actions ='<a href="hotpotatoes_exercise_report.php?' . api_get_cidreq() . '&path='.$path.'&filter_by_user='.api_get_user_id().'">' . Display :: return_icon('test_results.png', get_lang('Results'),'',ICON_SIZE_SMALL).'</a>';
875
                $item .= Display::tag('td', $actions);
876
                echo Display::tag('tr',$item, array('class'=>$class));
877
            }
878
        }
879
        $count ++;
880
    }
881
}
882
echo '</table>';
883

    
884
if (empty($exercise_list) && $hotpotatoes_exist == false) {
885
     if ($is_allowedToEdit && $origin != 'learnpath') {
886
        echo '<div id="no-data-view">';
887
        echo '<h2>'.get_lang('Quiz').'</h2>';
888
        echo Display::return_icon('quiz.png', '', array(), 64);
889
        echo '<div class="controls">';
890
        echo Display::url(get_lang('NewEx'), 'exercise_admin.php?' . api_get_cidreq(), array('class' => 'btn'));
891
        echo '</div>';
892
        echo '</div>';
893
    }
894
}
895
if ($origin != 'learnpath') { //so we are not in learnpath tool
896
	Display :: display_footer();
897
}
(4-4/4)