Project

General

Profile

Files » work.php

Fix for main/work/work.php security issue #2 - Yannick Warnier, 30/09/2010 18:53

 
1
<?php
2
/* For licensing terms, see /license.txt */
3

    
4
/**
5
*	@package chamilo.work
6
* 	@author Thomas, Hugues, Christophe - original version
7
* 	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University - ability for course admins to specify wether uploaded documents are visible or invisible by default.
8
* 	@author Roan Embrechts, code refactoring and virtual course support
9
* 	@author Frederic Vauthier, directories management
10
*  	@version $Id: work.php 22201 2009-07-17 19:57:03Z cfasanando $
11
*
12
* 	@todo refactor more code into functions, use quickforms, coding standards, ...
13
*/
14

    
15
/**
16
 * 	STUDENT PUBLICATIONS MODULE
17
 *
18
 * Note: for a more advanced module, see the dropbox tool.
19
 * This one is easier with less options.
20
 * This tool is better used for publishing things,
21
 * sending in assignments is better in the dropbox.
22
 *
23
 * GOALS
24
 * *****
25
 * Allow student to quickly send documents immediately
26
 * visible on the course website.
27
 *
28
 * The script does 5 things:
29
 *
30
 * 	1. Upload documents
31
 * 	2. Give them a name
32
 * 	3. Modify data about documents
33
 * 	4. Delete link to documents and simultaneously remove them
34
 * 	5. Show documents list to students and visitors
35
 *
36
 * On the long run, the idea is to allow sending realvideo . Which means only
37
 * establish a correspondence between RealServer Content Path and the user's
38
 * documents path.
39
 *
40
 * All documents are sent to the address /$_configuration['root_sys']/$currentCourseID/document/
41
 * where $currentCourseID is the web directory for the course and $_configuration['root_sys']
42
 * usually /var/www/html
43
 *
44
 *	Modified by Patrick Cool, february 2004:
45
 *	Allow course managers to specify wether newly uploaded documents should
46
 *	be visible or unvisible by default
47
 *	This is ideal for reviewing the uploaded documents before the document
48
 *	is available for everyone.
49
 *
50
 *	note: maybe the form to change the behaviour should go into the course
51
 *	properties page?
52
 *	note 2: maybe a new field should be created in the course table for
53
 *	this behaviour.
54
 *
55
 *	We now use the show_score field since this is not used.
56
 *
57
 */
58

    
59
/*		INIT SECTION */
60

    
61
$language_file = array('exercice', 'work', 'document', 'admin' );
62

    
63
require_once '../inc/global.inc.php';
64

    
65
// @todo why is this needed?
66
//session
67
if (isset ($_GET['id_session'])) {
68
	$_SESSION['id_session'] = Database::escape_string($_GET['id_session']);
69
}
70
isset($_SESSION['id_session']) ? $id_session = $_SESSION['id_session'] : $id_session = null;
71

    
72
// Including necessary files
73
require_once 'work.lib.php';
74
require_once api_get_path(LIBRARY_PATH).'course.lib.php';
75
require_once api_get_path(LIBRARY_PATH).'security.lib.php';
76
require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
77
require_once api_get_path(LIBRARY_PATH).'document.lib.php';
78
require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
79
require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
80
require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
81
require_once api_get_path(LIBRARY_PATH).'fckeditor/fckeditor.php';
82

    
83
// Section (for the tabs)
84
$this_section = SECTION_COURSES;
85
$ctok = $_SESSION['sec_token'];
86
$stok = Security::get_token();
87

    
88
$htmlHeadXtra[] = to_javascript_work();
89
$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
90
$htmlHeadXtra[] = '<script type="text/javascript">
91
function setFocus(){
92
$("#work_title").focus();
93
}
94
$(document).ready(function () {
95
  setFocus();
96
});
97
</script>';
98

    
99
// Table definitions
100
$main_course_table 	= Database :: get_main_table(TABLE_MAIN_COURSE);
101
$work_table 		= Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
102
$iprop_table 		= Database :: get_course_table(TABLE_ITEM_PROPERTY);
103
$TSTDPUBASG			= Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
104
$t_gradebook_link 	= Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
105
$table_course_user	= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
106
$table_user			= Database :: get_main_table(TABLE_MAIN_USER);
107
$table_session		= Database :: get_main_table(TABLE_MAIN_SESSION);
108
$table_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
109
$table_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
110

    
111
/*	Constants and variables */
112

    
113
$tool_name = get_lang('StudentPublications');
114
$user_id = api_get_user_id();
115
$course_code = $_course['sysCode'];
116
$session_id = api_get_session_id();
117

    
118
$is_course_member = CourseManager::is_user_subscribed_in_real_or_linked_course($user_id, $course_code,$session_id);
119
$is_course_member = $is_course_member || api_is_platform_admin();
120

    
121
$currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/';
122
$currentCourseRepositoryWeb = api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/';
123
$currentUserFirstName = $_user['firstName'];
124
$currentUserLastName = $_user['lastName'];
125
$currentUserEmail = $_user['mail'];
126

    
127
$authors = isset($_POST['authors']) ? Database::escape_string($_POST['authors']) : '';
128
$delete = isset($_REQUEST['delete']) ? Database::escape_string($_REQUEST['delete']) : '';
129
$description = isset($_REQUEST['description']) ? Database::escape_string($_REQUEST['description']) : '';
130
$display_tool_options = isset($_REQUEST['display_tool_options']) ? $_REQUEST['display_tool_options'] : '';
131
$display_upload_form = isset($_REQUEST['display_upload_form']) ? $_REQUEST['display_upload_form'] : '';
132
$edit = isset($_REQUEST['edit']) ? Database::escape_string($_REQUEST['edit']) : '';
133
$parent_id = isset($_REQUEST['parent_id']) ? Database::escape_string($_REQUEST['parent_id']) : '';
134
$make_invisible = isset($_REQUEST['make_invisible']) ? Database::escape_string($_REQUEST['make_invisible']) : '';
135
$make_visible = isset($_REQUEST['make_visible']) ? Database::escape_string($_REQUEST['make_visible']) : '';
136
$origin = isset($_REQUEST['origin']) ? Security::remove_XSS($_REQUEST['origin']) : '';
137
$submitGroupWorkUrl = isset($_REQUEST['submitGroupWorkUrl']) ? Security::remove_XSS($_REQUEST['submitGroupWorkUrl']) : '';
138
$title = isset($_REQUEST['title']) ? Database::escape_string($_REQUEST['title']) : '';
139
$uploadvisibledisabled = isset($_REQUEST['uploadvisibledisabled']) ? Database::escape_string($_REQUEST['uploadvisibledisabled']) : '';
140
$id = isset($_REQUEST['id']) ? strval(intval($_REQUEST['id'])) : '';
141

    
142
// get data for publication assignment
143
$has_expired = false;
144
$has_ended = false;
145
$curdirpath = isset($_GET['curdirpath']) ? Database::escape_string($_GET['curdirpath']) : '';
146

    
147
//This means that we are in a folder assignment
148
$sql_select ='SELECT id, description FROM '.Database :: get_course_table(TABLE_STUDENT_PUBLICATION).' WHERE filetype = '."'folder'".' and has_properties != '."''".' and url = '."'/".$curdirpath."'".' LIMIT 1';
149
$sql = Database::query($sql_select);
150
$is_special = Database::num_rows($sql);
151
if ($is_special > 0) {
152
	$publication = Database::fetch_array($sql);
153
}
154

    
155
//directories management
156
$sys_course_path = api_get_path(SYS_COURSE_PATH);
157
$course_dir = $sys_course_path . $_course['path'];
158
$base_work_dir = $course_dir . '/work';
159
$http_www = api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/work';
160
$cur_dir_path = '';
161
if (isset ($_GET['curdirpath']) && $_GET['curdirpath'] != '') {
162
	//$cur_dir_path = preg_replace('#[\.]+/#','',$_GET['curdirpath']); //escape '..' hack attempts
163
	//now using common security approach with security lib
164
	$in_course = Security :: check_abs_path($base_work_dir . '/' . $_GET['curdirpath'], $base_work_dir);
165
	if (!$in_course) {
166
		$cur_dir_path = "/";
167
	} else {
168
		$cur_dir_path = $_GET['curdirpath'];
169
	}
170
} elseif (isset ($_POST['curdirpath']) && $_POST['curdirpath'] != '') {
171
	//$cur_dir_path = preg_replace('#[\.]+/#','/',$_POST['curdirpath']); //escape '..' hack attempts
172
	//now using common security approach with security lib
173
	$in_course = Security :: check_abs_path($base_work_dir . '/' . $_POST['curdirpath'], $base_work_dir);
174
	if (!$in_course) {
175
		$cur_dir_path = "/";
176
	} else {
177
		$cur_dir_path = $_POST['curdirpath'];
178
	}
179
} else {
180
	$cur_dir_path = '/';
181
}
182
if ($cur_dir_path == '.') {
183
	$cur_dir_path = '/';
184
}
185
$cur_dir_path_url = urlencode($cur_dir_path);
186

    
187
//prepare a form of path that can easily be added at the end of any url ending with "work/"
188
$my_cur_dir_path = $cur_dir_path;
189
if ($my_cur_dir_path == '/') {
190
	$my_cur_dir_path = '';
191
} elseif (substr($my_cur_dir_path, -1, 1) != '/') {
192
	$my_cur_dir_path = $my_cur_dir_path . '/';
193
}
194

    
195
/*	Configuration settings */
196

    
197
$link_target_parameter = ""; //or e.g. "target=\"_blank\"";
198
$always_show_tool_options = false;
199
$always_show_upload_form = false;
200

    
201
if ($always_show_tool_options) {
202
	$display_tool_options = true;
203
}
204
if ($always_show_upload_form) {
205
	$display_upload_form = true;
206
}
207

    
208
$display_list_users_without_publication = isset($_GET['list']) && Security::remove_XSS($_GET['list']) == 'without';
209

    
210
if (isset($_GET['action']) && $_GET['action'] == 'send_mail') {
211
	if ($_GET['sec_token'] == $_SESSION['token']) {
212
		send_reminder_users_without_publication($publication['id']);
213
		unset($_SESSION['token']);
214
	}
215
}
216

    
217
api_protect_course_script(true);
218

    
219
/*	More init stuff */
220

    
221
if (isset ($_POST['cancelForm']) && !empty ($_POST['cancelForm'])) {
222
	header('Location: ' . api_get_self() . '?origin='.$origin.'&amp;gradebook='.$gradebook);
223
	exit ();
224
}
225

    
226
if (!empty($_POST['submitWork']) || !empty($submitGroupWorkUrl)) {
227
	// These libraries are only used for upload purpose, so we only include them when necessary.
228
	require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
229
	require_once api_get_path(LIBRARY_PATH).'fileDisplay.lib.php'; // need format_url function
230
}
231

    
232
// If the POST's size exceeds 8M (default value in php.ini) the $_POST array is emptied
233
// If that case happens, we set $submitWork to 1 to allow displaying of the error message
234
// The redirection with header() is needed to avoid apache to show an error page on the next request
235
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !sizeof($_POST)) {
236
	if (strstr($_SERVER['REQUEST_URI'], '?')) {
237
		header('Location: ' . $_SERVER['REQUEST_URI'] . '&submitWork=1');
238
		exit ();
239
	} else {
240
		header('Location: ' . $_SERVER['REQUEST_URI'] . '?submitWork=1');
241
		exit ();
242
	}
243
}
244

    
245
//toolgroup comes from group. the but of tis variable is to limit post to the group of the student
246
//if (!api_is_course_admin()) {
247
	if (!empty ($_GET['toolgroup'])) {
248
		$toolgroup = Database::escape_string($_GET['toolgroup']);
249
		api_session_register('toolgroup');
250
	}
