Project

General

Profile

Bug #3918 » work.php

Yoselyn Castillo, 11/09/2012 15:50

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

    
4
use ChamiloSession as Session;
5

    
6
/**
7
*	@package chamilo.work
8
* 	@author Thomas, Hugues, Christophe - original version
9
* 	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University - ability for course admins to specify wether uploaded documents are visible or invisible by default.
10
* 	@author Roan Embrechts, code refactoring and virtual course support
11
* 	@author Frederic Vauthier, directories management
12
*   @author Julio Montoya <gugli100@gmail.com> BeezNest 2011 LOTS of bug fixes
13
*
14
* 	@todo refactor more code into functions, use quickforms, coding standards, ... jm
15
*/
16

    
17
/**
18
 * 	STUDENT PUBLICATIONS MODULE
19
 *
20
 * Note: for a more advanced module, see the dropbox tool.
21
 * This one is easier with less options.
22
 * This tool is better used for publishing things,
23
 * sending in assignments is better in the dropbox.
24
 *
25
 * GOALS
26
 * *****
27
 * Allow student to quickly send documents immediately visible on the Course 
28
 *
29
 * The script does 5 things:
30
 *
31
 * 	1. Upload documents
32
 * 	2. Give them a name
33
 * 	3. Modify data about documents
34
 * 	4. Delete link to documents and simultaneously remove them
35
 * 	5. Show documents list to students and visitors
36
 *
37
 * On the long run, the idea is to allow sending realvideo . Which means only
38
 * establish a correspondence between RealServer Content Path and the user's
39
 * documents path.
40
 * 
41
 *
42
*/
43

    
44
/*		INIT SECTION */
45

    
46
$language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
47

    
48
require_once '../inc/global.inc.php';
49
$current_course_tool  = TOOL_STUDENTPUBLICATION;
50

    
51
/*	Configuration settings */
52

    
53
api_protect_course_script(true);
54

    
55
// Including necessary files
56
require_once 'work.lib.php';
57

    
58
require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
59
include_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
60
require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
61
require_once api_get_path(LIBRARY_PATH).'fileDisplay.lib.php';
62

    
63
$course_id      = api_get_course_int_id();
64
$course_info    = api_get_course_info();
65
$user_id 	    = api_get_user_id();
66
$id_session     = api_get_session_id();
67

    
68
// Section (for the tabs)
69
$this_section = SECTION_COURSES;
70
$work_id = isset($_GET['id']) ? intval($_GET['id']) : null;
71
$my_folder_data = get_work_data_by_id($work_id);
72

    
73
$curdirpath = '';
74
$htmlHeadXtra[] = api_get_jqgrid_js();
75

    
76
$htmlHeadXtra[] = to_javascript_work();
77

    
78
$htmlHeadXtra[] = '<script type="text/javascript">
79
function setFocus(){
80
    $("#work_title").focus();
81
}
82
$(document).ready(function () {
83
    setFocus();
84
});
85
</script>';
86

    
87
// Table definitions
88
$main_course_table 	= Database :: get_main_table(TABLE_MAIN_COURSE);
89
$work_table 		= Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
90
$TSTDPUBASG			= Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
91
$table_course_user	= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
92
$table_user			= Database :: get_main_table(TABLE_MAIN_USER);
93
$table_session		= Database :: get_main_table(TABLE_MAIN_SESSION);
94
$table_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
95

    
96
/*	Constants and variables */
97

    
98
$tool_name 		= get_lang('StudentPublications');
99
$course_code 	= api_get_course_id();
100
$session_id 	= api_get_session_id();
101

    
102
$is_course_member = CourseManager::is_user_subscribed_in_real_or_linked_course($user_id, $course_code,$session_id);
103
$is_course_member = $is_course_member || api_is_platform_admin();
104

    
105
$currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/';
106
$currentCourseRepositoryWeb = api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/';
107

    
108
$currentUserFirstName 	= $_user['firstName'];
109
$currentUserLastName 	= $_user['lastName'];
110
$currentUserEmail 		= $_user['mail'];
111

    
112
$item_id 		        = isset($_REQUEST['item_id']) ? intval($_REQUEST['item_id']) : null;
113
$parent_id 		        = isset($_REQUEST['parent_id']) ? Database::escape_string($_REQUEST['parent_id']) : '';
114
$origin 		        = isset($_REQUEST['origin']) ? Security::remove_XSS($_REQUEST['origin']) : '';
115

    
116
$submitGroupWorkUrl     = isset($_REQUEST['submitGroupWorkUrl']) ? Security::remove_XSS($_REQUEST['submitGroupWorkUrl']) : '';
117
$title 			        = isset($_REQUEST['title']) ? $_REQUEST['title'] : '';
118
$description 	        = isset($_REQUEST['description']) ? $_REQUEST['description'] : '';
119

    
120
$uploadvisibledisabled  = isset($_REQUEST['uploadvisibledisabled']) ? Database::escape_string($_REQUEST['uploadvisibledisabled']) : $course_info['show_score'];
121

    
122
// get data for publication assignment
123
$has_expired = false;
124
$has_ended   = false;
125

    
126
//directories management
127
$sys_course_path 	= api_get_path(SYS_COURSE_PATH);
128
$course_dir 		= $sys_course_path . $_course['path'];
129
$base_work_dir 		= $course_dir . '/work';
130

    
131
$link_target_parameter = ""; // e.g. "target=\"_blank\"";
132

    
133
$display_list_users_without_publication = isset($_GET['list']) && Security::remove_XSS($_GET['list']) == 'without' ? true : false;
134

    
135
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'list';
136

    
137
//Download folder
138
if ($action == 'downloadfolder') {
139
	require 'downloadfolder.inc.php';
140
}
141

    
142
/*	More init stuff */
143

    
144
if (isset ($_POST['cancelForm']) && !empty ($_POST['cancelForm'])) {
145
	header('Location: ' . api_get_self() . '?origin='.$origin.'&amp;gradebook='.$gradebook);
146
	exit;
147
}
148

    
149
// If the POST's size exceeds 8M (default value in php.ini) the $_POST array is emptied
150
// If that case happens, we set $submitWork to 1 to allow displaying of the error message
151
// The redirection with header() is needed to avoid apache to show an error page on the next request
152
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !sizeof($_POST)) {
153
	if (strstr($_SERVER['REQUEST_URI'], '?')) {
154
		header('Location: ' . $_SERVER['REQUEST_URI'] . '&submitWork=1');
155
		exit ();
156
	} else {
157
		header('Location: ' . $_SERVER['REQUEST_URI'] . '?submitWork=1');
158
		exit ();
159
	}
160
}
161

    
162
$group_id = api_get_group_id();
163
  
