Project

General

Profile

Bug #2248 » dropbox_functions.inc.php

Jonas Fangstrom, 23/11/2010 09:06

 
1
<?php //$id: $
2
/* For licensing terms, see /dokeos_license.txt */
3
/**
4
* This file contains additional dropbox functions. Initially there were some
5
* functions in the init files also but I have moved them over
6
* to one file 		-- Patrick Cool <patrick.cool@UGent.be>, Ghent University
7
*/
8
require_once '../inc/global.inc.php';
9
/*
10
-----------------------------------------------------------
11
	Javascript
12
-----------------------------------------------------------
13
*/
14

    
15
$this_section=SECTION_COURSES;
16

    
17
$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
18
$htmlHeadXtra[] = '<script type="text/javascript">
19
function setFocus(){
20
$("#category_title").focus();
21
}
22
$(document).ready(function () {
23
  setFocus();
24
});
25
</script>';
26

    
27
/**
28
* This function is a wrapper function for the multiple actions feature.
29
* @return	Mixed	If there is a problem, return a string message, otherwise nothing
30
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
31
* @version march 2006
32
*/
33
function handle_multiple_actions()
34
{
35
	global $_user, $is_courseAdmin, $is_courseTutor;
36

    
37
	// STEP 1: are we performing the actions on the received or on the sent files?
38
	if($_POST['action']=='delete_received' || $_POST['action']=='download_received')
39
	{
40
		$part = 'received';
41
	}
42
	elseif($_POST['action']=='delete_sent' || $_POST['action']=='download_sent')
43
	{
44
		$part = 'sent';
45
	}
46

    
47
	// STEP 2: at least one file has to be selected. If not we return an error message
48
	foreach ($_POST as $key=>$value)
49
	{
50
		if (strstr($value,$part.'_') AND $key!='view_received_category' AND $key!='view_sent_category')
51
		{
52
			$checked_files=true;
53
			$checked_file_ids[]=intval(substr($value,strrpos($value,'_')));
54
		}
55
	}
56
	$checked_file_ids = $_POST['id'];
57

    
58
	if (!is_array($checked_file_ids) || count($checked_file_ids)==0)
59
	{
60
		return get_lang('CheckAtLeastOneFile');
61
	}
62

    
63

    
64
	// STEP 3A: deleting
65
	if ($_POST['action']=='delete_received' || $_POST['action']=='delete_sent')
66
	{
67
		$dropboxfile=new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
68
		foreach ($checked_file_ids as $key=>$value)
69
		{
70
			if ($_GET['view']=='received')
71
			{
72
				$dropboxfile->deleteReceivedWork($value);
73
				$message=get_lang('ReceivedFileDeleted');
74
			}
75
			if ($_GET['view']=='sent' OR empty($_GET['view']))
76
			{
77
				$dropboxfile->deleteSentWork($value);
78
				$message=get_lang('SentFileDeleted');
79
			}
80
		}
81
		return $message;
82
	}
83

    
84
	// STEP 3B: giving comment
85
	if ($_POST['actions']=='comment')
86
	{
87
		// This has not been implemented.
88
		// The idea was that it would be possible to write the same feedback for the selected documents.
89
	}
90

    
91
	// STEP 3C: moving
92
	if (strstr($_POST['action'], 'move_'))
93
	{
94
        	// check move_received_n or move_sent_n command
95
		if (strstr($_POST['action'],'received')){
96
                	$part = 'received';
97
                	$to_cat_id = str_replace('move_received_','',$_POST['action']);
98
        	}
99
        	else {
100
                	$part = 'sent';
101
                	$to_cat_id = str_replace('move_sent_','',$_POST['action']);
102
        	}
103

    
104
		foreach ($checked_file_ids as $key=>$value)
105
		{
106
			var_dump($value);
107
			var_dump($to_cat_id);
108
			var_dump($part);
109
			store_move($value, $to_cat_id, $part);
110
		}
111
		return get_lang('FilesMoved');
112
    }
113

    
114
	// STEP 3D: downloading
115
	if ($_POST['action']=='download_sent' || $_POST['action']=='download_received')
116
	{
117
		zip_download($checked_file_ids);
118
	}
119

    
120
}
121

    
122
/**
123
* This function deletes a dropbox category
124
*
125
* @todo give the user the possibility what needs to be done with the files in this category: move them to the root, download them as a zip, delete them
126
*
127
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
128
* @version march 2006
129
*/
130
function delete_category($action, $id)
131
{
132
	global $dropbox_cnf;
133
	global $_user, $is_courseAdmin, $is_courseTutor;
134

    
135
	// an additional check that might not be necessary
136
	if ($action=='deletereceivedcategory')
137
	{
138
		$sentreceived='received';
139
		$entries_table=$dropbox_cnf['tbl_post'];
140
		$id_field='file_id';
141
		$return_message = get_lang('ReceivedCatgoryDeleted');
142
	}
143
	elseif ($action=='deletesentcategory')
144
	{
145
		$sentreceived='sent';
146
		$entries_table=$dropbox_cnf['tbl_file'];
147
		$id_field='id';
148
		$return_message = get_lang('SentCatgoryDeleted');
149
	}
150
	else
151
	{
152
		return get_lang('Error');
153
	}
154

    
155
	// step 1: delete the category
156
	$sql="DELETE FROM ".$dropbox_cnf['tbl_category']." WHERE cat_id='".Database::escape_string($id)."' AND $sentreceived='1'";
157
	$result=Database::query($sql,__FILE__,__LINE__);
158

    
159
	// step 2: delete all the documents in this category
160
	$sql="SELECT * FROM ".$entries_table." WHERE cat_id='".Database::escape_string($id)."'";
161
	$result=Database::query($sql,__FILE__,__LINE__);
162

    
163
	while ($row=Database::fetch_array($result))
164
	{
165
		$dropboxfile=new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
166
		if ($action=='deletereceivedcategory')
167
		{
168
			$dropboxfile->deleteReceivedWork($row[$id_field]);
169
		}
170
		if ($action=='deletesentcategory')
171
		{
172
			$dropboxfile->deleteSentWork($row[$id_field]);
173
		}
174
	}
175
	return $return_message;
176
}
177

    
178
/**
179
* Displays the form to move one individual file to a category
180
*
181
* @return html code of the form that appears in a dokeos message box.
182
*
183
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
184
* @version march 2006
185
*/
186
function display_move_form($part, $id, $target=array())
187
{
188
	echo '<div class="row"><div class="form_header">'.get_lang('MoveFileTo').'</div></div>';
189
	echo '<form name="form1" method="post" action="'.api_get_self().'?view_received_category='.$_GET['view_received_category'].'&view_sent_category='.$_GET['view_sent_category'].'&view='.$_GET['view'].'">';
190
	echo '<input type="hidden" name="id" value="'.Security::remove_XSS($id).'">';
191
	echo '<input type="hidden" name="part" value="'.Security::remove_XSS($part).'">';
192
	echo '
193
			<div class="row">
194
				<div class="label">
195
					<span class="form_required">*</span> '.get_lang('MoveFileTo').'
196
				</div>
197
				<div class="formw">';
198
	echo '<select name="move_target">';
199
	echo '<option value="0">'.get_lang('Root').'</option>';
200
	foreach ($target as $key=>$category)
201
	{
202
		echo '<option value="'.$category['cat_id'].'">'.$category['cat_name'].'</option>';
203
	}
204
	echo  '</select>';
205
	echo '	</div>
206
			</div>';
207

    
208
	echo '
209
		<div class="row">
210
			<div class="label">
211
			</div>
212
			<div class="formw">
213
				<button class="next" type="submit" name="do_move" value="'.get_lang('Ok').'">'.get_lang('MoveFile').'</button>
214
			</div>
215
		</div>
216
	';
217
	echo '</form>';
218

    
219
	echo '<div style="clear: both;"></div>';
220
}
221

    
222
/**
223
* This function moves a file to a different category
224
*
225
* @param $id the id of the file we are moving
226
* @param $target the id of the folder we are moving to
227
* @param $part are we moving a received file or a sent file?
228
*
229
* @return language string
230
*
231
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
232
* @version march 2006
233
*/
234
function store_move($id, $target, $part)
235
{
236
	global $_user;
237
	global $dropbox_cnf;
238

    
239
	if ((isset($id) AND $id<>'') AND (isset($target) AND $target<>'') AND (isset($part) AND $part<>''))
240
	{
241
		if ($part=='received')
242
		{
243
			$sql="UPDATE ".$dropbox_cnf["tbl_post"]." SET cat_id='".Database::escape_string($target)."'
244
						WHERE dest_user_id='".Database::escape_string($_user['user_id'])."'
245
						AND file_id='".Database::escape_string($id)."'
246
						";
247
			Database::query($sql,__FILE__,__LINE__);
248
			$return_message=get_lang('ReceivedFileMoved');
249
		}
250
		if ($part=='sent')
251
		{
252
			$sql="UPDATE ".$dropbox_cnf["tbl_file"]." SET cat_id='".Database::escape_string($target)."'
253
						WHERE uploader_id='".Database::escape_string($_user['user_id'])."'
254
						AND id='".Database::escape_string($id)."'
255
						";
256
			Database::query($sql,__FILE__,__LINE__);
257
			$return_message=get_lang('SentFileMoved');
258
		}
259
	}
260
	else
261
	{
262
		$return_message=get_lang('NotMovedError');
263
	}
264
	return $return_message;
265
}
266

    
267
/**
268
* This functions displays all teh possible actions that can be performed on multiple files. This is the dropdown list that
269
* appears below the sortable table of the sent / or received files.
270
*
271
* @return html value for the dropdown list
272
*
273
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
274
* @version march 2006
275
*/
276
function display_action_options($part, $categories, $current_category=0)
277
{
278
	echo '<select name="actions">';
279
	echo '<option value="download">'.get_lang('Download').'</option>';
280
	echo '<option value="delete">'.get_lang('Delete').'</option>';
281
	if(is_array($categories))
282
	{
283
		echo '<optgroup label="'.get_lang('MoveTo').'">';
284
		if ($current_category<>0)
285
		{
286
			echo '<option value="move_0">'.get_lang('Root').'</a>';
287
		}
288
		foreach ($categories as $key=>$value)
289
		{
290
			if( $current_category<>$value['cat_id'])
291
			{
292
				echo '<option value="move_'.$value['cat_id'].'">'.$value['cat_name'].'</option>';
293
			}
294
		}
295
		echo '</optgroup>';
296
	}
297
	echo '</select>';
298
	echo '<input type="submit" name="do_actions_'.Security::remove_XSS($part).'" value="'.get_lang('Ok').'" />';
299
}
300

    
301
/**
302
* this function returns the html code that displays the checkboxes next to the files so that
303
* multiple actions on one file are possible.
304
*
305
* @param $id the unique id of the file
306
* @param $part are we dealing with a sent or with a received file?
307
*
308
* @return html code
309
*
310
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
311
* @version march 2006
312
*/
313
function display_file_checkbox($id, $part)
314
{
315
	if (isset($_GET['selectall']))
316
	{
317
		$checked='checked';
318
	}
319
	$return_value='<input type="checkbox" name="'.Security::remove_XSS($part).'_'.Security::remove_XSS($id).'" value="'.Security::remove_XSS($id).'" '.$checked.' />';
320
	return $return_value;
321
}
322

    
323

    
324
/**
325
* This function retrieves all the dropbox categories and returns them as an array
326
*
327
* @param $filter default '', when we need only the categories of the sent or the received part.
328
*
329
* @return array
330
*
331
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
332
* @version march 2006
333
*/
334
function get_dropbox_categories($filter='')
335
{
336
	global $_user;
337
	global $dropbox_cnf;
338

    
339
	$return_array=array();
340
	
341
	$session_id = api_get_session_id();
342
	$condition_session = api_get_session_condition($session_id);
343
		
344
	$sql="SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE user_id='".$_user['user_id']."' $condition_session";
345

    
346
	$result=Database::query($sql,__FILE__,__LINE__);
347
	while ($row=Database::fetch_array($result))
348
	{
349
		if(($filter=='sent' AND $row['sent']==1) OR ($filter=='received' AND $row['received']==1) OR $filter=='')
350
		{
351
			$return_array[$row['cat_id']]=$row;
352
		}
353
	}
354

    
355
	return $return_array;
356
}
357

    
358
/**
359
* This functions stores a new dropboxcategory
360
*
361
* @var 	it might not seem very elegant if you create a category in sent and in received with the same name that you get two entries in the
362
*		dropbox_category table but it is the easiest solution. You get
363
*		cat_name | received | sent | user_id
364
*		test	 |	  1		|	0  |	237
365
*		test	 |	  0		|	1  |	237
366
*		more elegant would be
367
*		test	 |	  1		|	1  |	237
368
*
369
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
370
* @version march 2006
371
*/
372
function store_addcategory()
373
{
374
	global $_user;
375
	global $dropbox_cnf;
376

    
377
	// check if the target is valid
378
	if ($_POST['target']=='sent')
379
	{
380
		$sent=1;
381
		$received=0;
382
	}
383
	elseif ($_POST['target']=='received')
384
	{
385
		$sent=0;
386
		$received=1;
387
	}
388
	else
389
	{
390
		return get_lang('Error');
391
	}
392

    
393
	// check if the category name is valid
394
	if ($_POST['category_name']=='')
395
	{
396
		return array('type' => 'error', 'message'=>get_lang('ErrorPleaseGiveCategoryName'));
397
	}
398

    
399
	if (!$_POST['edit_id'])
400
	{
401
		$session_id = api_get_session_id();
402
		// step 3a, we check if the category doesn't already exist
403
		$sql="SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE user_id='".$_user['user_id']."' AND cat_name='".Database::escape_string(Security::remove_XSS($_POST['category_name']))."' AND received='".$received."' AND sent='$sent' AND session_id='$session_id'";
404
		$result=Database::query($sql,__FILE__,__LINE__);
405

    
406

    
407
		// step 3b, we add the category if it does not exist yet.
408
		if (Database::num_rows($result)==0)
409
		{
410
			$sql="INSERT INTO ".$dropbox_cnf['tbl_category']." (cat_name, received, sent, user_id, session_id)
411
					VALUES ('".Database::escape_string(Security::remove_XSS($_POST['category_name']))."', '".Database::escape_string($received)."', '".Database::escape_string($sent)."', '".Database::escape_string($_user['user_id'])."',$session_id)";
412
			Database::query($sql,__FILE__,__LINE__);
413
			return array('type' => 'confirmation', 'message'=>get_lang('CategoryStored'));
414
		}
415
		else
416
		{
417
			return array('type' => 'error', 'message'=>get_lang('CategoryAlreadyExistsEditIt'));
418
		}
419
	}
420
	else
421
	{
422
		$sql="UPDATE ".$dropbox_cnf['tbl_category']." SET cat_name='".Database::escape_string(Security::remove_XSS($_POST['category_name']))."', received='".Database::escape_string($received)."' , sent='".Database::escape_string($sent)."'
423
				WHERE user_id='".Database::escape_string($_user['user_id'])."'
424
				AND cat_id='".Database::escape_string(Security::remove_XSS($_POST['edit_id']))."'";
425
		Database::query($sql,__FILE__,__LINE__);
426
		return array('type' => 'confirmation', 'message'=>get_lang('CategoryModified'));
427
	}
428
}
429

    
430
/**
431
* This function displays the form to add a new category.
432
*
433
* @param $category_name this parameter is the name of the category (used when no section is selected)
434
* @param $id this is the id of the category we are editing.
435
*
436
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
437
* @version march 2006
438
*/
439
function display_addcategory_form($category_name='', $id='',$action)
440
{
441
	global $dropbox_cnf;
442

    
443
	$title=get_lang('AddNewCategory');
444

    
445
	if (isset($id) AND $id<>'')
446
	{
447
		// retrieve the category we are editing
448
		$sql="SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE cat_id='".Database::escape_string($id)."'";
449
		$result=Database::query($sql,__FILE__,__LINE__);
450
		$row=Database::fetch_array($result);
451

    
452
		if ($category_name=='') // after an edit with an error we do not want to return to the original name but the name we already modified. (happens when createinrecievedfiles AND createinsentfiles are not checked)
453
		{
454
			$category_name=$row['cat_name'];
455
		}
456
		if ($row['received']=='1')
457
		{
458
			$target='received';
459
		}
460
		if ($row['sent']=='1')
461
		{
462
			$target='sent';
463
		}
464
		$title=get_lang('EditCategory');
465

    
466
	}
467

    
468
	if ($action=='addreceivedcategory') {
469
		$target='received';
470
	}
471
	if ($action=='addsentcategory') {
472
		$target='sent';
473
	}
474

    
475
	if ($action=='editcategory') {
476
		$text=get_lang('ModifyCategory');
477
		$class='save';
478
	} else if ($action=='addreceivedcategory' or $action=='addsentcategory')  {
479
		$text=get_lang('CreateCategory');
480
		$class='add';
481
	}
482

    
483

    
484
	echo "<form name=\"add_new_category\" method=\"post\" action=\"".api_get_self()."?view=".Security::remove_XSS($_GET['view'])."\">\n";
485
	if (isset($id) AND $id<>'')
486
	{
487
		echo '<input name="edit_id" type="hidden" value="'.Security::remove_XSS($id).'">';
488
	}
489
	echo '<input name="action" type="hidden" value="'.Security::remove_XSS($action).'">';
490
	echo '<input name="target" type="hidden" value="'.$target.'">';
491

    
492
	echo '<div class="row"><div class="form_header">'.$title.'</div></div>';
493

    
494
	echo '	<div class="row">
495
				<div class="label">
496
					<span class="form_required">*</span> '.get_lang('CategoryName').'
497
				</div>
498
				<div class="formw">';
499
	if ($_POST AND empty($_POST['category_name']))
500
	{
501
		echo '<span class="form_error">'.get_lang('ThisFieldIsRequired').'. '.get_lang('ErrorPleaseGiveCategoryName').'<span><br />';
502
	}
503
	if ($_POST AND !empty($_POST['category_name']))
504
	{
505
		echo '<span class="form_error">'.get_lang('CategoryAlreadyExistsEditIt').'<span><br />';
506
	}
507
	echo '			<input type="text" id="category_title" name="category_name" value="'.Security::remove_XSS($category_name).'" />
508
				</div>
509
			</div>';
510

    
511
	echo '	<div class="row">
512
				<div class="label">
513
				</div>
514
				<div class="formw">
515
					<button class="'.$class.'" type="submit" name="StoreCategory">'.$text.'</button>
516
				</div>
517
			</div>';
518
	echo '	<div class="row">
519
				<div class="label">
520
				</div>
521
				<div class="formw">
522
					<span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>
523
				</div>
524
			</div>';
525
	echo '</form>';
526
	echo '<div style="clear: both;"></div>';
527
}
528

    
529
/**
530
* this function displays the form to upload a new item to the dropbox.
531
*
532
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
533
* @version march 2006
534
*/
535
function display_add_form()
536
{
537
	global $_user, $is_courseAdmin, $is_courseTutor, $course_info, $origin, $dropbox_unid;
538

    
539
	$token = Security::get_token();
540
	$dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
541
	?>
542
	<form method="post" action="index.php?view_received_category=<?php echo Security::remove_XSS($_GET['view_received_category']); ?>&view_sent_category=<?php echo Security::remove_XSS($_GET['view_sent_category']); ?>&view=<?php echo Security::remove_XSS($_GET['view']); ?>&<?php echo "origin=$origin"."&".api_get_cidreq(); ?>" enctype="multipart/form-data" onsubmit="return checkForm(this)">
543

    
544
	<div class="row"><div class="form_header"><?php echo get_lang('UploadNewFile'); ?></div></div>
545

    
546
	<div class="row">
547
		<div class="label">
548
			<span class="form_required">*</span><?php echo dropbox_lang("uploadFile")?>:
549
		</div>
550
		<div class="formw">
551
				<input type="hidden" name="MAX_FILE_SIZE" value='<?php echo dropbox_cnf("maxFilesize")?>' />
552
				<input type="file" name="file" size="20" <?php if (dropbox_cnf("allowOverwrite")) echo 'onChange="checkfile(this.value)"'; ?> />
553
				<input type="hidden" name="dropbox_unid" value="<?php echo $dropbox_unid ?>" />
554
				<input type="hidden" name="sec_token" value="<?php echo $token ?>" />
555
				<?php
556
				if ($origin=='learnpath')
557
				{
558
					echo '<input type="hidden" name="origin" value="learnpath" />';
559
				}
560
				?>
561
		</div>
562
	</div>
563

    
564
	<?php
565
	if (dropbox_cnf("allowOverwrite"))
566
	{
567
		?>
568
		<div class="row">
569
			<div class="label">
570

    
571
			</div>
572
			<div class="formw">
573
				<input type="checkbox" name="cb_overwrite" id="cb_overwrite" value="true" /><?php echo dropbox_lang("overwriteFile")?>
574
			</div>
575
		</div>
576
		<?php
577
	}
578
	?>
579

    
580
	<div class="row">
581
		<div class="label">
582
			<?php echo dropbox_lang("sendTo")?>
583
		</div>
584
		<div class="formw">
585
	<?php
586

    
587
	//list of all users in this course and all virtual courses combined with it
588
	if(isset($_SESSION['id_session'])){
589
		$complete_user_list_for_dropbox = array();
590
		if(api_get_setting('dropbox_allow_student_to_student')=='true' || $_user['status'] != STUDENT)
591
		{
592
			$complete_user_list_for_dropbox = CourseManager :: get_user_list_from_course_code($course_info['code'],true,$_SESSION['id_session']);
593
		}
594
		$complete_user_list2 = CourseManager :: get_coach_list_from_course_code($course_info['code'],$_SESSION['id_session']);
595
		$complete_user_list_for_dropbox = array_merge($complete_user_list_for_dropbox,$complete_user_list2);
596
	}
597
	else{
598
		if(api_get_setting('dropbox_allow_student_to_student')=='true' || $_user['status'] != STUDENT)
599
		{
600
			$complete_user_list_for_dropbox = CourseManager :: get_user_list_from_course_code($course_info['code'],true,$_SESSION['id_session']);
601
		}
602
		else
603
		{
604
			$complete_user_list_for_dropbox = CourseManager :: get_teacher_list_from_course_code($course_info['code']);
605
		}
606
	}    
607

    
608
	
609

    
610
	foreach ($complete_user_list_for_dropbox as $k => $e) {
611
	    $complete_user_list_for_dropbox[$k] = $e + array('lastcommafirst' => api_get_person_name($e['firstname'], $e['lastname']));
612
	}
613

    
614
	$complete_user_list_for_dropbox = TableSort::sort_table($complete_user_list_for_dropbox, 'lastcommafirst');
615

    
616
	?>
617

    
618
				<select name="recipients[]" size="
619
	<?php
620
		if ( $dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin)
621
		{
622
			echo 10;
623
		}
624
		else
625
		{
626
			echo 6;
627
		}
628

    
629

    
630
	?>" multiple style="width: 350px;">
631
	<?php
632

    
633
	/*
634
		Create the options inside the select box:
635
		List all selected users their user id as value and a name string as display
636
	*/
637

    
638
	$current_user_id = '';
639
	foreach ($complete_user_list_for_dropbox as $current_user)
640
	{
641
		if ( ($dropbox_person -> isCourseTutor
642
		|| $dropbox_person -> isCourseAdmin
643
		|| dropbox_cnf("allowStudentToStudent")	// RH: also if option is set
644
		|| $current_user['status']!=5				// always allow teachers
645
		|| $current_user['tutor_id']==1				// always allow tutors
646
		) && $current_user['user_id'] != $_user['user_id'] ) 	// don't include yourself
647
		{
648
			if ($current_user['user_id'] == $current_user_id) continue;
649
			$full_name = $current_user['lastcommafirst'];
650
			$current_user_id = $current_user['user_id'];
651
			echo '<option value="user_' . $current_user_id . '">' . $full_name . '</option>';
652
		}
653
	}
654

    
655
	/*
656
	* Show groups
657
	*/
658
    if ( ($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin)
659
    && dropbox_cnf("allowGroup") || dropbox_cnf("allowStudentToStudent"))
660
    {
661
		$complete_group_list_for_dropbox = GroupManager::get_group_list(null,dropbox_cnf("courseId"));
662

    
663
		if (count($complete_group_list_for_dropbox) > 0)
664
		{
665
			foreach ($complete_group_list_for_dropbox as $current_group)
666
			{
667
				if ($current_group['number_of_members'] > 0)
668
				{
669
					echo '<option value="group_'.$current_group['id'].'">G: '.$current_group['name'].' - '.$current_group['number_of_members'].' '.get_lang('Users').'</option>';
670
				}
671
			}
672
		}
673
    }
674

    
675
    if ( ($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin) && dropbox_cnf("allowMailing"))  // RH: Mailing starting point
676
	{
677
			// echo '<option value="mailing">'.dropbox_lang("mailingInSelect").'</option>';
678
	}
679

    
680
    if ( dropbox_cnf("allowJustUpload"))  // RH
681
    {
682
	  //echo '<option value="upload">'.dropbox_lang("justUploadInSelect").'</option>';
683
	  echo '<option value="user_'.$_user['user_id'].'">'.dropbox_lang("justUploadInSelect").'</option>';
684
    }
685

    
686
		echo '</select>
687
		</div>
688
	</div>';
689

    
690
	echo '
691
		<div class="row">
692
			<div class="label">
693
			</div>
694
			<div class="formw">
695
				<button type="Submit" class="upload" name="submitWork">'.dropbox_lang("upload", "noDLTT").'</button>
696
			</div>
697
		</div>
698
	';
699

    
700
	echo "</form>";
701
}
702

    
703
/**
704
* returns username or false if user isn't registered anymore
705
* @todo check if this function is still necessary. There might be a library function for this.
706
*/
707
function getUserNameFromId ( $id)  // RH: Mailing: return 'Mailing ' + id
708
{
709
    $mailingId = $id - dropbox_cnf("mailingIdBase");
710
    if ( $mailingId > 0)
711
    {
712
	    return dropbox_lang("mailingAsUsername", "noDLTT") . $mailingId;
713
    }
714
    $id = intval($id);
715
    $sql = "SELECT ".(api_is_western_name_order() ? "CONCAT(firstname,' ', lastname)" : "CONCAT(lastname,' ', firstname)")." AS name
716
			FROM " . dropbox_cnf("tbl_user") . "
717
			WHERE user_id='$id'";
718
    $result = Database::query($sql,__FILE__,__LINE__);
719
    $res = Database::fetch_array( $result);
720

    
721
    if ( $res == FALSE) return FALSE;
722
    return stripslashes( $res["name"]);
723
}
724

    
725
/**
726
* returns loginname or false if user isn't registered anymore
727
* @todo check if this function is still necessary. There might be a library function for this.
728
*/
729
function getLoginFromId ( $id)
730
{
731
    $id = intval($id);
732
    $sql = "SELECT username
733
			FROM " . dropbox_cnf("tbl_user") . "
734
			WHERE user_id='$id'";
735
    $result =Database::query($sql,__FILE__,__LINE__);
736
    $res = Database::fetch_array( $result);
737
    if ( $res == FALSE) return FALSE;
738
    return stripslashes( $res["username"]);
739
}
740

    
741
/**
742
* @return boolean indicating if user with user_id=$user_id is a course member
743
* @todo eliminate global
744
* @todo check if this function is still necessary. There might be a library function for this.
745
*/
746
function isCourseMember( $user_id)
747
{
748
    global $_course;
749
	$course_code = $_course['sysCode'];
750
	$is_course_member = CourseManager::is_user_subscribed_in_course($user_id, $course_code,true);
751
	return $is_course_member;
752
}
753

    
754
/**
755
* Checks if there are files in the dropbox_file table that aren't used anymore in dropbox_person table.
756
* If there are, all entries concerning the file are deleted from the db + the file is deleted from the server
757
*/
758
function removeUnusedFiles( )
759
{
760
    // select all files that aren't referenced anymore
761
    $sql = "SELECT DISTINCT f.id, f.filename
762
			FROM " . dropbox_cnf("tbl_file") . " f
763
			LEFT JOIN " . dropbox_cnf("tbl_person") . " p ON f.id = p.file_id
764
			WHERE p.user_id IS NULL";
765
    $result = Database::query($sql,__FILE__,__LINE__);
766
    while ( $res = Database::fetch_array( $result))
767
    {
768
		//delete the selected files from the post and file tables
769
        $sql = "DELETE FROM " . dropbox_cnf("tbl_post") . " WHERE file_id='" . $res['id'] . "'";
770
        $result1 = Database::query($sql,__FILE__,__LINE__);
771
        $sql = "DELETE FROM " . dropbox_cnf("tbl_file") . " WHERE id='" . $res['id'] . "'";
772
        $result1 = Database::query($sql,__FILE__,__LINE__);
773

    
774
		//delete file from server
775
        @unlink( dropbox_cnf("sysPath") . "/" . $res["filename"]);
776
    }
777
}
778

    
779
/**
780
* RH: Mailing (2 new functions)
781
*
782
* Mailing zip-file is posted to (dest_user_id = ) mailing pseudo_id
783
* and is only visible to its uploader (user_id).
784
*
785
* Mailing content files have uploader_id == mailing pseudo_id, a normal recipient,
786
* and are visible initially to recipient and pseudo_id.
787
*
788
* @author René Haentjens, Ghent University
789
*
790
* @todo check if this function is still necessary.
791
*/
792
function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '')
793
{
794
    $mailingPseudoId = intval($mailingPseudoId);
795
    $sql = "SELECT f.uploader_id
796
			FROM " . dropbox_cnf("tbl_file") . " f
797
			LEFT JOIN " . dropbox_cnf("tbl_post") . " p ON f.id = p.file_id
798
			WHERE p.dest_user_id = '" . $mailingPseudoId . "'";
799
    $result = Database::query($sql,__FILE__,__LINE__);
800

    
801
    if (!($res = Database::fetch_array($result)))
802
        die(dropbox_lang("generalError")." (code 901)");
803

    
804
    if ($owner == 0) return $res['uploader_id'];
805

    
806
    if ($res['uploader_id'] == $owner) return TRUE;
807

    
808
    die(dropbox_lang("generalError")." (code ".$or_die.")");
809
}
810
/**
811
* @author Ren� Haentjens, Ghent University
812
* @todo check if this function is still necessary.
813
*/
814
function removeMoreIfMailing($file_id)
815
{
816
    // when deleting a mailing zip-file (posted to mailingPseudoId):
817
    // 1. the detail window is no longer reachable, so
818
    //    for all content files, delete mailingPseudoId from person-table
819
    // 2. finding the owner (getUserOwningThisMailing) is no longer possible, so
820
    //    for all content files, replace mailingPseudoId by owner as uploader
821
    $file_id = intval($file_id);
822
    $sql = "SELECT p.dest_user_id
823
			FROM " . dropbox_cnf("tbl_post") . " p
824
			WHERE p.file_id = '" . $file_id . "'";
825
    $result = Database::query($sql,__FILE__,__LINE__);
826

    
827
    if ( $res = Database::fetch_array( $result))
828
    {
829
	    $mailingPseudoId = $res['dest_user_id'];
830
	    if ( $mailingPseudoId > dropbox_cnf("mailingIdBase"))
831
	    {
832
	        $sql = "DELETE FROM " . dropbox_cnf("tbl_person") . " WHERE user_id='" . $mailingPseudoId . "'";
833
	        $result1 = Database::query($sql,__FILE__,__LINE__);
834

    
835
	        $sql = "UPDATE " . dropbox_cnf("tbl_file") .
836
	            " SET uploader_id='" . api_get_user_id() . "' WHERE uploader_id='" . $mailingPseudoId . "'";
837
	        $result1 = Database::query($sql,__FILE__,__LINE__);
838
        }
839
    }
840
}
841

    
842
/**
843
* The dropbox has a deviant naming scheme for language files so it needs an additional language function
844
*
845
* @todo check if this function is still necessary.
846
*
847
* @author René Haentjens, Ghent University
848
*/
849
function dropbox_lang($variable, $notrans = 'DLTT')
850
{
851
    global $charset;
852
    return (api_get_setting('server_type') == 'test' ?
853
        get_lang('dropbox_lang["'.$variable.'"]', $notrans) :
854
        api_html_entity_decode(api_to_system_encoding(str_replace("\\'", "'", $GLOBALS['dropbox_lang'][$variable]), null, true), ENT_QUOTES, $charset));
855
}
856
/**
857
* Function that finds a given config setting
858
*
859
* @author René Haentjens, Ghent University
860
*/
861
function dropbox_cnf($variable)
862
{
863
    return $GLOBALS['dropbox_cnf'][$variable];
864
}
865

    
866

    
867

    
868

    
869

    
870
/**
871
*
872
*/
873
function store_add_dropbox()
874
{
875
	global $dropbox_cnf;
876
	global $_user;
877
	global $_course;
878

    
879
	// ----------------------------------------------------------
880
	// Validating the form data
881
	// ----------------------------------------------------------
882

    
883
	// the author is
884
	/*
885
    if (!isset( $_POST['authors']))
886
    {
887
        return get_lang('AuthorFieldCannotBeEmpty');
888
    }
889
    */
890

    
891
    // there are no recipients selected
892
	if ( !isset( $_POST['recipients']) || count( $_POST['recipients']) <= 0)
893
    {
894
        return get_lang('YouMustSelectAtLeastOneDestinee');
895
    }
896
    // Check if all the recipients are valid
897
    else
898
    {
899
        $thisIsAMailing = FALSE;  // RH: Mailing selected as destination
900
        $thisIsJustUpload = FALSE;  // RH
901
	    foreach( $_POST['recipients'] as $rec)
902
        {
903
			if ( $rec == 'mailing')
904
			{
905
				$thisIsAMailing = TRUE;
906
			}
907
			elseif ( $rec == 'upload')
908
			{
909
				$thisIsJustUpload = TRUE;
910
			}
911
			elseif (strpos($rec, 'user_') === 0 && !isCourseMember(substr($rec, strlen('user_') ) ))
912
			{
913
		        return get_lang('InvalideUserDetected');
914
			}
915
			elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0)
916
			{
917
				return get_lang('InvalideGroupDetected');
918
			}
919
        }
920
    }