251
//}
252

    
253
//download of an completed folder
254
if (isset($_GET['action']) && $_GET['action'] == 'downloadfolder') {
255
	require 'downloadfolder.inc.php';
256
}
257

    
258
/*	Header */
259

    
260
if (!empty($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
261
	$_SESSION['gradebook'] = Security::remove_XSS($_GET['gradebook']);
262
	$gradebook =	$_SESSION['gradebook'];
263
} elseif (empty($_GET['gradebook'])) {
264
	unset($_SESSION['gradebook']);
265
	$gradebook = '';
266
}
267

    
268
if (!empty($gradebook) && $gradebook == 'view') {
269
	$interbreadcrumb[] = array (
270
		'url' => '../gradebook/' . $_SESSION['gradebook_dest'],
271
		'name' => get_lang('ToolGradebook')
272
	);
273
}
274

    
275
if (!empty($_SESSION['toolgroup'])) {
276
	$_clean['toolgroup'] = (int)$_SESSION['toolgroup'];
277
	$group_properties  = GroupManager :: get_group_properties($_clean['toolgroup']);
278
	$interbreadcrumb[] = array ('url' => '../group/group.php', 'name' => get_lang('Groups'));
279
	$interbreadcrumb[] = array ('url' => '../group/group_space.php?gidReq='.$_SESSION['toolgroup'], 'name' => get_lang('GroupSpace').' ('.$group_properties['name'].')');
280

    
281
	$url_dir ='';
282
	$interbreadcrumb[] = array ('url' => $url_dir,'name' => get_lang('StudentPublications'));
283

    
284
	//if (!$display_tool_options  && !$display_upload_form)
285
	//{
286
		// interbreadcrumb for the current directory root path
287
		$dir_array = explode('/', $cur_dir_path);
288
		$array_len = count($dir_array);
289
		/*
290
		if ($array_len > 0) {
291
			$url_dir = 'work.php?&curdirpath=/';
292
			$interbreadcrumb[] = array (
293
				'url' => $url_dir,
294
				'name' => get_lang('HomeDirectory'));
295
		}*/
296

    
297
		$dir_acum = '';
298
		for ($i = 0; $i < $array_len; $i++) {
299
			$url_dir = 'work.php?&curdirpath=' . $dir_acum . $dir_array[$i];
300
			$interbreadcrumb[] = array (
301
				'url' => $url_dir,
302
				'name' => $dir_array[$i]
303
			);
304
			$dir_acum .= $dir_array[$i] . '/';
305
		}
306
	//}
307

    
308
	if ($display_upload_form) {
309
		$interbreadcrumb[] = array (
310
			'url' => 'work.php',
311
			'name' => get_lang('UploadADocument'));
312
	}
313

    
314
	if ($display_tool_options) {
315
		$interbreadcrumb[] = array (
316
			'url' => 'work.php',
317
			'name' => get_lang('EditToolOptions'));
318
	}
319

    
320
	if ($_GET['createdir'] == 1) {
321
		$interbreadcrumb[] = array (
322
			'url' => 'work.php',
323
			'name' => get_lang('CreateFolder'));
324
	}
325

    
326
	Display :: display_header(null);
327

    
328
} else {
329

    
330
	if (isset($origin) && $origin != 'learnpath') {
331
		$url_dir = '';
332
		$interbreadcrumb[] = array ('url' => $url_dir.'?gradebook='.$gradebook, 'name' => get_lang('StudentPublications'));
333
		//if (!$display_tool_options  && !$display_upload_form)
334
		//{
335
		//------interbreadcrumb for the current directory root path
336
		$dir_array = explode('/', $cur_dir_path);
337
		$array_len = count($dir_array);
338

    
339
		/*if ($array_len > 0) {
340
			$url_dir = 'work.php?gradebook='.$gradebook.'&curdirpath=/';
341
			$interbreadcrumb[] = array (
342
				'url' => $url_dir,
343
				'name' => get_lang('HomeDirectory'));
344
		}*/
345

    
346
		$dir_acum = '';
347
		for ($i = 0; $i < $array_len; $i++) {
348
			$url_dir = 'work.php?gradebook='.$gradebook.'&amp;curdirpath=' . $dir_acum . $dir_array[$i];
349
			$interbreadcrumb[] = array (
350
				'url' => $url_dir,
351
				'name' => $dir_array[$i]
352
			);
353
			$dir_acum .= $dir_array[$i] . '/';
354
		}
355
		//	}
356

    
357
		if ($display_upload_form) {
358
			$interbreadcrumb[] = array (
359
				'url' => 'work.php?gradebook='.$gradebook,
360
				'name' => get_lang('UploadADocument'));
361
		}
362

    
363
		if ($display_tool_options) {
364
			$interbreadcrumb[] = array (
365
				'url' => 'work.php?gradebook='.$gradebook,
366
				'name' => get_lang('EditToolOptions'));
367
		}
368
		if ($_GET['createdir'] == 1) {
369
			$interbreadcrumb[] = array (
370
				'url' => 'work.php?gradebook='.$gradebook,
371
				'name' => get_lang('CreateDir'));
372
		}
373

    
374
		Display :: display_header(null);
375

    
376
	} else {
377
		//we are in the learnpath tool
378
		require api_get_path(INCLUDE_PATH).'reduced_header.inc.php';
379
	}
380
}
381

    
382
//stats
383
event_access_tool(TOOL_STUDENTPUBLICATION);
384

    
385
$is_allowed_to_edit = api_is_allowed_to_edit(); //has to come after display_tool_view_option();
386
//api_display_tool_title($tool_name);
387

    
388
/*		MAIN CODE */
389

    
390
if (!empty ($_POST['changeProperties'])) {
391
	// changing the tool setting: default visibility of an uploaded document
392
	$query = "UPDATE " . $main_course_table . " SET show_score='" . $uploadvisibledisabled . "' WHERE code='" . $_course['sysCode'] . "'";
393
	Database::query($query);
394

    
395
	// changing the tool setting: is a student allowed to delete his/her own document
396
	// database table definition
397
	$table_course_setting = Database :: get_course_table(TOOL_COURSE_SETTING);
398

    
399
	// counting the number of occurrences of this setting (if 0 => add, if 1 => update)
400
	$query = "SELECT * FROM " . $table_course_setting . " WHERE variable = 'student_delete_own_publication'";
401
	$result = Database::query($query);
402
	$number_of_setting = Database::num_rows($result);
403

    
404
	if ($number_of_setting == 1) {
405
		$query = "UPDATE " . $table_course_setting . " SET value='" . Database::escape_string($_POST['student_delete_own_publication']) . "' WHERE variable='student_delete_own_publication'";
406
		Database::query($query);
407
	} else {
408
		$query = "INSERT INTO " . $table_course_setting . " (variable, value, category) VALUES ('student_delete_own_publication','" . Database::escape_string($_POST['student_delete_own_publication']) . "','work')";
409
		Database::query($query);
410
	}
411

    
412
	$_course['show_score'] = $uploadvisibledisabled;
413
} else {
414
	$query = "SELECT * FROM " . $main_course_table . " WHERE code=\"" . $_course['sysCode'] . "\"";
415
	$result = Database::query($query);
416
	$row = Database::fetch_array($result);
417
	$uploadvisibledisabled = $row["show_score"];
418
}
419

    
420
// introduction section
421

    
422
if ($origin == 'learnpath') {
423
	echo '<div style="height:15px">&nbsp;</div>';
424
}
425

    
426
Display :: display_introduction_section(TOOL_STUDENTPUBLICATION);
427

    
428
/*	EDIT COMMAND WORK COMMAND */
429

    
430
$qualification_number = 0;
431
if (!empty($edit)) {
432

    
433
	if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
434
		api_not_allowed();
435
	}
436

    
437
	$sql = "SELECT * FROM  " . $work_table . "  WHERE id='" . $edit . "'";
438
	$result = Database::query($sql);
439

    
440
	if (!empty($result)) {
441
		$row = Database::fetch_array($result);
442
		$workTitle = $row['title'];
443
		$workAuthor = $row['author'];
444
		$workDescription = $row['description'];
445
		$workUrl = $row['url'];
446
		$qualification_number = $row['qualification'];
447
	}
448
}
449

    
450
/*	MAKE INVISIBLE WORK COMMAND */
451

    
452
if (!empty($make_invisible)) {
453
	if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
454
		api_not_allowed();
455
	}