164
$display_upload_form = false;	
165
if ($action == 'upload_form') {
166
	$display_upload_form = true;
167
}
168

    
169
/*	Header */
170

    
171
if (!empty($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
172
	$_SESSION['gradebook'] = Security::remove_XSS($_GET['gradebook']);
173
	$gradebook =	$_SESSION['gradebook'];
174
} elseif (empty($_GET['gradebook'])) {
175
	unset($_SESSION['gradebook']);
176
	$gradebook = '';
177
}
178

    
179
if (!empty($gradebook) && $gradebook == 'view') {    
180
    $interbreadcrumb[] = array ('url' => '../gradebook/' . $_SESSION['gradebook_dest'],'name' => get_lang('ToolGradebook'));    
181
}
182

    
183
if (!empty($group_id)) {
184
	$group_properties  = GroupManager :: get_group_properties($group_id);    
185
    $show_work = false;
186
    
187
    if (api_is_allowed_to_edit(false, true)) {        
188
        $show_work = true;
189
    } else {
190
        // you are not a teacher              
191
        $show_work = GroupManager::user_has_access($user_id, $group_id, GROUP_TOOL_WORK);
192
    }
193
    
194
    if (!$show_work) {
195
        api_not_allowed();
196
    }
197
    
198
	$interbreadcrumb[] = array ('url' => '../group/group.php', 'name' => get_lang('Groups'));
199
	$interbreadcrumb[] = array ('url' => '../group/group_space.php?gidReq='.$group_id, 'name' => get_lang('GroupSpace').' '.$group_properties['name']);
200

    
201
	$url_dir ='';
202
	$interbreadcrumb[] = array ('url' =>'work.php?gidReq='.$group_id,'name' => get_lang('StudentPublications'));
203

    
204
	$url_dir = 'work.php?&id=' . $work_id;
205
	$interbreadcrumb[] = array ('url' => $url_dir,'name' =>  $my_folder_data['title']);	
206

    
207
	if ($action == 'upload_form') {
208
		$interbreadcrumb[] = array ('url' => 'work.php','name' => get_lang('UploadADocument'));
209
	}
210
        
211
	if ($action == 'create_dir') {
212
		$interbreadcrumb[] = array ('url' => 'work.php','name' => get_lang('CreateAssignment'));
213
	}
214
	Display :: display_header(null);
215
} else { 
216
	if (isset($origin) && $origin != 'learnpath') {
217
		
218
	    if (isset($_GET['id']) && !empty($_GET['id']) || $display_upload_form || $action == 'settings' || $action == 'create_dir') {
219
            $interbreadcrumb[] = array ('url' => 'work.php', 'name' => get_lang('StudentPublications'));
220
        } else {        	
221
            $interbreadcrumb[] = array ('url' => '#', 'name' => get_lang('StudentPublications'));
222
        }
223
        
224
        $url_dir = 'work.php?id=' . $work_id;
225
		$interbreadcrumb[] = array ('url' => $url_dir,'name' =>  $my_folder_data['title']);	
226
		
227
		if ($action == 'upload_form') {
228
			$interbreadcrumb[] = array ('url' => '#', 'name' => get_lang('UploadADocument'));
229
		}
230
		if ($action == 'settings') {
231
			$interbreadcrumb[] = array ('url' => '#', 'name' => get_lang('EditToolOptions'));
232
		}
233
		if ($action == 'create_dir') {
234
			$interbreadcrumb[] = array ('url' => '#','name' => get_lang('CreateAssignment'));
235
		}
236
		Display :: display_header(null);
237

    
238
	} else {
239
		//we are in the learnpath tool
240
		Display::display_reduced_header();
241
	}
242
}
243

    
244

    
245
//stats
246
event_access_tool(TOOL_STUDENTPUBLICATION);
247

    
248
$is_allowed_to_edit = api_is_allowed_to_edit(); //has to come after display_tool_view_option();
249

    
250
$student_can_edit_in_session = api_is_allowed_to_session_edit(false, true);
251

    
252
Display :: display_introduction_section(TOOL_STUDENTPUBLICATION);
253

    
254
// introduction section
255

    
256
if ($origin == 'learnpath') {
257
	echo '<div style="height:15px">&nbsp;</div>';
258
}
259

    
260
/*	Display links to upload form and tool options */
261

    
262
if (!in_array($action, array('send_mail','add','create_dir','upload'))) {
263
    $token = Security::get_token();    
264
}
265

    
266
$show_tool_options = (in_array($action, array('list', 'add'))) ? true : false;
267

    
268
$display_upload_link = $action == 'upload_form' ? false : true;
269

    
270
if (!empty($my_folder_data)) {
271
	$homework = get_work_assignment_by_id($my_folder_data['id']);    
272
	
273
	if ($homework['expires_on'] != '0000-00-00 00:00:00' || $homework['ends_on'] != '0000-00-00 00:00:00') {
274
		$time_now		= time();
275

    
276
		if (!empty($homework['expires_on']) && $homework['expires_on'] != '0000-00-00 00:00:00') {            
277
			$time_expires 	= api_strtotime($homework['expires_on'], 'UTC');
278
			$difference 	= $time_expires - $time_now;
279
			if ($difference < 0) {
280
				$has_expired = true;				
281
			}
282
		}
283
        
284
        if (empty($homework['expires_on']) || $homework['expires_on'] == '0000-00-00 00:00:00') {
285
			$has_expired = false;
286
		}
287
        
288
		if (!empty($homework['ends_on']) && $homework['ends_on'] != '0000-00-00 00:00:00') {
289
			$time_ends 		= api_strtotime($homework['ends_on'], 'UTC');
290
			$difference2 	= $time_ends - $time_now;
291
			if ($difference2 < 0) {
292
				$has_ended = true;
293
			}
294
		}
295
		
296
		$ends_on 	= api_convert_and_format_date($homework['ends_on']);
297
		$expires_on = api_convert_and_format_date($homework['expires_on']);
298

    
299
		if ($has_ended) {            
300
            //if (!api_is_allowed_to_edit()) {                
301
                $display_upload_link = false;
302
            //}
303
			$message = Display::return_message(get_lang('EndDateAlreadyPassed').' '.$ends_on, 'error');
304
		} elseif ($has_expired) {            
305
            $display_upload_link = true;                       	
306
			$message = Display::return_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on, 'warning');
307
		} else {	
308
			if ($has_expired) {
309
				$message = Display::return_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
310
			}
311
		}        
312
	}
313
}
314

    
315
display_action_links($work_id, $curdirpath, $show_tool_options, $display_upload_link, $action);
316

    
317
echo $message;
318

    
319
//for teachers
320

    
321
switch ($action) {
322
    case 'send_mail':        
323
		if (Security::check_token('get')) {
324
			$mails_sent_to = send_reminder_users_without_publication($my_folder_data);
325
            if (empty($mails_sent_to)) {
326
                Display::display_warning_message(get_lang('NoResults'));
327
            } else {
328
                Display::display_confirmation_message(get_lang('MessageHasBeenSent').' '.implode(', ', $mails_sent_to));
329
            }            
330
            Security::clear_token();			
331
		}
332
		break;		
333
	case 'settings':
334
		//if posts
335
		if ($is_allowed_to_edit && !empty($_POST['changeProperties'])) {
336
			// changing the tool setting: default visibility of an uploaded document
337
			$query = "UPDATE " . $main_course_table . " SET show_score='" . $uploadvisibledisabled . "' WHERE code='" . api_get_course_id() . "'";
338
			$res = Database::query($query);
339
            /**
340
             * Course data are cached in session so we need to update both the database
341
             * and the session data 
342
             */
343
            $_course['show_score'] = $uploadvisibledisabled;
344
            Session::write('_course', $course);
345
            
346
		
347
			// changing the tool setting: is a student allowed to delete his/her own document
348
			// database table definition
349
			$table_course_setting = Database :: get_course_table(TOOL_COURSE_SETTING);
350
		
351
			// counting the number of occurrences of this setting (if 0 => add, if 1 => update)
352
			$query = "SELECT * FROM " . $table_course_setting . " WHERE c_id = $course_id AND variable = 'student_delete_own_publication'";
353
			$result = Database::query($query);
354
			$number_of_setting = Database::num_rows($result);
355
		
356
			if ($number_of_setting == 1) {
357
				$query = "UPDATE " . $table_course_setting . " SET value='" . Database::escape_string($_POST['student_delete_own_publication']) . "'
358
						WHERE variable='student_delete_own_publication' AND c_id = $course_id";
359
				Database::query($query);
360
			} else {
361
				$query = "INSERT INTO " . $table_course_setting . " (c_id, variable, value, category) VALUES
362
				($course_id, 'student_delete_own_publication','" . Database::escape_string($_POST['student_delete_own_publication']) . "','work')";
363
				Database::query($query);
364
			}
365
			Display::display_confirmation_message(get_lang('Saved'));
366
		}		
367
		/*	Display of tool options */
368
		display_tool_options($uploadvisibledisabled, $origin);		
369
		break;
370
	case 'mark_work':
371
        if (!api_is_allowed_to_edit()) {
372
            echo Display::return_message(get_lang('ActionNotAllowed'), 'error');
373
            Display::display_footer();					
374
        }
375
        break;
376
    case 'edit':
377
	case 'upload_form': //can be add or edit work
378
        $is_author = false;        
379
		if (empty($item_id)) {
380
			$parent_data = get_work_data_by_id($work_id);            
381
			$parent_data['qualification'] = intval($parent_data['qualification']);
382
			
383
			if (!empty($parent_data) && !empty($parent_data['qualification']))  {
384
				$count =  get_work_count_by_student($user_id, $work_id);                		
385
				if ($count >= 1 ) {
386
					if (api_get_course_setting('student_delete_own_publication') == '1') {
387
						Display::display_warning_message(get_lang('CantUploadDeleteYourPaperFirst'));					
388
					} else {
389
						Display::display_warning_message(get_lang('YouAlreadySentAPaperYouCantUpload'));
390
					}				
391
					Display::display_footer();
392
					exit;
393
				}
394
			}
395
		} else {
396
			//we found the current user is the author
397
			$sql = "SELECT * FROM  $work_table WHERE c_id = $course_id AND id = $item_id";
398
			$result = Database::query($sql);
399
			$work_item = array();
400
			if ($result) {
401
				$work_item = Database::fetch_array($result);
402
			}			
403
			
404
			//Get the author ID for that document from the item_property table	
405
            $is_author 			= user_is_author($item_id);   
406
            if (!$is_author) {
407
                Display::display_warning_message(get_lang('NotAllowed'));	
408
                Display::display_footer();
409
            }
410
		} 
411
                        
412
		$form = new FormValidator('form', 'POST', api_get_self() . "?action=upload&id=".$work_id."&gradebook=".Security::remove_XSS($_GET['gradebook'])."&origin=$origin", '', array('enctype' => "multipart/form-data"));
413
	
414
		// form title
415
		if ($item_id) {
416
			$form_title = get_lang('Edit');
417
		} else {
418
			$form_title = get_lang('UploadADocument');
419
		}
420
		$form->addElement('header', $form_title);
421
	
422
		if (!empty ($error_message)) {
423
			Display :: display_error_message($error_message);
424
		}
425
		$show_progress_bar = false;
426
	
427
		if ($submitGroupWorkUrl) {
428
			// For user comming from group space to publish his work
429
			$realUrl = str_replace($_configuration['root_sys'], api_get_path(WEB_PATH), str_replace("\\", '/', realpath($submitGroupWorkUrl)));
430
			$form->addElement('hidden', 'newWorkUrl', $submitGroupWorkUrl);
431
			$text_document = & $form->addElement('text', 'document', get_lang('Document'));
432
			$defaults['document'] = '<a href="' . format_url($submitGroupWorkUrl) . '">' . $realUrl . '</a>';
433
			$text_document->freeze();
434
		} elseif ($item_id && ($is_allowed_to_edit or $is_author)) {
435
			$workUrl = $currentCourseRepositoryWeb . $workUrl;			
436
		} else {
437
			// else standard upload option
438
			$form->addElement('file', 'file', get_lang('UploadADocument'), 'size="40" onchange="updateDocumentTitle(this.value)"');
439
			$show_progress_bar = true;
440
		}		
441
		
442
        $form->addElement('hidden', 'id', $work_id);
443
		if (empty($item_id)) {
444
			$form->addElement('checkbox', 'contains_file', null, get_lang('ContainsAfile'), array('id'=>'contains_file_id'));
445
		} else {
446
            $form->addElement('hidden', 'item_id', $item_id);
447
        }
448
		$form->addElement('text', 'title', get_lang('Title'), array('id' => 'file_upload', 'class' => 'span4'));
449
		//$form->addElement('html_editor', 'description', get_lang("Description"));        
450
        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'Work', 'Width' => '100%', 'Height' => '200'));