921

    
922
	// we are doing a mailing but an additional recipient is selected
923
	if ( $thisIsAMailing && ( count($_POST['recipients']) != 1))
924
	{
925
		return get_lang('MailingSelectNoOther');
926
	}
927

    
928
	// we are doing a just upload but an additional recipient is selected.
929
	// note: why can't this be valid? It is like sending a document to yourself AND to a different person (I do this quite often with my e-mails)
930
	if ( $thisIsJustUpload && ( count($_POST['recipients']) != 1))
931
	{
932
		return get_lang('mailingJustUploadSelectNoOther');
933
	}
934

    
935
	if ( empty( $_FILES['file']['name']))
936
	{
937
		$error = TRUE;
938
		return  get_lang('NoFileSpecified');
939
	}
940

    
941
	// ----------------------------------------------------------
942
	// are we overwriting a previous file or sending a new one
943
	// ----------------------------------------------------------
944
	$dropbox_overwrite = false;
945
	if ( isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']==true)
946
	{
947
		$dropbox_overwrite = true;
948
	}
949

    
950
	// ----------------------------------------------------------
951
	// doing the upload
952
	// ----------------------------------------------------------
953
	$dropbox_filename = $_FILES['file']['name'];
954
	$dropbox_filesize = $_FILES['file']['size'];
955
	$dropbox_filetype = $_FILES['file']['type'];
956
	$dropbox_filetmpname = $_FILES['file']['tmp_name'];
957

    
958
	// check if the filesize does not exceed the allowed size.
959
	if ( $dropbox_filesize <= 0 || $dropbox_filesize > $dropbox_cnf["maxFilesize"])
960
	{
961
		return get_lang('DropboxFileTooBig');
962
	}
963

    
964
	// check if the file is actually uploaded
965
	if ( !is_uploaded_file( $dropbox_filetmpname)) // check user fraud : no clean error msg.
966
	{
967
		return get_lang('TheFileIsNotUploaded');
968
	}
969

    
970
	// Try to add an extension to the file if it hasn't got one
971
	$dropbox_filename = add_ext_on_mime( $dropbox_filename,$dropbox_filetype);
972
	// Replace dangerous characters
973
	$dropbox_filename = replace_dangerous_char( $dropbox_filename);
974
	// Transform any .php file in .phps fo security
975
	$dropbox_filename = php2phps ( $dropbox_filename);
976
	//filter extension
977
    if(!filter_extension($dropbox_filename))
978
    {
979
    	return get_lang('UplUnableToSaveFileFilteredExtension');
980
    }
981

    
982
	// set title
983
	$dropbox_title = $dropbox_filename;
984
	// set author
985
	if ( $_POST['authors'] == '')
986
	{
987
		$_POST['authors'] = getUserNameFromId( $_user['user_id']);
988
	}
989

    
990
	// note: I think we could better migrate everything from here on to separate functions: store_new_dropbox, store_new_mailing, store_just_upload
991

    
992
	if ($dropbox_overwrite)  // RH: Mailing: adapted
993
	{
994
		$dropbox_person = new Dropbox_Person( $_user['user_id'], api_is_course_admin(), api_is_course_tutor());
995

    
996
		foreach($dropbox_person->sentWork as $w)
997
		{
998
			if ($w->title == $dropbox_filename)
999
			{
1000
			    if ( ($w->recipients[0]['id'] > dropbox_cnf("mailingIdBase")) xor $thisIsAMailing)
1001
			    {
1002
					return get_lang('MailingNonMailingError');
1003
				}
1004
				if ( ($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload)
1005
				{
1006
					return get_lang('MailingJustUploadSelectNoOther');
1007
				}
1008
				$dropbox_filename = $w->filename;
1009
				$found = true; // note: do we still need this?
1010
				break;
1011
			}
1012
		}
1013
	}
1014
	else  // rename file to login_filename_uniqueId format
1015
	{
1016
		$dropbox_filename = getLoginFromId( $_user['user_id']) . "_" . $dropbox_filename . "_".uniqid('');
1017
	}
1018

    
1019
	// creating the array that contains all the users who will receive the file
1020
	$new_work_recipients = array();
1021
	foreach ($_POST["recipients"] as $rec)
1022
	{
1023
		if (strpos($rec, 'user_') === 0)
1024
		{
1025
			$new_work_recipients[] = substr($rec, strlen('user_') );
1026
		}
1027
		elseif (strpos($rec, 'group_') === 0 )
1028
		{
1029
			$userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_') ));
1030
			foreach ($userList as $usr)
1031
			{
1032
				if (! in_array($usr['user_id'], $new_work_recipients) && $usr['user_id'] != $_user['user_id'])
1033
				{
1034
					$new_work_recipients[] = $usr['user_id'];
1035
				}
1036
			}
1037
		}
1038
	}
1039

    
1040
	@move_uploaded_file( $dropbox_filetmpname, dropbox_cnf("sysPath") . '/' . $dropbox_filename);
1041

    
1042
	$b_send_mail = api_get_course_setting('email_alert_on_new_doc_dropbox');
1043

    
1044
	if($b_send_mail)
1045
	{
1046
		foreach($new_work_recipients as $recipient_id)
1047
		{
1048
			include_once(api_get_path(LIBRARY_PATH) . 'usermanager.lib.php');
1049
			$recipent_temp=UserManager :: get_user_info_by_id($recipient_id);
1050
			api_mail(api_get_person_name($recipent_temp['firstname'].' '.$recipent_temp['lastname'], null, PERSON_NAME_EMAIL_ADDRESS), $recipent_temp['email'],
1051
				get_lang('NewDropboxFileUploaded'),
1052
				get_lang('NewDropboxFileUploadedContent').' '.api_get_path(WEB_CODE_PATH).'dropbox/index.php?cidReq='.$_course['sysCode']."\n\n".api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS)."\n".  get_lang('Email') ." : ".$_user['mail'], api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS), $_user['mail']);
1053
				//get_lang('NewDropboxFileUploadedContent').' '.api_get_path(WEB_CODE_PATH).'dropbox/index.php?cidReq='.$_course['sysCode']."\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS)."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator'), api_get_person_name(api_get_setting('administratorName')." ".api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS), api_get_setting('emailAdministrator'));
1054
		}
1055
	}