456
	if (isset($make_invisible) && $make_invisible == 'all') {
457
		$sql = "ALTER TABLE " . $work_table . "
458
				CHANGE accepted accepted TINYINT(1) DEFAULT '0'";
459
		Database::query($sql);
460
		$sql = "UPDATE  " . $work_table . " SET accepted = 0";
461
		Database::query($sql);
462
		Display::display_confirmation_message(get_lang('AllFilesInvisible'));
463
	} else {
464
		$sql = "UPDATE  " . $work_table . " SET accepted = 0
465
				WHERE id = '" . $make_invisible . "'";
466
		Database::query($sql);
467
		Display::display_confirmation_message(get_lang('FileInvisible'));
468
	}
469
}
470

    
471
/*	MAKE VISIBLE WORK COMMAND */
472

    
473
if (!empty($make_visible)) {
474
	if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
475
		api_not_allowed();
476
	}
477
	if (isset($make_visible) && $make_visible == 'all') {
478
		$sql = "ALTER TABLE  " . $work_table . " CHANGE accepted accepted TINYINT(1) DEFAULT '1'";
479
		Database::query($sql);
480
		$sql = "UPDATE  " . $work_table . " SET accepted = 1";
481
		Database::query($sql);
482
		Display::display_confirmation_message(get_lang('AllFilesVisible'));
483

    
484
	} else {
485
		$sql = "UPDATE  " . $work_table . "	SET accepted = 1
486
				WHERE id = '" . $make_visible . "'";
487
		Database::query($sql);
488
		Display::display_confirmation_message(get_lang('FileVisible'));
489
	}
490

    
491
	// update all the parents in the table item propery
492
	$list_id = get_parent_directories($my_cur_dir_path);
493
	for ($i = 0; $i < count($list_id); $i++) {
494
		api_item_property_update($_course, 'work', $list_id[$i], 'FolderUpdated', $user_id);
495
	}
496
}
497

    
498
/*	Create dir command */
499

    
500
if (!empty($_REQUEST['new_dir'])) {
501

    
502
	if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
503
		api_not_allowed();
504
	}
505

    
506
	function get_date_from_select($prefix) {
507
		return $_POST[$prefix.'_year'].'-'.two_digits($_POST[$prefix.'_month']).'-'.two_digits($_POST[$prefix.'_day']).' '.two_digits($_POST[$prefix.'_hour']).':'.two_digits($_POST[$prefix.'_minute']).':00';
508
	}
509

    
510
	$fexpire = get_date_from_select('expires');
511
	$fend 	 = get_date_from_select('ends');
512

    
513
	require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
514
	$added_slash = (substr($cur_dir_path, -1, 1) == '/') ? '' : '/';
515
	$directory = Security::remove_XSS($_POST['new_dir']);
516
	$directory = replace_dangerous_char($directory);
517
	$directory = disable_dangerous_file($directory);
518
	$dir_name = $cur_dir_path . $added_slash . $directory;
519
	$created_dir = create_unexisting_work_directory($base_work_dir, $dir_name);
520

    
521
	// we insert here the directory in the table $work_table
522
	$dir_name_sql = '';
523

    
524
	if ($ctok == $_POST['sec_token']) {
525
		if (!empty($created_dir)) {
526
			if ($cur_dir_path == '/') {
527
				$dir_name_sql = $created_dir;
528
			} else {
529
				$dir_name_sql = '/'.$created_dir;
530
			}
531

    
532
			// Insert into agenda
533
			$agenda_id = 0;
534
			if (isset($_POST['add_to_calendar']) && $_POST['add_to_calendar'] == 1) {
535
				require_once api_get_path(SYS_CODE_PATH).'calendar/agenda.inc.php';
536
				require_once api_get_path(SYS_CODE_PATH).'resourcelinker/resourcelinker.inc.php';
537
				$course = isset($course_info) ? $course_info : null;
538
				$date = api_get_utc_datetime();
539
				$title = Security::remove_XSS($_POST['new_dir']);
540
				if (!empty($_POST['type1'])) {
541
					$date = api_get_utc_datetime(get_date_from_select('expires'));
542
					$title = sprintf(get_lang('HandingOverOfTaskX'),Security::remove_XSS($_POST['new_dir']));
543
				}
544
				$content = '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;curdirpath='.substr(Security::remove_XSS($dir_name_sql), 1).'" >'.Security::remove_XSS($_POST['new_dir']).'</a> - '.Security::remove_XSS($_POST['description']);
545
				
546
				$agenda_id = agenda_add_item($course, $title, $content, $date, $date, array('GROUP:'.$toolgroup), 0);
547
			}
548
			$sql_add_publication = "INSERT INTO " . $work_table . " SET " .
549
									   "url         = '".Database::escape_string($dir_name_sql)."',
550
								       title        = '',
551
					                   description 	= '".Database::escape_string($_POST['description'])."',
552
					                   author      	= '',
553
									   active		= '0',
554
									   accepted		= '1',
555
									   filetype 	= 'folder',
556
									   post_group_id = '".$toolgroup."',
557
									   sent_date	= '".api_get_utc_datetime()."',
558
									   qualification	= '".(($_POST['qualification_value']!='') ? Database::escape_string($_POST['qualification_value']) : '') ."',
559
									   parent_id	= '',
560
									   qualificator_id	= '',
561
									   date_of_qualification	= '0000-00-00 00:00:00',
562
									   weight   = '".Database::escape_string($_POST['weight'])."',
563
									   session_id   = '".intval($id_session)."',
564
									   user_id = '".$user_id."'";
565

    
566
			Database::query($sql_add_publication);
567

    
568
			// add the directory
569
			$id = Database::insert_id();
570
			//Folder created
571
			api_item_property_update($_course, 'work', $id, 'DirectoryCreated', $user_id);
572
			Display :: display_confirmation_message(get_lang('DirectoryCreated'), false);
573
			//Database :: escape_string($_REQUEST['make_visible']);
574
			//if($_POST['type1']==1)
575
			//$insert_limite
576

    
577
			 // insert into student_publication_assignment
578

    
579
			//return something like this: 2008-02-45 00:00:00
580

    
581
			if (!empty($_POST['type1']) || !empty($_POST['type2'])) {
582

    
583
				$enable_calification = isset($_POST['enable_calification']) ? (int)$_POST['enable_calification'] : null;
584
				$sql_add_homework = "INSERT INTO $TSTDPUBASG SET " .
585
														   "expires_on         = '".((isset($_POST['type1']) && $_POST['type1']==1) ? api_get_utc_datetime(get_date_from_select('expires')) : '0000-00-00 00:00:00'). "',
586
													        ends_on        = '".((isset($_POST['type2']) && $_POST['type2']==1) ? api_get_utc_datetime(get_date_from_select('ends')) : '0000-00-00 00:00:00')."',
587
										                    add_to_calendar  = '$agenda_id',
588
										                    enable_qualification = '".$enable_calification."',
589
										                    publication_id = '".$id."'";
590
				Database::query($sql_add_homework);
591

    
592
				$sql_add_publication = "UPDATE ".$work_table." SET "."has_properties  = ".Database::insert_id().", view_properties = 1 ".' where id = '.$id;
593
				Database::query($sql_add_publication);
594

    
595
			} else {
596

    
597
				$sql_add_homework = "INSERT INTO $TSTDPUBASG SET " .
598
														   "expires_on     = '0000-00-00 00:00:00',
599
													        ends_on        = '0000-00-00 00:00:00',
600
										                    add_to_calendar  = '$agenda_id',
601
										                    enable_qualification = '".(isset($_POST['enable_calification'])?(int)$_POST['enable_calification']:'')."',
602
										                    publication_id = '".$id."'";
603
				Database::query($sql_add_homework);
604

    
605
				$sql_add_publication = "UPDATE ".$work_table." SET "."has_properties  = ".Database::insert_id().", view_properties = 0 ".' where id = '.$id;
606
				Database::query($sql_add_publication);
607

    
608
			}
609

    
610
			if (isset($_POST['make_calification']) && $_POST['make_calification'] == 1) {
611

    
612
				require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/gradebookitem.class.php';
613
				require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/evaluation.class.php';
614
				require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/abstractlink.class.php';
615
				require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
616

    
617
				$resource_name = (empty($_POST['qualification_name'])) ? $_POST['new_dir'] : $_POST['qualification_name'];
618
				add_resource_to_course_gradebook(api_get_course_id(), 3, $id, Database::escape_string($resource_name), $_POST['weight'], $_POST['qualification_value'], Database::escape_string($_POST['description']), time(), 1, api_get_session_id());
619

    
620
			}
621

    
622
			// end features
623

    
624
			if(api_get_course_setting('email_alert_students_on_new_homework') == 1) {
625
				send_email_on_homework_creation(api_get_course_id());
626
			}
627

    
628
			// update all the parents in the table item propery
629
			$list_id = get_parent_directories($my_cur_dir_path);
630

    
631
			for ($i = 0; $i < count($list_id); $i++) {
632
				api_item_property_update($_course, 'work', $list_id[$i], 'FolderUpdated', $user_id);
633
			}
634

    
635
			//uncomment if you want to enter the created dir
636
			//$curdirpath = $created_dir;
637
			//$curdirpathurl = urlencode($curdirpath);
638
		} else {
639
			Display :: display_error_message(get_lang('CannotCreateDir'));
640
		}
641
	}