451
		
452
		if ($item_id && !empty($work_item)) {
453
			$defaults['title'] 			= $work_item['title'];
454
			$defaults["description"] 	= $work_item['description'];
455
			$defaults['qualification']  = $work_item['qualification'];			
456
		}
457
	
458
		if ($is_allowed_to_edit && !empty($item_id)) {
459
			// Get qualification from parent_id that'll allow the validation qualification over
460
			$sql = "SELECT qualification FROM $work_table WHERE c_id = $course_id AND id ='$parent_id' ";
461
			$result = Database::query($sql);
462
			$row = Database::fetch_array($result);
463
            $qualification_over = $row['qualification'];
464
            if (!empty($qualification_over) && intval($qualification_over) > 0) {
465
                $form->addElement('text', 'qualification', array(get_lang('Qualification'),  null, " / ".$qualification_over), 'size="10"');			
466
                $form->addElement('hidden', 'qualification_over', $qualification_over);
467
            }
468
		}	
469
		
470
		$form->addElement('hidden', 'active',   1);
471
		$form->addElement('hidden', 'accepted', 1);
472
		$form->addElement('hidden', 'item_to_edit', $item_id);
473
        $token = Security::get_token();
474
		$form->addElement('hidden', 'sec_token', $token);
475
		
476
		if ($item_id) {
477
			$text = get_lang('UpdateWork');
478
			$class = 'save';
479
		} else {
480
			$text = get_lang('Send');
481
			$class = 'upload';
482
		}
483
	
484
		// fix the Ok button when we see the tool in the learn path
485
		if ($origin == 'learnpath') {
486
			$form->addElement('html', '<div style="margin-left:137px">');			
487
			$form->addElement('style_submit_button', 'submitWork', $text, array('class'=> $class, 'value' => "submitWork"));
488
			$form->addElement('html', '</div>');
489
		} else {
490
			if ($item_id) {
491
				$form->addElement('style_submit_button', 'editWork', $text, array('class'=> $class, 'value' => "editWork"));
492
			} else {
493
				$form->addElement('style_submit_button', 'submitWork', $text, array('class'=> $class, 'value' => "submitWork"));				
494
			}			
495
		}