1056

    
1057
	new Dropbox_SentWork( $_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $new_work_recipients);
1058

    
1059
	Security::clear_token();
1060
    return get_lang('FileUploadSucces');
1061
}
1062

    
1063

    
1064

    
1065
/**
1066
* This function displays the firstname and lastname of the user as a link to the user tool.
1067
*
1068
* @see this is the same function as in the new forum, so this probably has to move to a user library.
1069
*
1070
* @todo move this function to the user library
1071
*
1072
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1073
* @version march 2006
1074
*/
1075
function display_user_link($user_id, $name='')
1076
{
1077
	global $_otherusers;
1078

    
1079
	if ($user_id<>0)
1080
	{
1081
		if ($name=='')
1082
		{
1083
			$table_user = Database::get_main_table(TABLE_MAIN_USER);
1084
			$sql="SELECT * FROM $table_user WHERE user_id='".Database::escape_string($user_id)."'";
1085
			$result=Database::query($sql,__FILE__,__LINE__);
1086
			$row=Database::fetch_array($result);
1087
			return "<a href=\"../user/userInfo.php?uInfo=".$row['user_id']."\">".api_get_person_name($row['firstname'], $row['lastname'])."</a>";
1088
		}
1089
		else
1090
		{
1091
            $user_id = intval($user_id);
1092
			return "<a href=\"../user/userInfo.php?uInfo=".$user_id."\">".Security::remove_XSS($name)."</a>";
1093
		}
1094
	}
1095
	else
1096
	{
1097
		return $name.' ('.get_lang('Anonymous').')';
1098
	}
1099
}
1100

    
1101
/**
1102
* this function transforms the array containing all the feedback into something visually attractive.
1103
*
1104
* @param an array containing all the feedback about the given message.
1105
*
1106
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1107
* @version march 2006
1108
*/
1109
function feedback($array)
1110
{
1111

    
1112
	foreach ($array as $key=>$value)
1113
	{
1114
		$output.=format_feedback($value);
1115
	}
1116
	$output.=feedback_form();
1117
	return $output;
1118
}
1119

    
1120
/**
1121
* This function returns the html code to display the feedback messages on a given dropbox file
1122
* @param $feedback_array an array that contains all the feedback messages about the given document.
1123
* @return html code
1124
* @todo add the form for adding new comment (if the other party has not deleted it yet).
1125
*
1126
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1127
* @version march 2006
1128
*/
1129
function format_feedback($feedback)
1130
{
1131
	$output.=display_user_link($feedback['author_user_id']);
1132
	$output.='&nbsp;&nbsp;['.$feedback['feedback_date'].']<br />';
1133
	$output.='<div style="padding-top:6px">'.nl2br($feedback['feedback']).'</div><hr size="1" noshade/><br />';
1134
	return $output;
1135
}
1136

    
1137
/**
1138
* this function returns the code for the form for adding a new feedback message to a dropbox file.
1139
* @return html code
1140
*
1141
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1142
* @version march 2006
1143
*/
1144
function feedback_form()
1145
{
1146
	global $dropbox_cnf;
1147

    
1148
	$return = get_lang('AddNewFeedback').'<br />';
1149

    
1150
	// we now check if the other users have not delete this document yet. If this is the case then it is useless to see the
1151
	// add feedback since the other users will never get to see the feedback.
1152
	$sql="SELECT * FROM ".$dropbox_cnf["tbl_person"]." WHERE file_id='".Database::escape_string($_GET['id'])."'";
1153
	$result=Database::query($sql,__LINE__, __FILE__);
1154
	$number_users_who_see_file=Database::num_rows($result);
1155
	if ($number_users_who_see_file>1)
1156
	{
1157
		$token = Security::get_token();
1158
		$return .= '<textarea name="feedback" style="width: 80%; height: 80px;"></textarea>';
1159
		$return .= '<input type="hidden" name="sec_token" value="'.$token.'"/>';		
1160
		$return .= '<br /><button type="submit" class="add" name="store_feedback" value="'.get_lang('Ok').'"
1161
					onclick="document.form_tablename.attributes.action.value = document.location;">'.get_lang('AddComment').'</button>';
1162
	}
1163
	else
1164
	{
1165
		$return .= get_lang('AllUsersHaveDeletedTheFileAndWillNotSeeFeedback');
1166
	}
1167
	return $return;
1168
}
1169

    
1170
/**
1171
* @return a language string (depending on the success or failure.
1172
*
1173
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1174
* @version march 2006
1175
*/
1176
function store_feedback()
1177
{
1178
	global $dropbox_cnf;
1179
	global $_user;
1180

    
1181
	if (!is_numeric($_GET['id']))
1182
	{
1183
		return get_lang('FeedbackError');
1184
	}
1185

    
1186
	if ($_POST['feedback']=='')
1187
	{
1188
		return get_lang('PleaseTypeText');
1189
	}
1190
	else
1191
	{
1192
		$sql="INSERT INTO ".$dropbox_cnf['tbl_feedback']." (file_id, author_user_id, feedback, feedback_date) VALUES
1193
				('".Database::escape_string($_GET['id'])."','".Database::escape_string($_user['user_id'])."','".Database::escape_string($_POST['feedback'])."',NOW())";
1194
		Database::query($sql,__FILE__,__LINE__);
1195
		return get_lang('DropboxFeedbackStored');
1196
	}
1197
}
1198

    
1199
/**
1200
* This function downloads all the files of the inputarray into one zip
1201
* @param $array an array containing all the ids of the files that have to be downloaded.
1202
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1203
* @todo consider removing the check if the user has received or sent this file (zip download of a folder already sufficiently checks for this).
1204
* @todo integrate some cleanup function that removes zip files that are older than 2 days
1205
*
1206
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1207
* @version march 2006
1208
*/
1209
function zip_download ($array)
1210
{
1211
	global $_course;
1212
	global $dropbox_cnf;
1213
	global $_user;
1214
	global $files;
1215

    
1216
	$sys_course_path = api_get_path(SYS_COURSE_PATH);
1217

    
1218
	// zip library for creation of the zipfile
1219
	include(api_get_path(LIBRARY_PATH)."/pclzip/pclzip.lib.php");
1220

    
1221
	// place to temporarily stash the zipfiles
1222
	$temp_zip_dir = api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/";
1223

    
1224
	// create the directory if it does not exist yet.
1225
	if(!is_dir($temp_zip_dir))
1226
	{
1227
		mkdir($temp_zip_dir);
1228
	}
1229

    
1230
	cleanup_temp_dropbox();
1231

    
1232
	$files='';
1233

    
1234
	// note: we also have to add the check if the user has received or sent this file. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1235
	$sql="SELECT distinct file.filename, file.title, file.author, file.description
1236
			FROM ".$dropbox_cnf["tbl_file"]." file, ".$dropbox_cnf["tbl_person"]." person
1237
			WHERE file.id IN (".implode(', ',$array).")
1238
			AND file.id=person.file_id
1239
			AND person.user_id='".$_user['user_id']."'";
1240
	$result=Database::query($sql,__FILE__,__LINE__);
1241
	while ($row=Database::fetch_array($result))
1242
	{
1243
		$files[$row['filename']]=array('filename'=>$row['filename'],'title'=>$row['title'], 'author'=>$row['author'], 'description'=>$row['description']);
1244
	}
1245

    
1246
	//$alternative is a variable that uses an alternative method to create the zip
1247
	// because the renaming of the files inside the zip causes error on php5 (unexpected end of archive)
1248
	$alternative=true;
1249
	if ($alternative)
1250
	{
1251
		zip_download_alternative($files);
1252
		exit;
1253
	}
1254

    
1255
	// create the zip file
1256
    $name = 'dropboxdownload-'.$_user['user_id'].'-'.mktime().'.zip';
1257
	$temp_zip_file=$temp_zip_dir.'/'.$name;
1258
	$zip_folder=new PclZip($temp_zip_file);
1259

    
1260
	foreach ($files as $key=>$value)
1261
	{
1262
		// met hernoemen van de files in de zip
1263
		$zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox/".$value['filename'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox", PCLZIP_CB_PRE_ADD, 'my_pre_add_callback');
1264
		// zonder hernoemen van de files in de zip
1265
		//$zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox/".$value['filename'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox");
1266
	}