642
}
643

    
644
/*	Delete dir command */
645

    
646
if (!empty($_REQUEST['delete_dir'])) {
647

    
648
	if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
649
		api_not_allowed();
650
	}
651

    
652
	$delete_directory	= $_REQUEST['delete_dir'];
653
	$id					= $_REQUEST['delete2'];
654
	del_dir($base_work_dir . '/', $delete_directory, $id);
655

    
656
	Display :: display_confirmation_message(get_lang('DirDeleted') . ': '.$delete_directory);
657
}
658
if (!empty($_REQUEST['delete2'])) {
659

    
660
	if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
661
		api_not_allowed();
662
	}
663
	$delete_2 = intval($_REQUEST['delete2']);
664
	// gets calendar_id from student_publication_assigment
665
	$sql = "SELECT add_to_calendar FROM $TSTDPUBASG WHERE publication_id ='$delete_2'";
666
	$res = Database::query($sql);
667
	$calendar_id = Database::fetch_row($res);
668
	// delete from agenda if it exists
669
	if (!empty($calendar_id[0])) {
670
		$t_agenda   = Database::get_course_table(TABLE_AGENDA);
671
		$sql = "DELETE FROM $t_agenda WHERE id ='".$calendar_id[0]."'";
672
		Database::query($sql);
673
	}
674
	$sql2 = "DELETE FROM $TSTDPUBASG WHERE publication_id ='$delete_2'";
675
	$result2 = Database::query($sql2);
676
	$sql3 = "DELETE FROM $t_gradebook_link WHERE course_code='$course_code' AND ref_id='$delete_2'";
677
	$result3 = Database::query($sql3);
678
}
679

    
680
/*	Move file form request */
681

    
682
if (!empty ($_REQUEST['move'])) {
683
	$folders = array();
684
	$session_id = api_get_session_id();
685
	$session_id == 0 ? $withsession = " AND session_id = 0 " : $withsession = " AND session_id='".$session_id."'";
686

    
687
	$sql = "SELECT id, url FROM $work_table  WHERE url LIKE '/%' AND post_group_id = '".(empty($_SESSION['toolgroup'])?0:intval($_SESSION['toolgroup']))."'".$withsession;
688
	$res = Database::query($sql);
689
	while($folder = Database::fetch_array($res)) {
690
		$folders[$folder['id']] = substr($folder['url'], 1, strlen($folder['url']) - 1);
691
	}
692
	echo build_work_move_to_selector($folders, $cur_dir_path, $_REQUEST['move']);
693
}
694

    
695
/*	Move file command */
696

    
697
if (isset ($_POST['move_to']) && isset ($_POST['move_file'])) {
698
	require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
699
	$move_to = $_POST['move_to'];
700
	$move_to_path = get_work_path($move_to);
701

    
702
	if ($move_to_path==-1) {
703
		$move_to_path = '/';
704
	} elseif (substr($move_to_path, -1, 1) != '/') {
705
		$move_to_path = $move_to_path .'/';
706
	}
707
	//security fix: make sure they can't move files that are not in the document table
708
	$move_file_id = $_POST['move_file'];
709
	if ($path = get_work_path($move_file_id)) {
710
		//Display::display_normal_message('We want to move '.$_POST['move_file'].' to '.$_POST['move_to']);
711
		if (move($course_dir . '/' . $path, $base_work_dir . $move_to_path)) {
712
			//update db
713

    
714
			update_work_url($move_file_id, 'work' . $move_to_path, $move_to);
715
			//set the current path
716
			$cur_dir_path = $move_to_path;
717
			$cur_dir_path_url = urlencode($move_to_path);
718

    
719
			// update all the parents in the table item propery
720
			$list_id = get_parent_directories($cur_dir_path);
721
			for ($i = 0; $i < count($list_id); $i++) {
722
				api_item_property_update($_course, 'work', $list_id[$i], 'FolderUpdated', $user_id);
723
			}
724

    
725
			Display :: display_confirmation_message(get_lang('DirMv'));
726
		} else {
727
			Display :: display_error_message(get_lang('Impossible'));
728
		}
729
	} else {
730
		Display :: display_error_message(get_lang('Impossible'));
731
	}
732
}
733

    
734
/*	COMMANDS SECTION (reserved for others - check they're authors each time) */
735

    
736
else {
737
	$iprop_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
738
	$user_id = api_get_user_id();
739

    
740
	/*	DELETE WORK COMMAND */
741

    
742
	if ($delete) {
743
		if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
744
			api_not_allowed();
745
		}
746
		if ($delete == 'all' && api_is_allowed_to_edit(null, true)) {
747

    
748
			$queryString1 = "SELECT url FROM ".$work_table."";
749
			$queryString2 = "DELETE FROM  ".$work_table."";
750
			$queryString3 = "DELETE FROM  ".$TSTDPUBASG. "";
751

    
752
			$sql_agenda = "SELECT add_to_calendar FROM ".$TSTDPUBASG." WHERE add_to_calendar <> 0";
753
			$rs_agenda = Database::query($sql_agenda);
754
			$t_agenda   = Database::get_course_table(TABLE_AGENDA);
755
			while ($row_agenda=Database::fetch_array($rs_agenda)) {
756
				$deleteagenda = "DELETE FROM  ".$t_agenda." WHERE id='".$row_agenda['add_to_calendar']."'";
757
				$rsdeleteagenda = Database::query($deleteagenda);
758

    
759
			}
760

    
761
			$result1 = Database::query($queryString1);
762
			$result2 = Database::query($queryString2);
763
			$result3 = Database::query($queryString3);
764

    
765
			$path = $currentCourseRepositorySys.'work/';
766
			$d = dir($path);
767

    
768
			if (api_get_setting('permanently_remove_deleted_files') == 'true') {
769
				while (false !== $entry = $d->read()) {
770
					if ($entry == '.' || $entry == '..') continue;
771
					rmdirr($path.$entry);
772
				}
773
			} else {
774
				while (false !== $entry = $d->read()) {
775
					if ($entry == '.' || $entry == '..' || substr($entry, 0, 8) == 'DELETED_') continue;
776
					$new_file = 'DELETED_'.$entry;
777
					rename($path.$entry, $path.$new_file);
778
				}
779
			}
780
		} else {
781
            $file_deleted = false;
782
			//Get the author ID for that document from the item_property table
783
			$author_sql = "SELECT * FROM $iprop_table WHERE tool = 'work' AND insert_user_id='$user_id' AND ref=" .Database::escape_string($delete);
784
			$author_qry = Database::query($author_sql);
785
            
786

    
787
			if (Database :: num_rows($author_qry) == 1 AND api_get_course_setting('student_delete_own_publication') == 1 || api_is_allowed_to_edit(null,true)) {
788
				//we found the current user is the author
789
				$queryString1 = "SELECT url FROM  " . $work_table . "  WHERE id = '$delete'";                
790
				$result1 = Database::query($queryString1);				
791
                $row = Database::fetch_array($result1);
792
                
793
				if (Database::num_rows($result1) > 0) {         
794
                    $queryString2 = "DELETE FROM  " . $work_table . "  WHERE id='$delete'";
795
                    $queryString3 = "DELETE FROM  " . $TSTDPUBASG . "  WHERE publication_id='$delete'";
796
                    $result2 = Database::query($queryString2);
797
                    $result3 = Database::query($queryString3);           
798
                     
799
					api_item_property_update($_course, 'work', $delete, 'DocumentDeleted', $user_id);					
800
					$work = $row['url'];
801
                    if (!empty($work)) {			
802
                        if (api_get_setting('permanently_remove_deleted_files') == 'true') {                        
803
                            my_delete($currentCourseRepositorySys.'/'.$work);
804
                            Display::display_confirmation_message(get_lang('TheDocumentHasBeenDeleted'));
805
                            $file_deleted = true;
806
                        } else {         
807
                            require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
808
                            $extension = pathinfo($work, PATHINFO_EXTENSION);
809
                            $basename_file = basename($work, '.'.$extension);
810
                            $new_dir = $work.'_DELETED_'.$delete.'.'.$extension;           
811
					        rename($currentCourseRepositorySys.'/'.$work, $currentCourseRepositorySys.'/'.$new_dir);
812
                            Display::display_confirmation_message(get_lang('TheDocumentHasBeenDeleted'));
813
                            $file_deleted = true;                            
814
					   }
815
                    }
816
				}
817
                if (!$file_deleted) {
818
				    Display::display_error_message(get_lang('YouAreNotAllowedToDeleteThisDocument'));
819
                }
820
			} else {
821
				Display::display_error_message(get_lang('YouAreNotAllowedToDeleteThisDocument'));
822
			}
823
		}
824
	}