496
	
497
		if (!empty($_POST['submitWork']) || $item_id) {
498
			$form->addElement('style_submit_button', 'cancelForm', get_lang('Cancel'), 'class="cancel"');
499
		}
500
	
501
		if ($show_progress_bar) {
502
			$form->add_real_progress_bar('uploadWork', 'file');
503
		}
504
		$form->setDefaults($defaults);
505
        
506
        //fixes bug when showing modification form		
507
        if (!empty($work_id)) {
508
            if ($is_allowed_to_edit) {
509
                if (api_resource_is_locked_by_gradebook($work_id, LINK_STUDENTPUBLICATION)) {
510
                    echo Display::display_warning_message(get_lang('ResourceLockedByGradebook'));
511
                } else {
512
                    $form->display();
513
                }
514
            } elseif ($is_author) {
515
                if (empty($work_item['qualificator_id']) || $work_item['qualificator_id'] == 0) {
516
                    $form->display();
517
                } else {
518
                    Display::display_error_message(get_lang('ActionNotAllowed'));
519
                }
520
            } elseif ($student_can_edit_in_session && $has_ended == false) {          
521
                $form->display();
522
            } else {
523
                Display::display_error_message(get_lang('ActionNotAllowed'));
524
            }
525
        } else {
526
            Display::display_error_message(get_lang('ActionNotAllowed'));
527
        }        
528
		break;        
529
    case 'upload': 
530
        $check = Security::check_token('post');  
531
        
532
		if ($student_can_edit_in_session && $check) {
533
			
534
			//check the token inserted into the form
535
			if (isset($_POST['submitWork']) && !empty($is_course_member)) {
536
				$authors = api_get_person_name($currentUserFirstName, $currentUserLastName);
537
				$url = null;
538
                $contains_file = 0;
539
                
540
				if ($_POST['contains_file'] && !empty($_FILES['file']['size'])) {
541
					$updir = $currentCourseRepositorySys . 'work/'; //directory path to upload
542
		
543
					// Try to add an extension to the file if it has'nt one
544
					$new_file_name = add_ext_on_mime(stripslashes($_FILES['file']['name']), $_FILES['file']['type']);
545
		
546
					// Replace dangerous characters
547
					$new_file_name = replace_dangerous_char($new_file_name, 'strict');
548
		
549
					// Transform any .php file in .phps fo security
550
					$new_file_name = php2phps($new_file_name);
551
						
552
					$filesize = filesize($_FILES['file']['tmp_name']);
553
						
554
					if (empty($filesize)) {
555
						Display :: display_error_message(get_lang('UplUploadFailedSizeIsZero'));
556
						$succeed = false;
557
					} elseif (!filter_extension($new_file_name)) {
558
						//filter extension
559
						Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
560
						$succeed = false;
561
					}
562
					if (!$title) {
563
						$title = $_FILES['file']['name'];
564
					}
565
					
566
					// Compose a unique file name to avoid any conflict
567
					$new_file_name = api_get_unique_id();
568
                    $curdirpath = basename($my_folder_data['url']);
569
                    
570
					//if we come from the group tools the groupid will be saved in $work_table
571
					$result = @move_uploaded_file($_FILES['file']['tmp_name'], $updir.$curdirpath.'/'.$new_file_name);
572
                    if ($result) {
573
                        $url = 'work/'.$curdirpath.'/'.$new_file_name;
574
                        $contains_file = 1;
575
                    }
576
				}
577
				
578
				if (empty($title)) {
579
					$title = get_lang('Untitled');
580
				}
581
				
582
                $documents_total_space = DocumentManager::documents_total_space();
583
                $course_max_space = DocumentManager::get_course_quota();
584
                $total_size = $filesize + $documents_total_space;
585
                if ($total_size > $course_max_space) {
586
			       $error_message = get_lang('langNoSpace');             
587
                } else {
588
                    
589
                    $active = '1';
590
			        $sql_add_publication = "INSERT INTO " . $work_table . " SET
591
									   c_id 		= $course_id ,
592
								       url         	= '" . $url . "',
593
								       title       	= '" . Database::escape_string($title) . "',
594
					                   description	= '" . Database::escape_string($description) . "',
595
					                   author      	= '" . Database::escape_string($authors) . "',
596
					                   contains_file = '".$contains_file."',  
597
									   active		= '" . $active . "',                                           
598
									   accepted		= '1',
599
									   post_group_id = '".$group_id."',
600
									   sent_date	=  '".api_get_utc_datetime()."',
601
									   parent_id 	=  '".$work_id."' ,
602
                                       session_id	= '".intval($id_session)."' ,                                               
603
                                       user_id 		= '".$user_id."'";
604
    				//var_dump($sql_add_publication);exit;
605
    				Database::query($sql_add_publication);
606
    				$id = Database::insert_id();	
607
                }	
608
				
609
				if ($id) {				
610
					api_item_property_update($course_info, 'work', $id, 'DocumentAdded', $user_id, api_get_group_id());
611
                    /*
612
                     * See task #5145
613
                    if($uploadvisibledisabled){
614
                        $sql = "UPDATE $work_table SET accepted = 0 WHERE c_id = $course_id AND id = $id";
615
                        Database::query($sql);
616
                        api_item_property_update($course_info, 'work', $id, 'invisible', api_get_user_id());
617
                    }else{
618
                        //api_item_property_update($course_info, 'work', $id, 'visible', api_get_user_id());
619
                    }*/
620
					$succeed = true;
621
				}														
622
			} elseif ($newWorkUrl) {
623
			
624
				// SPECIAL CASE ! For a work coming from another area (i.e. groups)
625
	/*
626
				$url = str_replace('../../' . $_course['path'] . '/', '', $newWorkUrl);
627
	
628
				if (!$title) {
629
					$title = basename($workUrl);
630
				}	
631
				$sql = "INSERT INTO  " . $work_table . " SET
632
									c_id = $course_id,
633
									url        	= '" . $url . "',
634
						            title       	= '" . Database::escape_string($title) . "',
635
						            description 	= '" . Database::escape_string($description) . "',
636
						            author      	= '" . Database::escape_string($authors) . "',
637
								    post_group_id   = '".$group_id."',
638
						            sent_date    	= '".api_get_utc_datetime()."',
639
						            session_id 		= '".intval($id_session)."',
640
						            user_id 		= '".$user_id."'";
641
	
642
				Database::query($sql);
643
	
644
				$insertId = Database::insert_id();
645
				api_item_property_update($_course, 'work', $insertId, 'DocumentAdded', $user_id, $group_id);
646
				$succeed = true;*/
647
			} elseif (isset($_POST['editWork'])) {	
648
				/*
649
				 * SPECIAL CASE ! For a work edited
650
				*/					
651
				//Get the author ID for that document from the item_property table
652
                $item_to_edit_id 	= intval($_POST['item_to_edit']);
653
				$is_author 			= user_is_author($item_to_edit_id);
654
					
655
				if ($is_author) {
656
					$work_data = get_work_data_by_id($item_to_edit_id);
657
                    
658
					if (!empty($_POST['title']))
659
					$title 		 = isset($_POST['title']) ? $_POST['title'] : $work_data['title'];
660
					$description = isset($_POST['description']) ? $_POST['description'] : $work_data['description'];					
661
	
662
					if ($is_allowed_to_edit && ($_POST['qualification'] !='' )) {
663
						$add_to_update = ', qualificator_id ='."'".api_get_user_id()."',";
664
						$add_to_update .= ' qualification = '."'".Database::escape_string($_POST['qualification'])."',";
665
						$add_to_update .= ' date_of_qualification ='."'".api_get_utc_datetime()."'";
666
					}
667
	
668
					if ((int)$_POST['qualification'] > (int)$_POST['qualification_over']) {
669
						Display::display_error_message(get_lang('QualificationMustNotBeMoreThanQualificationOver'));
670
					} else {
671
						$sql = "UPDATE  " . $work_table . "
672
						        SET	title       = '" . Database::escape_string($title) . "',
673
						            description = '" . Database::escape_string($description) . "'
674
						            ".$add_to_update."
675
						        WHERE c_id = $course_id AND id = $item_to_edit_id";					
676
						Database::query($sql);
677
					}
678
					api_item_property_update($_course, 'work', $item_to_edit_id, 'DocumentUpdated', $user_id);
679
					$succeed = true;
680
                    Display :: display_confirmation_message(get_lang('ItemUpdated'), false);
681
				} else {
682
					$error_message = get_lang('IsNotPosibleSaveTheDocument');
683
				}
684
			} else {
685
                $error_message = get_lang('IsNotPosibleSaveTheDocument');
686
            }   
687
            Security::clear_token();
688
		} else {
689
            //Bad token or can't add works
690
            $error_message = get_lang('IsNotPosibleSaveTheDocument');
691
        }