1267

    
1268
	// create the overview file
1269
	$overview_file_content=generate_html_overview($files, array('filename'), array('title'));
1270
	$overview_file=$temp_zip_dir.'/overview.html';
1271
	$handle=fopen($overview_file,'w');
1272
	fwrite($handle,$overview_file_content);
1273

    
1274

    
1275
	// send the zip file
1276
	DocumentManager::file_send_for_download($temp_zip_file,true,$name);
1277
	exit;
1278
}
1279
/**
1280
* This is a callback function to decrypt the files in the zip file to their normal filename (as stored in the database)
1281
* @param $p_event a variable of PCLZip
1282
* @param $p_header a variable of PCLZip
1283
*
1284
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1285
* @version march 2006
1286
*/
1287
function my_pre_add_callback($p_event, &$p_header)
1288
{
1289
	global $files;
1290

    
1291
	$p_header['stored_filename']=$files[$p_header['stored_filename']]['title'];
1292
	return 1;
1293
}
1294

    
1295
/**
1296
* This function is an alternative zip download. It was added because PCLZip causes problems on PHP5 when using PCLZIP_CB_PRE_ADD and a callback function to rename
1297
* the files inside the zip file (dropbox scrambles the files to prevent
1298
* @todo consider using a htaccess that denies direct access to the file but only allows the php file to access it. This would remove the scrambling requirement
1299
*		but it would require additional checks to see if the filename of the uploaded file is not used yet.
1300
* @param $files is an associative array that contains the files that the user wants to download (check to see if the user is allowed to download these files already
1301
*		 happened so the array is clean!!. The key is the filename on the filesystem. The value is an array that contains both the filename on the filesystem and
1302
*		 the original filename (that will be used in the zip file)
1303
* @todo when we copy the files there might be two files with the same name. We need a function that (recursively) checks this and changes the name
1304
*
1305
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1306
* @version march 2006
1307
*/
1308
function zip_download_alternative($files)
1309
{
1310
	global $_course;
1311
	global $_user;
1312

    
1313
	$temp_zip_dir = api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/";
1314

    
1315
	// Step 2: we copy all the original dropbox files to the temp folder and change their name into the original name
1316
	foreach ($files as $key=>$value)
1317
	{
1318
		$value['title']=check_file_name(api_strtolower($value['title']));
1319
		$files[$value['filename']]['title']=$value['title'];
1320
		copy(api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox/".$value['filename'], api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$value['title']);
1321
	}
1322

    
1323
	// Step 3: create the zip file and add all the files to it
1324
	$temp_zip_file=$temp_zip_dir.'/dropboxdownload-'.$_user['user_id'].'-'.mktime().'.zip';
1325
	$zip_folder=new PclZip($temp_zip_file);
1326
	foreach ($files as $key=>$value)
1327
	{
1328
		$zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$value['title'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/temp");
1329
	}
1330

    
1331
	// Step 1: create the overview file and add it to the zip
1332
	$overview_file_content=generate_html_overview($files, array('filename'), array('title'));
1333
	$overview_file=$temp_zip_dir.'overview'.replace_dangerous_char(api_is_western_name_order() ? $_user['firstname'].$_user['lastname'] : $_user['lastname'].$_user['firstname'], 'strict').'.html';
1334
	$handle=fopen($overview_file,'w');
1335
	fwrite($handle,$overview_file_content);
1336
	// todo: find a different solution for this because even 2 seconds is no guarantee.
1337
	sleep(2);
1338

    
1339
	// Step 4: we add the overview file
1340
	$zip_folder->add($overview_file,PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/temp");
1341

    
1342
	// Step 5: send the file for download;
1343
	DocumentManager::file_send_for_download($temp_zip_file,true);
1344

    
1345
	// Step 6: remove the files in the temp dir
1346
	foreach ($files as $key=>$value)
1347
	{
1348
		unlink(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$value['title']);
1349
	}
1350
	//unlink($overview_file);
1351

    
1352
	exit;
1353
}
1354

    
1355
/**
1356
* @desc This function checks if the real filename of the dropbox files doesn't already exist in the temp folder. If this is the case then
1357
*		it will generate a different filename;
1358
*
1359
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1360
* @version march 2006
1361
*/
1362
function check_file_name($file_name_2_check, $counter=0)
1363
{
1364
	global $_course;
1365

    
1366
	$new_file_name=$file_name_2_check;
1367
	if ($counter<>0)
1368
	{
1369
		$new_file_name=$counter.$new_file_name;
1370
	}
1371

    
1372
	if (!file_exists(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$new_file_name))
1373
	{
1374
		return $new_file_name;
1375
	}
1376
	else
1377
	{
1378
		$counter++;
1379
		$new_file_name=check_file_name($file_name_2_check,$counter);
1380
		return $new_file_name;
1381
	}
1382
}
1383

    
1384

    
1385
/**
1386
* @desc Cleans the temp zip files that were created when users download several files or a whole folder at once.
1387
*		T
1388
* @return true
1389
* @todo
1390
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1391
* @version march 2006
1392
*/
1393

    
1394
function cleanup_temp_dropbox()
1395
{
1396
	global $_course;
1397

    
1398
	$handle=opendir(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp");
1399
	while (false !== ($file = readdir($handle)))
1400
	{
1401
		if ($file<>'.' OR $file<>'..')
1402
		{
1403
			$name=str_replace('.zip', '',$file);
1404
			$name_part=explode('-',$name);
1405
			$timestamp_of_file=$name_part[count($name_part)-1];
1406
			// if it is a dropboxdownloadfile and the file is older than one day then we delete it
1407
			if (strstr($file, 'dropboxdownload') AND $timestamp_of_file<(mktime()-86400))
1408
			{
1409
				unlink(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$file);
1410
			}
1411
		}
1412

    
1413
	}
1414
	closedir($handle);
1415
	return true;
1416
}
1417

    
1418
/**
1419
* @desc generates the contents of a html file that gives an overview of all the files in the zip file.
1420
*		This is to know the information of the files that are inside the zip file (who send it, the comment, ...)
1421
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1422
* @version march 2006
1423
*/
1424
function generate_html_overview($files, $dont_show_columns=array(), $make_link=array())
1425
{
1426
	$return="<html>\n<head>\n\t<title>".get_lang('OverviewOfFilesInThisZip')."</title>\n</head>";
1427
	$return.="\n\n<body>\n<table border=\"1px\">";
1428

    
1429
	$counter=0;
1430
	foreach ($files as $key=>$value)
1431
	{
1432
		// We add the header
1433
		if ($counter==0)
1434
		{
1435
			$columns_array=array_keys($value);
1436
			$return.="\n<tr>";
1437
			foreach ($columns_array AS $columns_array_key=>$columns_array_value)
1438
			{
1439
				if (!in_array($columns_array_value,$dont_show_columns))
1440
				{
1441
					$return.="\n\t<th>".$columns_array_value."</th>";
1442
				}
1443
				$column[]=$columns_array_value;
1444
			}
1445
			$return.="</tr><n";
1446
		}
1447
		$counter++;
1448

    
1449
		// We add the content
1450
		$return.="\n<tr>";
1451
		foreach ($column AS $column_key=>$column_value)
1452
		{
1453
			if (!in_array($column_value,$dont_show_columns))
1454
			{
1455
				$return.="\n\t<td>";
1456
				if (in_array($column_value, $make_link))
1457
				{
1458
					$return.='<a href="'.$value[$column_value].'">'.$value[$column_value].'</a>';
1459
				}
1460
				else
1461
				{
1462
					$return.=$value[$column_value];
1463
				}
1464
				$return.="</td>";
1465
			}
1466
		}
1467
		$return.="</tr><n";
1468

    
1469

    
1470
	}
1471
	$return.="\n</table>\n\n</body>";
1472
	$return.="\n</html>";
1473

    
1474
	return $return;
1475
}
1476

    
1477
/**
1478
* @desc This function retrieves the number of feedback messages on every document. This function might become obsolete when
1479
* 		the feedback becomes user individual.
1480
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1481
* @version march 2006
1482
*/
1483
function get_total_number_feedback($file_id='')
1484
{
1485
	global $dropbox_cnf;
1486

    
1487
	$sql="SELECT COUNT(feedback_id) AS total, file_id FROM ".$dropbox_cnf['tbl_feedback']." GROUP BY file_id";
1488
	$result=Database::query($sql, __FILE__, __LINE__);
1489
	while ($row=Database::fetch_array($result))
1490
	{
1491
		$return[$row['file_id']]=$row['total'];
1492
	}
1493
	return $return;
1494
}
1495

    
1496

    
1497
/**
1498
* @desc this function checks if the key exists. If this is the case it returns the value, if not it returns 0
1499
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1500
* @version march 2006
1501
*/
1502
function check_number_feedback($key, $array)
1503
{
1504
	if (is_array($array))
1505
	{
1506
		if (key_exists($key,$array))
1507
		{
1508
			return $array[$key];
1509
		}
1510
		else
1511
		{
1512
			return 0;
1513
		}
1514
	}
1515
	else
1516
	{
1517
		return 0;
1518
	}
1519
}
1520

    
1521

    
1522

    
1523

    
1524

    
1525

    
1526
/**
1527
 * Get the last access to a given tool of a given user
1528
 * @param $tool string the tool constant
1529
 * @param $course_code the course_id
1530
 * @param $user_id the id of the user
1531
 * @return string last tool access date
1532
 *
1533
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
1534
 * @version march 2006
1535
 *
1536
 * @todo consider moving this function to a more appropriate place.
1537
 */
1538
function get_last_tool_access($tool, $course_code='', $user_id='')
1539
{
1540
	global $_course, $_user;
1541

    
1542
	// The default values of the parameters
1543
	if ($course_code=='')
1544
	{
1545
		$course_code=$_course['id'];
1546
	}
1547
	if ($user_id=='')
1548
	{
1549
		$user_id=$_user['user_id'];
1550
	}
1551

    
1552
	// the table where the last tool access is stored (=track_e_lastaccess)
1553
	$table_last_access=Database::get_statistic_table('track_e_lastaccess');
1554

    
1555
	$sql="SELECT access_date FROM $table_last_access WHERE access_user_id='".Database::escape_string($user_id)."'
1556
				AND access_cours_code='".Database::escape_string($course_code)."'
1557
				AND access_tool='".Database::escape_string($tool)."'
1558
				ORDER BY access_date DESC
1559
				LIMIT 1";
1560
	$result=Database::query($sql,__FILE__,__LINE__);
1561
	$row=Database::fetch_array($result);
1562
	return $row['access_date'];
1563
}
    (1-1/1)