825

    
826
	/*	EDIT COMMAND WORK COMMAND */
827

    
828
	if ($edit) {
829

    
830
		if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
831
			api_not_allowed();
832
		}
833

    
834
		//Get the author ID for that document from the item_property table
835
		$author_sql = "SELECT * FROM $iprop_table WHERE tool = 'work' AND insert_user_id='$user_id' AND ref=" . $edit;
836
		$author_qry = Database::query($author_sql);
837
		if (Database :: num_rows($author_qry) == 1) {
838
			//we found the current user is the author
839
			$sql = "SELECT * FROM  " . $work_table . "  WHERE id='" . $edit . "'";
840
			$result = Database::query($sql);
841
			if ($result) {
842
				$row = Database::fetch_array($result);
843
				$workTitle = $row['title'];
844
				$workAuthor = $row['author'];
845
				$workDescription = $row['description'];
846
				$workUrl = $row['url'];
847
				$qualification_number = $row['qualification'];
848
			}
849
		}
850
	}
851

    
852
}
853

    
854
/*	FORM SUBMIT PROCEDURE */
855

    
856
$error_message = '';
857

    
858
if ($ctok == $_POST['sec_token']) { //check the token inserted into the form
859
	if (!empty($_POST['submitWork']) && !empty($is_course_member)) {
860
		if (!empty($_FILES['file']['size'])) {
861
			$updir = $currentCourseRepositorySys . 'work/'; //directory path to upload
862

    
863
			// Try to add an extension to the file if it has'nt one
864
			$new_file_name = add_ext_on_mime(stripslashes($_FILES['file']['name']), $_FILES['file']['type']);
865

    
866
			// Replace dangerous characters
867
			$new_file_name = replace_dangerous_char($new_file_name, 'strict');
868

    
869
			// Transform any .php file in .phps fo security
870
			$new_file_name = php2phps($new_file_name);
871
			//filter extension
872
			if (!filter_extension($new_file_name)) {
873
				Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
874
				$succeed = false;
875
			} else {
876
				if (!$title) {
877
					$title = $_FILES['file']['name'];
878
				}
879
				//if (!$authors) {
880
				$authors = api_get_person_name($currentUserFirstName, $currentUserLastName);
881
				//}
882
				// compose a unique file name to avoid any conflict
883
				$new_file_name = uniqid('') . $new_file_name;
884
				if (isset ($_SESSION['toolgroup'])) {
885
					$post_group_id = $_SESSION['toolgroup'];
886
				} else {
887
					$post_group_id = '0';
888
				}
889
				//if we come from the group tools the groupid will be saved in $work_table
890
				@move_uploaded_file($_FILES['file']['tmp_name'], $updir . $my_cur_dir_path . $new_file_name);
891
				$url = 'work/' . $my_cur_dir_path . $new_file_name;
892
				$result = Database::query("SHOW FIELDS FROM " . $work_table . " LIKE 'sent_date'");
893

    
894
				if (!Database::num_rows($result)) {
895
					Database::query("ALTER TABLE " . $work_table . " ADD sent_date DATETIME NOT NULL");
896
				}
897
				$current_date = api_get_utc_datetime();
898
				$parent_id = '';
899
				$active = '';
900
				$user_id = api_get_user_id();
901

    
902
				$sql = Database::query('SELECT id FROM '.Database::get_course_table(TABLE_STUDENT_PUBLICATION).' WHERE url = '."'/".Database::escape_string($_GET['curdirpath'])."' AND filetype='folder' LIMIT 1");
903
				if (Database::num_rows($sql) > 0) {
904
					$dir_row = Database::fetch_array($sql);
905
					$parent_id = $dir_row['id'];
906
				}
907
				$sql_add_publication = "INSERT INTO " . $work_table . " SET " .
908
										       "url         = '" . $url . "',
909
										       title       = '" . Database::escape_string($title) . "',
910
							                   description = '" . Database::escape_string($description) . "',
911
							                   author      = '" . Database::escape_string($authors) . "',
912
											   active		= '" . $active . "',
913
											   accepted		= '" . (api_is_allowed_to_edit(null,true)?$uploadvisibledisabled:(!$uploadvisibledisabled)) . "',
914
											   post_group_id = '" . $post_group_id . "',
915
											   sent_date	=  '".$current_date ."',
916
											   parent_id 	=  '".$parent_id ."' ,
917
	                                           session_id = '".intval($id_session)."' ,
918
	                                           user_id = '".$user_id."'";
919

    
920
				Database::query($sql_add_publication);
921

    
922
				$Id = Database::insert_id();
923
				api_item_property_update($_course, 'work', $Id, 'DocumentAdded', $user_id);
924
				$succeed = true;
925

    
926
				// update all the parents in the table item propery
927
				$list_id = get_parent_directories($my_cur_dir_path);
928
				for ($i = 0; $i < count($list_id); $i++) {
929
					api_item_property_update($_course, 'work', $list_id[$i], 'FolderUpdated', $user_id);
930
				}
931
			}
932

    
933
		} elseif ($newWorkUrl) {
934

    
935
			if (isset ($_SESSION['toolgroup'])) {
936
				$post_group_id = $_SESSION['toolgroup'];
937
			} else {
938
				$post_group_id = '0';
939
			}
940

    
941
			/*
942
			 * SPECIAL CASE ! For a work coming from another area (i.e. groups)
943
			 */
944
			$url = str_replace('../../' . $_course['path'] . '/', '', $newWorkUrl);
945

    
946
			if (!$title) {
947
				$title = basename($workUrl);
948
			}
949

    
950
			$result = Database::query("SHOW FIELDS FROM " . $work_table . " LIKE 'sent_date'");
951

    
952
			if (!Database::num_rows($result)) {
953
				Database::query("ALTER TABLE " . $work_table . " ADD sent_date DATETIME NOT NULL");
954
			}
955
			$current_date = api_get_utc_datetime();
956
			$sql = "INSERT INTO  " . $work_table . "
957
					        	SET url        	= '" . $url . "',
958
					            title       	= '" . Database::escape_string($title) . "',
959
					            description 	= '" . Database::escape_string($description) . "',
960
					            author      	= '" . Database::escape_string($authors) . "',
961
							    post_group_id = '".$post_group_id."',
962
					            sent_date    	= '".$current_date."',
963
					            session_id = '".intval($id_session)."',
964
					            user_id = '".$user_id."'";
965

    
966
			Database::query($sql);
967

    
968
			$insertId = Database::insert_id();
969
			api_item_property_update($_course, 'work', $insertId, 'DocumentAdded', $user_id);
970
			$succeed = true;
971

    
972
			// update all the parents in the table item propery
973
			$list_id=get_parent_directories($my_cur_dir_path);
974
			for ($i = 0; $i < count($list_id); $i++) {
975
				api_item_property_update($_course, 'work', $list_id[$i], 'FolderUpdated', $user_id);
976
			}
977
		}
978

    
979
		/*
980
		 * SPECIAL CASE ! For a work edited
981
		 */
982

    
983
		else {
984
			//Get the author ID for that document from the item_property table
985
			$is_author = false;
986
			if ($id != '') {
987
				$author_sql = "SELECT * FROM $iprop_table WHERE tool = 'work' AND insert_user_id='$user_id' AND ref=" . Database::escape_string($id);
988

    
989
				$author_qry = Database::query($author_sql);
990
				if (Database :: num_rows($author_qry) == 1) {
991
					$is_author = true;
992
				}
993
			} else {
994
				Display::display_error_message(get_lang('IsNotPosibleSaveTheDocument'));
995
			}
996
			if ($id && ($is_allowed_to_edit or $is_author)) {
997
				if (!$title) {
998
					$title = basename($newWorkUrl);
999
				}
1000

    
1001
				if($is_allowed_to_edit && ($_POST['qualification']!='')) {
1002
					$add_to_update = ',qualificator_id ='."'".api_get_user_id()."',";
1003
					$add_to_update .= 'qualification ='."'".Database::escape_string($_POST['qualification'])."',";
1004
					$add_to_update .= 'date_of_qualification ='."'".api_get_utc_datetime()."'";
1005
				}
1006

    
1007
				if ((int)$_POST['qualification'] > (int)$_POST['qualification_over']) {
1008
					Display::display_error_message(get_lang('QualificationMustNotBeMoreThanQualificationOver'));
1009
				} else {
1010
					$sql = "UPDATE  " . $work_table . "
1011
					        SET	title       = '" . Database::escape_string($title) . "',
1012
					            description = '" . Database::escape_string($description) . "'
1013
					            ".$add_to_update."
1014
					        WHERE id    = '$id'";
1015
					Database::query($sql);
1016
				}
1017

    
1018
				$insertId = $id;
1019
				api_item_property_update($_course, 'work', $insertId, 'DocumentUpdated', $user_id);
1020
				$succeed = true;
1021
			} else {
1022
				$error_message = get_lang('TooBig');
1023
			}
1024
		}
1025
	}
1026
}
1027

    
1028
if (!empty($_POST['submitWork']) && !empty($succeed) && !$id) {
1029
	//last value is to check this is not "just" an edit
1030
	//YW Tis part serve to send a e-mail to the tutors when a new file is sent
1031
	$send = api_get_course_setting('email_alert_manager_on_new_doc');
1032

    
1033
	if ($send > 0) {
1034
		// Lets predefine some variables. Be sure to change the from address!
1035

    
1036
		$emailto = array ();
1037
		if (empty ($id_session)) {
1038
			$sql_resp = 'SELECT u.email as myemail FROM ' . $table_course_user . ' cu, ' . $table_user . ' u WHERE cu.course_code = ' . "'" . api_get_course_id() . "'" . ' AND cu.status = 1 AND u.user_id = cu.user_id';
1039
			$res_resp = Database::query($sql_resp);
1040
			while ($row_email = Database :: fetch_array($res_resp)) {
1041
				if (!empty ($row_email['myemail'])) {
1042
					$emailto[$row_email['myemail']] = $row_email['myemail'];
1043
				}
1044
			}
1045
		} else {
1046
			// coachs of the session
1047
			$sql_resp = 'SELECT user.email as myemail
1048
									FROM ' . $table_session . ' session
1049
									INNER JOIN ' . $table_user . ' user
1050
										ON user.user_id = session.id_coach
1051
									WHERE session.id = ' . intval($id_session);
1052
			$res_resp = Database::query($sql_resp);
1053
			while ($row_email = Database :: fetch_array($res_resp)) {
1054
				if (!empty ($row_email['myemail'])) {
1055
					$emailto[$row_email['myemail']] = $row_email['myemail'];
1056
				}
1057
			}
1058

    
1059
			//coach of the course
1060
			$sql_resp = 'SELECT user.email as myemail
1061
									FROM ' . $table_session_course_user . ' scu
1062
									INNER JOIN ' . $table_user . ' user
1063
										ON user.user_id = scu.id_user AND scu.status=2
1064
									WHERE scu.id_session = ' . intval($id_session);
1065
			$res_resp = Database::query($sql_resp);
1066
			while ($row_email = Database :: fetch_array($res_resp)) {
1067
				if (!empty ($row_email['myemail'])) {
1068
					$emailto[$row_email['myemail']] = $row_email['myemail'];
1069
				}
1070
			}
1071
		}
1072

    
1073
		if (count($emailto) > 0) {
1074

    
1075
			$emailto = implode(',', $emailto);
1076
			$emailfromaddr = api_get_setting('emailAdministrator');
1077
			$emailfromname = api_get_setting('siteName');
1078
			$emailsubject = "[" . api_get_setting('siteName') . "] ";
1079
			$sender_name = api_get_setting('administratorName').' '.api_get_setting('administratorSurname');
1080
		    $email_admin = api_get_setting('emailAdministrator');
1081
			// The body can be as long as you wish, and any combination of text and variables
1082

    
1083
			$emailbody = get_lang('SendMailBody')."\n".get_lang('CourseName')." : ".$_course['name']."\n";
1084
			$emailbody .= get_lang('WorkName')." : ".substr($my_cur_dir_path, 0, -1)."\n";
1085
			$emailbody .= get_lang('UserName')." : ".$currentUserFirstName .' '.$currentUserLastName ."\n";
1086
			$emailbody .= get_lang('DateSent')." : ".api_get_local_time()."\n";
1087
			$emailbody .= get_lang('FileName')." : ".$title."\n\n".get_lang('DownloadLink')."\n";
1088
			$emailbody .= api_get_path(WEB_CODE_PATH)."work/work.php?".api_get_cidreq()."&amp;curdirpath=".$my_cur_dir_path."\n\n" . api_get_setting('administratorName') . " " . api_get_setting('administratorSurname') . "\n" . get_lang('Manager') . " " . api_get_setting('siteName') . "\n" . get_lang('Email') . " : " . api_get_setting('emailAdministrator');
1089
			// Here we are forming one large header line
1090
			// Every header must be followed by a \n except the last
1091
			@api_mail('', $emailto, $emailsubject, $emailbody, $sender_name,$email_admin);
1092

    
1093
			$emailbody_user = get_lang('Dear')." ".$currentUserFirstName .' '.$currentUserLastName ."\n";
1094
			$emailbody_user .= get_lang('MessageConfirmSendingOfTask')."\n".get_lang('CourseName')." : ".$_course['name']."\n";
1095
			$emailbody_user .= get_lang('WorkName')." : ".substr($my_cur_dir_path, 0, -1)."\n";
1096
			$emailbody_user .= get_lang('DateSent')." : ".api_get_local_time()."\n";
1097
			$emailbody_user .= get_lang('FileName')." : ".$title."\n\n".api_get_setting('administratorName')." ".api_get_setting('administratorSurname') . "\n" . get_lang('Manager') . " " . api_get_setting('siteName') . "\n" . get_lang('Email') . " : " . api_get_setting('emailAdministrator');;
1098

    
1099
			//Mail to user
1100
			@api_mail('', $currentUserEmail, $emailsubject, $emailbody_user, $sender_name,$email_admin);
1101

    
1102
		}
1103
	}
1104
	$message = get_lang('DocAdd');
1105
	if ($uploadvisibledisabled && !$is_allowed_to_edit) {
1106
		$message .= "<br />" . get_lang('_doc_unvisible') . "<br />";
1107
	}
1108

    
1109
	//stats
1110
	if (!$Id) {
1111
		$Id = $insertId;
1112
	}
1113
	event_upload($Id);
1114
	$submit_success_message = $message . "<br />\n";
1115
	Display :: display_confirmation_message($submit_success_message, false);
1116
}
1117

    
1118
/*	Display links to upload form and tool options */
1119

    
1120
/*
1121
$has_expired = false;
1122
$has_ended = false;
1123
isset($_GET['curdirpath'])?$curdirpath=Database::escape_string($_GET['curdirpath']):$curdirpath='';
1124
$sql = Database::query('SELECT description,id FROM '.Database :: get_course_table(TABLE_STUDENT_PUBLICATION).' WHERE filetype = '."'folder'".' and has_properties != '."''".' and url = '."'/".$curdirpath."'".' LIMIT 1');
1125
$is_special = Database::num_rows($sql);
1126
*/
1127

    
1128
if ($is_special > 0) {
1129
	$is_special = true; //we are in a folder
1130
	define('IS_ASSIGNMENT', 1);
1131
	$sql = Database::query('SELECT * FROM '.$TSTDPUBASG.' WHERE publication_id = '.intval($publication['id']).' LIMIT 1');
1132
	$homework = Database::fetch_array($sql);
1133
	$has_expired = $has_ended = false;
1134
	$has_expiry_date = true;
1135

    
1136
	if ($homework['expires_on'] != '0000-00-00 00:00:00' || $homework['ends_on'] != '0000-00-00 00:00:00') {
1137
		$time_now		= convert_date_to_number(api_get_local_time());
1138
		
1139
		if ($homework['expires_on'] != '0000-00-00 00:00:00') {
1140
			$time_expires 	= convert_date_to_number(api_get_local_time($homework['expires_on']));
1141
			$difference 	= $time_expires - $time_now;					
1142
			if ($difference < 0)			
1143
				$has_expired = true;
1144
		}
1145
		if ($homework['ends_on'] != '0000-00-00 00:00:00') {
1146
			$time_ends 		= convert_date_to_number(api_get_local_time($homework['ends_on']));
1147
			$difference2 	= $time_ends - $time_now;				
1148
			if ($difference2 < 0) {
1149
				$has_ended = true;
1150
			}
1151
		}
1152
		if ($homework['expires_on'] == '0000-00-00 00:00:00') {
1153
			$has_expiry_date = false;
1154
		}
1155
		if (!$has_expiry_date) {
1156
			//@todo fix me
1157
			define('ASSIGNMENT_EXPIRES', $time_expires);
1158
		}
1159
		$ends_on 	= api_convert_and_format_date($homework['ends_on']);
1160
		$expires_on = api_convert_and_format_date($homework['expires_on']);
1161

    
1162
		if ($has_ended) {
1163
			display_action_links($cur_dir_path, $always_show_tool_options, true);
1164
			Display :: display_error_message(get_lang('EndDateAlreadyPassed').' '.$ends_on);
1165
		} elseif ($has_expired) {
1166
			display_action_links($cur_dir_path, $always_show_tool_options, $always_show_upload_form);
1167
			Display :: display_warning_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on);
1168
		} else {
1169
            display_action_links($cur_dir_path, $always_show_tool_options, $always_show_upload_form);
1170
			if ($has_expiry_date) {
1171
				Display :: display_normal_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
1172
			}
1173
		}
1174
	} else {
1175
		display_action_links($cur_dir_path, $always_show_tool_options, $always_show_upload_form);
1176
	}