692
                    
693
		if (!empty($succeed) && !empty($id)) {
694
			//last value is to check this is not "just" an edit
695
			//YW Tis part serve to send a e-mail to the tutors when a new file is sent
696
			$send = api_get_course_setting('email_alert_manager_on_new_doc');
697
            
698
			if ($send > 0) {
699
				// Lets predefine some variables. Be sure to change the from address!				
700
				if (empty($id_session)) {
701
                    //Teachers
702
                    $user_list = CourseManager::get_user_list_from_course_code(api_get_course_id(), null, null, null, COURSEMANAGER);
703
				} else {				
704
                    //Coaches
705
                    $user_list = CourseManager::get_user_list_from_course_code(api_get_course_id(), $session_id, null, null, 2);					
706
				}
707
                
708
                $emailsubject = "[" . api_get_setting('siteName') . "] ".get_lang('SendMailBody')."\n".get_lang('CourseName')." : ".$_course['name']."  ";
709
                
710
                foreach ($user_list as $user_data) {
711
                    $user_id = $user_data;                    
712
                    $emailbody = get_lang('SendMailBody')."\n".get_lang('CourseName')." : ".$_course['name']."\n";
713
					//$emailbody .= get_lang('WorkName')." : ".substr($my_cur_dir_path, 0, -1)."\n";
714
					$emailbody .= get_lang('UserName')." : ".api_get_person_name($user_data['firstname'], $user_data['lastname'])."\n";
715
					$emailbody .= get_lang('DateSent')." : ".api_format_date(api_get_local_time())."\n";
716
					$emailbody .= get_lang('WorkName')." : ".$title."\n\n".get_lang('DownloadLink')."\n";
717
                    $url = api_get_path(WEB_CODE_PATH)."work/work.php?".api_get_cidreq()."&amp;id=".$work_id;
718
					$emailbody .= Display::url($url, $url)." \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');
719
                    
720
                    MessageManager::send_message_simple($user_id, $emailsubject, $emailbody);                    
721
                }			
722
			}
723
			$message = get_lang('DocAdd');			
724
			event_upload($id);			
725
			Display :: display_confirmation_message(get_lang('DocAdd'), false);
726
		} else {
727
            if (!empty($error_message)) {
728
                Display :: display_warning_message($error_message, false);    
729
            }
730
        }
731
    case 'create_dir':	
732
	case 'add':
733
        //$check = Security::check_token('post');                
734
        //show them the form for the directory name
735
        
736
		if ($is_allowed_to_edit && in_array($action, array('create_dir','add'))) {   		    
737
			//create the form that asks for the directory name
738
            $form = new FormValidator('form1', 'post', api_get_self().'?action=create_dir&'. api_get_cidreq());
739
            
740
            $form->addElement('header', get_lang('CreateAssignment').$token);
741
            $form->addElement('hidden', 'action', 'add');
742
            $form->addElement('hidden', 'curdirpath', Security :: remove_XSS($curdirpath));            
743
           // $form->addElement('hidden', 'sec_token', $token);      
744
            
745
            $form->addElement('text', 'new_dir', get_lang('AssignmentName'));                        
746
            $form->addRule('new_dir', get_lang('ThisFieldIsRequired'), 'required');
747
            
748
            //$form->addElement('html_editor', 'description', get_lang('Description'));
749
            $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'Work', 'Width' => '100%', 'Height' => '200'));
750
            
751
            $form->addElement('advanced_settings', '<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>');
752
            
753
            $form->addElement('html', '<div id="options" style="display: none;">');
754
                        
755
            if (Gradebook::is_active()) {              
756
                //QualificationOfAssignment
757
                $form->addElement('text', 'qualification_value', get_lang('QualificationNumeric'));
758
                $form->addElement('checkbox', 'make_calification', null, get_lang('MakeQualifiable'), array('id' =>'make_calification_id', 'onclick' => "javascript: if(this.checked){document.getElementById('option1').style.display='block';}else{document.getElementById('option1').style.display='none';}"));
759
            } else {                
760
                //QualificationOfAssignment
761
                $form->addElement('hidden', 'qualification_value',0);
762
                $form->addElement('hidden', 'make_calification', false);
763
            }
764
            
765
            $form->addElement('html', '<div id="option1" style="display: none;">');
766
            
767
            //Loading gradebook select
768
            load_gradebook_select_in_tool($form);        
769
            
770
            $form->addElement('text', 'weight', get_lang('WeightInTheGradebook'));
771
            $form->addElement('html', '</div>');            
772
            
773
            $form->addElement('checkbox', 'type1', null, get_lang('EnableExpiryDate'), array('id' =>'make_calification_id', 'onclick' => "javascript: if(this.checked){document.getElementById('option2').style.display='block';}else{document.getElementById('option2').style.display='none';}"));
774
            
775
            $form->addElement('html', '<div id="option2" style="display: none;">');
776
            $form->addElement('advanced_settings',draw_date_picker('expires'));
777
            $form->addElement('html', '</div>');
778
            
779
            
780
            $form->addElement('checkbox', 'type2', null, get_lang('EnableEndDate'), array('id' =>'make_calification_id', 'onclick' => "javascript: if(this.checked){document.getElementById('option3').style.display='block';}else{document.getElementById('option3').style.display='none';}"));
781
            
782
            $form->addElement('html', '<div id="option3" style="display: none;">');
783
            $form->addElement('advanced_settings', draw_date_picker('ends'));
784
            $form->addElement('html', '</div>');
785
               
786
            $form->addElement('checkbox', 'add_to_calendar', null, get_lang('AddToCalendar'));            
787
            $form->addElement('checkbox', 'allow_text_assignment', null, get_lang('AllowTextAssignments'));      
788
            $form->addElement('html', '</div>');            
789
            $form->addElement('style_submit_button', 'submit', get_lang('CreateDirectory'));
790
		        
791
            if ($form->validate()) {
792

    
793
                $directory 		= Security::remove_XSS($_POST['new_dir']);
794
                $directory 		= replace_dangerous_char($directory);
795
                $directory 		= disable_dangerous_file($directory);
796
                $dir_name 		= $curdirpath.$directory;
797
                $created_dir 	= create_unexisting_work_directory($base_work_dir, $dir_name);
798

    
799
                // we insert here the directory in the table $work_table
800
                $dir_name_sql = '';
801

    
802
                if (!empty($created_dir)) {
803
                    if ($curdirpath == '/') {
804
                        $dir_name_sql = $created_dir;
805
                    } else {
806
                        $dir_name_sql = '/'.$created_dir;
807
                    }
808
                    $time = time();
809
                    $today = api_get_utc_datetime($time);
810

    
811
                    $sql_add_publication = "INSERT INTO " . $work_table . " SET
812
                                            c_id				= $course_id,  
813
                                            url         		= '".Database::escape_string($dir_name_sql)."',
814
                                            title               = '".Database::escape_string($_POST['new_dir'])."',
815
                                            description 		= '".Database::escape_string($_POST['description'])."',
816
                                            author      		= '',
817
                                            active              = '1',
818
                                            accepted			= '1',
819
                                            filetype            = 'folder',
820
                                            post_group_id       = '".$group_id."',
821
                                            sent_date           = '".$today."',
822
                                            qualification       = '".(($_POST['qualification_value']!='') ? Database::escape_string($_POST['qualification_value']) : '') ."',
823
                                            parent_id           = '',
824
                                            qualificator_id     = '',
825
                                            date_of_qualification	= '0000-00-00 00:00:00',
826
                                            weight              = '".Database::escape_string($_POST['weight'])."',
827
                                            session_id          = '".intval($id_session)."',
828
                                            allow_text_assignment   = '".Database::escape_string($_POST['allow_text_assignment'])."',
829
                                            contains_file    = 0, 
830
                                            user_id 			= '".$user_id."'";
831

    
832
                    Database::query($sql_add_publication);
833

    
834
                    // add the directory
835
                    $id = Database::insert_id();
836
                    if ($id) {
837
                        // Insert into agenda
838
                        $agenda_id = 0;
839
                        $end_date = '';
840
                        if (isset($_POST['add_to_calendar']) && $_POST['add_to_calendar'] == 1) {
841
                            require_once api_get_path(SYS_CODE_PATH).'calendar/agenda.inc.php';
842
                            require_once api_get_path(SYS_CODE_PATH).'resourcelinker/resourcelinker.inc.php';						
843

    
844
                            // Setting today date
845
                            $date = $end_date = $time;
846

    
847
                            $title = sprintf(get_lang('HandingOverOfTaskX'), $_POST['new_dir']);
848
                            if (!empty($_POST['type1'])) {
849
                                $end_date = get_date_from_select('expires');
850
                                $date	  = $end_date;
851
                            }
852
                            $description = isset($_POST['description']) ? $_POST['description'] : '';
853
                            $content = '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;curdirpath='.api_substr($dir_name_sql, 1).'" >'.$_POST['new_dir'].'</a>'.$description;
854

    
855
                            $agenda_id = agenda_add_item($course_info, $title, $content, $date, $end_date, array('GROUP:'.$group_id), 0);
856
                        }
857
                    }
858

    
859
                    //Folder created
860
                    api_item_property_update($course_info, 'work', $id, 'DirectoryCreated', $user_id, $group_id);
861
                    Display :: display_confirmation_message(get_lang('DirectoryCreated'), false);
862

    
863
                    // insert into student_publication_assignment	
864
                    //return something like this: 2008-02-45 00:00:00
865

    
866
                    $enable_calification = isset($_POST['qualification_value']) && !empty($_POST['qualification_value']) ? 1 : 0;
867

    
868
                    if (!empty($_POST['type1']) || !empty($_POST['type2'])) {
869
                        
870
                        echo $sql_add_homework = "INSERT INTO $TSTDPUBASG SET
871
                                                c_id = $course_id ,
872
                                                expires_on       		= '".((isset($_POST['type1']) && $_POST['type1']==1) ? api_get_utc_datetime(get_date_from_select('expires')) : '0000-00-00 00:00:00'). "',
873
                                                ends_on        	 		= '".((isset($_POST['type2']) && $_POST['type2']==1) ? api_get_utc_datetime(get_date_from_select('ends')) : '0000-00-00 00:00:00')."',
874
                                                add_to_calendar  		= '$agenda_id',
875
                                                enable_qualification 	= '$enable_calification',
876
                                                publication_id 			= '$id'";
877
                        Database::query($sql_add_homework);	
878
                        $my_last_id = Database::insert_id();
879
                        $sql_add_publication = "UPDATE $work_table SET has_properties  = $my_last_id , view_properties = 1  WHERE c_id = $course_id AND id = $id";
880
                        Database::query($sql_add_publication);
881
                    } else {
882
                        $sql_add_homework = "INSERT INTO $TSTDPUBASG SET
883
                                                c_id = $course_id ,
884
                                                expires_on     = '0000-00-00 00:00:00',
885
                                                ends_on        = '0000-00-00 00:00:00',
886
                                                add_to_calendar  = '$agenda_id',
887
                                                enable_qualification = '".$enable_calification."',
888
                                                publication_id = '".$id."'";
889
                        Database::query($sql_add_homework);
890
                        $inserted_id = Database::insert_id();
891
                        $sql_add_publication = "UPDATE $work_table SET has_properties  = $inserted_id, view_properties = 0 WHERE c_id = $course_id AND id = $id";
892
                        Database::query($sql_add_publication);
893
                    }
894
                    if (!empty($_POST['category_id'])) {
895
                 
896
                        if (isset($_POST['make_calification']) && $_POST['make_calification'] == 1) {
897

    
898
                            require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/gradebookitem.class.php';
899
                            require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/evaluation.class.php';
900
                            require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/abstractlink.class.php';
901
                            require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
902

    
903
                            $resource_name = $_POST['new_dir'];
904
                            add_resource_to_course_gradebook($_POST['category_id'], api_get_course_id(), 3, $id, $resource_name, $_POST['weight'], $_POST['qualification_value'], $_POST['description'], 1, api_get_session_id());
905
                        }	
906
                    }
907
                    
908
                    if (api_get_course_setting('email_alert_students_on_new_homework') == 1) {
909
                        send_email_on_homework_creation(api_get_course_id());
910
                    }
911
                } else {
912
                    Display :: display_error_message(get_lang('CannotCreateDir'));
913
                }
914
            } else {
915
                $form->display();     
916
            }     	
917
        }
918
	case 'make_visible':
919
    case 'delete':
920
	case 'make_invisible':	
921
	case 'move':
922
	case 'move_to':
923
	case 'list':		
924
		/*	Move file command */