1177
} else {
1178
	display_action_links($cur_dir_path, $always_show_tool_options, $always_show_upload_form);
1179
}
1180

    
1181
/*	Display form to upload document */
1182

    
1183
if ($is_course_member) {
1184
	if (($display_upload_form || $edit)&&!$has_ended) {
1185

    
1186
		if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
1187
			api_not_allowed();
1188
		}
1189

    
1190
		if ($edit) {
1191
			//Get the author ID for that document from the item_property table
1192
			$is_author = false;
1193
			$author_sql = "SELECT * FROM $iprop_table WHERE tool = 'work' AND insert_user_id='$user_id' AND ref=" . $edit;
1194
			$author_qry = Database::query($author_sql);
1195
			if (Database :: num_rows($author_qry) == 1) {
1196
				$is_author = true;
1197
			}
1198
		}
1199

    
1200
		//require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
1201
		require_once (api_get_path(LIBRARY_PATH).'fileDisplay.lib.php');
1202

    
1203
		$form = new FormValidator('form', 'POST', api_get_self() . "?curdirpath=" . rtrim(Security :: remove_XSS($cur_dir_path),'/') . "&gradebook=".Security::remove_XSS($_GET['gradebook'])."&origin=$origin", '', 'enctype="multipart/form-data"');
1204

    
1205
		// form title
1206
		if ($edit) {
1207
			$form_title = get_lang('EditMedia');
1208
		} else {
1209
			$form_title = get_lang('UploadADocument');
1210
		}
1211
		$form->addElement('header', '', $form_title);
1212

    
1213
		if (!empty ($error_message)) {
1214
			Display :: display_error_message($error_message);
1215
		}
1216
		$show_progress_bar = false;
1217

    
1218
		if ($submitGroupWorkUrl) {
1219
			// For user comming from group space to publish his work
1220
			$realUrl = str_replace($_configuration['root_sys'], $_configuration['root_web'], str_replace("\\", '/', realpath($submitGroupWorkUrl)));
1221
			$form->addElement('hidden', 'newWorkUrl', $submitGroupWorkUrl);
1222
			$text_document = & $form->addElement('text', 'document', get_lang('Document'));
1223
			$defaults['document'] = '<a href="' . format_url($submitGroupWorkUrl) . '">' . $realUrl . '</a>';
1224
			$text_document->freeze();
1225
		} elseif ($edit && ($is_allowed_to_edit or $is_author)) {
1226
			$workUrl = $currentCourseRepositoryWeb . $workUrl;
1227
			$form->addElement('hidden', 'id', $edit);
1228

    
1229
			$html = '<div class="row">
1230
								<div class="label">' . get_lang("Document") . '
1231
								</div>
1232
								<div class="formw">
1233
									<a href="' . $workUrl . '">' . get_lang("ClickHereToDownloadTheFile") . '</a>
1234
								</div>
1235
					</div>';
1236
			$form->addElement('html', $html);
1237
		} else {
1238
			// else standard upload option
1239
			$form->addElement('file', 'file', get_lang('UploadADocument'), 'size="40" onchange="updateDocumentTitle(this.value)"');
1240
			$show_progress_bar = true;
1241
		}
1242

    
1243
		$titleWork = $form->addElement('text', 'title', get_lang('TitleWork'), 'id="file_upload"  style="width: 350px;"');
1244
		$defaults['title'] = $edit ? stripslashes($workTitle) : stripslashes($title);
1245

    
1246
		//Removed to avoid incoherences
1247
		//$titleAuthors = $form->addElement('text', 'authors', get_lang("Authors"), 'style="width: 350px;"');
1248

    
1249
		//if (empty ($authors)) {
1250
		$authors = api_get_person_name($_user['firstName'], $_user['lastName']);
1251
		//}
1252

    
1253
		//$defaults["authors"] = ($edit ? stripslashes($workAuthor) : stripslashes($authors));
1254
		$titleAuthors = $form->addElement('textarea', 'description', get_lang("Description"), 'style="width: 350px; height: 60px;"');
1255
		$defaults["description"] = ($edit ? stripslashes($workDescription) : stripslashes($description));
1256

    
1257
		if ($is_allowed_to_edit && !empty($edit) && !empty($parent_id)) {
1258
			// Get qualification from parent_id that'll allow the validation qualification over
1259
			$sql = "SELECT qualification FROM $work_table WHERE id='$parent_id'";
1260
			$result = Database::query($sql);
1261
			$row = Database::fetch_array($result);
1262
			$qualification_over = $row['qualification'];
1263
			$form->addElement('text', 'qualification', get_lang('Qualification'), 'size="10"');
1264
			$form->addElement('html', '<div style="margin-left:20%">'.get_lang('QualificationNumeric').'&nbsp;:&nbsp;'.$qualification_over.'</div>');
1265
			$form->addElement('hidden', 'qualification_over', $qualification_over);
1266
		}
1267

    
1268
		$defaults['qualification'] = $qualification_number;//($edit ? stripslashes($qualification_number) : stripslashes($qualification_number));
1269
		$form->addElement('hidden', 'active', 1);
1270
		$form->addElement('hidden', 'accepted', 1);
1271
		$form->addElement('hidden', 'sec_token', $stok);
1272

    
1273
		if (isset($_GET['edit'])) {
1274
			$text = get_lang('UpdateWork');
1275
			$class = 'save';
1276
		} else {
1277
			$text = get_lang('SendWork');
1278
			$class = 'upload';
1279
		}
1280

    
1281
		// fix the Ok button when we see the tool in the learn path
1282
		if ($origin == 'learnpath') {
1283
			$form->addElement('html', '<div style="margin-left:137px">');
1284
			$form->addElement('style_submit_button', 'submitWork', $text, array('class="'.$class.'"', 'value="submitWork"'));
1285
			$form->addElement('html', '</div>');
1286
		} else {
1287
			//$form->addElement('submit','submitWork', get_lang('SendFile'));
1288
			$form->addElement('style_submit_button', 'submitWork', $text, array('class="'.$class.'"', 'value="submitWork"'));
1289
		}
1290

    
1291
		if (!empty($_POST['submitWork']) || $edit) {
1292
			$form->addElement('style_submit_button', 'cancelForm', get_lang('Cancel'), 'class="cancel"');
1293
		}
1294

    
1295
		if ($show_progress_bar) {
1296
			$form->add_real_progress_bar('uploadWork', 'file');
1297
		}
1298

    
1299
		$form->setDefaults($defaults);
1300
		//$form->addRule('file', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
1301
		$form->display();
1302

    
1303
	}