925
		if ($is_allowed_to_edit && $action == 'move_to') {
926
			$move_to_path = get_work_path($_REQUEST['move_to_id']);
927
		
928
			if ($move_to_path==-1) {
929
				$move_to_path = '/';
930
			} elseif (substr($move_to_path, -1, 1) != '/') {
931
				$move_to_path = $move_to_path .'/';
932
			}
933
			
934
			//security fix: make sure they can't move files that are not in the document table			
935
			if ($path = get_work_path($item_id)) {
936
			    
937
				if (move($course_dir.'/'.$path, $base_work_dir . $move_to_path)) {
938
					//update db		
939
					update_work_url($item_id, 'work' . $move_to_path, $_REQUEST['move_to_id']);
940
                    
941
                    api_item_property_update($_course, 'work', $_REQUEST['move_to_id'], 'FolderUpdated', $user_id);
942
                    
943
                    /*
944
					// update all the parents in the table item propery
945
					$list_id = get_parent_directories($move_to_path);
946
					for ($i = 0; $i < count($list_id); $i++) {
947
						api_item_property_update($_course, 'work', $list_id[$i], 'FolderUpdated', $user_id);
948
					}*/		
949
					Display :: display_confirmation_message(get_lang('DirMv'));
950
				} else {
951
					Display :: display_error_message(get_lang('Impossible'));
952
				}
953
			} else {
954
				Display :: display_error_message(get_lang('Impossible'));
955
			}
956
		}
957

    
958
		/*	Move file form request */
959
		if ($is_allowed_to_edit && $action == 'move') {
960
			if (!empty($item_id)) {
961
				$folders = array();
962
				$session_id = api_get_session_id();
963
				$session_id == 0 ? $withsession = " AND session_id = 0 " : $withsession = " AND session_id='".$session_id."'";			
964
				$sql = "SELECT id, url, title FROM $work_table 
965
				        WHERE c_id = $course_id AND active IN (0, 1) AND url LIKE '/%' AND post_group_id = '".$group_id."'".$withsession;                
966
				$res = Database::query($sql);
967
				while($folder = Database::fetch_array($res)) {
968
					$folders[$folder['id']] = $folder['title'];
969
				}
970
				echo build_work_move_to_selector($folders, $curdirpath, $item_id);
971
			}
972
		}
973
		
974
		/*	MAKE VISIBLE WORK COMMAND */
975
		if ($is_allowed_to_edit && $action == 'make_visible') {
976
			if (!empty($item_id)) {
977
				if (isset($item_id) && $item_id == 'all') {
978
					//never happens
979
					/*
980
					$sql = "ALTER TABLE  " . $work_table . " CHANGE accepted accepted TINYINT(1) DEFAULT '1'";
981
					Database::query($sql);
982
					$sql = "UPDATE  " . $work_table . " SET accepted = 1";
983
					Database::query($sql);
984
					Display::display_confirmation_message(get_lang('AllFilesVisible'));*/
985
				} else {
986
					$sql = "UPDATE " . $work_table . "	SET accepted = 1 WHERE c_id = $course_id AND id = '" . $item_id . "'";
987
					Database::query($sql);                    
988
                    api_item_property_update($course_info, 'work', $item_id, 'visible', api_get_user_id());
989
					Display::display_confirmation_message(get_lang('FileVisible'));
990
				}
991
			}
992
		}	
993
		
994
		if ($is_allowed_to_edit && $action == 'make_invisible') {
995
		
996
			/*	MAKE INVISIBLE WORK COMMAND */
997
			if (!empty($item_id)) {
998
				if (isset($item_id) && $item_id == 'all') {
999
					/*
1000
					$sql = "ALTER TABLE " . $work_table . "
1001
						CHANGE accepted accepted TINYINT(1) DEFAULT '0'";
1002
					Database::query($sql);
1003
					$sql = "UPDATE  " . $work_table . " SET accepted = 0";
1004
					Database::query($sql);
1005
					Display::display_confirmation_message(get_lang('AllFilesInvisible'));*/
1006
				} else {
1007
					$sql = "UPDATE  " . $work_table . " SET accepted = 0
1008
							WHERE c_id = $course_id AND id = '" . $item_id . "'";
1009
					Database::query($sql);
1010
                    api_item_property_update($course_info, 'work', $item_id, 'invisible', api_get_user_id());
1011
					Display::display_confirmation_message(get_lang('FileInvisible'));
1012
				}
1013
			}
1014
		}		
1015
		
1016
		/*	Delete dir command */
1017
		
1018
		if ($is_allowed_to_edit && !empty($_REQUEST['delete_dir'])) {
1019
            $delete_dir_id = intval($_REQUEST['delete_dir']);
1020
            $locked = api_resource_is_locked_by_gradebook($delete_dir_id, LINK_STUDENTPUBLICATION);
1021
            
1022
            if ($locked == false) {
1023
            
1024
                $work_to_delete = get_work_data_by_id($delete_dir_id);
1025
                del_dir($delete_dir_id);	
1026

    
1027
                // gets calendar_id from student_publication_assigment
1028
                $sql = "SELECT add_to_calendar FROM $TSTDPUBASG WHERE c_id = $course_id AND publication_id ='$delete_dir_id'";
1029
                $res = Database::query($sql);
1030
                $calendar_id = Database::fetch_row($res);
1031

    
1032
                // delete from agenda if it exists
1033
                if (!empty($calendar_id[0])) {
1034
                    $t_agenda   = Database::get_course_table(TABLE_AGENDA);
1035
                    $sql = "DELETE FROM $t_agenda WHERE c_id = $course_id AND id ='".$calendar_id[0]."'";
1036
                    Database::query($sql);
1037
                }
1038
                $sql = "DELETE FROM $TSTDPUBASG WHERE c_id = $course_id AND publication_id ='$delete_dir_id'";
1039
                Database::query($sql);
1040

    
1041
                $link_info = is_resource_in_course_gradebook(api_get_course_id(), 3 , $delete_dir_id, api_get_session_id());
1042
                $link_id = $link_info['id'];
1043
                if ($link_info !== false) {
1044
                    remove_resource_from_course_gradebook($link_id);
1045
                }            
1046
                Display :: display_confirmation_message(get_lang('DirDeleted') . ': '.$work_to_delete['title']);            
1047
            } else {
1048
                Display::display_warning_message(get_lang('ResourceLockedByGradebook'));
1049
            }
1050
		}
1051
		
1052
		/*	DELETE WORK COMMAND */
1053
		
1054
		if ($action == 'delete' && $item_id) {
1055
							
1056
            $file_deleted = false;	
1057
            $is_author = user_is_author($item_id);     
1058
            $work_data = get_work_data_by_id($item_id);            
1059
            $locked = api_resource_is_locked_by_gradebook($work_data['parent_id'], LINK_STUDENTPUBLICATION);
1060
            
1061
            if ( ($is_allowed_to_edit && $locked == false) || ($locked == false AND $is_author && api_get_course_setting('student_delete_own_publication') == 1 && $work_data['qualificator_id'] == 0)) {
1062
                //we found the current user is the author
1063
                $queryString1 	= "SELECT url, contains_file FROM  " . $work_table . "  WHERE c_id = $course_id AND id = $item_id";
1064
                $result1 		= Database::query($queryString1);
1065
                $row 			= Database::fetch_array($result1);
1066

    
1067
                if (Database::num_rows($result1) > 0) {
1068
                    $queryString2 	= "UPDATE " . $work_table . "  SET active  = 2 WHERE c_id = $course_id AND id = $item_id";
1069
                    $queryString3 	= "DELETE FROM  " . $TSTDPUBASG . "  WHERE c_id = $course_id AND publication_id = $item_id";
1070
                    Database::query($queryString2);
1071
                    Database::query($queryString3);						 
1072
                    api_item_property_update($_course, 'work', $item_id, 'DocumentDeleted', $user_id);
1073
                    $work = $row['url'];
1074

    
1075
                    if ($row['contains_file'] == 1) {
1076
                        if (!empty($work)) {
1077
                            if (api_get_setting('permanently_remove_deleted_files') == 'true') {
1078
                                my_delete($currentCourseRepositorySys.'/'.$work);
1079
                                Display::display_confirmation_message(get_lang('TheDocumentHasBeenDeleted'));
1080
                                $file_deleted = true;
1081
                            } else {                                
1082
                                $extension = pathinfo($work, PATHINFO_EXTENSION);                                
1083
                                $new_dir = $work.'_DELETED_'.$item_id.'.'.$extension;
1084

    
1085
                                if (file_exists($currentCourseRepositorySys.'/'.$work)) {
1086
                                    rename($currentCourseRepositorySys.'/'.$work, $currentCourseRepositorySys.'/'.$new_dir);
1087
                                    Display::display_confirmation_message(get_lang('TheDocumentHasBeenDeleted'));
1088
                                    $file_deleted = true;
1089
                                }
1090
                            }
1091
                        }
1092
                    } else {
1093
                        $file_deleted = true;
1094
                    }
1095
                }					
1096
            }
1097
            if (!$file_deleted) {
1098
                Display::display_error_message(get_lang('YouAreNotAllowedToDeleteThisDocument'));
1099
            }        
1100
		}		
1101
		
1102
		/*	Display list of student publications */		
1103
		if ($curdirpath == '/') {
1104
			$my_cur_dir_path = '';
1105
		} else {
1106
			$my_cur_dir_path = $curdirpath;
1107
		}		
1108
		
1109
		if (!empty($my_folder_data['description'])) {
1110
			echo '<p><div><strong>'.get_lang('Description').':</strong><p>'.Security::remove_XSS($my_folder_data['description'], STUDENT).'</p></div></p>';
1111
		}
1112
        
1113
        //User works
1114
        if (isset($work_id) && !empty($work_id) && !$display_list_users_without_publication) {
1115
            $work_data = get_work_assignment_by_id($work_id);                    
1116
            $check_qualification = intval($my_folder_data['qualification']);
1117
            
1118
            if (!empty($work_data['enable_qualification']) && !empty($check_qualification)) {
1119
                $type = 'simple';
1120
                $columns        = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), 
1121
                                        get_lang('Qualification'), get_lang('Date'),  get_lang('Status'), get_lang('Actions'));
1122
                $column_model   = array (
1123
                    array('name'=>'type',           'index'=>'file',            'width'=>'12',   'align'=>'left', 'search' => 'false'),                        
1124
                    array('name'=>'firstname',      'index'=>'firstname',       'width'=>'35',   'align'=>'left', 'search' => 'true'),                        
1125
                    array('name'=>'lastname',		'index'=>'lastname',        'width'=>'35',   'align'=>'left', 'search' => 'true'),
1126
                    array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),                                 
1127
                    array('name'=>'title',          'index'=>'title',           'width'=>'40',   'align'=>'left', 'search' => 'false', 'wrap_cell' => 'true'),
1128
    //                array('name'=>'file',           'index'=>'file',            'width'=>'20',   'align'=>'left', 'search' => 'false'),
1129
                    array('name'=>'qualification',	'index'=>'qualification',	'width'=>'20',   'align'=>'left', 'search' => 'true'),                        
1130
                    array('name'=>'sent_date',           'index'=>'sent_date',            'width'=>'50',   'align'=>'left', 'search' => 'true'),                        
1131
                    array('name'=>'qualificator_id','index'=>'qualificator_id', 'width'=>'30',   'align'=>'left', 'search' => 'true'),      
1132
                    array('name'=>'actions',        'index'=>'actions',         'width'=>'40',   'align'=>'left', 'search' => 'false', 'sortable'=>'false')
1133
                    
1134
                );
1135
            } else {
1136
                $type = 'complex';
1137
                $columns        = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), 
1138
                                         get_lang('Date'),  get_lang('Actions'));
1139
                $column_model   = array (
1140
                    array('name'=>'type',           'index'=>'file',            'width'=>'12',   'align'=>'left', 'search' => 'false'),                        
1141
                    array('name'=>'firstname',      'index'=>'firstname',       'width'=>'35',   'align'=>'left', 'search' => 'true'),                        
1142
                    array('name'=>'lastname',		'index'=>'lastname',        'width'=>'35',   'align'=>'left', 'search' => 'true'),
1143
                    array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),              
1144
                    array('name'=>'title',          'index'=>'title',           'width'=>'40',   'align'=>'left', 'search' => 'false', 'wrap_cell' => "true"),
1145
    //                array('name'=>'file',           'index'=>'file',            'width'=>'20',   'align'=>'left', 'search' => 'false'),
1146
                    //array('name'=>'qualification',	'index'=>'qualification',	'width'=>'20',   'align'=>'left', 'search' => 'true'),                        
1147
                    array('name'=>'sent_date',       'index'=>'sent_date',            'width'=>'50',   'align'=>'left', 'search' => 'true'),                        
1148
                    //array('name'=>'qualificator_id','index'=>'qualificator_id', 'width'=>'30',   'align'=>'left', 'search' => 'true'),      
1149
                    array('name'=>'actions',        'index'=>'actions',         'width'=>'40',   'align'=>'left', 'search' => 'false', 'sortable'=>'false')
1150
                );
1151
            }         
1152

    
1153
            $extra_params = array();
1154

    
1155
            //Autowidth             
1156
            $extra_params['autowidth'] = 'true';
1157

    
1158
            //height auto 
1159
            $extra_params['height'] = 'auto';
1160
            //$extra_params['excel'] = 'excel';
1161

    
1162
            //$extra_params['rowList'] = array(10, 20 ,30);
1163
            
1164
            $extra_params['sortname'] = 'firstname';            
1165
            $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_user_list&work_id='.$work_id.'&type='.$type;
1166
            ?>
1167
            <script>
1168
                $(function() {
1169
                <?php
1170
                echo Display::grid_js('results', $url, $columns, $column_model, $extra_params);                
1171
            ?>
1172
                 });
1173
            </script>
1174
            <?php                
1175
            echo Display::grid_html('results');                    
1176
        } elseif (isset($_GET['list']) && $_GET['list'] == 'without') {
1177
            //User with no works
1178
            display_list_users_without_publication($work_id);                
1179
        } else {
1180
            //Work list
1181
            display_student_publications_list($work_id, $link_target_parameter, $dateFormatLong, $origin, $add_query);
1182
        }		
1183
		break;
1184
}
1185
if ($origin != 'learnpath') {
1186
	//we are not in the learning path tool
1187
	Display :: display_footer();
1188
}
(2-2/3)