1304

    
1305

    
1306
	//show them the form for the directory name
1307
	if (isset($_REQUEST['createdir']) && $is_allowed_to_edit) {
1308
		//create the form that asks for the directory name
1309
		$new_folder_text = '<form name="form1"  method="POST">';
1310
		$new_folder_text .= '<div class="row"><div class="form_header">'.get_lang('CreateAssignment').'</div></div>';
1311
		$new_folder_text .= '<input type="hidden" name="curdirpath" value="' . Security :: remove_XSS($cur_dir_path) . '"/>';
1312
		$new_folder_text .= '<input type="hidden" name="sec_token" value="'.$stok.'" />';
1313
		$new_folder_text .= '<div class="row">
1314
								<div class="label">
1315
									<span class="form_required">*</span> '.get_lang('AssignmentName').'
1316
								</div>
1317
								<div class="formw">
1318
									<div id="msg_error1" style="display:none;color:red"></div>
1319
									<input type="text" id="work_title" name="new_dir" onfocus="document.getElementById(\'msg_error1\').style.display=\'none\';"/>
1320
								</div>
1321
							</div>';
1322
		//$new_folder_text .= '<button type="button" name="create_dir" class="add" onClick="validate();" value="' . get_lang('Ok') . '"/>'.get_lang('CreateDirectory').'</button>';
1323

    
1324
		//new additional fields inside the "if condition" just to agroup
1325
		if(true):
1326

    
1327
		$new_folder_text .= '<div class="row">
1328
								<div class="label">
1329
									'.get_lang('Description').'
1330
								</div>
1331
								<div class="formw">';
1332

    
1333
				$oFCKeditor = new FCKeditor('description') ;
1334
				$oFCKeditor->ToolbarSet = 'profile';
1335
				$oFCKeditor->Width		= '80%';
1336
				$oFCKeditor->Height		= '130';
1337
				$oFCKeditor->Value		= $message;
1338
				$return =	$oFCKeditor->CreateHtml();
1339
				$new_folder_text .= $return;
1340

    
1341
		$new_folder_text .= '</div>
1342
							</div>';
1343

    
1344
		// Advanced parameters
1345
		$addtext .='<div id="options" style="display: none;">';
1346
		$addtext .= '<div style="padding:10px">';
1347
		$addtext .= '<b>'.get_lang('QualificationOfAssignment').'</b>';
1348
		$addtext .= '<table cellspacing="0" cellpading="0" border="0"><tr>';
1349
		$addtext .= '<td colspan="2">&nbsp;&nbsp;'.get_lang('QualificationNumeric').'&nbsp;';
1350
		$addtext .= '<input type="text" name="qualification_value" value="" size="5"/></td><tr><td colspan="2">';
1351
		$addtext .= '<input type="checkbox" value="1" name="make_calification" onclick="javascript: if(this.checked){document.getElementById(\'option1\').style.display=\'block\';}else{document.getElementById(\'option1\').style.display=\'none\';}"/>'.get_lang('MakeQualifiable').'</td></tr><tr>';
1352
		$addtext .= '<td colspan="2"><div id="option1" style="display:none">';
1353
		$addtext .= '<div id="msg_error_weight" style="display:none;color:red"></div>';
1354
		$addtext .=	'&nbsp;&nbsp;'.get_lang('WeightInTheGradebook').'&nbsp;';
1355
		$addtext .= '<input type="text" name="weight" value="" size="5" onfocus="document.getElementById(\'msg_error_weight\').style.display=\'none\';"/></div></td></tr>';
1356
		$addtext .= '</tr></table>';
1357
		$addtext .= '<br />';
1358
		$addtext .= '<b>'.get_lang('DatesAvailables').'</b><br />';
1359
		$addtext .= '<input type="checkbox" value="1" name="type1" onclick="javascript: if(this.checked){document.getElementById(\'option2\').style.display=\'block\';}else{document.getElementById(\'option2\').style.display=\'none\';}"/>'.get_lang('EnableExpiryDate').'';
1360
		$addtext .= '&nbsp;&nbsp;&nbsp;<span id="msg_error2" style="display:none;color:red"></span>';
1361
		$addtext .= '&nbsp;&nbsp;&nbsp;<span id="msg_error3" style="display:none;color:red"></span>';
1362
		$addtext .= '<div id="option2" style="padding:4px;display:none">&nbsp;&nbsp;';
1363
		$addtext .= draw_date_picker('expires').'</div>';
1364
		$addtext .= '<br /><input type="checkbox" value="1" name="type2" onclick="javascript: if(this.checked){document.getElementById(\'option3\').style.display=\'block\';}else{document.getElementById(\'option3\').style.display=\'none\';}"/>'.get_lang('EnableEndDate').'';
1365
		$addtext .= '<div id="option3" style="padding:4px;display:none">';
1366
		$addtext .= '&nbsp;&nbsp;&nbsp;<div id="msg_error4" style="display:none;color:red"></div>';
1367
		$addtext .= draw_date_picker('ends').'<br />';
1368
		$addtext .= '</div>';
1369
		$addtext .= '<br /><br /><b>'.get_lang('Agenda').'</b><br />';
1370
		$addtext .= '&nbsp;&nbsp;'.make_checkbox('add_to_calendar').get_lang('AddToCalendar').'</div>';
1371
		$addtext .= '</div>';
1372

    
1373
		$new_folder_text .= '<div class="row">
1374
								<div class="label">
1375

    
1376
								</div>
1377
								<div class="formw"><a href="javascript: void(0);" onclick="javascript: return plus();"><span id="plus">'.Display::return_icon('div_show.gif',get_lang('AdvancedParameters'), array('style' => 'vertical-align:center')).' '.get_lang('AdvancedParameters').'</span></a><br />
1378
									'.$addtext.'
1379
								</div>
1380
							</div>';
1381

    
1382

    
1383
		endif;
1384

    
1385
		$new_folder_text .= '<div class="row">
1386
								<div class="label">
1387
								</div>
1388
								<div class="formw">
1389
									<button type="button" class="add" name="create_dir" onClick="javascript: validate();" value="' . addslashes(get_lang('CreateDirectory')) . '"/>' . addslashes(get_lang('ButtonCreateAssignment')) . '</button>
1390
								</div>
1391
							</div>';
1392

    
1393

    
1394
		$new_folder_text .= '</form>';
1395
		//show the form
1396
		echo $new_folder_text;
1397
	}
1398
} else {
1399
	//the user is not registered in this course
1400
	echo '<p style="font-weight:bold">' . get_lang('MustBeRegisteredUser') . '</p>';
1401
}
1402

    
1403
/*	Display of tool options */
1404

    
1405
if ($display_tool_options) {
1406
	display_tool_options($uploadvisibledisabled, $origin, $base_work_dir, $cur_dir_path, $cur_dir_path_url);
1407
}
1408

    
1409
/*	Display list of student publications */
1410

    
1411
if ($cur_dir_path == '/') {
1412
	$my_cur_dir_path = '';
1413
} else {
1414
	$my_cur_dir_path = $cur_dir_path;
1415
}
1416

    
1417
//If no upload form is showed and if NO tooloptions
1418

    
1419
if (!$display_upload_form && !$display_tool_options) {
1420
	$add_query = '';
1421
	//Getting if I'm a teacher
1422
	$sql = "SELECT user.firstname, user.lastname FROM $table_user user, $table_course_user course_user
1423
			WHERE course_user.user_id=user.user_id AND course_user.course_code='".api_get_course_id()."' AND course_user.status='1'";
1424
	$res = Database::query($sql);
1425
	$admin_course = '';
1426
	while ($row = Database::fetch_row($res)) {
1427
		$admin_course .='\''.api_get_person_name($row[0], $row[1]).'\',';
1428
	}
1429

    
1430
	//If I'm student & I'm in a special work and check the work setting: "New documents are visible for all users"
1431

    
1432
	if (!$is_allowed_to_edit && $is_special && $uploadvisibledisabled == 1) {
1433
		$add_query = ' AND author IN('.$admin_course.'\''.api_get_person_name($_user['firstName'], $_user['lastName']).'\')';
1434
	}
1435
	if ($is_allowed_to_edit && $is_special) {
1436

    
1437
		if (!empty($_REQUEST['filter'])) {
1438
			switch($_REQUEST['filter']) {
1439
				case 1:
1440
					$add_query = ' AND qualification = '."''";
1441
					break;
1442
				case 2:
1443
					$add_query = ' AND qualification != '."''";
1444
					break;
1445
				case 3:
1446
					$add_query = ' AND sent_date < '."'".$homework['expires_on']."'";
1447
					break;
1448
				default:
1449
			 		$add_query = '';
1450
			}
1451
		}
1452
		$cidreq = isset($_GET['cidreq']) ? Security::remove_XSS($_GET['cidreq']) : '';
1453
		$curdirpath = isset($_GET['curdirpath']) ? Security::remove_XSS($_GET['curdirpath']) : '';
1454
		$filter = isset($_REQUEST['filter']) ? (int)$_REQUEST['filter'] : '';
1455

    
1456
		if ($origin != 'learnpath') {
1457
			$form_filter = '<form method="post" action="'.api_get_self().'?cidReq='.$cidreq.'&curdirpath='.$curdirpath.'&gradebook='.$gradebook.'">';
1458
			$form_filter .= make_select('filter', array(0 => get_lang('SelectAFilter'), 1 => get_lang('FilterByNotRevised'), 2 => get_lang('FilterByRevised'), 3 => get_lang('FilterByNotExpired')), $filter).'&nbsp&nbsp';
1459
			$form_filter .= '<button type="submit" class="save" value="'.get_lang('FilterAssignments').'">'.get_lang('FilterAssignments').'</button></form>';
1460
			echo $form_filter;
1461

    
1462
		}
1463
	}
1464

    
1465
	if (!empty($publication['description'])) {
1466
			echo '<p><div><strong>'.get_lang('Description').':</strong><p>'.Security::remove_XSS($publication['description'], STUDENT).'</p></div></p>';
1467
	}
1468
	if ($display_list_users_without_publication) {
1469
		display_list_users_without_publication($publication['id']);
1470
	} else {
1471
		//var_dump($add_query);
1472
		display_student_publications_list($base_work_dir . '/' . $my_cur_dir_path, 'work/' . $my_cur_dir_path, $currentCourseRepositoryWeb, $link_target_parameter, $dateFormatLong, $origin,$add_query);
1473
	}
1474
}
1475

    
1476
/*	Footer */
1477

    
1478
if ($origin != 'learnpath') {
1479
	//we are not in the learning path tool
1480
	Display :: display_footer();
1481
}
1482

    
1483

    
1484
/*	Some functions */
1485

    
1486
function make_select($name, $values, $checked = '') {
1487
	$output = '<select name="'.$name.'" id="'.$name.'">';
1488
 	foreach($values as $key => $value) {
1489
 		$output .= '<option value="'.$key.'" '.(($checked==$key) ? 'selected="selected"' : '').'>'.$value.'</option>';
1490
 	}
1491
 	$output .= '</select>';
1492
 	return $output;
1493
}
1494

    
1495
function make_checkbox($name, $checked = '') {
1496
	return '<input type="checkbox" value="1" name="'.$name.'" '.((!empty($checked))?'checked="checked"':'').'/>';
1497
}
1498

    
1499
function draw_date_picker($prefix, $default = '') {
1500
	//$default = 2008-10-01 10:00:00
1501
	if (empty($default)) {
1502
		//$default = date('Y-m-d H:i:s');		
1503
		$default = api_get_local_time();
1504
	}
1505
	$parts = split(' ', $default);
1506
	list($d_year, $d_month, $d_day) = split('-', $parts[0]);
1507
	list($d_hour, $d_minute) = split(':', $parts[1]);
1508

    
1509
	$minute = range(10, 59);
1510
	array_unshift($minute, '00', '01', '02', '03', '04', '05', '06', '07', '08', '09');
1511
	$date_form = make_select($prefix.'_day', array_combine(range(1, 31), range(1, 31)), $d_day);
1512
	$date_form .= make_select($prefix.'_month', array_combine(range(1, 12), api_get_months_long()), $d_month);
1513
	$date_form .= make_select($prefix.'_year', array($d_year => $d_year, $d_year + 1 => $d_year + 1), $d_year).'&nbsp;&nbsp;&nbsp;&nbsp;';
1514
	$date_form .= make_select($prefix.'_hour', array_combine(range(0, 23), range(0, 23)), $d_hour).' : ';
1515
	$date_form .= make_select($prefix.'_minute', $minute, $d_minute);
1516
	return $date_form;
1517
}
(2-2/4)