### Eclipse Workspace Patch 1.0
#P CONTRIB
Index: plugins/blocks/file_manager/sharing.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/file_manager/sharing.php,v
retrieving revision 1.1
diff -u -r1.1 sharing.php
--- plugins/blocks/file_manager/sharing.php	30 Jan 2006 01:26:09 -0000	1.1
+++ plugins/blocks/file_manager/sharing.php	24 Feb 2008 22:33:34 -0000
@@ -1,226 +1,236 @@
-<?php
-/**********************************************************/
-// sharing.php
-// 
-// This file allows users to view a list of people who are
-// currently enrolled in the current course (if courseid == 1
-// then all people are shown)  This also shows groups as specified
-// in the course variables. This allows students to share a link
-// or group of links or a folder/category? to an individual, 
-// group, all students, or any combination.
-/*********************************************************/
-	global $USER, $CFG;
-    require_once("../../config.php");
-    require_once("lib.php");
-	require_once("print_lib.php");
-	
-	$id = required_param(id, PARAM_INT);
-	$linkid = optional_param(linkid, NULL, PARAM_INT);		// only used when clicking action button, not by using dropdown menu
-	$from = optional_param(from, "link", PARAM_ALPHA);		// link/cat/folder
-	$rootdir = optional_param(rootdir, 0, PARAM_INT);		// specifies the working dir
-	$msg = "";  // For storing various warnings
-	$cb = fm_clean_checkbox_arr();
-
-	if ($linkid != NULL && $linkid != 0) {
-		$cb = array($linkid);
-	} 
-	// Cleaning for checkbox array (users)
-	$cbu = NULL;
-	$cbu = $_POST['cbu'];		// Checkbox array
-	if (is_array($cbu)) {
-		$tmp = array();
-		foreach($cbu as $c) {
-			$tmp[] = (int)$c;
-		}
-		$cbu = $tmp;
-	} else {
-		//$cbu[] = (int)$cb;
-	}	
-
-    if (! $course = get_record("course", "id", $id) ) {
-        error("That's an invalid course id", "view.php?id=$id&rootdir=$rootdir");
-    }
-	require_login($course->id);
-	
-	$courselink = "";
-	if ($course->id != 1) {		// To print link to home page
-		$courselink .= "<a href=$SESSION->fromdiscussion>$course->shortname</a> -> ";
-	}	
-	
-	// Ensures the user is able to view the fmanager and can share files
-	fm_check_access_rights($course->id, true, true);	
-	$type = 0; 		// Link shared by default
-	if ($from == "link") {
-		$type = 0;
-		foreach ($cb as $c) {
-			if (substr($c, 0, 2) == 'f-') {
-				fm_user_owns_folder(substr($c,2));
-			} else {
-				fm_user_owns_link($c);
-			}
-		}
-	} else if ($from == "category") {
-		$type = 1;
-		foreach ($cb as $c) {
-			fm_user_owns_cat($c);
-		}
-	} else if ($from == "folder") {
-		// $from is folder only when sharing 1 folder
-		$type = 2;
-	}
-	
-	if(isset($_POST['share'])) {
-		if ($course->id != 1) {
-			$count = count_records("user_students","course",$course->id);
-			$count += count_records("user_teachers","course",$course->id);
-		} else {
-			$count = count_records("user", "idnumber", "");
-		}
-		// Deletes all existing records for the file in the course
-		foreach ($cb as $c) {
-			$tmp = $c;
-			$tmptype = $type;
-			if (substr($c, 0, 2) == "f-") {
-				$tmp = substr($c, 2);
-				$tmptype = 2;
-			}
-			if ($tmp != 0) {
-				delete_records("fmanager_shared", "owner = $USER->id AND type", $tmptype, "course", $course->id, "sharedlink", $tmp);
-			}
-		}
-		if (is_array($cbu)) {
-			// If they are sharing to everyone in the course
-			if ($cbu[0] != 0) { $count--;}		// Dont include the check-all checkbox
-			
-			if (count($cbu) == $count) {
-				foreach($cb as $c) {
-					if ($c != 0 || substr($c, 0, 2) == "f-") {
-						$entry = NULL;
-						$entry->owner = $USER->id;
-						$entry->course = $course->id;
-						if (substr($c, 0, 2) == "f-") {
-							$entry->type = STYPE_FOLD;		// Folder type
-							$entry->sharedlink = substr($c, 2);
-						} else {
-							$entry->type = $type;
-							$entry->sharedlink = $c;
-						}
-						$entry->userid = 0;			// Represents share to all
-						$entry->viewed = 1;			// Removes the viewed flag
-						if (!insert_record("fmanager_shared", $entry)) {
-							notify(get_string('errnoinsert',"block_file_manager"));
-						}
-					}
-				}
-			} else {
-				// Shares each file to each user
-				foreach($cbu as $u) {
-					if ($u != 0) {
-						foreach($cb as $c) {
-							if ($c != 0 || substr($c, 0, 2) == "f-") {
-								$entry = NULL;
-								$entry->owner = $USER->id;
-								$entry->course = $course->id;
-								if (substr($c, 0, 2) == "f-") {
-									$entry->type = STYPE_FOLD;
-									$entry->sharedlink = substr($c,2);
-								} else {
-									$entry->type = $type;
-									$entry->sharedlink = $c;
-								}
-								$entry->userid = $u;
-								if (!insert_record("fmanager_shared", $entry)) {
-									notify(get_string('errnoinsert','block_file_manager'));
-								}					
-							}
-						}
-					}
-				}
-			}		
-		}
-		redirect("view.php?id=$id&rootdir=$rootdir");
-	} else if (isset($_POST['cancel'])) {
-		redirect("view.php?id=$id&rootdir=$rootdir");
-	}
-
-	// selects all the checkboxes for the form
-	echo "<script language=\"javascript\">
-			<!--
-				function selectboxes(allbox, whichform) {
-					if (whichform == 1) {
-						for (var i = 0; i < document.shareform[\"cbu[]\"].length; i++) {
-							document.shareform[\"cbu[]\"][i].checked = allbox.checked;
-						}
-					} else if (whichform == 2) {
-						for (var i = 0; i < document.gshareform[\"cbu[]\"].length; i++) {
-							document.gshareform[\"cbu[]\"][i].checked = allbox.checked;
-						}
-					}
-				}
-			-->
-			</script>";
-		
-    print_header(strip_tags(get_string("addlink", "block_file_manager")), "$course->fullname",
-        " $courselink <a href=\"view.php?id=$id&rootdir=$rootdir\">".get_string("filemanager", "block_file_manager")."</a> -> ".get_string("btnfilesharing", "block_file_manager"), "", "", true, "",
-        navmenu($course, 1),"","");
-	
-	// Means that the all checkbox was checked, but there were no files checked
-	$tmp = $cb[0];
-	if (substr($tmp, 0, 2) == "f-") {
-		$tmp = substr($tmp,2);
-	}
-	if (($tmp == 0) && (count($cb) == 1)) {
-		notify(get_string('msgnofilessel','block_file_manager'));		
-		redirect("view.php?id=$id&rootdir=$rootdir", 3);
-	}
-	
-	print_heading(get_string("msgsharetoothers", "block_file_manager"));
-    echo "<br>";
-	// Warns that sharing more than one file will delete all their other shared properties
-	if (count($cb) > 1) {
-		$msg = text_to_html(get_string("msgsharemulti","block_file_manager"));
-	}
-	$msg = text_to_html(get_string("msgshare","block_file_manager")).$msg;
-    print_simple_box($msg, "center");
-	echo "<br>";
-	
-	echo "<form name=\"shareform\" action=\"sharing.php?id=$id&linkid=$linkid&from=$from&rootdir=$rootdir\" method=\"post\">";
-	if (count($cb) == 1) {
-		$linkid = $cb[0];
-	}
-	print_table(fm_print_share_course_members($course->id, $linkid, $type));
-	// Stores $cb id's
-	if ($cb != NULL) {
-		foreach($cb as $c) {
-			echo "<input type=\"hidden\" name=\"cb[]\" value=\"$c\">";
-		}
-	}
-	echo "<center>";
-	echo "<input type=\"submit\" value=\"".get_string("btnshare","block_file_manager")."\" name=\"share\">";
-	echo "&nbsp;&nbsp;<input type=\"submit\" value=\"".get_string("btncancel","block_file_manager")."\" name=\"cancel\">";
-	echo "</center></form>";
-	
-	// If no groups...wont display any group info
-	if ($course->groupmode == NOGROUPS) {
-		print_footer();
-		die();
-	}
-	echo "<form name=\"gshareform\" action=\"sharing.php?id=$id&linkid=$linkid&from=$from&rootdir=$rootdir\" method=\"post\">";
-	// Always displays all groups to teachers
-	if (isteacher($course->id) || ($course->groupmode == VISIBLEGROUPS)) {
-		echo fm_print_visible_groups();
-	} else {
-		if ($course->groupmode == SEPARATEGROUPS) {
-			echo fm_print_separate_groups();
-		}
-	}
-	// Stores $cb id's
-	if ($cb != NULL) {
-		foreach($cb as $c) {
-			echo "<input type=\"hidden\" name=\"cb[]\" value=\"$c\">";
-		}
-	}
-	echo "<input type=\"hidden\" value=\"$rootdir\" name=\"rootdir\">";
-	echo "</form>";	
-	print_footer();
+<?php
+/**********************************************************/
+// sharing.php
+// 
+// This file allows users to view a list of people who are
+// currently enrolled in the current course (if courseid == 1
+// then all people are shown)  This also shows groups as specified
+// in the course variables. This allows students to share a link
+// or group of links or a folder/category? to an individual, 
+// group, all students, or any combination.
+/*********************************************************/
+	global $USER, $CFG;
+    require_once("../../config.php");
+    require_once("lib.php");
+	require_once("print_lib.php");
+	
+	$id = required_param(id, PARAM_INT);
+	$linkid = optional_param(linkid, NULL, PARAM_INT);		// only used when clicking action button, not by using dropdown menu
+	$from = optional_param(from, "link", PARAM_ALPHA);		// link/cat/folder
+	$rootdir = optional_param(rootdir, 0, PARAM_INT);		// specifies the working dir
+	$msg = "";  // For storing various warnings
+	$cb = fm_clean_checkbox_arr();
+
+	if ($linkid != NULL && $linkid != 0) {
+		$cb = array($linkid);
+	} 
+	// Cleaning for checkbox array (users)
+	$cbu = NULL;
+	$cbu = $_POST['cbu'];		// Checkbox array
+	if (is_array($cbu)) {
+		$tmp = array();
+		foreach($cbu as $c) {
+			$tmp[] = (int)$c;
+		}
+		$cbu = $tmp;
+	} else {
+		//$cbu[] = (int)$cb;
+	}	
+
+    if (! $course = get_record("course", "id", $id) ) {
+        error("That's an invalid course id", "view.php?id=$id&rootdir=$rootdir");
+    }
+	require_login($course->id);
+	
+	$courselink = "";
+	if ($course->id != 1) {		// To print link to home page
+		$courselink .= "<a href=$SESSION->fromdiscussion>$course->shortname</a> -> ";
+	}	
+	
+	// Ensures the user is able to view the fmanager and can share files
+	fm_check_access_rights($course->id, true, true);	
+	$type = 0; 		// Link shared by default
+	if ($from == "link") {
+		$type = 0;
+		foreach ($cb as $c) {
+			if (substr($c, 0, 2) == 'f-') {
+				fm_user_owns_folder(substr($c,2));
+			} else {
+				fm_user_owns_link($c);
+			}
+		}
+	} else if ($from == "category") {
+		$type = 1;
+		foreach ($cb as $c) {
+			fm_user_owns_cat($c);
+		}
+	} else if ($from == "folder") {
+		// $from is folder only when sharing 1 folder
+		$type = 2;
+	}
+	
+	if(isset($_POST['share'])) {
+		if ($course->id != 1) {
+			//DWT, Moodle 1.8 fix - uses role and context
+			$count = 0;
+			if ($course_context = get_context_instance(CONTEXT_COURSE, $course->id)){
+				$count = count_records('role_assignments', 'contextid', $course_context->id);
+			}
+			//$count = count_records("user_students","course",$course->id);
+			//$count += count_records("user_teachers","course",$course->id);
+		} else {
+			//DWT, I consider this as a bug since users can change the idnumber
+			//and this query becomes bad!
+			//$count = count_records("user", "idnumber", "");
+			$count = count_records("user");
+		}
+		// Deletes all existing records for the file in the course
+		foreach ($cb as $c) {
+			$tmp = $c;
+			$tmptype = $type;
+			if (substr($c, 0, 2) == "f-") {
+				$tmp = substr($c, 2);
+				$tmptype = 2;
+			}
+			if ($tmp != 0) {
+				//DWT - future enhancement, one DB call for every shared file, too expensive
+				//Should look into combining all the deletes in one DB call.
+				delete_records("fmanager_shared", "owner = $USER->id AND type", $tmptype, "course", $course->id, "sharedlink", $tmp);
+			}
+		}
+		if (is_array($cbu)) {
+			// If they are sharing to everyone in the course
+			if ($cbu[0] != 0) { $count--;}		// Dont include the check-all checkbox
+			
+			if (count($cbu) == $count) {
+				foreach($cb as $c) {
+					if ($c != 0 || substr($c, 0, 2) == "f-") {
+						$entry = NULL;
+						$entry->owner = $USER->id;
+						$entry->course = $course->id;
+						if (substr($c, 0, 2) == "f-") {
+							$entry->type = STYPE_FOLD;		// Folder type
+							$entry->sharedlink = substr($c, 2);
+						} else {
+							$entry->type = $type;
+							$entry->sharedlink = $c;
+						}
+						$entry->userid = 0;			// Represents share to all
+						$entry->viewed = 1;			// Removes the viewed flag
+						if (!insert_record("fmanager_shared", $entry)) {
+							notify(get_string('errnoinsert',"block_file_manager"));
+						}
+					}
+				}
+			} else {
+				// Shares each file to each user
+				foreach($cbu as $u) {
+					if ($u != 0) {
+						foreach($cb as $c) {
+							if ($c != 0 || substr($c, 0, 2) == "f-") {
+								$entry = NULL;
+								$entry->owner = $USER->id;
+								$entry->course = $course->id;
+								if (substr($c, 0, 2) == "f-") {
+									$entry->type = STYPE_FOLD;
+									$entry->sharedlink = substr($c,2);
+								} else {
+									$entry->type = $type;
+									$entry->sharedlink = $c;
+								}
+								$entry->userid = $u;
+								if (!insert_record("fmanager_shared", $entry)) {
+									notify(get_string('errnoinsert','block_file_manager'));
+								}					
+							}
+						}
+					}
+				}
+			}		
+		}
+		redirect("view.php?id=$id&rootdir=$rootdir");
+	} else if (isset($_POST['cancel'])) {
+		redirect("view.php?id=$id&rootdir=$rootdir");
+	}
+
+	// selects all the checkboxes for the form
+	echo "<script language=\"javascript\">
+			<!--
+				function selectboxes(allbox, whichform) {
+					if (whichform == 1) {
+						for (var i = 0; i < document.shareform[\"cbu[]\"].length; i++) {
+							document.shareform[\"cbu[]\"][i].checked = allbox.checked;
+						}
+					} else if (whichform == 2) {
+						for (var i = 0; i < document.gshareform[\"cbu[]\"].length; i++) {
+							document.gshareform[\"cbu[]\"][i].checked = allbox.checked;
+						}
+					}
+				}
+			-->
+			</script>";
+		
+    print_header(strip_tags(get_string("addlink", "block_file_manager")), "$course->fullname",
+        " $courselink <a href=\"view.php?id=$id&rootdir=$rootdir\">".get_string("filemanager", "block_file_manager")."</a> -> ".get_string("btnfilesharing", "block_file_manager"), "", "", true, "",
+        navmenu($course, 1),"","");
+	
+	// Means that the all checkbox was checked, but there were no files checked
+	$tmp = $cb[0];
+	if (substr($tmp, 0, 2) == "f-") {
+		$tmp = substr($tmp,2);
+	}
+	if (($tmp == 0) && (count($cb) == 1)) {
+		notify(get_string('msgnofilessel','block_file_manager'));		
+		redirect("view.php?id=$id&rootdir=$rootdir", 3);
+	}
+	
+	print_heading(get_string("msgsharetoothers", "block_file_manager"));
+    echo "<br>";
+	// Warns that sharing more than one file will delete all their other shared properties
+	if (count($cb) > 1) {
+		$msg = text_to_html(get_string("msgsharemulti","block_file_manager"));
+	}
+	$msg = text_to_html(get_string("msgshare","block_file_manager")).$msg;
+    print_simple_box($msg, "center");
+	echo "<br>";
+	
+	echo "<form name=\"shareform\" action=\"sharing.php?id=$id&linkid=$linkid&from=$from&rootdir=$rootdir\" method=\"post\">";
+	if (count($cb) == 1) {
+		$linkid = $cb[0];
+	}
+	print_table(fm_print_share_course_members($course->id, $linkid, $type));
+	// Stores $cb id's
+	if ($cb != NULL) {
+		foreach($cb as $c) {
+			echo "<input type=\"hidden\" name=\"cb[]\" value=\"$c\">";
+		}
+	}
+	echo "<center>";
+	echo "<input type=\"submit\" value=\"".get_string("btnshare","block_file_manager")."\" name=\"share\">";
+	echo "&nbsp;&nbsp;<input type=\"submit\" value=\"".get_string("btncancel","block_file_manager")."\" name=\"cancel\">";
+	echo "</center></form>";
+	
+	// If no groups...wont display any group info
+	if ($course->groupmode == NOGROUPS) {
+		print_footer();
+		die();
+	}
+	echo "<form name=\"gshareform\" action=\"sharing.php?id=$id&linkid=$linkid&from=$from&rootdir=$rootdir\" method=\"post\">";
+	// Always displays all groups to teachers
+	if (isteacher($course->id) || ($course->groupmode == VISIBLEGROUPS)) {
+		echo fm_print_visible_groups();
+	} else {
+		if ($course->groupmode == SEPARATEGROUPS) {
+			echo fm_print_separate_groups();
+		}
+	}
+	// Stores $cb id's
+	if ($cb != NULL) {
+		foreach($cb as $c) {
+			echo "<input type=\"hidden\" name=\"cb[]\" value=\"$c\">";
+		}
+	}
+	echo "<input type=\"hidden\" value=\"$rootdir\" name=\"rootdir\">";
+	echo "</form>";	
+	print_footer();
 ?>
\ No newline at end of file
Index: plugins/blocks/file_manager/print_lib.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/file_manager/print_lib.php,v
retrieving revision 1.2.8.1
diff -u -r1.2.8.1 print_lib.php
--- plugins/blocks/file_manager/print_lib.php	14 Jul 2007 20:29:35 -0000	1.2.8.1
+++ plugins/blocks/file_manager/print_lib.php	24 Feb 2008 22:33:34 -0000
@@ -1,794 +1,863 @@
-<?php
-/****************************************************************************
- Filename:  print_lib.php
-  Created:  Michael Avelar
-  Created:  6/8/05
- Modified:  6/8/05
-  Purpose:  This file contains all the print function mess used within the file_manager 
-*****************************************************************************/
-/**************************** Organization **********************************/
-// Print Functions				// (See print_lib.php) Functions to print tables/forms to screen etc.
-// JS Print Functions			// (See print_lib.php) Prints short javascript functions
-/****************************************************************************/
-
-/*************************** Print Functions ********************************/
-// Returns an object of all files shared to USER from the for use in print_table()
-// 	fm_print_users_shared($id, $sitewide)
-// Returns an object of all files shared to USER from selected user for use in print_table()
-//	fm_print_user_shared($record, $id)
-// Prints the category list owned by current user
-// 	fm_print_category_list($id)
-// Returns an object of all files/links USER has uploaded for use in print_table
-//	fm_print_user_files_form($id)
-// Returns a box to be printed containing actions for multiple selections
-// 	fm_print_actions_menu($id, $for)
-// Returns an object of all users for use in the print_table
-// 	fm_print_share_course_members($id)
-// Prints a list of members of users group
-//	fm_print_separate_groups()
-// Prints a list of all groups in the course
-// 	fm_print_visible_groups()
-// Returns an object with all links with applied category for viewing in shared table
-//	fm_print_user_shared_cat($id,$catid,$original)
-// Returns an object with all links under the folder for viewing in shared table
-//	fm_print_user_shared_folder($id,$foldid,$original)
-/****************************************************************************/
-
-// $id 		= source course id
-// $sitewide = if true (1) then shows all shared sitewide
-function fm_print_users_shared($id, $sitewide = NULL) {
-	global $CFG, $USER;
-	$table = NULL;
-	$fmdir = fm_get_root_dir();
-	
-	$table->align = array("center");
-	$table->width = "35%";
-	$table->data = array();
-	
-	$table->head = array(get_string("usersshared", "block_file_manager"));
-	// Prepares sql statement and counts newfiles
-	if ($sitewide == 1) {
-		$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE  userid = '$USER->id' OR userid = '0'"; 
-	} else {
-		$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '$USER->id' AND course = '$id' OR userid = '0' AND course = '$id'";
-	}
-	// Pulls out all shared users files
-	$users = get_records_sql($mysql);
-	if ($users) {
-		$userarr = array();
-		// Stores one entry per user per course who is sharing
-		foreach ($users as $u) {
-			$userarr[$u->course][$u->owner] = $u;
-		}
-		// Prints out users name once for all shared files
-		foreach ($userarr as $ua) {
-			foreach ($ua as $u) {
-				$username = get_record("user", "id", $u->owner);
-				$userentry = "";
-				$userentry .= "<a href=\"view_shared.php?id=$u->course&original=$u->owner\"><img border=\"0\" src=\"../file_manager/pix/noteitshared.gif\" width=\"16\" height=\"16\">";	
-				$userentry .= $username->lastname.", ".$username->firstname;
-				if (!$course = get_record("course","id",$u->course)) {
-					error("That's an invalid course id", "view.php?id=$id&rootdir=$rootdir");
-				}
-				if ($sitewide == 1) {
-					$userentry .= "  (Course: $course->shortname)";
-				}
-				if ($u->viewed == 0) {
-					$userentry .= " <img border=\"0\" src=\"../file_manager/pix/new.gif\" width=\"28\" height=\"11\">";
-				}
-				$table->data[] = array($userentry);
-			}
-		}
-	}
-	print_table($table);
-}
-
-// $record 		= record of user who has shared files to current USER
-// $id 			= course id
-function fm_print_user_shared($record, $id=1) {
-	global $CFG, $USER;
-	$table = NULL;
-	
-	$table->align = array("center","","center","center","center","center");
-	$table->size = array("5%", "23%", "15%", "40%", "10%", "7%");
-	$table->data = array();
-		
-	$sharedfiles = NULL;
-	$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '$USER->id' AND owner = '$record->id' AND course = '$id' OR userid = '0' AND owner = '$record->id' AND course = '$id'";
-	$sharedfiles = get_records_sql($mysql);
-	if (!$sharedfiles) {
-		error(get_string("errnosharedfound", "block_file_manager"));
-	}
-
-	$fmdir = fm_get_root_dir();
-	$strcbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"0\" onClick=\"selectboxes(this)\">&nbsp;".get_string("selectall", "block_file_manager");
-	$strnamename = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortname\">".get_string("namename","block_file_manager")."</a>";
-	$strcatname = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortcat\">".get_string("catname","block_file_manager")."</a>";
-	$strdescname = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortdesc\">".get_string("descname","block_file_manager")."</a>";
-	$strdatename = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortdate\">".get_string("datename","block_file_manager")."</a>";
-	$stractionname = get_string("actionsname","block_file_manager");
-	$table->head = array($strcbx, $strnamename, $strcatname, $strdescname, $strdatename, $stractionname);
-
-	// Gets all shared files from the user
-	foreach ($sharedfiles as $sharedfile){
-		// So far...if the user views a users shared files, the NEW flag will be removed at this point
-		$sharedfile->viewed = 1;
-		if (!update_record("fmanager_shared",$sharedfile)) {
-			notify(get_string('errnoupdate','block_file_manager'));
-		}
-		if ($sharedfile->type == STYPE_FILE) {	// for links
-			$fileinfo = get_record("fmanager_link", "id", $sharedfile->sharedlink);
-		} else if ($sharedfile->type == STYPE_CAT) {		// for categories
-			$fileinfo = get_record("fmanager_categories", "id", $sharedfile->sharedlink);
-		} else if ($sharedfile->type == STYPE_FOLD) {
-			$fileinfo = get_record("fmanager_folders","id", $sharedfile->sharedlink);
-		}
-		if ($fileinfo) {
-			fm_user_has_shared($fileinfo->owner, $sharedfile->sharedlink);	// Ensures they can view the file
-		}
-		
-		$options = "menubar=1,toolbar=1,status=1,location=0,scrollbars,resizable,width=700,height=500,top=20,left=20";
-		if ($sharedfile->type == STYPE_FILE) {		// for links
-			if ($fileinfo->type == TYPE_FILE) {
-				$icon = "file.gif";
-				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$fileinfo->id";
-				$hreflink = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $sf->link)."\" href=\"$tmphref\" onClick=\"window.open('$fileinfo->link','urlpopup','$options');\">";
-			} else if ($fileinfo->type == TYPE_URL) {
-				$hreflink = "<a target=\"urlpopup\" title=\"".get_string("msgopenlink","block_file_manager")."\" href=\"$fileinfo->link\"".
-				"onClick=\"window.open('$fileinfo->link','urlpopup','$options');\">";
-				$icon = "www.gif";
-			} else if ($fileinfo->type == TYPE_ZIP) {
-				$icon = "zip.gif";
-				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$fileinfo->id";
-				$hreflink = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $sf->link)."\" href=\"$tmphref\" onClick=\"window.open('$fileinfo->link','urlpopup','$options');\">";
-			}
-		} else if ($sharedfile->type == STYPE_CAT) {		// for categories
-			$icon = "cat.gif";
-			$tmphref = "$CFG->wwwroot/blocks/file_manager/view_shared.php?id=$id&original=$record->id&catlinkid=$fileinfo->id";
-			$hreflink = "<a target=\"catpopup\" title=\"".get_string("msgopencat","block_file_manager")."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','catpopup','$options');\">";
-		} else if ($sharedfile->type == STYPE_FOLD) {
-			$icon = "folder.gif";
-			$tmphref = "$CFG->wwwroot/blocks/file_manager/view_shared.php?id=$id&original=$record->id&foldlinkid=$fileinfo->id";
-			$hreflink = "<a target=\"foldpopup\" title=\"".get_string("msgopenfold","block_file_manager")."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','foldpopup','$options');\">";	
-		}	
-		if ($sharedfile->userid == 0) {
-			$cbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"$sharedfile->id\">";
-		} else {
-			$cbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"$sharedfile->id\">";
-		}
-		$name = "$hreflink<img src=\"$CFG->wwwroot/blocks/file_manager/pix/$icon\" width=\"25\" height=\"25\">&nbsp;$fileinfo->name</a>";
-		$tmp = fm_get_user_categories($fileinfo->category);
-		$desc = $fileinfo->description;
-		$date = "<font size=1>".userdate($fileinfo->timemodified, "%m/%d/%Y  %H:%I")."</font>";
-		$actions = "<a href=\"conf_delete.php?id=$id&from='shared'&fromid=$link->id&rootdir=$rootdir&cb=$sharedfile->id\"><img border=\"0\" src=\"../file_manager/pix/delete.gif\" width=\"11\" height=\"11\" alt=\"" . get_string("delete"). "\"></a>";
-		$table->data[] = array($cbx,$name,$tmp,$desc,$date, $actions);
-	}
-	return $table;
-}
-
-// $id 		= course id
-function fm_print_category_list($id, $rootdir) {
-	global $CFG, $USER;
-
-	$fmdir = fm_get_root_dir();
-	$fmdir = "$CFG->wwwroot/$fmdir/view.php?id=$id&tsort";
-	$strcbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"0\" onClick=\"selectboxes(this, 2)\">&nbsp;".get_string("selectall","block_file_manager");
-	$cathead = "<a href=\"$fmdir=sortnamecat\">".get_string("catname","block_file_manager")." ".get_string("namename", "block_file_manager")."</a>";
-    $actionhead = get_string("actionsname", "block_file_manager");
-	
-    echo "<center><table width=\"325\">";
-    echo "<tr><th align=\"center\" nowrap>$strcbx</th><th align=\"center\" nowrap>$cathead</th><th align=\"center\" nowrap>$actionhead</th></tr>";
-
-    $owncats = get_records_select("fmanager_categories", "owner=$USER->id", "name ASC");
-    if ($owncats){
-		foreach ($owncats as $owncat){			
-			$tmpcount = count_records("fmanager_shared","sharedlink",$owncat->id,"type",1,'course',$id);
-			if ($tmpcount > 0) {
-				$icon = "group.gif";
-			} else {
-				$icon = "group_noshare.gif";
-			}
-			echo "<tr><td align=\"center\"><input type=\"checkbox\" name=\"cb[]\" value=\"$owncat->id\"></td>";
-			echo "<td align=\"center\">$owncat->name</td>";
-			echo "<td align=\"center\"><a href=\"cat_manage.php?id=$id&catid=$owncat->id&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->pixpath/i/edit.gif\" width=\"16\" height=\"16\" alt=\"" . get_string("edit"). "\"></a>";
-			echo "   ";
-			echo "<a href=\"conf_delete.php?id=$id&from=category&fromid=$owncat->id&rootdir=$rootdir\"><img border=\"0\" src=\"../file_manager/pix/delete.gif\" width=\"11\" height=\"11\" alt=\"" . get_string("delete"). "\"></a>";
-			echo "   ";
-			//removed by PA
-			//echo "<a href=\"sharing.php?id=$id&linkid=$owncat->id&from=category&rootdir=$rootdir\"><img border=\"0\" src=\"../file_manager/pix/".$icon."\" width=\"11\" height=\"11\" alt=\"".get_string("msgsharetoothers","block_file_manager")."\"></a>";
-			echo "</td></tr>";
-		}
-    } else {
-		echo "<tr><td></td><td align=\"center\"><i><b>".get_string("msgnonedefined","block_file_manager")."</b></i></tr>";
-	}
-	echo "</table><br>";
-}
-
-// $id		= course id
-// $rootdir	= target directory
-function fm_print_user_files_form($id=1, $rootdir=0, $action='none') {
-	global $CFG, $USER;
-
-	$table = NULL;
-	$fmdir = fm_get_root_dir();
-	
-	$table->align = array("center", "left", "center", "center", "center", "center");
-	$table->width = "90%";
-	$table->size = array("5%", "23%", "15%", "30%", "10%", "10%", "7%");
-	$table->wrap = array(NULL, 'no', 'no', 'no', 'no', 'no');
-	$table->data = array();
-	$strcbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"0\" onClick=\"selectboxes(this, 1)\">&nbsp;".get_string("selectall", "block_file_manager");
-	$strnamename = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortname\">".get_string("namename","block_file_manager")."</a>";
-	$strcatname = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortcat\">".get_string("catname","block_file_manager")."</a>";
-	$strdescname = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortdesc\">".get_string("descname","block_file_manager")."</a>";
-	$strfilesizename = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortsize\">".get_string('filesizename','block_file_manager')."</a>";
-	$strdatename = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortdate\">".get_string("datename","block_file_manager")."</a>";
-	$stractionname = get_string("actionsname","block_file_manager");
-	$table->head = array($strcbx, $strnamename, $strcatname, $strdescname, $strfilesizename, $strdatename, $stractionname);
-	if ($action == 'movesel') {
-		$moveurl = "&action='$action'";
-	} else {
-		$moveurl = '';
-	}
-	// Not at root...so print an up folder link
-	if ($rootdir != 0) {
-		$tmpfold = get_record("fmanager_folders", "id", $rootdir);
-		$name = "<a href=\"view.php?id=$id&rootdir=$tmpfold->pathid$moveurl\"><img border=\"0\" src=\"$CFG->pixpath/f/parent.gif\" width=\"20\" height=\"20\" alt=\"".get_string("msgrootdir","block_file_manager")."\">&nbsp;".get_string("msgrootdir","block_file_manager")."</a>";
-		$table->data[] = array("", $name, "", "", "", "","", "");
-	}
-	// Prints folders
-	if ($allfolders = get_records("fmanager_folders", "owner=$USER->id AND pathid", $rootdir, "name")) {
-		foreach($allfolders as $folder) {
-			$date = "<font size=1>".userdate($folder->timemodified, "%m/%d/%Y  %H:%I")."</font>";
-			$cbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"fold$folder->id\">";
-			$actions = "<a href=\"folder_manage.php?id=$id&foldid=$folder->id&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->pixpath/i/edit.gif\" width=\"16\" height=\"16\" alt=\"" . get_string("edit"). "\"></a>&nbsp;
-						<a href=\"conf_delete.php?id=$id&from=folder&fromid=$folder->id&rootdir=$rootdir\"><img border=\"0\" src=\"../file_manager/pix/delete.gif\" width=\"11\" height=\"11\" alt=\"" . get_string("delete"). "\"></a>";
-			// Determines if the user can view the share option in the main course (default is no)
-			$userinttype = fm_get_user_int_type();
-			$tmpcount = count_records("fmanager_shared","sharedlink",$folder->id,"type",2,"course",$id);
-			if ($tmpcount > 0) {
-				$icon = "group.gif";
-			} else {
-				$icon = "group_noshare.gif";
-			}
-			$priv = NULL;
-			$priv = get_record("fmanager_admin", "usertype", $userinttype);			
-			if ($id == 1) {	
-				// They can share from the main page to anyone
-				if ($priv->sharetoany == 1) {
-					//$actions .= "&nbsp;&nbsp;<a href=\"sharing.php?id=$id&linkid=$folder->id&from=folder&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->wwwroot/blocks/file_manager/pix/".$icon."\" width=\"11\" height=\"11\" alt=\"".get_string('sharetoany',"block_file_manager")."\"></a>";
-				}
-			} else {
-				if ($priv->allowsharing == 1) {
-					//$actions .= "&nbsp;&nbsp;<a href=\"sharing.php?id=$id&linkid=$folder->id&from=folder&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->wwwroot/blocks/file_manager/pix/".$icon."\" width=\"11\" height=\"11\" alt=\"".get_string('msgsharetoothers',"block_file_manager")."!\"></a>";
-				}
-			}
-			$name = "<a href=\"$CFG->wwwroot/".fm_get_root_dir()."/view.php?id=$id&rootdir=$folder->id$moveurl\"><img border=\"0\" src=\"$CFG->wwwroot/blocks/file_manager/pix/folder.gif\" width=\"30\" height=\"30\" alt=\"".get_string('msgfolder','block_file_manager',$folder->name)."\">$folder->name</a>";
-			$catname = get_record("fmanager_categories","id",$folder->category);
-			$catname = $catname->name;
-			// Finds size of folder
-			$tmpdir = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($folder->id);
-			$filesize = fm_get_size($tmpdir);
-			$table->data[] = array($cbx, $name, $catname, $desc, $filesize, $date, $actions);
-		}
-	}
-	// Prints all links
-	if (!$alllinks = get_records("fmanager_link", "owner=$USER->id AND folder", $rootdir, "name")) {
-		$table->data[] = array("","<center><i><b>".get_string("msgnolinks", "block_file_manager")."</b></i></center>");
-	} else {
-		// Gets all associative information tied with user's links
-		foreach($alllinks as $link) {
-			$catname = fm_get_user_categories($link->category);
-			$date = "<font size=1>".userdate($link->timemodified, "%m/%d/%Y  %H:%I")."</font>";
-			$cbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"$link->id\">";
-			$actions = "<a href=\"link_manage.php?id=$id&linkid=$link->id&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->pixpath/i/edit.gif\" width=\"16\" height=\"16\" alt=\"" . get_string("edit"). "\"></a>&nbsp;
-						<a href=\"conf_delete.php?id=$id&from=link&fromid=$link->id&rootdir=$rootdir\"><img border=\"0\" src=\"../file_manager/pix/delete.gif\" width=\"11\" height=\"11\" alt=\"" . get_string("delete"). "\"></a>";
-			// Determines if the user can view the share option in the main course (default is no)
-			$userinttype = fm_get_user_int_type();
-			$tmpcount = count_records("fmanager_shared","sharedlink",$link->id,"type",0,"course",$id);
-			if ($tmpcount > 0) {
-				$icon = "group.gif";
-			} else {
-				$icon = "group_noshare.gif";
-			}
-			$priv = NULL;
-			$priv = get_record("fmanager_admin", "usertype", $userinttype);			
-			if ($id == 1) {	
-				// They can share from the main page to anyone
-				if ($priv->sharetoany == 1) {
-					//$actions .= "&nbsp;&nbsp;<a href=\"sharing.php?id=$id&linkid=$link->id&from='link'&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->wwwroot/blocks/file_manager/pix/".$icon."\" width=\"11\" height=\"11\" alt=\"".get_string('sharetoany',"block_file_manager")."\"></a>";
-				}
-			} else {
-				if ($priv->allowsharing == 1) {
-					//$actions .= "&nbsp;&nbsp;<a href=\"sharing.php?id=$id&linkid=$link->id&from='link'&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->wwwroot/blocks/file_manager/pix/".$icon."\" width=\"11\" height=\"11\" alt=\"".get_string('msgsharetoothers',"block_file_manager")."!\"></a>";
-				}
-			}
-			
-			$options = "menubar=1,toolbar=1,status=1,location=0,scrollbars,resizable,width=700,height=500,top=20,left=20";
-			if ($link->type == TYPE_FILE) {
-				if ($link->folder != 0) {
-					$folderinfo = fm_get_folder_path($link->folder);
-					$bdir = $folderinfo->path.$link->link;
-				} else {
-					$bdir = $link->link;
-				}				
-				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$link->id";
-				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $link->link)."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/file.gif\" width=\"25\" height=\"25\">&nbsp;$link->name</a>";
-			} else if ($link->type == TYPE_URL) {
-				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenlink","block_file_manager")."\" href=\"$link->link\"".
-				"onClick=\"window.open('$link->link','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/www.gif\" width=\"25\" height=\"25\">&nbsp;$link->name</a>";
-			} else if ($link->type == TYPE_ZIP) {
-				if ($link->folder != 0) {
-					$folderinfo = fm_get_folder_path($link->folder);
-					$bdir = $folderinfo->path.$link->link;
-				} else {
-					$bdir = $link->link;
-				}				
-				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$link->id";
-				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager",$link->link)."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/zip.gif\" width=\"25\" height=\"25\">&nbsp;$link->name</a>";                                                                                                                                        
-			}
-			$desc = wordwrap($link->description, 70, "<br>");
-			$tmp = "";
-			if (strlen($desc) > 120) { 
-				$tmp = "&nbsp;&nbsp;<b><i>(More)...</i></b>";
-			} 
-			$desc = substr($desc, 0, 120);
-			$desc = $desc.$tmp;
-			// Finds size of file
-			$filesize = '';
-			if ($link->type == TYPE_FILE || $link->type == TYPE_ZIP) {
-				$tmpdir = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($link->folder)."/".$link->link;
-				$filesize = fm_get_size($tmpdir);
-			}
-			$table->data[] = array($cbx, $name, $catname, $desc, $filesize, $date, $actions);
-		}
-	}
-	return $table;	
-}
-
-// $id 		= course id
-// $for 	= What menu this is for ['link' or 'category' or 'shared']
-function fm_print_actions_menu($id, $for, $rootdir=0) {
-	$opt = NULL;
-	if ($for == 'link') {
-		$opt = array("view.php?id=$id&rootdir=$rootdir&action='movesel'" => get_string("btnmoveact","block_file_manager"),
-					 "cat_manage.php?id=$id&rootdir=$rootdir&from='link'" => get_string("btnassigncatact","block_file_manager"),
-					 "zip.php?id=$id&rootdir=$rootdir&action='zipsel'" => get_string("btnzipact","block_file_manager"),
-					 // Removed by PA
-					 //"sharing.php?id=$id&rootdir=$rootdir&linkid=&from='link'" => get_string('msgsharetoothers',"block_file_manager"),
-					 "sepsel" => "----------",
-					 "conf_delete.php?id=$id&rootdir=$rootdir&from='link'&rootdir=$rootdir" => get_string("btndelact","block_file_manager"));
-					 
-		return choose_from_menu($opt, "linksel", "", get_string("btnlinkact","block_file_manager"), "alinkmenu()", "", true);
-	} else if ($for == 'category') {
-		//Removed by PA
-		//$opt = array("sharing.php?id=$id&rootdir=$rootdir&linkid=&from='category'" => get_string("msgsharetoothers","block_file_manager"),
-		//Edited by PA
-		$opt = array("conf_delete.php?id=$id&rootdir=$rootdir&from='category'&rootdir=$rootdir" => get_string("btndelact","block_file_manager"));
-					 
-		return choose_from_menu($opt, "catsel", "", get_string("btncatact","block_file_manager"), "acatmenu()", "", true);
-	} else if ($for == 'shared') {	
-		$opt = array("sepsel" => "----------",
-					 "conf_delete.php?id=$id&from='shared'&rootdir=$rootdir" => get_string("btndelact","block_file_manager"));
-					 
-		return choose_from_menu($opt, "sharedsel", "", get_string("btnsharedact","block_file_manager"), "amenushared()", "", true);
-	}
-}
-
-// $id		= course id
-// $linkid	= id of the link to share
-// $type 	= type of item to share (0=link;1=cat;2=folder)
-function fm_print_share_course_members($id, $linkid=NULL, $type=0) {
-	global $CFG, $USER;
-	
-	$fmdir = fm_get_root_dir();
-	
-	$table->align = array("center", "left", "left", "center");
-	$table->width = "60%";
-	$table->size = array("10%", "35%", "35%", "20%");
-	$table->wrap = array(NULL, 'no', 'no', 'no');
-	$table->data = array();
-	
-	$strcbx = "<input type=\"checkbox\" name=\"cbu[]\" value=\"0\" onClick=\"selectboxes(this, 1)\">&nbsp;".get_string("selectall", "block_file_manager");
-	$strlastname = "<a href=\"$CFG->wwwroot/$fmdir/sharing.php?id=$id&linkid=$linkid&from=$from&tsort=sortlast\">".get_string("userlastname","block_file_manager")."</a>";
-	$strfirstname = "<a href=\"$CFG->wwwroot/$fmdir/sharing.php?id=$id&linkid=$linkid&from=$from&tsort=sortfirst\">".get_string("userfirstname","block_file_manager")."</a>";
-	$struserrole = "<a href=\"$CFG->wwwroot/$fmdir/sharing.php?id=$id&linkid=$linkid&from=$from&tsort=sortrole\">".get_string("userrole","block_file_manager")."</a>";
-
-	$table->head = array($strcbx, $strlastname, $strfirstname, $struserrole);
-	if ($id == 1) {
-		if (!$allusers = get_records_select("user", 'idnumber != \'NULL\'', 'lastname', 'lastname, firstname, id')) {
-			$table->data[] = array("","<center><i><b>".get_string("msgnocourseusers","block_file_manager")."</b></i></center>");
-		} else {
-			// Prints all roles of user throughout site
-			foreach($allusers as $key => $au) {
-				$allusers[$key]->role = NULL;
-				if (isadmin($au->id)) {
-					$allusers[$key]->role = "Admin ";
-					$allusers[$key]->userid = $au->id;
-				} 
-				if (isteacherinanycourse($au->id, false)) {
-					if ($allusers[$key]->role) { $slash = "/"; }
-					$allusers[$key]->role .= "$slash Teacher ";
-					$allusers[$key]->userid = $au->id;
-				} 
-				if (record_exists('user_students', 'userid', $au->id)) {
-					$slash = "";
-					if ($allusers[$key]->role) { $slash = "/"; }
-					$allusers[$key]->role .= "$slash Student ";
-					$allusers[$key]->userid = $au->id;					
-				}
-			}
-		}
-	} else {
-		if ((!$allteach = get_records("user_teachers", "course", $id)) && (!$allstu = get_records("user_students", "course", $id))) {
-			$table->data[] = array("","<center><i><b>".get_string("msgnocourseusers", "block_file_manager")."</b></i></center>");
-		} else {
-			// Gives all users their role in the course
-			$allstu = get_records("user_students", "course", $id);		// Doesnt get populated above for some reason...
-			$allusers = array();
-			if ($allteach) {
-				foreach($allteach as $key => $au) {
-					$tmp = get_record("user", "id", $au->userid); 
-					$allusers[$au->userid]->role = "Teacher";
-					$allusers[$au->userid]->lastname = $tmp->lastname;
-					$allusers[$au->userid]->firstname = $tmp->firstname;
-					$allusers[$au->userid]->userid = $au->userid;
-				}
-			} 
-			if ($allstu) {
-				foreach($allstu as $key => $au) {
-					$tmp = get_record("user", "id", $au->userid); 
-					$allusers[$au->userid]->role = "Student";
-					$allusers[$au->userid]->lastname = $tmp->lastname;
-					$allusers[$au->userid]->firstname = $tmp->firstname;
-					$allusers[$au->userid]->userid = $au->userid;
-				}
-			}
-		}
-	}
-	if ($allusers) {
-		$sharetoall = false;
-		// checks if file is shared to all
-		if (count_records_sql("SELECT * FROM {$CFG->prefix}fmanager_shared WHERE owner = '$USER->id' AND course = '$id' AND userid = '0' AND sharedlink = '$linkid' AND type = '$type'")) {
-			$sharetoall = true;
-		}
-		foreach ($allusers as $au) {
-			if ($au->userid != $USER->id) {		// Cant share to yourself
-				if ($linkid != NULL) {
-					$thecount = 0;
-					if ($sharetoall) { 
-						$thecount = 1; 
-					} else {
-						$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE owner = '$USER->id' AND course = '$id' AND userid = '$au->userid' AND sharedlink = '$linkid' AND type = '$type'";
-						$thecount = count_records_sql($mysql);
-					}
-					if ($thecount > 0) {
-						$cbx = "<input type=\"checkbox\" name=\"cbu[]\" value=\"$au->userid\" checked>";
-					} else {
-						$cbx = "<input type=\"checkbox\" name=\"cbu[]\" value=\"$au->userid\">";
-					}
-				} else {
-					$cbx = "<input type=\"checkbox\" name=\"cbu[]\" value=\"$au->userid\">";
-				}
-				$table->data[] = array($cbx, $au->lastname, $au->firstname, $au->role);
-			}
-		}
-	} 
-	
-	return $table;
-}
-
-// When called, outputs members of the group that user is a member of
-function fm_print_separate_groups() {/*
-	$cblnprinted = false;
-	if ($users = get_group_users($group->id)) {
-		foreach ($users as $user) {
-			if (!$cblnprinted) {
-				echo "<tr><td width=\"5%\" align=\"center\"><input type=\"checkbox\" name=\"sharegrpall\" value=\"1\"><input type=\"hidden\" name=\"sharegroup[]\" value=\"$user->id\" checked hidden></td>";
-				echo "<td width=\"35%\" align\"left\">$group->name</td>";
-				echo "<td width=\"60%\" align=\"left\">" . fullname($user, false) . "</td></tr>";
-				$cblnprinted = true;
-			} else {
-				echo "<tr><td width=\"5%\"align=\"center\"><input type=\"hidden\" name=\"sharegroup[]\" value=\"$user->id\" checked hidden></td><td width=\"35%\"></td><td width=\"60%\" align=\"left\">" . fullname($user, false) . "</td></tr>";
-			}
-		}
-	} else {
-		print_heading(get_string('nousersyet'));
-	}*/
-}
-
-function fm_print_visible_groups() {
-	
-}
-
-// $id			= course id
-// $catid		= category id
-// $original 	= user who shared cat
-function fm_print_user_shared_cat($id,$catid,$original) {
-	global $USER, $CFG;
-	
-	$fmdir = fm_get_root_dir();
-	$options = "menubar=1,toolbar=1,status=1,location=0,scrollbars,resizable,width=600,height=400,top=150,left=100";
-	$table->align = array("", "center", "center", "center");
-	$table->width = "100%";
-	$table->size = array("25%", "25%", "30%", "20%");
-	$table->wrap = array('no', 'no', 'yes', 'no');
-	$table->data = array();
-	$strnamename = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$catid&tsort=sortname\">".get_string("namename","block_file_manager")."</a>";
-	$strcatname = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$catid&tsort=sortcat\">".get_string("catname","block_file_manager")."</a>";
-	$strdescname = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$catid&tsort=sortdesc\">".get_string("descname","block_file_manager")."</a>";
-	$strdatename = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$catid&tsort=sortdate\">".get_string("datename","block_file_manager")."</a>";
-	$table->head = array($strnamename, $strcatname, $strdescname, $strdatename);
-	
-	$sharedfolders = fm_get_folder_shared_by_cat($original, $catid);
-	if ($sharedfolders) {
-		foreach($sharedfolders as $sf) {
-			$name = "";
-			$cat =  "";
-			$desc = "";
-			$date = "";
-			$linkurl = $CFG->wwwroot."/blocks/file_manager/view_shared.php?id=$id&original=$original&foldlinkid=$sf->id";
-			$name = "<a target=\"foldpopup\" title=\"".get_string("msgopenlink","block_file_manager")."\" href=\"$linkurl\"".
-				"onClick=\"window.open('$linkurl','foldpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/folder.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
-			$desc = $sf->description;
-			$cat = fm_get_user_categories($sf->category);
-			$date = "<font size=1>".userdate($sf->timemodified, "%m/%d/%Y  %H:%I")."</font>";
-			$table->data[] = array($name, $cat, $desc, $date);			
-		}	
-	} 
-
-	$sharedfiles = fm_get_links_shared_by_cat($original, $catid);
-	if ($sharedfiles) {
-		foreach($sharedfiles as $sf) {
-			$name = "";
-			$cat =  "";
-			$desc = "";
-			$date = "";
-			if ($sf->type == TYPE_FILE) {
-				if ($sf->folder != 0) {
-					$folderinfo = fm_get_folder_path($sf->folder, true);
-					$bdir = $folderinfo->path.$sf->link;
-				} else {
-					$bdir = $sf->link;
-				}				
-				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$sf->id";
-				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $sf->link)."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/file.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
-			} else if ($sf->type == TYPE_URL) {
-				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenlink","block_file_manager")."\" href=\"$sf->link\"".
-				"onClick=\"window.open('$sf->link','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/www.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
-			} else if ($sf->type == TYPE_ZIP) {
-				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$sf->id";
-				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $sf->link)."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/zip.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
-			}
-			$desc = $sf->description;
-			$cat = fm_get_user_categories($sf->category);
-			$date = "<font size=1>".userdate($sf->timemodified, "%m/%d/%Y  %H:%I")."</font>";
-			$table->data[] = array($name, $cat, $desc, $date);			
-		}	
-	} else {
-		$table->data[] = array(get_string("msgnosharedcatlink","block_file_manager"));
-	}
-	
-	return $table;
-}
-
-// $id 			= course id	
-// $foldid		= folder id
-// $original 	= owner of the folder's user id
-function fm_print_user_shared_folder($id,$foldid,$original) {
-	global $USER, $CFG;
-	
-	$fmdir = fm_get_root_dir();
-	$options = "menubar=1,toolbar=1,status=1,location=0,scrollbars,resizable,width=600,height=400,top=150,left=100";
-	$table->align = array("", "center", "center", "center");
-	$table->width = "100%";
-	$table->size = array("25%", "25%", "30%", "20%");
-	$table->wrap = array('no', 'no', 'yes', 'no');
-	$table->data = array();
-	$strnamename = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$foldid&tsort=sortname\">".get_string("namename","block_file_manager")."</a>";
-	$strcatname = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$foldid&tsort=sortcat\">".get_string("catname","block_file_manager")."</a>";
-	$strdescname = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$foldid&tsort=sortdesc\">".get_string("descname","block_file_manager")."</a>";
-	$strdatename = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$foldid&tsort=sortdate\">".get_string("datename","block_file_manager")."</a>";
-	$table->head = array($strnamename, $strcatname, $strdescname, $strdatename);
-
-	// Get all shared folders under folder
-	$sharedfolder = fm_get_all_sharedf_by_folder($original, $foldid);
-	
-	if ($sharedfolder) {
-		foreach($sharedfolder as $sf) {
-			$name = "";
-			$cat =  "";
-			$desc = "";
-			$date = "";
-			$tmpurl = "$CFG->wwwroot/blocks/file_manager/view_shared.php?id=$id&original=$original&foldlinkid=$sf->id";
-			$name = "<a target=\"foldpopup\" title=\"".get_string("msgopenfold","block_file_manager")."\" href=\"$tmpurl\">".
-					"<img src=\"$CFG->wwwroot/blocks/file_manager/pix/folder.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
-			
-			$table->data[] = array($name, $cat, $desc, $date);			
-		}	
-	} 
-
-	// Get all shared files under folder
-	$sharedfiles = fm_get_all_shared_by_folder($original, $foldid);
-	
-	if ($sharedfiles) {
-		foreach($sharedfiles as $sf) {
-			$name = "";
-			$cat =  "";
-			$desc = "";
-			$date = "";
-			
-			if ($sf->type == TYPE_FILE) {
-				if ($sf->folder != 0) {
-					$folderinfo = fm_get_folder_path($sf->folder, true);
-					$bdir = $folderinfo->path.$sf->link;
-				} else {
-					$bdir = $sf->link;
-				}				
-				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$sf->id";
-				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $sf->link)."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/file.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
-			} else if ($sf->type == TYPE_URL) {
-				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenlink","block_file_manager")."\" href=\"$sf->link\"".
-				"onClick=\"window.open('$sf->link','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/www.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
-			} else if ($sf->type == TYPE_ZIP) {
-				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$sf->id";
-				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $sf->link)."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/zip.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
-			}
-			$desc = $sf->description;
-			$cat = fm_get_user_categories($sf->category);
-			$date = "<font size=1>".userdate($sf->timemodified, "%m/%d/%Y  %H:%I")."</font>";
-			$table->data[] = array($name, $cat, $desc, $date);			
-		}	
-	}
-	// If folder is empty
-	if (!$sharedfiles && !$sharedfolder) {
-		$table->data[] = array(get_string("msgnosharedfoldlink","block_file_manager"));
-	}
-	
-	return $table;
-}
-/*************************** JS Print Functions *****************************/
-// Returns js function to allow a js popup
-// 	fm_print_js_popup()
-// Returns js function to select all/none checkboxes
-// 	fm_print_js_select()			 
-// Returns js function to allow forms to send to various pages
-//	fm_print_js_sendform($tourl,$formname)
-// Returns js function to execute pages according to drop-menu selection
-//	fm_print_js_amenu()
-// Returns js function to execute pages according to drop-menu selection from view_shared.php
-//	fm_print_js_amenushared()
-/****************************************************************************/
-
-function fm_print_js_popup() {
-	$retval = "<script language=\"javascript\">
-				<!--
-					// Opens a popup window
-					function popup(url) {
-						window.open(url, \"Popup\", \"height=450, width=425, scrollbars=yes\");
-					}
-				-->
-				</script>";
-	return $retval;
-}
-
-function fm_print_js_select() {
-	$retval = "<script language=\"javascript\">
-				<!--
-					// selects all the checkboxes for the form
-					function selectboxes(allbox, whichform) {
-						if (whichform == 1) {
-							for (var i = 0; i < document.linkform[\"cb[]\"].length; i++) {
-								document.linkform[\"cb[]\"][i].checked = allbox.checked;
-							}
-						} 
-						if (whichform == 2) {
-							for (var i = 0; i < document.catform[\"cb[]\"].length; i++) {
-								document.catform[\"cb[]\"][i].checked = allbox.checked;
-							}
-						}							
-					}
-				-->
-				</script>";
-	return $retval;
-}
-
-// $tourl		= to what page (entire url)
-// $formname	= name of the form to submit to
-function fm_print_js_sendform($tourl, $formname) {
-	$retval = "<script language=\"javascript\">
-				<!--
-					// sets form's url
-					function sendForm() {
-						document.$formname.action = '$tourl';
-						document.$formname.submit();
-					}
-				-->
-				</script>";
-	return $retval;
-}
-
-function fm_print_js_amenu() {
-	$retval = "<script language=\"javascript\">
-				<!--
-					// submits to linkform according to what was selected
-					function alinkmenu() {
-						sel = document.linkform.menulinksel;
-						dest = sel.options[sel.selectedIndex].value;
-						if (dest != '' && dest != 'sepsel') {
-							nonechecked = true;
-							for (var i = 0; i < document.linkform[\"cb[]\"].length; i++) {
-								if (document.linkform[\"cb[]\"][i].checked) {
-									nonechecked = false;
-									i = document.linkform[\"cb[]\"].length; 
-								}
-							}
-							if (nonechecked == false) {
-								document.linkform.action = dest;
-								document.linkform.submit();
-							} else {
-								document.linkform.menulinksel.value = '';
-							}
-						} else {
-							document.linkform.menulinksel.value = '';
-						}
-					}
-					
-					// submits to cat form
-					function acatmenu() {
-						sel = document.catform.menucatsel;
-						dest = sel.options[sel.selectedIndex].value;
-						if (dest != '' && dest != 'sepsel') {		// If default or separator are not selected
-							nonechecked = true;					// Flag to ensure at least 1 box is checked
-							for (var i = 0; i < document.catform[\"cb[]\"].length; i++) {
-								if (document.catform[\"cb[]\"][i].checked) {
-									nonechecked = false;
-									i = document.catform[\"cb[]\"].length; 
-								}
-							}
-							if (nonechecked == false) {				// If at least 1 is checked, process, otherwise reset menu
-								document.catform.action = dest;
-								document.catform.submit();
-							} else {
-								document.catform.menucatsel.value = '';
-							}
-						} else {
-							document.catform.menucatsel.value = '';
-						}
-					}
-				-->
-				</script>";
-	return $retval;
-}
-
-function fm_print_js_amenushared() {
-	$retval = "<script language=\"javascript\">
-				<!--
-					// submits to viewshared form
-					function amenushared() {
-						sel = document.sharedform.menusharedsel;
-						dest = sel.options[sel.selectedIndex].value;
-						if (dest != '' && dest != 'sepsel') {
-							nonechecked = true;
-							for (var i = 0; i <document.sharedform[\"cb[]\"].length; i++) {
-								if (document.sharedform[\"cb[]\"][i].checked) {
-									nonechecked = false;
-									i = document.sharedform[\"cb[]\"].length; 
-								}
-							}
-							if (nonechecked == false) {
-								document.sharedform.action = dest;
-								document.sharedform.submit();
-							} else {
-								document.sharedform.menusharedsel.value = '';
-							}
-						} else {
-							document.sharedform.menusharedsel.value = '';
-						}
-					}
-				-->
-				</script>";
-	return $retval;
-}
-
+<?php
+/****************************************************************************
+ Filename:  print_lib.php
+  Created:  Michael Avelar
+  Created:  6/8/05
+ Modified:  6/8/05
+  Purpose:  This file contains all the print function mess used within the file_manager 
+*****************************************************************************/
+/**************************** Organization **********************************/
+// Print Functions				// (See print_lib.php) Functions to print tables/forms to screen etc.
+// JS Print Functions			// (See print_lib.php) Prints short javascript functions
+/****************************************************************************/
+
+/*************************** Print Functions ********************************/
+// Returns an object of all files shared to USER from the for use in print_table()
+// 	fm_print_users_shared($id, $sitewide)
+// Returns an object of all files shared to USER from selected user for use in print_table()
+//	fm_print_user_shared($record, $id)
+// Prints the category list owned by current user
+// 	fm_print_category_list($id)
+// Returns an object of all files/links USER has uploaded for use in print_table
+//	fm_print_user_files_form($id)
+// Returns a box to be printed containing actions for multiple selections
+// 	fm_print_actions_menu($id, $for)
+// Returns an object of all users for use in the print_table
+// 	fm_print_share_course_members($id)
+// Prints a list of members of users group
+//	fm_print_separate_groups()
+// Prints a list of all groups in the course
+// 	fm_print_visible_groups()
+// Returns an object with all links with applied category for viewing in shared table
+//	fm_print_user_shared_cat($id,$catid,$original)
+// Returns an object with all links under the folder for viewing in shared table
+//	fm_print_user_shared_folder($id,$foldid,$original)
+/****************************************************************************/
+
+// $id 		= source course id
+// $sitewide = if true (1) then shows all shared sitewide
+function fm_print_users_shared($id, $sitewide = NULL) {
+	global $CFG, $USER;
+	$table = NULL;
+	$fmdir = fm_get_root_dir();
+	
+	$table->align = array("center");
+	$table->width = "35%";
+	$table->data = array();
+	
+	$table->head = array(get_string("usersshared", "block_file_manager"));
+	// Prepares sql statement and counts newfiles
+	if ($sitewide == 1) {
+		$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE  userid = '$USER->id' OR userid = '0'"; 
+	} else {
+		$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '$USER->id' AND course = '$id' OR userid = '0' AND course = '$id'";
+	}
+	// Pulls out all shared users files
+	$users = get_records_sql($mysql);
+	if ($users) {
+		$userarr = array();
+		// Stores one entry per user per course who is sharing
+		foreach ($users as $u) {
+			$userarr[$u->course][$u->owner] = $u;
+		}
+		// Prints out users name once for all shared files
+		foreach ($userarr as $ua) {
+			foreach ($ua as $u) {
+				$username = get_record("user", "id", $u->owner);
+				$userentry = "";
+				$userentry .= "<a href=\"view_shared.php?id=$u->course&original=$u->owner\"><img border=\"0\" src=\"../file_manager/pix/noteitshared.gif\" width=\"16\" height=\"16\">";	
+				$userentry .= $username->lastname.", ".$username->firstname;
+				if (!$course = get_record("course","id",$u->course)) {
+					error("That's an invalid course id", "view.php?id=$id&rootdir=$rootdir");
+				}
+				if ($sitewide == 1) {
+					$userentry .= "  (Course: $course->shortname)";
+				}
+				if ($u->viewed == 0) {
+					$userentry .= " <img border=\"0\" src=\"../file_manager/pix/new.gif\" width=\"28\" height=\"11\">";
+				}
+				$table->data[] = array($userentry);
+			}
+		}
+	}
+	print_table($table);
+}
+
+// $record 		= record of user who has shared files to current USER
+// $id 			= course id
+function fm_print_user_shared($record, $id=1) {
+	global $CFG, $USER;
+	$table = NULL;
+	
+	$table->align = array("center","","center","center","center","center");
+	$table->size = array("5%", "23%", "15%", "40%", "10%", "7%");
+	$table->data = array();
+		
+	$sharedfiles = NULL;
+	$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '$USER->id' AND owner = '$record->id' AND course = '$id' OR userid = '0' AND owner = '$record->id' AND course = '$id'";
+	$sharedfiles = get_records_sql($mysql);
+	if (!$sharedfiles) {
+		error(get_string("errnosharedfound", "block_file_manager"));
+	}
+
+	$fmdir = fm_get_root_dir();
+	$strcbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"0\" onClick=\"selectboxes(this)\">&nbsp;".get_string("selectall", "block_file_manager");
+	$strnamename = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortname\">".get_string("namename","block_file_manager")."</a>";
+	$strcatname = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortcat\">".get_string("catname","block_file_manager")."</a>";
+	$strdescname = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortdesc\">".get_string("descname","block_file_manager")."</a>";
+	$strdatename = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortdate\">".get_string("datename","block_file_manager")."</a>";
+	$stractionname = get_string("actionsname","block_file_manager");
+	$table->head = array($strcbx, $strnamename, $strcatname, $strdescname, $strdatename, $stractionname);
+
+	// Gets all shared files from the user
+	foreach ($sharedfiles as $sharedfile){
+		// So far...if the user views a users shared files, the NEW flag will be removed at this point
+		$sharedfile->viewed = 1;
+		if (!update_record("fmanager_shared",$sharedfile)) {
+			notify(get_string('errnoupdate','block_file_manager'));
+		}
+		if ($sharedfile->type == STYPE_FILE) {	// for links
+			$fileinfo = get_record("fmanager_link", "id", $sharedfile->sharedlink);
+		} else if ($sharedfile->type == STYPE_CAT) {		// for categories
+			$fileinfo = get_record("fmanager_categories", "id", $sharedfile->sharedlink);
+		} else if ($sharedfile->type == STYPE_FOLD) {
+			$fileinfo = get_record("fmanager_folders","id", $sharedfile->sharedlink);
+		}
+		if ($fileinfo) {
+			fm_user_has_shared($fileinfo->owner, $sharedfile->sharedlink);	// Ensures they can view the file
+		}
+		
+		$options = "menubar=1,toolbar=1,status=1,location=0,scrollbars,resizable,width=700,height=500,top=20,left=20";
+		if ($sharedfile->type == STYPE_FILE) {		// for links
+			if ($fileinfo->type == TYPE_FILE) {
+				$icon = "file.gif";
+				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$fileinfo->id";
+				$hreflink = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $sf->link)."\" href=\"$tmphref\" onClick=\"window.open('$fileinfo->link','urlpopup','$options');\">";
+			} else if ($fileinfo->type == TYPE_URL) {
+				$hreflink = "<a target=\"urlpopup\" title=\"".get_string("msgopenlink","block_file_manager")."\" href=\"$fileinfo->link\"".
+				"onClick=\"window.open('$fileinfo->link','urlpopup','$options');\">";
+				$icon = "www.gif";
+			} else if ($fileinfo->type == TYPE_ZIP) {
+				$icon = "zip.gif";
+				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$fileinfo->id";
+				$hreflink = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $sf->link)."\" href=\"$tmphref\" onClick=\"window.open('$fileinfo->link','urlpopup','$options');\">";
+			}
+		} else if ($sharedfile->type == STYPE_CAT) {		// for categories
+			$icon = "cat.gif";
+			$tmphref = "$CFG->wwwroot/blocks/file_manager/view_shared.php?id=$id&original=$record->id&catlinkid=$fileinfo->id";
+			$hreflink = "<a target=\"catpopup\" title=\"".get_string("msgopencat","block_file_manager")."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','catpopup','$options');\">";
+		} else if ($sharedfile->type == STYPE_FOLD) {
+			$icon = "folder.gif";
+			$tmphref = "$CFG->wwwroot/blocks/file_manager/view_shared.php?id=$id&original=$record->id&foldlinkid=$fileinfo->id";
+			$hreflink = "<a target=\"foldpopup\" title=\"".get_string("msgopenfold","block_file_manager")."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','foldpopup','$options');\">";	
+		}	
+		if ($sharedfile->userid == 0) {
+			$cbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"$sharedfile->id\">";
+		} else {
+			$cbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"$sharedfile->id\">";
+		}
+		$name = "$hreflink<img src=\"$CFG->wwwroot/blocks/file_manager/pix/$icon\" width=\"25\" height=\"25\">&nbsp;$fileinfo->name</a>";
+		$tmp = fm_get_user_categories($fileinfo->category);
+		$desc = $fileinfo->description;
+		$date = "<font size=1>".userdate($fileinfo->timemodified, "%m/%d/%Y  %H:%I")."</font>";
+		$actions = "<a href=\"conf_delete.php?id=$id&from='shared'&fromid=$link->id&rootdir=$rootdir&cb=$sharedfile->id\"><img border=\"0\" src=\"../file_manager/pix/delete.gif\" width=\"11\" height=\"11\" alt=\"" . get_string("delete"). "\"></a>";
+		$table->data[] = array($cbx,$name,$tmp,$desc,$date, $actions);
+	}
+	return $table;
+}
+
+// $id 		= course id
+function fm_print_category_list($id, $rootdir) {
+	global $CFG, $USER;
+
+	$fmdir = fm_get_root_dir();
+	$fmdir = "$CFG->wwwroot/$fmdir/view.php?id=$id&tsort";
+	$strcbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"0\" onClick=\"selectboxes(this, 2)\">&nbsp;".get_string("selectall","block_file_manager");
+	$cathead = "<a href=\"$fmdir=sortnamecat\">".get_string("catname","block_file_manager")." ".get_string("namename", "block_file_manager")."</a>";
+    $actionhead = get_string("actionsname", "block_file_manager");
+	
+    echo "<center><table width=\"325\">";
+    echo "<tr><th align=\"center\" nowrap>$strcbx</th><th align=\"center\" nowrap>$cathead</th><th align=\"center\" nowrap>$actionhead</th></tr>";
+
+    $owncats = get_records_select("fmanager_categories", "owner=$USER->id", "name ASC");
+    if ($owncats){
+		foreach ($owncats as $owncat){			
+			$tmpcount = count_records("fmanager_shared","sharedlink",$owncat->id,"type",1,'course',$id);
+			if ($tmpcount > 0) {
+				$icon = "group.gif";
+			} else {
+				$icon = "group_noshare.gif";
+			}
+			echo "<tr><td align=\"center\"><input type=\"checkbox\" name=\"cb[]\" value=\"$owncat->id\"></td>";
+			echo "<td align=\"center\">$owncat->name</td>";
+			echo "<td align=\"center\"><a href=\"cat_manage.php?id=$id&catid=$owncat->id&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->pixpath/i/edit.gif\" width=\"16\" height=\"16\" alt=\"" . get_string("edit"). "\"></a>";
+			echo "   ";
+			echo "<a href=\"conf_delete.php?id=$id&from=category&fromid=$owncat->id&rootdir=$rootdir\"><img border=\"0\" src=\"../file_manager/pix/delete.gif\" width=\"11\" height=\"11\" alt=\"" . get_string("delete"). "\"></a>";
+			echo "   ";
+			//removed by PA
+			//Uncommented by DWT
+			echo "<a href=\"sharing.php?id=$id&linkid=$owncat->id&from=category&rootdir=$rootdir\"><img border=\"0\" src=\"../file_manager/pix/".$icon."\" width=\"11\" height=\"11\" alt=\"".get_string("msgsharetoothers","block_file_manager")."\"></a>";
+			echo "</td></tr>";
+		}
+    } else {
+		echo "<tr><td></td><td align=\"center\"><i><b>".get_string("msgnonedefined","block_file_manager")."</b></i></tr>";
+	}
+	echo "</table><br>";
+}
+
+// $id		= course id
+// $rootdir	= target directory
+function fm_print_user_files_form($id=1, $rootdir=0, $action='none') {
+	global $CFG, $USER;
+
+	$table = NULL;
+	$fmdir = fm_get_root_dir();
+	
+	$table->align = array("center", "left", "center", "center", "center", "center");
+	$table->width = "90%";
+	$table->size = array("5%", "23%", "15%", "30%", "10%", "10%", "7%");
+	$table->wrap = array(NULL, 'no', 'no', 'no', 'no', 'no');
+	$table->data = array();
+	$strcbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"0\" onClick=\"selectboxes(this, 1)\">&nbsp;".get_string("selectall", "block_file_manager");
+	$strnamename = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortname\">".get_string("namename","block_file_manager")."</a>";
+	$strcatname = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortcat\">".get_string("catname","block_file_manager")."</a>";
+	$strdescname = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortdesc\">".get_string("descname","block_file_manager")."</a>";
+	$strfilesizename = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortsize\">".get_string('filesizename','block_file_manager')."</a>";
+	$strdatename = "<a href=\"$CFG->wwwroot/$fmdir/view.php?id=$id&tsort=sortdate\">".get_string("datename","block_file_manager")."</a>";
+	$stractionname = get_string("actionsname","block_file_manager");
+	$table->head = array($strcbx, $strnamename, $strcatname, $strdescname, $strfilesizename, $strdatename, $stractionname);
+	if ($action == 'movesel') {
+		$moveurl = "&action='$action'";
+	} else {
+		$moveurl = '';
+	}
+	// Not at root...so print an up folder link
+	if ($rootdir != 0) {
+		$tmpfold = get_record("fmanager_folders", "id", $rootdir);
+		$name = "<a href=\"view.php?id=$id&rootdir=$tmpfold->pathid$moveurl\"><img border=\"0\" src=\"$CFG->pixpath/f/parent.gif\" width=\"20\" height=\"20\" alt=\"".get_string("msgrootdir","block_file_manager")."\">&nbsp;".get_string("msgrootdir","block_file_manager")."</a>";
+		$table->data[] = array("", $name, "", "", "", "","", "");
+	}
+	// Prints folders
+	if ($allfolders = get_records("fmanager_folders", "owner=$USER->id AND pathid", $rootdir, "name")) {
+		foreach($allfolders as $folder) {
+			$date = "<font size=1>".userdate($folder->timemodified, "%m/%d/%Y  %H:%I")."</font>";
+			$cbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"fold$folder->id\">";
+			$actions = "<a href=\"folder_manage.php?id=$id&foldid=$folder->id&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->pixpath/i/edit.gif\" width=\"16\" height=\"16\" alt=\"" . get_string("edit"). "\"></a>&nbsp;
+						<a href=\"conf_delete.php?id=$id&from=folder&fromid=$folder->id&rootdir=$rootdir\"><img border=\"0\" src=\"../file_manager/pix/delete.gif\" width=\"11\" height=\"11\" alt=\"" . get_string("delete"). "\"></a>";
+			// Determines if the user can view the share option in the main course (default is no)
+			$userinttype = fm_get_user_int_type();
+			$tmpcount = count_records("fmanager_shared","sharedlink",$folder->id,"type",2,"course",$id);
+			if ($tmpcount > 0) {
+				$icon = "group.gif";
+			} else {
+				$icon = "group_noshare.gif";
+			}
+			$priv = NULL;
+			$priv = get_record("fmanager_admin", "usertype", $userinttype);			
+			if ($id == 1) {	
+				// They can share from the main page to anyone
+				if ($priv->sharetoany == 1) {
+				//Uncommented by DWT
+					$actions .= "&nbsp;&nbsp;<a href=\"sharing.php?id=$id&linkid=$folder->id&from=folder&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->wwwroot/blocks/file_manager/pix/".$icon."\" width=\"11\" height=\"11\" alt=\"".get_string('sharetoany',"block_file_manager")."\"></a>";
+				}
+			} else {
+				if ($priv->allowsharing == 1) {
+					//Uncommented by DWT
+					$actions .= "&nbsp;&nbsp;<a href=\"sharing.php?id=$id&linkid=$folder->id&from=folder&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->wwwroot/blocks/file_manager/pix/".$icon."\" width=\"11\" height=\"11\" alt=\"".get_string('msgsharetoothers',"block_file_manager")."!\"></a>";
+				}
+			}
+			$name = "<a href=\"$CFG->wwwroot/".fm_get_root_dir()."/view.php?id=$id&rootdir=$folder->id$moveurl\"><img border=\"0\" src=\"$CFG->wwwroot/blocks/file_manager/pix/folder.gif\" width=\"30\" height=\"30\" alt=\"".get_string('msgfolder','block_file_manager',$folder->name)."\">$folder->name</a>";
+			$catname = get_record("fmanager_categories","id",$folder->category);
+			$catname = $catname->name;
+			// Finds size of folder
+			$tmpdir = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($folder->id);
+			$filesize = fm_get_size($tmpdir);
+			$table->data[] = array($cbx, $name, $catname, $desc, $filesize, $date, $actions);
+		}
+	}
+	// Prints all links
+	if (!$alllinks = get_records("fmanager_link", "owner=$USER->id AND folder", $rootdir, "name")) {
+		$table->data[] = array("","<center><i><b>".get_string("msgnolinks", "block_file_manager")."</b></i></center>");
+	} else {
+		// Gets all associative information tied with user's links
+		foreach($alllinks as $link) {
+			$catname = fm_get_user_categories($link->category);
+			$date = "<font size=1>".userdate($link->timemodified, "%m/%d/%Y  %H:%I")."</font>";
+			$cbx = "<input type=\"checkbox\" name=\"cb[]\" value=\"$link->id\">";
+			$actions = "<a href=\"link_manage.php?id=$id&linkid=$link->id&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->pixpath/i/edit.gif\" width=\"16\" height=\"16\" alt=\"" . get_string("edit"). "\"></a>&nbsp;
+						<a href=\"conf_delete.php?id=$id&from=link&fromid=$link->id&rootdir=$rootdir\"><img border=\"0\" src=\"../file_manager/pix/delete.gif\" width=\"11\" height=\"11\" alt=\"" . get_string("delete"). "\"></a>";
+			// Determines if the user can view the share option in the main course (default is no)
+			$userinttype = fm_get_user_int_type();
+			$tmpcount = count_records("fmanager_shared","sharedlink",$link->id,"type",0,"course",$id);
+			if ($tmpcount > 0) {
+				$icon = "group.gif";
+			} else {
+				$icon = "group_noshare.gif";
+			}
+			$priv = NULL;
+			$priv = get_record("fmanager_admin", "usertype", $userinttype);			
+			if ($id == 1) {	
+				// They can share from the main page to anyone
+				if ($priv->sharetoany == 1) {
+					//Uncommented by DWT
+					$actions .= "&nbsp;&nbsp;<a href=\"sharing.php?id=$id&linkid=$link->id&from='link'&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->wwwroot/blocks/file_manager/pix/".$icon."\" width=\"11\" height=\"11\" alt=\"".get_string('sharetoany',"block_file_manager")."\"></a>";
+				}
+			} else {
+				if ($priv->allowsharing == 1) {
+					//Uncommented by DWT
+					$actions .= "&nbsp;&nbsp;<a href=\"sharing.php?id=$id&linkid=$link->id&from='link'&rootdir=$rootdir\"><img border=\"0\" src=\"$CFG->wwwroot/blocks/file_manager/pix/".$icon."\" width=\"11\" height=\"11\" alt=\"".get_string('msgsharetoothers',"block_file_manager")."!\"></a>";
+				}
+			}
+			
+			$options = "menubar=1,toolbar=1,status=1,location=0,scrollbars,resizable,width=700,height=500,top=20,left=20";
+			if ($link->type == TYPE_FILE) {
+				if ($link->folder != 0) {
+					$folderinfo = fm_get_folder_path($link->folder);
+					$bdir = $folderinfo->path.$link->link;
+				} else {
+					$bdir = $link->link;
+				}				
+				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$link->id";
+				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $link->link)."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/file.gif\" width=\"25\" height=\"25\">&nbsp;$link->name</a>";
+			} else if ($link->type == TYPE_URL) {
+				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenlink","block_file_manager")."\" href=\"$link->link\"".
+				"onClick=\"window.open('$link->link','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/www.gif\" width=\"25\" height=\"25\">&nbsp;$link->name</a>";
+			} else if ($link->type == TYPE_ZIP) {
+				if ($link->folder != 0) {
+					$folderinfo = fm_get_folder_path($link->folder);
+					$bdir = $folderinfo->path.$link->link;
+				} else {
+					$bdir = $link->link;
+				}				
+				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$link->id";
+				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager",$link->link)."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/zip.gif\" width=\"25\" height=\"25\">&nbsp;$link->name</a>";                                                                                                                                        
+			}
+			$desc = wordwrap($link->description, 70, "<br>");
+			$tmp = "";
+			if (strlen($desc) > 120) { 
+				$tmp = "&nbsp;&nbsp;<b><i>(More)...</i></b>";
+			} 
+			$desc = substr($desc, 0, 120);
+			$desc = $desc.$tmp;
+			// Finds size of file
+			$filesize = '';
+			if ($link->type == TYPE_FILE || $link->type == TYPE_ZIP) {
+				$tmpdir = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($link->folder)."/".$link->link;
+				$filesize = fm_get_size($tmpdir);
+			}
+			$table->data[] = array($cbx, $name, $catname, $desc, $filesize, $date, $actions);
+		}
+	}
+	return $table;	
+}
+
+// $id 		= course id
+// $for 	= What menu this is for ['link' or 'category' or 'shared']
+function fm_print_actions_menu($id, $for, $rootdir=0) {
+	$opt = NULL;
+	if ($for == 'link') {
+		$opt = array("view.php?id=$id&rootdir=$rootdir&action='movesel'" => get_string("btnmoveact","block_file_manager"),
+					 "cat_manage.php?id=$id&rootdir=$rootdir&from='link'" => get_string("btnassigncatact","block_file_manager"),
+					 "zip.php?id=$id&rootdir=$rootdir&action='zipsel'" => get_string("btnzipact","block_file_manager"),
+					 // Removed by PA
+					 //Uncommented by DWT
+					 "sharing.php?id=$id&rootdir=$rootdir&linkid=&from='link'" => get_string('msgsharetoothers',"block_file_manager"),
+					 "sepsel" => "----------",
+					 "conf_delete.php?id=$id&rootdir=$rootdir&from='link'&rootdir=$rootdir" => get_string("btndelact","block_file_manager"));
+					 
+		return choose_from_menu($opt, "linksel", "", get_string("btnlinkact","block_file_manager"), "alinkmenu()", "", true);
+	} else if ($for == 'category') {
+		//Removed by PA
+		//Uncommented by DWT
+		$opt = array("sharing.php?id=$id&rootdir=$rootdir&linkid=&from='category'" => get_string("msgsharetoothers","block_file_manager"),
+					 "conf_delete.php?id=$id&rootdir=$rootdir&from='category'&rootdir=$rootdir" => get_string("btndelact","block_file_manager"));
+		//Edited by PA
+		//$opt = array("conf_delete.php?id=$id&rootdir=$rootdir&from='category'&rootdir=$rootdir" => get_string("btndelact","block_file_manager"));
+					 
+		return choose_from_menu($opt, "catsel", "", get_string("btncatact","block_file_manager"), "acatmenu()", "", true);
+	} else if ($for == 'shared') {	
+		$opt = array("sepsel" => "----------",
+					 "conf_delete.php?id=$id&from='shared'&rootdir=$rootdir" => get_string("btndelact","block_file_manager"));
+					 
+		return choose_from_menu($opt, "sharedsel", "", get_string("btnsharedact","block_file_manager"), "amenushared()", "", true);
+	}
+}
+
+// $id		= course id
+// $linkid	= id of the link to share
+// $type 	= type of item to share (0=link;1=cat;2=folder)
+function fm_print_share_course_members($id, $linkid=NULL, $type=0) {
+	global $CFG, $USER;
+
+	$fmdir = fm_get_root_dir();
+	
+	$table->align = array("center", "left", "left", "center");
+	$table->width = "60%";
+	$table->size = array("10%", "35%", "35%", "20%");
+	$table->wrap = array(NULL, 'no', 'no', 'no');
+	$table->data = array();
+	
+	$strcbx = "<input type=\"checkbox\" name=\"cbu[]\" value=\"0\" onClick=\"selectboxes(this, 1)\">&nbsp;".get_string("selectall", "block_file_manager");
+	$strlastname = "<a href=\"$CFG->wwwroot/$fmdir/sharing.php?id=$id&linkid=$linkid&from=$from&tsort=sortlast\">".get_string("userlastname","block_file_manager")."</a>";
+	$strfirstname = "<a href=\"$CFG->wwwroot/$fmdir/sharing.php?id=$id&linkid=$linkid&from=$from&tsort=sortfirst\">".get_string("userfirstname","block_file_manager")."</a>";
+	$struserrole = "<a href=\"$CFG->wwwroot/$fmdir/sharing.php?id=$id&linkid=$linkid&from=$from&tsort=sortrole\">".get_string("userrole","block_file_manager")."</a>";
+
+	$table->head = array($strcbx, $strlastname, $strfirstname, $struserrole);
+	if ($id == 1) {
+	//DWT, don't know why idnumber is used in the query, it is an unreliable user data field.
+	//just list all the active users then.
+		//if (!$allusers = get_records_select("user", 'idnumber != \'NULL\'', 'lastname', 'lastname, firstname, id')) {
+		if (!$allusers = get_records_select("user", 'deleted=0', 'lastname', 'lastname, firstname, id')) {
+			$table->data[] = array("","<center><i><b>".get_string("msgnocourseusers","block_file_manager")."</b></i></center>");
+		} else {
+			// Prints all roles of user throughout site
+			//Save all the students in one query so no need to run one query for each students
+			$students_array = get_records_sql("select distinct(userid) from role_assignments where roleid=" . STUDENT_ROLEID);
+			$teachers_array = get_records_sql("select distinct(userid) from role_assignments where roleid in (" .
+											   COURSECREATOR_ROLEID . "," . TEACHER_ROLEID . "," . NONEDITING_TEACHER_ROLEID . ")");
+			foreach($allusers as $key => $au) {
+				$allusers[$key]->role = NULL;
+				//DWT, not 100% sure is this query right or not.
+				//Well, I have 2 thousand students and each have about 6 courses and this takes forever to finish
+				//I am saving all the students in a query and then compare to the result of this query
+				//Who wrote this code? this is so badly written! Always crap out on a site with many students!
+				//if (record_exists('user_students', 'userid', $au->id)) {
+				//if (record_exists('role_assignments', 'userid', $au->id, roleid, STUDENT_ROLEID)) {
+				if ( array_key_exists($au->id, $students_array) ) {
+					$slash = "";
+					if ($allusers[$key]->role) { $slash = "/"; }
+					$allusers[$key]->role .= "$slash Student ";
+					$allusers[$key]->userid = $au->id;					
+				}
+				elseif ( array_key_exists($au->id, $teachers_array) ) {
+					if ($allusers[$key]->role) { $slash = "/"; }
+					$allusers[$key]->role .= "$slash Teacher ";
+					$allusers[$key]->userid = $au->id;
+				}
+				elseif (isadmin($au->id)) {
+					$allusers[$key]->role = "Admin ";
+					$allusers[$key]->userid = $au->id;
+				} 
+				else {
+					//DWT, I added this assuming this data is for display only and does not go to the DB
+					//I know, auumption is bad. But, just don't have enought time.
+					$allusers[$key]->role = "N/A ";
+					$allusers[$key]->userid = $au->id;
+				}
+			}
+		}
+	} else {
+	//DWT, inefficient code here and it also breaks in Moodle 1.8
+	//Let's just rewrite most of it. Lesson to all programmers, DB calls are expensive avoid it if you can
+		/*
+		if ((!$allteach = get_records("user_teachers", "course", $id)) && (!$allstu = get_records("user_students", "course", $id))) {
+			$table->data[] = array("","<center><i><b>".get_string("msgnocourseusers", "block_file_manager")."</b></i></center>");
+		} else {
+			// Gives all users their role in the course
+			$allstu = get_records("user_students", "course", $id);		// Doesnt get populated above for some reason...
+			$allusers = array();
+			if ($allteach) {
+				foreach($allteach as $key => $au) {
+					$tmp = get_record("user", "id", $au->userid); 
+					$allusers[$au->userid]->role = "Teacher";
+					$allusers[$au->userid]->lastname = $tmp->lastname;
+					$allusers[$au->userid]->firstname = $tmp->firstname;
+					$allusers[$au->userid]->userid = $au->userid;
+				}
+			}
+			if ($allstu) {
+				foreach($allstu as $key => $au) {
+					$tmp = get_record("user", "id", $au->userid); 
+					$allusers[$au->userid]->role = "Student";
+					$allusers[$au->userid]->lastname = $tmp->lastname;
+					$allusers[$au->userid]->firstname = $tmp->firstname;
+					$allusers[$au->userid]->userid = $au->userid;
+				}
+			}
+		} */
+		
+		//DWT, just modify the queries to work in Moodle 1.8
+		$course_context = get_context_instance(CONTEXT_COURSE, $id);
+		if ( !$course_context )
+			error("Invalid course ID $id.");
+		$allstu = get_records_sql("SELECT u.id AS userid, u.firstname, u.lastname " .
+									"FROM user AS u, role_assignments AS ra " .
+									"WHERE ra.contextid=$course_context->id AND ra.roleid=" .
+									 STUDENT_ROLEID . " AND u.id=ra.userid");
+		
+		$allteach = get_records_sql("SELECT u.id AS userid, u.firstname, u.lastname " .
+								 "FROM user AS u, role_assignments AS ra " .
+								 "WHERE ra.contextid=$course_context->id AND ra.roleid in (" .
+								 ADMIN_ROLEID . "," . COURSECREATOR_ROLEID . "," . TEACHER_ROLEID . "," .
+								 NONEDITING_TEACHER_ROLEID . ") AND u.id=ra.userid" );
+		if ( !$allstu && !$allteach ) {
+			$table->data[] = array("","<center><i><b>".get_string("msgnocourseusers", "block_file_manager")."</b></i></center>");
+		}
+		else {
+			$allusers = array();
+			if ($allteach) {
+				foreach($allteach as $key => $au) {
+					$tmp = get_record("user", "id", $au->userid); 
+					$allusers[$au->userid]->role = "Teacher";
+					$allusers[$au->userid]->lastname = $tmp->lastname;
+					$allusers[$au->userid]->firstname = $tmp->firstname;
+					$allusers[$au->userid]->userid = $au->userid;
+				}
+			}
+			if ($allstu) {
+				foreach($allstu as $key => $au) {
+					$tmp = get_record("user", "id", $au->userid); 
+					$allusers[$au->userid]->role = "Student";
+					$allusers[$au->userid]->lastname = $tmp->lastname;
+					$allusers[$au->userid]->firstname = $tmp->firstname;
+					$allusers[$au->userid]->userid = $au->userid;
+				}
+			}
+		}
+	}
+	if ($allusers) {
+		$sharetoall = false;
+		// checks if file is shared to all
+		if (count_records_sql("SELECT * FROM {$CFG->prefix}fmanager_shared WHERE owner = '$USER->id' AND course = '$id' AND userid = '0' AND sharedlink = '$linkid' AND type = '$type'")) {
+			$sharetoall = true;
+		}
+		foreach ($allusers as $au) {
+			if ($au->userid != $USER->id) {		// Cant share to yourself
+				if ($linkid != NULL) {
+					$thecount = 0;
+					if ($sharetoall) { 
+						$thecount = 1; 
+					} else {
+						$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE owner = '$USER->id' AND course = '$id' AND userid = '$au->userid' AND sharedlink = '$linkid' AND type = '$type'";
+						$thecount = count_records_sql($mysql);
+					}
+					if ($thecount > 0) {
+						$cbx = "<input type=\"checkbox\" name=\"cbu[]\" value=\"$au->userid\" checked>";
+					} else {
+						$cbx = "<input type=\"checkbox\" name=\"cbu[]\" value=\"$au->userid\">";
+					}
+				} else {
+					$cbx = "<input type=\"checkbox\" name=\"cbu[]\" value=\"$au->userid\">";
+				}
+				$table->data[] = array($cbx, $au->lastname, $au->firstname, $au->role);
+			}
+		}
+	} 
+	
+	return $table;
+}
+
+// When called, outputs members of the group that user is a member of
+function fm_print_separate_groups() {/*
+	$cblnprinted = false;
+	if ($users = get_group_users($group->id)) {
+		foreach ($users as $user) {
+			if (!$cblnprinted) {
+				echo "<tr><td width=\"5%\" align=\"center\"><input type=\"checkbox\" name=\"sharegrpall\" value=\"1\"><input type=\"hidden\" name=\"sharegroup[]\" value=\"$user->id\" checked hidden></td>";
+				echo "<td width=\"35%\" align\"left\">$group->name</td>";
+				echo "<td width=\"60%\" align=\"left\">" . fullname($user, false) . "</td></tr>";
+				$cblnprinted = true;
+			} else {
+				echo "<tr><td width=\"5%\"align=\"center\"><input type=\"hidden\" name=\"sharegroup[]\" value=\"$user->id\" checked hidden></td><td width=\"35%\"></td><td width=\"60%\" align=\"left\">" . fullname($user, false) . "</td></tr>";
+			}
+		}
+	} else {
+		print_heading(get_string('nousersyet'));
+	}*/
+}
+
+function fm_print_visible_groups() {
+	
+}
+
+// $id			= course id
+// $catid		= category id
+// $original 	= user who shared cat
+function fm_print_user_shared_cat($id,$catid,$original) {
+	global $USER, $CFG;
+	
+	$fmdir = fm_get_root_dir();
+	$options = "menubar=1,toolbar=1,status=1,location=0,scrollbars,resizable,width=600,height=400,top=150,left=100";
+	$table->align = array("", "center", "center", "center");
+	$table->width = "100%";
+	$table->size = array("25%", "25%", "30%", "20%");
+	$table->wrap = array('no', 'no', 'yes', 'no');
+	$table->data = array();
+	$strnamename = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$catid&tsort=sortname\">".get_string("namename","block_file_manager")."</a>";
+	$strcatname = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$catid&tsort=sortcat\">".get_string("catname","block_file_manager")."</a>";
+	$strdescname = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$catid&tsort=sortdesc\">".get_string("descname","block_file_manager")."</a>";
+	$strdatename = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$catid&tsort=sortdate\">".get_string("datename","block_file_manager")."</a>";
+	$table->head = array($strnamename, $strcatname, $strdescname, $strdatename);
+	
+	$sharedfolders = fm_get_folder_shared_by_cat($original, $catid);
+	if ($sharedfolders) {
+		foreach($sharedfolders as $sf) {
+			$name = "";
+			$cat =  "";
+			$desc = "";
+			$date = "";
+			$linkurl = $CFG->wwwroot."/blocks/file_manager/view_shared.php?id=$id&original=$original&foldlinkid=$sf->id";
+			$name = "<a target=\"foldpopup\" title=\"".get_string("msgopenlink","block_file_manager")."\" href=\"$linkurl\"".
+				"onClick=\"window.open('$linkurl','foldpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/folder.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
+			$desc = $sf->description;
+			$cat = fm_get_user_categories($sf->category);
+			$date = "<font size=1>".userdate($sf->timemodified, "%m/%d/%Y  %H:%I")."</font>";
+			$table->data[] = array($name, $cat, $desc, $date);			
+		}	
+	} 
+
+	$sharedfiles = fm_get_links_shared_by_cat($original, $catid);
+	if ($sharedfiles) {
+		foreach($sharedfiles as $sf) {
+			$name = "";
+			$cat =  "";
+			$desc = "";
+			$date = "";
+			if ($sf->type == TYPE_FILE) {
+				if ($sf->folder != 0) {
+					$folderinfo = fm_get_folder_path($sf->folder, true);
+					$bdir = $folderinfo->path.$sf->link;
+				} else {
+					$bdir = $sf->link;
+				}				
+				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$sf->id";
+				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $sf->link)."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/file.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
+			} else if ($sf->type == TYPE_URL) {
+				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenlink","block_file_manager")."\" href=\"$sf->link\"".
+				"onClick=\"window.open('$sf->link','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/www.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
+			} else if ($sf->type == TYPE_ZIP) {
+				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$sf->id";
+				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $sf->link)."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/zip.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
+			}
+			$desc = $sf->description;
+			$cat = fm_get_user_categories($sf->category);
+			$date = "<font size=1>".userdate($sf->timemodified, "%m/%d/%Y  %H:%I")."</font>";
+			$table->data[] = array($name, $cat, $desc, $date);			
+		}	
+	} else {
+		$table->data[] = array(get_string("msgnosharedcatlink","block_file_manager"));
+	}
+	
+	return $table;
+}
+
+// $id 			= course id	
+// $foldid		= folder id
+// $original 	= owner of the folder's user id
+function fm_print_user_shared_folder($id,$foldid,$original) {
+	global $USER, $CFG;
+	
+	$fmdir = fm_get_root_dir();
+	$options = "menubar=1,toolbar=1,status=1,location=0,scrollbars,resizable,width=600,height=400,top=150,left=100";
+	$table->align = array("", "center", "center", "center");
+	$table->width = "100%";
+	$table->size = array("25%", "25%", "30%", "20%");
+	$table->wrap = array('no', 'no', 'yes', 'no');
+	$table->data = array();
+	$strnamename = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$foldid&tsort=sortname\">".get_string("namename","block_file_manager")."</a>";
+	$strcatname = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$foldid&tsort=sortcat\">".get_string("catname","block_file_manager")."</a>";
+	$strdescname = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$foldid&tsort=sortdesc\">".get_string("descname","block_file_manager")."</a>";
+	$strdatename = "<a href=\"$CFG->wwwroot/$fmdir/view_shared.php?id=$id&original=$original&catlinkid=$foldid&tsort=sortdate\">".get_string("datename","block_file_manager")."</a>";
+	$table->head = array($strnamename, $strcatname, $strdescname, $strdatename);
+
+	// Get all shared folders under folder
+	$sharedfolder = fm_get_all_sharedf_by_folder($original, $foldid);
+	
+	if ($sharedfolder) {
+		foreach($sharedfolder as $sf) {
+			$name = "";
+			$cat =  "";
+			$desc = "";
+			$date = "";
+			$tmpurl = "$CFG->wwwroot/blocks/file_manager/view_shared.php?id=$id&original=$original&foldlinkid=$sf->id";
+			$name = "<a target=\"foldpopup\" title=\"".get_string("msgopenfold","block_file_manager")."\" href=\"$tmpurl\">".
+					"<img src=\"$CFG->wwwroot/blocks/file_manager/pix/folder.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
+			
+			$table->data[] = array($name, $cat, $desc, $date);			
+		}	
+	} 
+
+	// Get all shared files under folder
+	$sharedfiles = fm_get_all_shared_by_folder($original, $foldid);
+	
+	if ($sharedfiles) {
+		foreach($sharedfiles as $sf) {
+			$name = "";
+			$cat =  "";
+			$desc = "";
+			$date = "";
+			
+			if ($sf->type == TYPE_FILE) {
+				if ($sf->folder != 0) {
+					$folderinfo = fm_get_folder_path($sf->folder, true);
+					$bdir = $folderinfo->path.$sf->link;
+				} else {
+					$bdir = $sf->link;
+				}				
+				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$sf->id";
+				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $sf->link)."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/file.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
+			} else if ($sf->type == TYPE_URL) {
+				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenlink","block_file_manager")."\" href=\"$sf->link\"".
+				"onClick=\"window.open('$sf->link','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/www.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
+			} else if ($sf->type == TYPE_ZIP) {
+				$tmphref = "$CFG->wwwroot/blocks/file_manager/file.php?cid=$id&fileid=$sf->id";
+				$name = "<a target=\"urlpopup\" title=\"".get_string("msgopenfile","block_file_manager", $sf->link)."\" href=\"$tmphref\" onClick=\"window.open('$tmphref','urlpopup','$options');\"><img src=\"$CFG->wwwroot/blocks/file_manager/pix/zip.gif\" width=\"25\" height=\"25\">&nbsp;$sf->name</a>";
+			}
+			$desc = $sf->description;
+			$cat = fm_get_user_categories($sf->category);
+			$date = "<font size=1>".userdate($sf->timemodified, "%m/%d/%Y  %H:%I")."</font>";
+			$table->data[] = array($name, $cat, $desc, $date);			
+		}	
+	}
+	// If folder is empty
+	if (!$sharedfiles && !$sharedfolder) {
+		$table->data[] = array(get_string("msgnosharedfoldlink","block_file_manager"));
+	}
+	
+	return $table;
+}
+/*************************** JS Print Functions *****************************/
+// Returns js function to allow a js popup
+// 	fm_print_js_popup()
+// Returns js function to select all/none checkboxes
+// 	fm_print_js_select()			 
+// Returns js function to allow forms to send to various pages
+//	fm_print_js_sendform($tourl,$formname)
+// Returns js function to execute pages according to drop-menu selection
+//	fm_print_js_amenu()
+// Returns js function to execute pages according to drop-menu selection from view_shared.php
+//	fm_print_js_amenushared()
+/****************************************************************************/
+
+function fm_print_js_popup() {
+	$retval = "<script language=\"javascript\">
+				<!--
+					// Opens a popup window
+					function popup(url) {
+						window.open(url, \"Popup\", \"height=450, width=425, scrollbars=yes\");
+					}
+				-->
+				</script>";
+	return $retval;
+}
+
+function fm_print_js_select() {
+	$retval = "<script language=\"javascript\">
+				<!--
+					// selects all the checkboxes for the form
+					function selectboxes(allbox, whichform) {
+						if (whichform == 1) {
+							for (var i = 0; i < document.linkform[\"cb[]\"].length; i++) {
+								document.linkform[\"cb[]\"][i].checked = allbox.checked;
+							}
+						} 
+						if (whichform == 2) {
+							for (var i = 0; i < document.catform[\"cb[]\"].length; i++) {
+								document.catform[\"cb[]\"][i].checked = allbox.checked;
+							}
+						}							
+					}
+				-->
+				</script>";
+	return $retval;
+}
+
+// $tourl		= to what page (entire url)
+// $formname	= name of the form to submit to
+function fm_print_js_sendform($tourl, $formname) {
+	$retval = "<script language=\"javascript\">
+				<!--
+					// sets form's url
+					function sendForm() {
+						document.$formname.action = '$tourl';
+						document.$formname.submit();
+					}
+				-->
+				</script>";
+	return $retval;
+}
+
+function fm_print_js_amenu() {
+	$retval = "<script language=\"javascript\">
+				<!--
+					// submits to linkform according to what was selected
+					function alinkmenu() {
+						sel = document.linkform.menulinksel;
+						dest = sel.options[sel.selectedIndex].value;
+						if (dest != '' && dest != 'sepsel') {
+							nonechecked = true;
+							for (var i = 0; i < document.linkform[\"cb[]\"].length; i++) {
+								if (document.linkform[\"cb[]\"][i].checked) {
+									nonechecked = false;
+									i = document.linkform[\"cb[]\"].length; 
+								}
+							}
+							if (nonechecked == false) {
+								document.linkform.action = dest;
+								document.linkform.submit();
+							} else {
+								document.linkform.menulinksel.value = '';
+							}
+						} else {
+							document.linkform.menulinksel.value = '';
+						}
+					}
+					
+					// submits to cat form
+					function acatmenu() {
+						sel = document.catform.menucatsel;
+						dest = sel.options[sel.selectedIndex].value;
+						if (dest != '' && dest != 'sepsel') {		// If default or separator are not selected
+							nonechecked = true;					// Flag to ensure at least 1 box is checked
+							for (var i = 0; i < document.catform[\"cb[]\"].length; i++) {
+								if (document.catform[\"cb[]\"][i].checked) {
+									nonechecked = false;
+									i = document.catform[\"cb[]\"].length; 
+								}
+							}
+							if (nonechecked == false) {				// If at least 1 is checked, process, otherwise reset menu
+								document.catform.action = dest;
+								document.catform.submit();
+							} else {
+								document.catform.menucatsel.value = '';
+							}
+						} else {
+							document.catform.menucatsel.value = '';
+						}
+					}
+				-->
+				</script>";
+	return $retval;
+}
+
+function fm_print_js_amenushared() {
+	$retval = "<script language=\"javascript\">
+				<!--
+					// submits to viewshared form
+					function amenushared() {
+						sel = document.sharedform.menusharedsel;
+						dest = sel.options[sel.selectedIndex].value;
+						if (dest != '' && dest != 'sepsel') {
+							nonechecked = true;
+							for (var i = 0; i <document.sharedform[\"cb[]\"].length; i++) {
+								if (document.sharedform[\"cb[]\"][i].checked) {
+									nonechecked = false;
+									i = document.sharedform[\"cb[]\"].length; 
+								}
+							}
+							if (nonechecked == false) {
+								document.sharedform.action = dest;
+								document.sharedform.submit();
+							} else {
+								document.sharedform.menusharedsel.value = '';
+							}
+						} else {
+							document.sharedform.menusharedsel.value = '';
+						}
+					}
+				-->
+				</script>";
+	return $retval;
+}
+
 ?>
\ No newline at end of file
Index: plugins/blocks/file_manager/lib.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/file_manager/lib.php,v
retrieving revision 1.2
diff -u -r1.2 lib.php
--- plugins/blocks/file_manager/lib.php	9 Mar 2006 22:00:38 -0000	1.2
+++ plugins/blocks/file_manager/lib.php	24 Feb 2008 22:33:34 -0000
@@ -1,1426 +1,1456 @@
-<?PHP 
-/****************************************************************************
- Filename:  lib.php
-  Created:  Michael Avelar
-   Edited:  Josh Abbott
-  Created:  5/23/05
- Modified:  1/6/06
-  Purpose:  This file contains all the functions used within the file_manager 
-*****************************************************************************/
-/**************************** Organization **********************************/
-// Link Types					// Defines link types
-// Link Functions				// Deals with all file related features
-// Folder Functions				// Deals with all folder related features
-// Category Functions			// Deals with all category related features
-// Shared Link Functions		// Deals with all shared links 
-// Security Functions			// Has all functions that check for ownership/permissions/etc
-// Database Functions			// Various db functions
-// ZIP Functions				// Deals with zip archiving and related functions
-// Print Functions				// (See print_lib.php) Functions to print tables/forms to screen etc.
-// JS Print Functions			// (See print_lib.php) Prints short javascript functions
-// Moodle Required Functions	// Required by moodle
-/****************************************************************************/
-require_once("$CFG->dirroot/lib/filelib.php");
-
-/*************************** Link Types *************************************/
-define('TYPE_FILE', 1);
-define('TYPE_URL', 2);
-define('TYPE_ZIP', 3);   
-define('STYPE_FILE',0);
-define('STYPE_CAT',1);
-define('STYPE_FOLD',2);
-
-/*************************** Link Functions *********************************/
-// Returns the link record
-//	fm_get_user_link($linkid)
-// Creates or Updates a link record
-// 	fm_update_link($link, $linkid)
-// Deletes references to a deleted category
-//	fm_update_links_cats($catid)
-// Uploads the specified file to the user's personal directory
-//	fm_upload_file($fileurl, $linkrename, $rootdir)
-// Deletes a file 
-//	fm_remove_file($file)
-/****************************************************************************/
-
-// $linkid 		= single link id
-function fm_get_user_link($linkid) {
-	global $USER;
-
-	if (!$linksrec = get_record("fmanager_link", "id", $linkid, "owner", $USER->id)) {
-		error(get_string("errnoviewfile","block_file_manager"));
-	}
-	
-	return $linksrec;
-}
-
-// $link    	= object containing updated info
-// $linkid		= id of link to be updated
-function fm_update_link($link, $linkid = NULL, $id=1, $rootdir=0) {
-	global $USER, $CFG;
-	
-	if ($linkid != NULL) {		// update a record
-		$link->id = $linkid;
-		$tmp = get_record("fmanager_link", "id", $linkid);
-		if ($tmp->type == TYPE_URL) {
-			// Appends any url link with an http:// if it doesnt exist
-			if (strncmp($link->url, "http://", 6) != 0) {
-				$link->url = "http://" . $link->url;
-			} 
-			$link->link = $link->url;
-		}
-		$link->timemodified = time();
-		// File name was changed
-		if ($tmp->link != $link->link) {
-			$destinationfile = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($tmp->folder)."/".$link->link;
-			$sourcefile = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($tmp->folder)."/".$tmp->link;
-			if (file_exists($destinationfile)) {
-				error(get_string('errfileexists','block_file_manager', $link->link),"link_manage.php?id=1&linkid=$linkid&rootdir=$rootdir");
-			}				
-			if (!@rename($sourcefile,$destinationfile)) {
-				error(get_string('errnorename','block_file_manager'));
-			}
-		} 
-		if (!update_record("fmanager_link", $link)) {
-			error(get_string("errnoupdate","block_file_manager"));
-		}
-	} else {
-		if ($link->radioval == "file") {
-			$link->type = TYPE_FILE;
-		} else if ($link->type != TYPE_ZIP) {
-			$link->type = TYPE_URL;
-			// Appends any url link with an http:// if it doesnt exist
-			if (strncmp($link->url, "http://", 6) != 0) {
-				$link->url = "http://" . $link->url;
-			} 
-		}
-		$link->owner = $USER->id;  
-		$link->link = $link->url;
-		$link->timemodified = time();
-		if ($link->type == TYPE_ZIP) {
-			$link->link = $link->name.".zip";
-		}
-		// Allows user to upload zip files
-		if (substr($link->link,-4) == ".zip") {
-			$link->type = TYPE_ZIP;
-		}
-		if (!insert_record("fmanager_link", $link)) {
-			error(get_string("errnoinsert","block_file_manager"));
-		}
-	}
-	return true;
-}
-
-// $catid 		= id of category being removed
-function fm_update_links_cats($catid) {
-	// Changes all associated links to deleted cat to 0
-	if ($linkcats = get_records("fmanager_link", "category", $catid)) {
-		foreach ($linkcats as $lc) {		
-			$lc->category = 0;
-			if (!update_record("fmanager_link", $lc)) {
-				error(get_string("errnoupdate","block_file_manager"));
-			}
-		}
-	}
-}
-// $fileurl 	= The file's location on the user's computer
-// $linkrename 	= If file existed already, this will store the renamed file if the user chooses to rename
-// $rootdir		= target directory of uploaded file
-function fm_upload_file($fileurl, $linkrename, $rootdir=0) {
-	global $USER;
-	
-	if ($linkrename != NULL) {
-		// renaming file and adding the extension
-		$newfilename = clean_filename($linkrename.stristr($fileurl['name'], '.'));
-	} else {
-		$newfilename = clean_filename($fileurl['name']);
-	}
-	
-	$folder = get_record("fmanager_folders", "id", $rootdir);
-
-    if (valid_uploaded_file($fileurl)) {
-        if (!$newfilename) {
-            error(get_string("errwierdfilename", "block_file_manager", $fileurl['name']));
-        } else if (!$dir = make_upload_directory(fm_get_user_dir_space()."$folder->path$folder->name")) {
-            error(get_string("errnodir","block_file_manager"));
-        } else {
-			if(file_exists("$dir/$newfilename")) {
-				$newfilename = "";		// flags the link_manage that file existed already
-			} else {
-				if (move_uploaded_file($fileurl['tmp_name'], "$dir/$newfilename")) {
-					chmod("$dir/$newfilename", 0755);
-				} else {
-					error(get_string("errserversave","block_file_manager"), "view.php?id=$id&rootdir=$rootdir");
-				}
-			}
-        }
-    } else {
-		error(get_string("errwierdfilename", "block_file_manager", $fileurl['name']));
-    }
-
-    return $newfilename;
-}
-
-// $file 	= link entry that is being deleted
-function fm_remove_file($file) {
-	global $CFG;
-	
-	$bdir = $CFG->dataroot."/".fm_get_user_dir_space();
-	// If there is no sub-folder
-	if ($file->folder == 0) {		
-		$bdir = $bdir."/".$file->link;
-	} else {
-		$bdir = $bdir."/".fm_get_folder_path($file->folder)."/".$file->link;
-	}
-	
-	if (!file_exists($bdir)) {		// If file isnt found for some reason...
-		return get_string("msgfilenotfound","block_file_manager", $file->link);
-	} else if (!@unlink($bdir)) {		// Deletes the attachment
-		error(get_string("errnodeletefile","block_file_manager"));
-	} 
-	return NULL;
-}
-
-/*************************** Folder Functions *******************************/
-// Returns the location of the file_manager folder...just incase
-// 	fm_get_root_dir()
-// Returns the user's personal directory space
-//	fm_get_user_dir_space()
-// Returns the folder entry given a fm_folders id
-//	fm_get_folder_path($folderid, $notsecure)
-// Deletes a folder and all subdirectories
-//  fm_delete_folder($path)
-// Moves specified file/link/folder into destination folder
-//  fm_move_to_folder($c, $rootdir)
-// Returns folder/file size
-//  fm_get_size($path)
-// Converts Bytes into more readable info
-//  fm_readable_filesize($size)
-/****************************************************************************/
-
-function fm_get_root_dir() {
-	return "blocks/file_manager";
-}
-
-function fm_get_user_dir_space($userid = NULL) {
-	global $USER;
-	
-	if ($userid == NULL) {
-		$userid = $USER->id;
-	}
-	
-	return "file_manager/users/$userid";
-}
-
-// $filderid 	= A fm_folders unique id number
-// $notsecure	= flag to not check for ownership...(for shared files)
-function fm_get_folder_path($folderid, $notsecure = false) {
-	global $USER;
-	
-	if ($folderid == 0) {
-		return "";
-	} else {
-		// Ensure user owns the folder
-		if ($notsecure == false) { fm_user_owns_folder($folderid); }
-		if (!$retval = get_record("fmanager_folders", "id", $folderid)) {
-			return "";
-		} 
-		return $retval->path.$retval->name;
-	}
-}
-
-// dir = folder database object
-function fm_delete_folder($dir) {
-	global $CFG, $USER;
-	
-	// if the dir being deleted is a root dir (eg. has some dir's under it)
-	if ($child = get_record("fmanager_folders","pathid",$dir->id)) {
-		fm_delete_folder($child);
-	} 
-	// Deletes all files/url links under folder
-	if ($allrecs = get_records("fmanager_link","folder",$dir->id)) {
-		foreach ($allrecs as $ar) {
-			// a file
-			if ($ar->type == TYPE_FILE || $ar->type == TYPE_ZIP) {
-				fm_remove_file($ar);
-			} 
-			// removes shared aspect
-			delete_records("fmanager_shared","sharedlink",$ar->id);					
-			// Delete link
-			delete_records("fmanager_link","id",$ar->id);
-		}
-	}
-	// delete shared to folder
-	delete_records("fmanager_shared","sharedlink",$dir->id);	
-
-	if (!@rmdir($CFG->dataroot."/file_manager/users/".$USER->id.$dir->path.$dir->name."/")) {
-		error(get_string("errnodeletefolder","block_file_manager"));
-	}
-	delete_records("fmanager_folders","id",$dir->id);
-	
-}
-
-// $c 		= id of link/folder (folders are 'f-' appended with id)
-// $rootdir = id of destination folder
-function fm_move_to_folder($c, $rootdir) {
-	global $CFG;
-	if ($c != 0 || substr($c,0,2) == 'f-') {
-		if (substr($c,0,2) == 'f-') {
-			$tmpfoldid = substr($c,2);
-			$rec = get_record("fmanager_folders","id",$tmpfoldid);
-			$tmp = get_record('fmanager_folders','id',$rootdir);
-			$destinationfile = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($rootdir)."/".$rec->name."/";
-			$sourcefile = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($rec->folder).$rec->path.$rec->name.'/';
-			$rec->pathid = $rootdir;
-			$rec->path = $tmp->path.$tmp->name."/";
-			// Quick catch of moving a folder into itself
-			if ($rootdir == $tmpfoldid) {
-				print_simple_box_start("center","500","red");
-				echo get_string('errsamefolder','block_file_manager', $tmp->name);
-				print_simple_box_end();
-			} else {
-				if (!@rename($sourcefile,$destinationfile)) {
-					// When moving a folder into itself...throws this error
-					print_simple_box_start("center","500","red");
-					echo get_string('errsamefolder','block_file_manager', $rec->name);
-					print_simple_box_end();
-				} else {
-					if (!update_record("fmanager_folders",$rec)) {
-						error(get_string('errnoupdate','block_file_manager'));
-					}
-				}
-			}
-		} else {
-			$rec = get_record("fmanager_link","id",$c);
-			$exists = false;	// Does file exist?
-			if ($rec->type == TYPE_FILE || $rec->type == TYPE_ZIP) {
-				$destinationfile = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($rootdir)."/".$rec->link;
-				$sourcefile = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($rec->folder)."/".$rec->link;
-				// Checks if file exists and prints warning, and doesnt change anything for that file only
-				if (file_exists($destinationfile)) {
-					print_simple_box_start("center",'500','red');
-					echo get_string('errfileexists','block_file_manager', $rec->name);
-					print_simple_box_end();
-					$exists = true;
-				} else {
-					if (!@copy($sourcefile,$destinationfile)) {
-						error(get_string('errcantmovefile','block_file_manager'));
-					}
-					if (!@unlink($sourcefile)) {
-						error(get_string('errnodeletefile','block_file_manager'));
-					}
-				}
-			}
-			$rec->folder = $rootdir;
-			if (!$exists && !update_record("fmanager_link",$rec)) {
-				error(get_string('errnoupdate','block_file_manager'));
-			}
-		}
-	}
-}
-	
-// $path  = Path of folder/file
-function fm_get_size($path, $rawbytes = 0) {
-	if (!is_dir($path)) {
-		return fm_readable_filesize(@filesize($path));
-	}
-	$dir = opendir($path);
-	while ($file = readdir($dir)) {
-		if (is_dir($path."/".$file) && $file != "." && $file != "..") {
-			$size += fm_get_size($path."/".$file, 1);
-		} else {
-			$size += @filesize($path."/".$file);
-		}
-	}
-	if ($rawbytes == 1) {
-		return $size;
-	}
-	if ($size == 0) {
-		return "0 Bytes";
-	} else {
-		return fm_readable_filesize($size);
-	}
-}
-
-function fm_readable_filesize($size) {
-	$filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
-	if ($size != 0) {
-		return round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i];
-	} else {
-		return "0".$filesizename[0];
-	}
-}
-/*************************** Category Functions *****************************/
-// This either creates a new category or updates the existing one
-// 	fm_update_category($name, $catid);	
-// This takes a num or an array of nums and returns a catname or an array of catnames
-// 	fm_get_user_categories($catid)			
-// Returns an array of user's categories for choose_from_menu function
-// 	fm_get_cat_list()
-/****************************************************************************/
-
-// $name 	= Name of category
-// $catid 	= If present, then updating an existing
-function fm_update_category($name, $catid = NULL) {
-	global $USER;
-	
-	if ($catid != NULL) {
-		$update->id = $catid;
-		$update->name = $name;
-		$update->timemodified = time();
-		if (!update_record("fmanager_categories", $update)) {
-			error(get_string("errnoupdate","block_file_manager"));
-		}
-	} else {
-		$new->name = $name;
-		$new->owner = $USER->id;
-		$new->timemodified = time();
-		if (!insert_record("fmanager_categories", $new)) {
-			error(get_string("errnoinsert","block_file_manager"));
-		}
-	}
-	return true;
-}
-
-// $catid		= An array of catids or a single catid
-function fm_get_user_categories($catid) {
-	if (!is_array($catid)) {	
-		$rec = get_record("fmanager_categories", "id", $catid);
-		return $rec->name;
-	} else {
-		$tmp = array();
-		foreach ($catid as $cid) {
-			$tmp[] = fm_get_user_categories($cid);
-		}
-		return $tmp;
-	}
-}
-
-function fm_get_cat_list() {
-	global $USER;
-	
-	$cats[0] = get_string("btnnoassigncat","block_file_manager");
-	if ($catsrec = get_records("fmanager_categories", "owner", $USER->id, "name")) {
-	foreach ($catsrec as $c) {
-		$cats[$c->id] = $c->name;
-	}
-	}
-	return $cats;
-}
-
-/************************* Shared Link Functions ****************************/
-// Deletes all shared link entries associated with deleted link or with unsharing all
-//	fm_update_shared_links($linkid)
-// Returns an object of all links with the specified category (not including folders)
-// 	fm_get_links_shared_by_cat($original, $catid)
-// Returns an object of all folders with specified category
-//	fm_get_folder_shared_by_cat($original,$catid)
-// Returns an object of all links under specified folder
-// 	fm_get_all_shared_by_folder($original, $foldid)
-// Returns an object of all folders under specified folder
-//  fm_get_all_sharedf_by_folder($original, $foldid)
-/****************************************************************************/
-
-// $linkid 		= id of deleted link
-function fm_update_shared_links($linkid) {
-
-	if ($sharedlinks = get_records("fmanager_shared", "sharedlink", $linkid)) {
-		foreach ($sharedlinks as $sl) {		
-			if (!delete_records("fmanager_shared", "id", $sl->id)) {
-				error(get_string("errnoupdate","block_file_manager"));
-			}
-		}
-	}
-}
-
-// $original	= owners id
-// $catid		= category id num
-function fm_get_links_shared_by_cat($original, $catid) {
-	return get_records("fmanager_link","owner = $original AND category",$catid);	
-}
-// $original 	= owners id
-// $catid		= category id num
-function fm_get_folder_shared_by_cat($original,$catid) {
-	return get_records('fmanager_folders',"owner = $original AND category",$catid);
-
-}
-// $original 	= owners id
-// $foldid 		= folder id num
-function fm_get_all_shared_by_folder($original, $foldid) {
-	$tmpvar = get_records("fmanager_link","owner=$original AND folder",$foldid);
-
-	return $tmpvar;	
-}
-
-// $original 	= owners id
-// $foldid 		= folder id num
-function fm_get_all_sharedf_by_folder($original, $foldid) {
-	$tmpvar = get_records("fmanager_folders","owner=$original AND pathid",$foldid);
-
-	return $tmpvar;	
-}
-/**************************** Security Functions ****************************/
-// Ensures the user can view shared files from specified user
-// 	fm_user_has_shared($original, $link)
-// Ensures the user can view the shared files 
-//	fm_user_has_shared_ind($sid)
-// Ensures the user can view the category for modification
-// 	fm_user_owns_cat($catid)
-// Ensures the user owns the link 
-//	fm_user_owns_link($linkid)
-// Ensures the user owns the folder 
-// 	fm_user_owns_folder($folderid)
-// Ensures the user can view the page according to settings set by admin
-// 	fm_check_access_rights()
-// Ensures user can view shared category
-// 	fm_user_has_shared_cat($original, $catid)
-// Ensures user can view shared folder
-// 	fm_user_has_shared_folder($original, $foldid)
-// Ensures user can view shared folder via category
-//  fm_user_has_shared_folder_cat
-// Ensures user can view a file from file.php (owner/shared/in a cat/under a folder)
-//	fm_user_can_view_file($id, $fileid)
-// Cleans checkbox array values
-// fm_clean_checkbox_arr($cb)
-/****************************************************************************/
-
-// $original = user who is sharing files to $USER
-// $link 	 = link id of the file being checked
-function fm_user_has_shared($original=0, $link=0) {
-	global $USER, $CFG;
-
-	if ($link == 0) {
-		if (!$sharedfiles = (count_records("fmanager_shared", "owner", $original, "userid", $USER->id) + count_records("fmanager_shared", "owner", $original, "userid", 0))) {	
-			error(get_string("errnoshared", "block_file_manager"));
-		}
-	} else {
-		if (!$sharedfiles = (count_records("fmanager_shared","owner",$original,"userid",$USER->id,"sharedlink",$link) + count_records("fmanager_shared","owner",$original,"userid",0,"sharedlink",$link))) {
-			error(get_string("errnoshared","block_file_manager"));
-		}
-	}
-	return true;
-}
-
-// $sid		= Shared link id
-function fm_user_has_shared_ind($sid) {
-	global $USER;
-	
-	if (!$sharedfiles = count_records("fmanager_shared","id",$sid,"userid", $USER->id)) {
-		if (!count_records("fmanager_shared","id",$sid,"userid",0)) {
-			error(get_string("errnoshared","block_file_manager"));
-		}
-	}
-	return true;
-}
-
-// $catid	= category id to check ownership
-function fm_user_owns_cat($catid) {
-	global $USER;
-	if ($catid == 0) {
-		return true;
-	}
-	if (!$owncat = count_records("fmanager_categories", "id", $catid, "owner", $USER->id)) {
-		error(get_string("errdontowncat", "block_file_manager"));
-	} else {
-		return true;
-	}
-}
-
-// $linkid		= id of the link
-function fm_user_owns_link($linkid) {
-	global $USER;
-	
-	if ($linkid == 0) {
-		return true;
-	}
-	if (!$ownlink = count_records("fmanager_link", "id", $linkid, "owner", $USER->id)) {
-		error(get_string("errdontownlink", "block_file_manager"));
-	} else {
-		return true;
-	}
-}
-
-// $folderid 	= id of the folder 
-function fm_user_owns_folder($folderid) {
-	global $USER;
-	// Default directory...no folder selected
-	if ($folderid == 0) {
-		return true;
-	}
-	if (!$ownfold = count_records("fmanager_folders", "id", $folderid, "owner", $USER->id)) {
-		error(get_string("errdontownfolder","block_file_manager"));
-	} else {
-		return true;
-	}
-}
-
-// $id 			= course id
-// $chk1		= Flags to check if can share files
-// $chk2		= Flags to check *******
-function fm_check_access_rights($id=0, $chk1=false, $chk2=false) {
-	$userinttype = fm_get_user_int_type();
-	$tmp = get_record("fmanager_admin", "usertype", $userinttype);
-	if ($tmp->enable_fmanager == 0) {
-		error(get_string("errfmandisabled","block_file_manager"), $SESSION->fromdiscussion);
-	}
-	// Checks if they can share files and if they can share from course 1
-	if (($tmp->sharetoany == 0) && ($id == 1) && ($chk2 != false)) {
-		error(get_string("errcantviewshared","block_file_manager", "from this course"));
-	}
-	if (($chk1 != false) && ($tmp->allowsharing == 0)) {
-		error(get_string("errcantviewshared","block_file_manager"));
-	}
-}
-
-// $original		= id of the person who is sharing
-// $catid			= id of the category being shared
-function fm_user_has_shared_cat($original, $catid) {
-	global $USER, $CFG;
-	$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '0' AND owner='$original' AND type='1' AND sharedlink='$catid' OR userid='$USER->id' AND owner='$original' AND type='1' AND sharedlink='$catid'";
-	if (!count_records_sql($mysql)) {
-		echo $mysql;
-		error(get_string('errnoviewcat','block_file_manager'));
-	} else {
-		return true;
-	}
-}
-
-// $original		= id of the person who is sharing
-// $foldid			= id of the category being shared
-function fm_user_has_shared_folder($original, $foldid) {
-	global $USER, $CFG;
-	
-	if (fm_user_has_shared_folder_cat($original, $foldid)) {
-		return true;
-	} else {
-		// Pulls out directly shared folder
-		$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '0' AND owner='$original' AND type='2' AND sharedlink='$foldid' OR userid='$USER->id' AND owner='$original' AND type='2' AND sharedlink='$foldid'";
-		if (!get_records_sql($mysql)) {
-			// Checks if the folder is shared via a cascaded folder share
-			$dummyvar = 1;
-			$tmpid = $foldid;
-			while($dummyvar) {
-				$tmp = get_record("fmanager_folders","id",$tmpid);
-				$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '0' AND owner='$original' AND type='2' AND sharedlink='$tmp->pathid' OR userid='$USER->id' AND owner='$original' AND type='2' AND sharedlink='$tmp->pathid'";
-				if (get_records_sql($mysql)) {
-					$dummyvar = 0;
-				} else {
-					$tmpid = $tmp->pathid;
-					if ($tmpid == 0) {		// If root folder is reached and it isnt shared...check if shared via categories
-						error(get_string('errnoviewfold','block_file_manager'));
-					}
-				}
-			}
-		} else {
-			return true;
-		}
-	}
-}
-// $original		= id of the person who is sharing
-// $foldid			= id of the category being shared
-function fm_user_has_shared_folder_cat($original, $foldid) {
-	global $USER, $CFG;
-	
-	while (1) {
-		$fold = get_record("fmanager_folders","id",$foldid);
-		$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '0' AND owner='$original' AND type='1' AND sharedlink ='$fold->category' OR userid='$USER->id' AND owner='$original' AND type='1' AND sharedlink='$fold->category'";
-		if (get_records_sql($mysql)) {
-			$dummyvar = 0;
-			return true;
-		} else if ($fold->pathid == 0) {
-			return false;
-		} else {
-			$foldid = $fold->pathid;
-		}
-	}
-	return false;
-}
-
-// $id 		= courseid
-// $fileid	= id of file to be viewed
-function fm_user_can_view_file($id, $fileid) {
-	global $USER, $CFG;
-			
-	// If they own the file, they can view
-	if (count_records("fmanager_link", "id", $fileid, "owner", $USER->id)) {  
-		return true;
-	}	
-	// If file is shared to them or to everyone in the course they can view
-	$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '0' AND sharedlink='$fileid' AND course='$id' OR userid='$USER->id' AND sharedlink='$fileid' AND course='$id'";
-	if (count_records_sql($mysql)) {
-		return true;
-	}
-	if (!$sharedfile = get_record("fmanager_link", "id", $fileid)) {
-		return false;
-	} 
-	// If shared via shared/nested folder they can view
-	$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid='0' AND type='2' AND course='$id' AND sharedlink='$sharedfile->folder' OR userid='$USER->id' AND type='2' AND course='$id' AND sharedlink='$sharedfile->folder'";
-	if (count_records_sql($mysql)) {
-		return true;
-	} else {   // File isnt under the main folder
-		$tmp = get_record("fmanager_folders", "id", $sharedfile->folder);
-		$foldid = $tmp->pathid;
-		while ($foldid) {	// While folder id isnt the root (0)
-			$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid='0' AND type='2' AND course='$id' AND sharedlink='$foldid' OR userid='$USER->id' AND type='2' AND course='$id' AND sharedlink='$foldid'";
-			if (count_records_sql($mysql)) {
-				return true;
-			}
-			$tmp = get_record("fmanager_folders","id", $tmp->pathid);
-			$foldid = $tmp->id;
-		}
-	}
-	// If file is shared via a shared category they can view
-	$dummyvar = 1;
-	$fid = $sharedfile->folder;
-	if ($fid == 0) {
-		$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid='0' AND type='1' AND course='$id' AND sharedlink='$sharedfile->category' OR userid='$USER->id' AND type = '1' AND course='$id' AND sharedlink='$sharedfile->category'";
-		if (get_record_sql($mysql)) {
-			return true;
-		} else {
-			return false;
-		}
-	}
-	while ($fid) {	
-		$fold = get_record('fmanager_folders','id',$fid);
-		
-		$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid='0' AND type='1' AND course='$id' AND sharedlink='$fold->category' OR userid='$USER->id' AND type='1' AND course='$id' AND sharedlink='$fold->category'";
-		if (count_records_sql($mysql)) {
-			return true;
-		} else {
-			$fid = $fold->pathid;
-		}
-	}
-	// Otherwise, error is displayed
-	return false;
-}
-
-// $cb 	= Checkbox array
-function fm_clean_checkbox_arr() {
-	$cb = NULL;
-	$cb = $_POST['cb'];		// Checkbox array	
-	if (is_array($cb)) {
-		$tmp = array();
-		foreach($cb as $c) {
-			if(substr($c,0,4) == "fold") {
-				$tmp[] = "f-".(int)substr($c,4);
-			} else if (substr($c,0,2) == "f-") {
-				$tmp[] = "f-".(int)substr($c,2);
-			} else {
-				$tmp[] = (int)$c;
-			}
-		}
-		$cb = $tmp;
-	} else {
-		if (substr($cb,0,4) == "fold") {
-			$cb[] = "f-".(int)substr($cb,4);
-		} else if (substr($cb,2) == "f-") {
-			$cb[] = "f-".(int)substr($cb,2);
-		} else {
-			$cb[] = (int)$cb;
-			$cb[]=$singlecb;
-		}
-	}	
-	// Removes 0 as default
-	$nullify = false;
-	foreach ($cb as $c) {
-		if ($c == 0 && substr($c,0,2) != 'f-') {
-			$nullify = true;
-		} else {	
-			$nullify = false;
-		}
-	}
-	if ($nullify == true) {
-		$cb = NULL;
-	}
-	
-	return $cb;
-}
-
-/*************************** Database Functions *****************************/
-// This function processes the submission of yes/no to the conf_delete form & returns strings
-//	fm_process_del($delfrom, $fromid)
-// This function deletes a shared attribute of a file for a user
-// 	fm_del_shared($id)
-// This func processes the submission from the admin_settings.php form
-//	fm_process_admin_settings($entry)
-// Returns the user's integer representation of their type (0=admin, 1=teacher, 2=student)
-// 	fm_get_user_int_type()
-/****************************************************************************/
-	
-// $delfrom		= table to delete record from
-// $fromid		= id(s) of the record(s) to delete
-function fm_process_del($delfrom, $fromid) {
-	global $USER;
-	
-	if (isset($_POST['yesdel'])) {
-		if (is_array($fromid)) {
-			foreach($fromid as $id) {
-				if (!delete_records($delfrom, "id", $id)) {
-					error(get_string("errnodelete","block_file_manager"));
-				}
-			} 
-		} else {
-			if (!delete_records($delfrom, "id", $fromid)) {
-				error(get_string("errnodelete","block_file_manager"));
-			}
-		}
-		return true;
-	} else if (isset($_POST['nodel'])) {
-		return true;
-	}
-}
-
-// $id 	= id of shared files to be removed
-function fm_del_shared($ids, $courseid) {
-	global $USER;
-	
-	if (isset($_POST['yesdel'])) {
-		if (is_array($ids)) {
-			foreach($ids as $id) {
-				// Ensures they can even view file to delete permission to view it
-				if ($id != 0) {
-					if (fm_user_has_shared_ind($id)) {
-						// Shared to the entire class
-						if ($t = get_record("fmanager_shared","id",$id,"userid",0)) {
-							// for courses with students/teachers
-							if ($courseid != 1) {
-								if ($teachers = get_records("user_teachers","course",$courseid)) {
-									foreach ($teachers as $teacher) {
-										if ($teacher->userid != $USER->id) {
-											$t->userid = $teacher->userid;
-											insert_record('fmanager_shared',$t);
-										}
-									}
-								}
-								if ($students = get_records("user_students","course",$courseid)) {
-									foreach ($students as $student) {
-										if ($student->userid != $USER->id) {
-											$t->userid = $student->userid;
-											insert_record('fmanager_shared',$t);
-										}
-									}
-								}
-								delete_records("fmanager_shared","id",$id);
-							} else {
-							// else share to all users sitewide
-								if ($users = get_records("user")) {
-									foreach($users as $user) {
-										if ($user->id != $USER->id  && $user->username != "guest") {
-											$t->userid = $user->id;
-											insert_record("fmanager_shared",$t);
-										}
-									}
-								}						
-								delete_records("fmanager_shared","id",$id);			
-							}
-						} else {
-							delete_records("fmanager_shared","id",$id);
-						}
-					}
-				}
-			}
-		}
-		return true;
-	} else if (isset($_POST['nodel'])) {
-		return true;
-	}
-}
-
-// $entry 		= object that contains all form data ($entry->usertype and any data required)
-function fm_process_admin_settings($entry) {
-	// Deals with all processing from the files section of admin
-	if (!$exist_record = get_record("fmanager_admin", "usertype", $entry->usertype)) {
-		$tmp = NULL;
-		$tmp->usertype = $entry->usertype;
-		if (!insert_record("fmanager_admin", $tmp)) {
-			$err = NULL;
-			$err->errtype = "insert";
-			$err->forhwho ="user";
-			error(get_string("errrecordmod","block_file_manager", $err), $_SERVER["HTTP_REFERER"]);
-		}
-	}
-	if ($exist_record = get_record("fmanager_admin", "usertype", $entry->usertype)) {
-		$entry->id = $exist_record->id;
-		if (!update_record("fmanager_admin", $entry)) {
-			$err = NULL;
-			$err->errtype = "update";
-			$err->forwho = "user";
-			error(get_string("errrecordmod", "block_file_manager", $err), $_SERVER["HTTP_REFERER"]);
-		}
-	}
-}
-
-function fm_get_user_int_type() {
-	if (isadmin()) {
-		return 0;
-	} else if (isteacherinanycourse("0", false)) {
-		return 1;
-	} else {
-		return 2;
-	}
-}
-
-/*************************** Zip Functions **********************************/
-// 	fm_zip_files($originalfiles, $destination)
-//  fm_unzip_file($zipfile, $destination = '', $showstatus = true)
-// Reorders a list of unzipped objects with folders first 
-//  fm_reorder_folders_list($obj1, $obj2)
-//  fm_unzip_cleanfilename($p_event, &$p_header)
-//  fm_unzip_show_status($list, $removepath)
-// Shows contents of target zipped file
-//  fm_view_zipped($file)
-/****************************************************************************/
-function fm_zip_files ($originalfiles, $destination, $zipname="zip01", $rootdir=0) {
-//Zip an array of files/dirs to a destination zip file
-//Both parameters must be FULL paths to the files/dirs
-// Modded for Myfiles 
-// Michael Avelar 1/19/06
-
-    global $CFG, $USER;
-
-    //Extract everything from destination
-    $path_parts = pathinfo(cleardoubleslashes($destination));
-    $destpath = $path_parts["dirname"];       //The path of the zip file
-    $destfilename = $path_parts["basename"];  //The name of the zip file
-    $extension = $path_parts["extension"];    //The extension of the file
-	// To put the zipped file into the current directory
-	$destpath = $destpath."/".$destfilename;
-	// To allow naming of zipfiles
-	$destfilename = $zipname;
-    //If no file, error
-    if (empty($destfilename)) {
-        return false;
-    }
-
-    //If no extension, add it
-    if (empty($extension)) {
-        $extension = 'zip';
-        $destfilename = $destfilename.'.'.$extension;
-    }
-
-    //Check destination path exists
-    if (!is_dir($destpath)) {
-        return false;
-    }
-
-    //Check destination path is writable. TODO!!
-
-    //Clean destination filename
-    $destfilename = clean_filename($destfilename);
-
-    //Now check and prepare every file
-    $files = array();
-    $origpath = NULL;
-
-    foreach ($originalfiles as $file) {  //Iterate over each file
-        //Check for every file
-        $tempfile = cleardoubleslashes($file); // no doubleslashes!
-        //Calculate the base path for all files if it isn't set
-        if ($origpath === NULL) {
-            $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
-        }
-        //See if the file is readable
-        if (!is_readable($tempfile)) {  //Is readable
-            continue;
-        }
-        //See if the file/dir is in the same directory than the rest
-        if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
-            continue;
-        }
-        //Add the file to the array
-        $files[] = $tempfile;
-    }
-
-    //Everything is ready:
-    //    -$origpath is the path where ALL the files to be compressed reside (dir).
-    //    -$destpath is the destination path where the zip file will go (dir).
-    //    -$files is an array of files/dirs to compress (fullpath)
-    //    -$destfilename is the name of the zip file (without path)
-
-    //print_object($files);                  //Debug
-
-    if (empty($CFG->zip)) {    // Use built-in php-based zip function
-
-        include_once("$CFG->libdir/pclzip/pclzip.lib.php");
-        $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
-        if (($list = $archive->create($files, PCLZIP_OPT_REMOVE_PATH,$origpath) == 0)) {
-            notice($archive->errorInfo(true));
-            return false;
-        }
-
-    } else {                   // Use external zip program
-
-        $filestozip = "";
-        foreach ($files as $filetozip) {
-            $filestozip .= escapeshellarg(basename($filetozip));
-            $filestozip .= " ";
-        }
-        //Construct the command
-        $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
-        $command = 'cd '.escapeshellarg($origpath).$separator.
-                    escapeshellarg($CFG->zip).' -r '.
-                    escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
-        //All converted to backslashes in WIN
-        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
-            $command = str_replace('/','\\',$command);
-        }
-        Exec($command);
-    }
-	// Adds an entry into myfiles api
-	$newentry = NULL;
-	$newentry->owner = $USER->id;
-	$newentry->type = TYPE_ZIP;
-	$newentry->folder = $rootdir;
-	$newentry->category = 0;
-	$newentry->name = substr($destfilename,0,-4);
-	$newentry->description = '';
-	$newentry->link = $destfilename;
-	$newentry->timemodified = time();
-	if (!fm_update_link($newentry)) {
-		error(get_string("errnoupdate","block_file_manager"));
-	}
-    return true;
-}
-
-function fm_unzip_file ($zipfile, $destination = '', $showstatus = false, $currentdir=0) {
-//Unzip one zip file to a destination dir
-//Both parameters must be FULL paths
-//If destination isn't specified, it will be the
-//SAME directory where the zip file resides.
-// Modded for Myfiles 
-// Michael Avelar 1/24/06 
-    global $CFG, $USER;
-
-    //Extract everything from zipfile
-    $path_parts = pathinfo(cleardoubleslashes($zipfile));
-    $zippath = $path_parts["dirname"];       //The path of the zip file
-    $zipfilename = $path_parts["basename"];  //The name of the zip file
-    $extension = $path_parts["extension"];    //The extension of the file
-
-    //If no file, error
-    if (empty($zipfilename)) {
-        return false;
-    }
-
-    //If no extension, error
-    if (empty($extension)) {
-        return false;
-    }
-
-    //If no destination, passed let's go with the same directory
-    if (empty($destination)) {
-        $destination = $zippath;
-    }
-
-    //Clear $destination
-    $destpath = rtrim(cleardoubleslashes($destination), "/");
-
-    //Check destination path exists
-    if (!is_dir($destpath)) {
-        return false;
-    }
-
-    //Check destination path is writable. TODO!!
-
-    //Everything is ready:
-    //    -$zippath is the path where the zip file resides (dir)
-    //    -$zipfilename is the name of the zip file (without path)
-    //    -$destpath is the destination path where the zip file will uncompressed (dir)
-
-    if (empty($CFG->unzip)) {    // Use built-in php-based unzip function
-
-        include_once("$CFG->libdir/pclzip/pclzip.lib.php");
-        $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
-        if (!$list = $archive->extract(PCLZIP_OPT_PATH, $destpath,
-                                       PCLZIP_CB_PRE_EXTRACT, 'unzip_cleanfilename')) {
-            notice($archive->errorInfo(true));
-            return false;
-        }
-
-    } else {                     // Use external unzip program
-
-        $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
-        $redirection = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '' : ' 2>&1';
-
-        $command = 'cd '.escapeshellarg($zippath).$separator.
-                    escapeshellarg($CFG->unzip).' -o '.
-                    escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
-                    escapeshellarg($destpath).$redirection;
-        //All converted to backslashes in WIN
-        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
-            $command = str_replace('/','\\',$command);
-        }
-        Exec($command,$list);
-    }
-	// Inserts unzipped objects into myfiles api
-	$afolder = $currentdir;
-	// Reorders list so that folders are inserted into database before links
-	$list2 = array();
-	foreach($list as $l) {
-		if ($l['folder'] == 1) {
-			$list2[] = $l;
-		}
-	}
-	// Reorders folders list to extract them in order, so the database has the folder before
-	// inserting stuff into that folder
-
-	usort($list2, 'fm_reorder_folders_list');
-	// Recompiles the completed list...with ordered folders first, then files
-	foreach($list as $l) {
-		if ($l['folder'] != 1) {
-			$list2[] = $l;
-		}
-	}
-	foreach($list2 as $l) {
-		if ($l['folder'] == 1) {	// is an unzipped folder
-			$newfolder = NULL;
-			$newfolder->owner = $USER->id;
-			$tmp = explode('/',$l['stored_filename']);
-			// compiles the path of the folder
-			$tmppath = '/';
-			foreach ($tmp as $t) {
-				if ($t != '') {
-					$tmppath .= $t."/";
-				}
-			}
-			$tmp = array_reverse($tmp);
-			$tmppath = substr($tmppath, 0, (strrpos($tmppath, $tmp[1])));
-			$newfolder->name = $tmp[1];
-			$newfolder->category = 0;
-			if ($tmp[2] == NULL) {			// Folder is root folder
-				$newfolder->path = '/';
-				$newfolder->pathid = 0;
-			} else {
-				// Puts all folders in their place :)
-				$pathtmp = '/';
-				$count = count($tmp);
-				while ($count > 3) {
-					$pathtmp .= $tmp[$count - 1].'/';
-					$count--;
-				}
-				$rec = get_record("fmanager_folders","name",$tmp[2],"path",$pathtmp);
-				$afolder = $rec->id;
-				$newfolder->path = fm_get_folder_path($afolder)."/";
-				$newfolder->pathid = $afolder;
-			}
-			$newfolder->timemodified = time();
-			if (!$afolder = insert_record('fmanager_folders',$newfolder)) {
-				error(get_string('errnoinsert','block_file_manager'));
-			}
-		} else {
-			$tmp = explode('/', $l['stored_filename']);
-			$newlink = NULL;
-			$newlink->owner = $USER->id;
-			$newlink->type = TYPE_FILE;	
-			$rootlinkstr = '';
-			// Compiles path string
-			$count = count($tmp);
-			$count = $count - 2;
-			foreach($tmp as $t) {
-				if ($count > 0) {
-					if ($t != '') {
-						$rootlinkstr .= '/'.$t;
-					}
-					$count--;
-				}
-			} 
-			if (substr($rootlinkstr,0,1) != '/') {
-				$rootlinkstr = '/'.$rootlinkstr;
-			}
-			if ($rootlinkstr != '/') {
-				$rootlinkstr = $rootlinkstr.'/';
-			}
-			$tmp = array_reverse($tmp);
-			if (!$foldstr = get_record("fmanager_folders","owner",$USER->id,"name",$tmp[1],"path",$rootlinkstr)) {
-				$foldstr->id = $currentdir;
-			}			
-			$newlink->folder = $foldstr->id;
-			$newlink->category = 0;
-			$newlink->name = substr($tmp[0],0,-4);
-			$newlink->description = '';
-			$newlink->link = $tmp[0];
-			$newlink->timemodified = time();
-			if (!$alink = insert_record('fmanager_link',$newlink)) {
-				error(get_string('errnoinsert','block_file_manager'));
-			}
-		}	
-	}
-    //Display some info about the unzip execution
-    if ($showstatus) {
-        fm_unzip_show_status($list,$destpath);
-    }
-
-    return $list;
-}
-
-// $list = list of the folders to be reordered
-function fm_reorder_folders_list($obj1, $obj2) {
-	$size1 = explode("/",$obj1['stored_filename']);
-	$size2 = explode("/",$obj2['stored_filename']);
-
-	if (count($size1) == count($size2)) {
-		return 0;
-	}
-	if (count($size1) > count($size2)) {
-		return 1;
-	}
-	if (count($size1) < count($size2)) {
-		return -1;
-	}
-}
-
-function fm_unzip_cleanfilename ($p_event, &$p_header) {
-//This function is used as callback in unzip_file() function
-//to clean illegal characters for given platform and to prevent directory traversal.
-//Produces the same result as info-zip unzip.
-    $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
-    $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
-    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
-        $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
-        $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
-    } else {
-        //Add filtering for other systems here
-        // BSD: none (tested)
-        // Linux: ??
-        // MacosX: ??
-    }
-    $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
-    return 1;
-}
-
-function fm_unzip_show_status ($list,$removepath) {
-//This function shows the results of the unzip execution
-//depending of the value of the $CFG->zip, results will be
-//text or an array of files.
-
-    global $CFG;
-
-    if (empty($CFG->unzip)) {    // Use built-in php-based zip function
-        $strname = get_string("name");
-        $strsize = get_string("size");
-        $strmodified = get_string("modified");
-        $strstatus = get_string("status");
-        echo "<table cellpadding=\"4\" cellspacing=\"2\" border=\"0\" width=\"640\">";
-        echo "<tr><th class=\"header\" align=\"left\">$strname</th>";
-        echo "<th class=\"header\" align=\"right\">$strsize</th>";
-        echo "<th class=\"header\" align=\"right\">$strmodified</th>";
-        echo "<th class=\"header\" align=\"right\">$strstatus</th></tr>";
-        foreach ($list as $item) {
-            echo "<tr>";
-            $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
-            print_cell("left", $item['filename']);
-            if (! $item['folder']) {
-                print_cell("right", display_size($item['size']));
-            } else {
-                echo "<td>&nbsp;</td>";
-            }
-            $filedate  = userdate($item['mtime'], get_string("strftimedatetime"));
-            print_cell("right", $filedate);
-            print_cell("right", $item['status']);
-            echo "</tr>";
-        }
-        echo "</table>";
-
-    } else {                   // Use external zip program
-        print_simple_box_start("center");
-        echo "<pre>";
-        foreach ($list as $item) {
-            echo str_replace(cleardoubleslashes($removepath.'/'), '', $item).'<br />';
-        }
-        echo "</pre>";
-        print_simple_box_end();
-    }
-}
-
-// $file = object of target zip file
-function fm_view_zipped($file) {
-	global $CFG, $USER;
-	
-	if ($file->folder == 0) {
-		$ziploc = $CFG->dataroot."/".fm_get_user_dir_space()."/".$file->link;
-	} else {
-		$ziploc = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($file->folder)."/".$file->link;
-	}
-
-	$filelist = array();
-	$zip = zip_open($ziploc);
-	if ($zip) {
-		$count = 0;
-		while ($zip_entry = zip_read($zip)) {
-		   $filelist[$count]->name = zip_entry_name($zip_entry);
-		   $filelist[$count]->actualsize = zip_entry_filesize($zip_entry);
-		   $filelist[$count]->compsize = zip_entry_compressedsize($zip_entry);
-		   $count++;
-		}
-		zip_close($zip);
-	}
-	return $filelist;
-}
-
-/*************************** Print Functions ********************************/
-// Located within print_lib.php
-/****************************************************************************/
-
-/*************************** JS Print Functions *****************************/
-// Located within print_lib.php
-/****************************************************************************/
-
-
-
-function shared_files_assignment_file_submission($entry, $assignment) {
-/// Copies a file to the teacher's assignment directory for that course
-	global $CFG, $USER;
-	$pathnew = "$assignment->course/moddata/assignment/$assignment->id/$USER->id";
-	$pathold = "$CFG->dataroot/shared_files/users/$entry->userid";
-
-	make_upload_directory($pathnew);
-
-	if (!copy("$pathold/$entry->attachment", "$CFG->dataroot/$pathnew/$entry->attachment")) {
-		error ("Failed to copy file!", "view.php?id=$id&rootdir=$rootdir");
-	}
-}
-
-
-// When called, outputs all groups and members of a course, using $listmembers and $listgroups defined in 
-// call to get_list_members()
-function show_visible_groups($course, $listmembers, $listgroups, $filerefphp) {	
-	// Print out the selection boxes and fill with groups/members
-	echo "<tr><td width=\"45%\" align=\"center\"><form name=\"form2\" id=\"form2\">
-		<input type=\"hidden\" name=\"id\" value=\"$course->id\"><select name=\"groups\" size=\"15\" onChange=\"updateMembers(this)\" multiple>";
-	if (!empty($listgroups)) {
-		foreach ($listgroups as $id => $listgroup) {
-			$selected = '';
-			if ($id == $selectedgroup) {
-			   $selected = 'selected="selected"';
-			}
-			echo "<option $selected value=\"$id\">$listgroup</option>";
-		}
-	}
-	echo "</select></form></td>";
-	$sharestring = get_string('share', 'block_shared_files');
-	echo "<td width=\"10%\" align=\"center\"><form name=\"formx\" id=\"formx\" method=\"post\" action=\"$filerefphp\">";
-	echo "<input type=\"hidden\" name=\"grpid\" value=\"\"><INPUT TYPE=\"hidden\" NAME=\"bookid\" VALUE=\"$bookid\"><input type=\"hidden\" name=\"id\" value=\"$course->id\"><input name=\"gshare\" type=\"submit\" value=\"$sharestring\"></form></td>";	
-	echo "<td width=\"45%\" align=\"center\"><form name=\"form3\" id=\"form3\">
-          <input type=\"hidden\" name=\"id\" value=\"$course->id\">
-          <select name=\"members[]\" size=\"15\">";
-    if (!empty($members)) {
-    	foreach ($members as $id => $membername) {
-        	echo "<option value=\"$id\">$membername</option>";
-    	}
-	}
-    echo "</select></form></td></tr>";
-}
-
-// called from share & sharefile.php to populate arrays passed by reference to pop js lists
-function get_list_members($course, &$nonmembers, &$listgroups)
-{
-/// First, get everyone into the nonmembers array
-    if ($students = get_course_students($course->id)) {
-        foreach ($students as $student) {
-            $nonmembers[$student->id] = fullname($student, true);
-        }
-        unset($students);
-    }
-
-    if ($teachers = get_course_teachers($course->id)) {
-        foreach ($teachers as $teacher) {
-            $prefix = '- ';
-            if (isteacheredit($course->id, $teacher->id)) {
-                $prefix = '# ';
-            }
-            $nonmembers[$teacher->id] = $prefix.fullname($teacher, true);
-        }
-        unset($teachers);
-    }
-
-/// Pull out all the members into little arrays
-	$groups = get_groups($course->id);
-    if ($groups) {
-        foreach ($groups as $group) {
-            $countusers = 0;
-            $listmembers[$group->id] = array();
-            if ($groupusers = get_group_users($group->id)) {
-                foreach ($groupusers as $groupuser) {
-                    $listmembers[$group->id][$groupuser->id] = $nonmembers[$groupuser->id];
-                    //unset($nonmembers[$groupuser->id]);
-                    $countusers++;
-                }
-                natcasesort($listmembers[$group->id]);
-            }
-            $listgroups[$group->id] = $group->name." ($countusers)";
-        }
-        natcasesort($listgroups);
-    }
-
-    natcasesort($nonmembers);
-	if (empty($selectedgroup)) {    // Choose the first group by default
-        if (!empty($listgroups) && ($selectedgroup = array_shift(array_keys($listgroups)))) {
-            $members = $listmembers[$selectedgroup];
-        }
-    } else {
-        $members = $listmembers[$selectedgroup];
-    }
-	return $listmembers;
-}
-
-/*********************** Moodle Required Functions **************************/
-//	upgrade_file_manager_db($continueto)  								
-/****************************************************************************/
-
-// This function upgrades the file_manager's tables, if necessary
-// It's called from admin/index.php
-function upgrade_file_manager_db($continueto) {
-    
-    global $CFG, $db;
-	$fmdir = fm_get_root_dir();
-
-    require_once ("$CFG->dirroot/$fmdir/version.php");  // Get code versions
-
-    if (empty($CFG->file_manager_version)) {                  // file_manager has never been installed.
-        $strdatabaseupgrades = get_string("databaseupgrades");
-        print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades, 
-                         "", "", false, "&nbsp;", "&nbsp;");
-
-        $db->debug=true;
-        if (modify_database("$CFG->dirroot/$fmdir/db/$CFG->dbtype.sql")) {
-            $db->debug = false;
-            if (set_config("file_manager_version", $file_manager_version) and set_config("file_manager_release", $file_manager_release)) {
-                notify(get_string("databasesuccess"), "green");
-                print_continue($continueto);
-                exit;
-            } else {
-                error("Upgrade of file_manager system failed! (Could not update version in config table)", "view.php?id=$id&rootdir=$rootdir");
-            }
-        } else {
-            error("file_manager tables could NOT be set up successfully!", "view.php?id=$id&rootdir=$rootdir");
-        }
-    }
-
-    if ($file_manager_version > $CFG->file_manager_version) {       // Upgrade tables
-        $strdatabaseupgrades = get_string("databaseupgrades");
-        print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades);
-
-        require_once ("$CFG->dirroot/$fmdir/db/$CFG->dbtype.php");
-
-        $db->debug=true;
-        if (file_manager_upgrade($CFG->file_manager_version)) {
-            $db->debug=false;
-            if (set_config("file_manager_version", $file_manager_version) and set_config("file_manager_release", $file_manager_release)) {
-                notify(get_string("databasesuccess"), "green");
-                notify(get_string("databaseupgradebackups", "", $file_manager_release));
-                print_continue($continueto);
-                exit;
-            } else {
-                error("Upgrade of file_manager system failed! (Could not update version in config table)", "view.php?id=$id&rootdir=$rootdir");
-            }
-        } else {
-            $db->debug=false;
-            error("Upgrade failed!  See file_manager/version.php", "view.php?id=$id&rootdir=$rootdir");
-        }
-
-    } else if ($file_manager_version < $CFG->file_manager_version) {
-        notify("WARNING!!!  The code you are using ($file_manager_version) is OLDER than the version that made the current database ($CFG->file_manager_version)!");
-    }
-}		 
-
-?>
+<?PHP 
+/****************************************************************************
+ Filename:  lib.php
+  Created:  Michael Avelar
+   Edited:  Josh Abbott
+  Created:  5/23/05
+ Modified:  1/6/06
+  Purpose:  This file contains all the functions used within the file_manager 
+*****************************************************************************/
+/**************************** Organization **********************************/
+// Link Types					// Defines link types
+// Link Functions				// Deals with all file related features
+// Folder Functions				// Deals with all folder related features
+// Category Functions			// Deals with all category related features
+// Shared Link Functions		// Deals with all shared links 
+// Security Functions			// Has all functions that check for ownership/permissions/etc
+// Database Functions			// Various db functions
+// ZIP Functions				// Deals with zip archiving and related functions
+// Print Functions				// (See print_lib.php) Functions to print tables/forms to screen etc.
+// JS Print Functions			// (See print_lib.php) Prints short javascript functions
+// Moodle Required Functions	// Required by moodle
+/****************************************************************************/
+require_once("$CFG->dirroot/lib/filelib.php");
+
+/*************************** Link Types *************************************/
+define('TYPE_FILE', 1);
+define('TYPE_URL', 2);
+define('TYPE_ZIP', 3);   
+define('STYPE_FILE',0);
+define('STYPE_CAT',1);
+define('STYPE_FOLD',2);
+//DWT, role id in table role for teacher and student.
+//Future enhancement - should get the ids from the table instead
+//This code will break id the site administrator redefines the roles!
+//I don't like to hard coding stuff but it gets the job done for now, a hack :).
+define('ADMIN_ROLEID', 1);
+define('COURSECREATOR_ROLEID', 2);
+define('TEACHER_ROLEID', 3);
+define('NONEDITING_TEACHER_ROLEID', 4);
+define('STUDENT_ROLEID', 5);
+
+
+/*************************** Link Functions *********************************/
+// Returns the link record
+//	fm_get_user_link($linkid)
+// Creates or Updates a link record
+// 	fm_update_link($link, $linkid)
+// Deletes references to a deleted category
+//	fm_update_links_cats($catid)
+// Uploads the specified file to the user's personal directory
+//	fm_upload_file($fileurl, $linkrename, $rootdir)
+// Deletes a file 
+//	fm_remove_file($file)
+/****************************************************************************/
+
+// $linkid 		= single link id
+function fm_get_user_link($linkid) {
+	global $USER;
+
+	if (!$linksrec = get_record("fmanager_link", "id", $linkid, "owner", $USER->id)) {
+		error(get_string("errnoviewfile","block_file_manager"));
+	}
+	
+	return $linksrec;
+}
+
+// $link    	= object containing updated info
+// $linkid		= id of link to be updated
+function fm_update_link($link, $linkid = NULL, $id=1, $rootdir=0) {
+	global $USER, $CFG;
+	
+	if ($linkid != NULL) {		// update a record
+		$link->id = $linkid;
+		$tmp = get_record("fmanager_link", "id", $linkid);
+		if ($tmp->type == TYPE_URL) {
+			// Appends any url link with an http:// if it doesnt exist
+			if (strncmp($link->url, "http://", 6) != 0) {
+				$link->url = "http://" . $link->url;
+			} 
+			$link->link = $link->url;
+		}
+		$link->timemodified = time();
+		// File name was changed
+		if ($tmp->link != $link->link) {
+			$destinationfile = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($tmp->folder)."/".$link->link;
+			$sourcefile = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($tmp->folder)."/".$tmp->link;
+			if (file_exists($destinationfile)) {
+				error(get_string('errfileexists','block_file_manager', $link->link),"link_manage.php?id=1&linkid=$linkid&rootdir=$rootdir");
+			}				
+			if (!@rename($sourcefile,$destinationfile)) {
+				error(get_string('errnorename','block_file_manager'));
+			}
+		} 
+		if (!update_record("fmanager_link", $link)) {
+			error(get_string("errnoupdate","block_file_manager"));
+		}
+	} else {
+		if ($link->radioval == "file") {
+			$link->type = TYPE_FILE;
+		} else if ($link->type != TYPE_ZIP) {
+			$link->type = TYPE_URL;
+			// Appends any url link with an http:// if it doesnt exist
+			if (strncmp($link->url, "http://", 6) != 0) {
+				$link->url = "http://" . $link->url;
+			} 
+		}
+		$link->owner = $USER->id;  
+		$link->link = $link->url;
+		$link->timemodified = time();
+		if ($link->type == TYPE_ZIP) {
+			$link->link = $link->name.".zip";
+		}
+		// Allows user to upload zip files
+		if (substr($link->link,-4) == ".zip") {
+			$link->type = TYPE_ZIP;
+		}
+		if (!insert_record("fmanager_link", $link)) {
+			error(get_string("errnoinsert","block_file_manager"));
+		}
+	}
+	return true;
+}
+
+// $catid 		= id of category being removed
+function fm_update_links_cats($catid) {
+	// Changes all associated links to deleted cat to 0
+	if ($linkcats = get_records("fmanager_link", "category", $catid)) {
+		foreach ($linkcats as $lc) {		
+			$lc->category = 0;
+			if (!update_record("fmanager_link", $lc)) {
+				error(get_string("errnoupdate","block_file_manager"));
+			}
+		}
+	}
+}
+// $fileurl 	= The file's location on the user's computer
+// $linkrename 	= If file existed already, this will store the renamed file if the user chooses to rename
+// $rootdir		= target directory of uploaded file
+function fm_upload_file($fileurl, $linkrename, $rootdir=0) {
+	global $USER;
+	
+	if ($linkrename != NULL) {
+		// renaming file and adding the extension
+		$newfilename = clean_filename($linkrename.stristr($fileurl['name'], '.'));
+	} else {
+		$newfilename = clean_filename($fileurl['name']);
+	}
+	
+	$folder = get_record("fmanager_folders", "id", $rootdir);
+
+    if (valid_uploaded_file($fileurl)) {
+        if (!$newfilename) {
+            error(get_string("errwierdfilename", "block_file_manager", $fileurl['name']));
+        } else if (!$dir = make_upload_directory(fm_get_user_dir_space()."$folder->path$folder->name")) {
+            error(get_string("errnodir","block_file_manager"));
+        } else {
+			if(file_exists("$dir/$newfilename")) {
+				$newfilename = "";		// flags the link_manage that file existed already
+			} else {
+				if (move_uploaded_file($fileurl['tmp_name'], "$dir/$newfilename")) {
+					chmod("$dir/$newfilename", 0755);
+				} else {
+					error(get_string("errserversave","block_file_manager"), "view.php?id=$id&rootdir=$rootdir");
+				}
+			}
+        }
+    } else {
+		error(get_string("errwierdfilename", "block_file_manager", $fileurl['name']));
+    }
+
+    return $newfilename;
+}
+
+// $file 	= link entry that is being deleted
+function fm_remove_file($file) {
+	global $CFG;
+	
+	$bdir = $CFG->dataroot."/".fm_get_user_dir_space();
+	// If there is no sub-folder
+	if ($file->folder == 0) {		
+		$bdir = $bdir."/".$file->link;
+	} else {
+		$bdir = $bdir."/".fm_get_folder_path($file->folder)."/".$file->link;
+	}
+	
+	if (!file_exists($bdir)) {		// If file isnt found for some reason...
+		return get_string("msgfilenotfound","block_file_manager", $file->link);
+	} else if (!@unlink($bdir)) {		// Deletes the attachment
+		error(get_string("errnodeletefile","block_file_manager"));
+	} 
+	return NULL;
+}
+
+/*************************** Folder Functions *******************************/
+// Returns the location of the file_manager folder...just incase
+// 	fm_get_root_dir()
+// Returns the user's personal directory space
+//	fm_get_user_dir_space()
+// Returns the folder entry given a fm_folders id
+//	fm_get_folder_path($folderid, $notsecure)
+// Deletes a folder and all subdirectories
+//  fm_delete_folder($path)
+// Moves specified file/link/folder into destination folder
+//  fm_move_to_folder($c, $rootdir)
+// Returns folder/file size
+//  fm_get_size($path)
+// Converts Bytes into more readable info
+//  fm_readable_filesize($size)
+/****************************************************************************/
+
+function fm_get_root_dir() {
+	return "blocks/file_manager";
+}
+
+function fm_get_user_dir_space($userid = NULL) {
+	global $USER;
+	
+	if ($userid == NULL) {
+		$userid = $USER->id;
+	}
+	
+	return "file_manager/users/$userid";
+}
+
+// $filderid 	= A fm_folders unique id number
+// $notsecure	= flag to not check for ownership...(for shared files)
+function fm_get_folder_path($folderid, $notsecure = false) {
+	global $USER;
+	
+	if ($folderid == 0) {
+		return "";
+	} else {
+		// Ensure user owns the folder
+		if ($notsecure == false) { fm_user_owns_folder($folderid); }
+		if (!$retval = get_record("fmanager_folders", "id", $folderid)) {
+			return "";
+		} 
+		return $retval->path.$retval->name;
+	}
+}
+
+// dir = folder database object
+function fm_delete_folder($dir) {
+	global $CFG, $USER;
+	
+	// if the dir being deleted is a root dir (eg. has some dir's under it)
+	if ($child = get_record("fmanager_folders","pathid",$dir->id)) {
+		fm_delete_folder($child);
+	} 
+	// Deletes all files/url links under folder
+	if ($allrecs = get_records("fmanager_link","folder",$dir->id)) {
+		foreach ($allrecs as $ar) {
+			// a file
+			if ($ar->type == TYPE_FILE || $ar->type == TYPE_ZIP) {
+				fm_remove_file($ar);
+			} 
+			// removes shared aspect
+			delete_records("fmanager_shared","sharedlink",$ar->id);					
+			// Delete link
+			delete_records("fmanager_link","id",$ar->id);
+		}
+	}
+	// delete shared to folder
+	delete_records("fmanager_shared","sharedlink",$dir->id);	
+
+	if (!@rmdir($CFG->dataroot."/file_manager/users/".$USER->id.$dir->path.$dir->name."/")) {
+		error(get_string("errnodeletefolder","block_file_manager"));
+	}
+	delete_records("fmanager_folders","id",$dir->id);
+	
+}
+
+// $c 		= id of link/folder (folders are 'f-' appended with id)
+// $rootdir = id of destination folder
+function fm_move_to_folder($c, $rootdir) {
+	global $CFG;
+	if ($c != 0 || substr($c,0,2) == 'f-') {
+		if (substr($c,0,2) == 'f-') {
+			$tmpfoldid = substr($c,2);
+			$rec = get_record("fmanager_folders","id",$tmpfoldid);
+			$tmp = get_record('fmanager_folders','id',$rootdir);
+			$destinationfile = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($rootdir)."/".$rec->name."/";
+			$sourcefile = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($rec->folder).$rec->path.$rec->name.'/';
+			$rec->pathid = $rootdir;
+			$rec->path = $tmp->path.$tmp->name."/";
+			// Quick catch of moving a folder into itself
+			if ($rootdir == $tmpfoldid) {
+				print_simple_box_start("center","500","red");
+				echo get_string('errsamefolder','block_file_manager', $tmp->name);
+				print_simple_box_end();
+			} else {
+				if (!@rename($sourcefile,$destinationfile)) {
+					// When moving a folder into itself...throws this error
+					print_simple_box_start("center","500","red");
+					echo get_string('errsamefolder','block_file_manager', $rec->name);
+					print_simple_box_end();
+				} else {
+					if (!update_record("fmanager_folders",$rec)) {
+						error(get_string('errnoupdate','block_file_manager'));
+					}
+				}
+			}
+		} else {
+			$rec = get_record("fmanager_link","id",$c);
+			$exists = false;	// Does file exist?
+			if ($rec->type == TYPE_FILE || $rec->type == TYPE_ZIP) {
+				$destinationfile = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($rootdir)."/".$rec->link;
+				$sourcefile = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($rec->folder)."/".$rec->link;
+				// Checks if file exists and prints warning, and doesnt change anything for that file only
+				if (file_exists($destinationfile)) {
+					print_simple_box_start("center",'500','red');
+					echo get_string('errfileexists','block_file_manager', $rec->name);
+					print_simple_box_end();
+					$exists = true;
+				} else {
+					if (!@copy($sourcefile,$destinationfile)) {
+						error(get_string('errcantmovefile','block_file_manager'));
+					}
+					if (!@unlink($sourcefile)) {
+						error(get_string('errnodeletefile','block_file_manager'));
+					}
+				}
+			}
+			$rec->folder = $rootdir;
+			if (!$exists && !update_record("fmanager_link",$rec)) {
+				error(get_string('errnoupdate','block_file_manager'));
+			}
+		}
+	}
+}
+	
+// $path  = Path of folder/file
+function fm_get_size($path, $rawbytes = 0) {
+	if (!is_dir($path)) {
+		return fm_readable_filesize(@filesize($path));
+	}
+	$dir = opendir($path);
+	//DWT, init $size
+	$size = 0;
+	while ($file = readdir($dir)) {
+		if (is_dir($path."/".$file) && $file != "." && $file != "..") {
+			$size += fm_get_size($path."/".$file, 1);
+		} else {
+			$size += @filesize($path."/".$file);
+		}
+	}
+	if ($rawbytes == 1) {
+		return $size;
+	}
+	if ($size == 0) {
+		return "0 Bytes";
+	} else {
+		return fm_readable_filesize($size);
+	}
+}
+
+function fm_readable_filesize($size) {
+	$filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
+	if ($size != 0) {
+		return round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i];
+	} else {
+		return "0".$filesizename[0];
+	}
+}
+/*************************** Category Functions *****************************/
+// This either creates a new category or updates the existing one
+// 	fm_update_category($name, $catid);	
+// This takes a num or an array of nums and returns a catname or an array of catnames
+// 	fm_get_user_categories($catid)			
+// Returns an array of user's categories for choose_from_menu function
+// 	fm_get_cat_list()
+/****************************************************************************/
+
+// $name 	= Name of category
+// $catid 	= If present, then updating an existing
+function fm_update_category($name, $catid = NULL) {
+	global $USER;
+	
+	if ($catid != NULL) {
+		$update->id = $catid;
+		$update->name = $name;
+		$update->timemodified = time();
+		if (!update_record("fmanager_categories", $update)) {
+			error(get_string("errnoupdate","block_file_manager"));
+		}
+	} else {
+		$new->name = $name;
+		$new->owner = $USER->id;
+		$new->timemodified = time();
+		if (!insert_record("fmanager_categories", $new)) {
+			error(get_string("errnoinsert","block_file_manager"));
+		}
+	}
+	return true;
+}
+
+// $catid		= An array of catids or a single catid
+function fm_get_user_categories($catid) {
+	if (!is_array($catid)) {	
+		$rec = get_record("fmanager_categories", "id", $catid);
+		return $rec->name;
+	} else {
+		$tmp = array();
+		foreach ($catid as $cid) {
+			$tmp[] = fm_get_user_categories($cid);
+		}
+		return $tmp;
+	}
+}
+
+function fm_get_cat_list() {
+	global $USER;
+	
+	$cats[0] = get_string("btnnoassigncat","block_file_manager");
+	if ($catsrec = get_records("fmanager_categories", "owner", $USER->id, "name")) {
+	foreach ($catsrec as $c) {
+		$cats[$c->id] = $c->name;
+	}
+	}
+	return $cats;
+}
+
+/************************* Shared Link Functions ****************************/
+// Deletes all shared link entries associated with deleted link or with unsharing all
+//	fm_update_shared_links($linkid)
+// Returns an object of all links with the specified category (not including folders)
+// 	fm_get_links_shared_by_cat($original, $catid)
+// Returns an object of all folders with specified category
+//	fm_get_folder_shared_by_cat($original,$catid)
+// Returns an object of all links under specified folder
+// 	fm_get_all_shared_by_folder($original, $foldid)
+// Returns an object of all folders under specified folder
+//  fm_get_all_sharedf_by_folder($original, $foldid)
+/****************************************************************************/
+
+// $linkid 		= id of deleted link
+function fm_update_shared_links($linkid) {
+
+	if ($sharedlinks = get_records("fmanager_shared", "sharedlink", $linkid)) {
+		foreach ($sharedlinks as $sl) {		
+			if (!delete_records("fmanager_shared", "id", $sl->id)) {
+				error(get_string("errnoupdate","block_file_manager"));
+			}
+		}
+	}
+}
+
+// $original	= owners id
+// $catid		= category id num
+function fm_get_links_shared_by_cat($original, $catid) {
+	return get_records("fmanager_link","owner = $original AND category",$catid);	
+}
+// $original 	= owners id
+// $catid		= category id num
+function fm_get_folder_shared_by_cat($original,$catid) {
+	return get_records('fmanager_folders',"owner = $original AND category",$catid);
+
+}
+// $original 	= owners id
+// $foldid 		= folder id num
+function fm_get_all_shared_by_folder($original, $foldid) {
+	$tmpvar = get_records("fmanager_link","owner=$original AND folder",$foldid);
+
+	return $tmpvar;	
+}
+
+// $original 	= owners id
+// $foldid 		= folder id num
+function fm_get_all_sharedf_by_folder($original, $foldid) {
+	$tmpvar = get_records("fmanager_folders","owner=$original AND pathid",$foldid);
+
+	return $tmpvar;	
+}
+/**************************** Security Functions ****************************/
+// Ensures the user can view shared files from specified user
+// 	fm_user_has_shared($original, $link)
+// Ensures the user can view the shared files 
+//	fm_user_has_shared_ind($sid)
+// Ensures the user can view the category for modification
+// 	fm_user_owns_cat($catid)
+// Ensures the user owns the link 
+//	fm_user_owns_link($linkid)
+// Ensures the user owns the folder 
+// 	fm_user_owns_folder($folderid)
+// Ensures the user can view the page according to settings set by admin
+// 	fm_check_access_rights()
+// Ensures user can view shared category
+// 	fm_user_has_shared_cat($original, $catid)
+// Ensures user can view shared folder
+// 	fm_user_has_shared_folder($original, $foldid)
+// Ensures user can view shared folder via category
+//  fm_user_has_shared_folder_cat
+// Ensures user can view a file from file.php (owner/shared/in a cat/under a folder)
+//	fm_user_can_view_file($id, $fileid)
+// Cleans checkbox array values
+// fm_clean_checkbox_arr($cb)
+/****************************************************************************/
+
+// $original = user who is sharing files to $USER
+// $link 	 = link id of the file being checked
+function fm_user_has_shared($original=0, $link=0) {
+	global $USER, $CFG;
+
+	if ($link == 0) {
+		if (!$sharedfiles = (count_records("fmanager_shared", "owner", $original, "userid", $USER->id) + count_records("fmanager_shared", "owner", $original, "userid", 0))) {	
+			error(get_string("errnoshared", "block_file_manager"));
+		}
+	} else {
+		if (!$sharedfiles = (count_records("fmanager_shared","owner",$original,"userid",$USER->id,"sharedlink",$link) + count_records("fmanager_shared","owner",$original,"userid",0,"sharedlink",$link))) {
+			error(get_string("errnoshared","block_file_manager"));
+		}
+	}
+	return true;
+}
+
+// $sid		= Shared link id
+function fm_user_has_shared_ind($sid) {
+	global $USER;
+	
+	if (!$sharedfiles = count_records("fmanager_shared","id",$sid,"userid", $USER->id)) {
+		if (!count_records("fmanager_shared","id",$sid,"userid",0)) {
+			error(get_string("errnoshared","block_file_manager"));
+		}
+	}
+	return true;
+}
+
+// $catid	= category id to check ownership
+function fm_user_owns_cat($catid) {
+	global $USER;
+	if ($catid == 0) {
+		return true;
+	}
+	if (!$owncat = count_records("fmanager_categories", "id", $catid, "owner", $USER->id)) {
+		error(get_string("errdontowncat", "block_file_manager"));
+	} else {
+		return true;
+	}
+}
+
+// $linkid		= id of the link
+function fm_user_owns_link($linkid) {
+	global $USER;
+	
+	if ($linkid == 0) {
+		return true;
+	}
+	if (!$ownlink = count_records("fmanager_link", "id", $linkid, "owner", $USER->id)) {
+		error(get_string("errdontownlink", "block_file_manager"));
+	} else {
+		return true;
+	}
+}
+
+// $folderid 	= id of the folder 
+function fm_user_owns_folder($folderid) {
+	global $USER;
+	// Default directory...no folder selected
+	if ($folderid == 0) {
+		return true;
+	}
+	if (!$ownfold = count_records("fmanager_folders", "id", $folderid, "owner", $USER->id)) {
+		error(get_string("errdontownfolder","block_file_manager"));
+	} else {
+		return true;
+	}
+}
+
+// $id 			= course id
+// $chk1		= Flags to check if can share files
+// $chk2		= Flags to check *******
+function fm_check_access_rights($id=0, $chk1=false, $chk2=false) {
+	$userinttype = fm_get_user_int_type();
+	$tmp = get_record("fmanager_admin", "usertype", $userinttype);
+	if ($tmp->enable_fmanager == 0) {
+		error(get_string("errfmandisabled","block_file_manager"), $SESSION->fromdiscussion);
+	}
+	// Checks if they can share files and if they can share from course 1
+	if (($tmp->sharetoany == 0) && ($id == 1) && ($chk2 != false)) {
+		error(get_string("errcantviewshared","block_file_manager", "from this course"));
+	}
+	if (($chk1 != false) && ($tmp->allowsharing == 0)) {
+		error(get_string("errcantviewshared","block_file_manager"));
+	}
+}
+
+// $original		= id of the person who is sharing
+// $catid			= id of the category being shared
+function fm_user_has_shared_cat($original, $catid) {
+	global $USER, $CFG;
+	$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '0' AND owner='$original' AND type='1' AND sharedlink='$catid' OR userid='$USER->id' AND owner='$original' AND type='1' AND sharedlink='$catid'";
+	if (!count_records_sql($mysql)) {
+		echo $mysql;
+		error(get_string('errnoviewcat','block_file_manager'));
+	} else {
+		return true;
+	}
+}
+
+// $original		= id of the person who is sharing
+// $foldid			= id of the category being shared
+function fm_user_has_shared_folder($original, $foldid) {
+	global $USER, $CFG;
+	
+	if (fm_user_has_shared_folder_cat($original, $foldid)) {
+		return true;
+	} else {
+		// Pulls out directly shared folder
+		$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '0' AND owner='$original' AND type='2' AND sharedlink='$foldid' OR userid='$USER->id' AND owner='$original' AND type='2' AND sharedlink='$foldid'";
+		if (!get_records_sql($mysql)) {
+			// Checks if the folder is shared via a cascaded folder share
+			$dummyvar = 1;
+			$tmpid = $foldid;
+			while($dummyvar) {
+				$tmp = get_record("fmanager_folders","id",$tmpid);
+				$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '0' AND owner='$original' AND type='2' AND sharedlink='$tmp->pathid' OR userid='$USER->id' AND owner='$original' AND type='2' AND sharedlink='$tmp->pathid'";
+				if (get_records_sql($mysql)) {
+					$dummyvar = 0;
+				} else {
+					$tmpid = $tmp->pathid;
+					if ($tmpid == 0) {		// If root folder is reached and it isnt shared...check if shared via categories
+						error(get_string('errnoviewfold','block_file_manager'));
+					}
+				}
+			}
+		} else {
+			return true;
+		}
+	}
+}
+// $original		= id of the person who is sharing
+// $foldid			= id of the category being shared
+function fm_user_has_shared_folder_cat($original, $foldid) {
+	global $USER, $CFG;
+	
+	while (1) {
+		$fold = get_record("fmanager_folders","id",$foldid);
+		$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '0' AND owner='$original' AND type='1' AND sharedlink ='$fold->category' OR userid='$USER->id' AND owner='$original' AND type='1' AND sharedlink='$fold->category'";
+		if (get_records_sql($mysql)) {
+			$dummyvar = 0;
+			return true;
+		} else if ($fold->pathid == 0) {
+			return false;
+		} else {
+			$foldid = $fold->pathid;
+		}
+	}
+	return false;
+}
+
+// $id 		= courseid
+// $fileid	= id of file to be viewed
+function fm_user_can_view_file($id, $fileid) {
+	global $USER, $CFG;
+			
+	// If they own the file, they can view
+	if (count_records("fmanager_link", "id", $fileid, "owner", $USER->id)) {  
+		return true;
+	}	
+	// If file is shared to them or to everyone in the course they can view
+	$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid = '0' AND sharedlink='$fileid' AND course='$id' OR userid='$USER->id' AND sharedlink='$fileid' AND course='$id'";
+	if (count_records_sql($mysql)) {
+		return true;
+	}
+	if (!$sharedfile = get_record("fmanager_link", "id", $fileid)) {
+		return false;
+	} 
+	// If shared via shared/nested folder they can view
+	$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid='0' AND type='2' AND course='$id' AND sharedlink='$sharedfile->folder' OR userid='$USER->id' AND type='2' AND course='$id' AND sharedlink='$sharedfile->folder'";
+	if (count_records_sql($mysql)) {
+		return true;
+	} else {   // File isnt under the main folder
+		$tmp = get_record("fmanager_folders", "id", $sharedfile->folder);
+		$foldid = $tmp->pathid;
+		while ($foldid) {	// While folder id isnt the root (0)
+			$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid='0' AND type='2' AND course='$id' AND sharedlink='$foldid' OR userid='$USER->id' AND type='2' AND course='$id' AND sharedlink='$foldid'";
+			if (count_records_sql($mysql)) {
+				return true;
+			}
+			$tmp = get_record("fmanager_folders","id", $tmp->pathid);
+			$foldid = $tmp->id;
+		}
+	}
+	// If file is shared via a shared category they can view
+	$dummyvar = 1;
+	$fid = $sharedfile->folder;
+	if ($fid == 0) {
+		$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid='0' AND type='1' AND course='$id' AND sharedlink='$sharedfile->category' OR userid='$USER->id' AND type = '1' AND course='$id' AND sharedlink='$sharedfile->category'";
+		if (get_record_sql($mysql)) {
+			return true;
+		} else {
+			return false;
+		}
+	}
+	while ($fid) {	
+		$fold = get_record('fmanager_folders','id',$fid);
+		
+		$mysql = "SELECT * FROM {$CFG->prefix}fmanager_shared WHERE userid='0' AND type='1' AND course='$id' AND sharedlink='$fold->category' OR userid='$USER->id' AND type='1' AND course='$id' AND sharedlink='$fold->category'";
+		if (count_records_sql($mysql)) {
+			return true;
+		} else {
+			$fid = $fold->pathid;
+		}
+	}
+	// Otherwise, error is displayed
+	return false;
+}
+
+// $cb 	= Checkbox array
+function fm_clean_checkbox_arr() {
+	$cb = NULL;
+	$cb = $_POST['cb'];		// Checkbox array	
+	if (is_array($cb)) {
+		$tmp = array();
+		foreach($cb as $c) {
+			if(substr($c,0,4) == "fold") {
+				$tmp[] = "f-".(int)substr($c,4);
+			} else if (substr($c,0,2) == "f-") {
+				$tmp[] = "f-".(int)substr($c,2);
+			} else {
+				$tmp[] = (int)$c;
+			}
+		}
+		$cb = $tmp;
+	} else {
+		if (substr($cb,0,4) == "fold") {
+			$cb[] = "f-".(int)substr($cb,4);
+		} else if (substr($cb,2) == "f-") {
+			$cb[] = "f-".(int)substr($cb,2);
+		} else {
+			$cb[] = (int)$cb;
+			$cb[]=$singlecb;
+		}
+	}	
+	// Removes 0 as default
+	$nullify = false;
+	foreach ($cb as $c) {
+		if ($c == 0 && substr($c,0,2) != 'f-') {
+			$nullify = true;
+		} else {	
+			$nullify = false;
+		}
+	}
+	if ($nullify == true) {
+		$cb = NULL;
+	}
+	
+	return $cb;
+}
+
+/*************************** Database Functions *****************************/
+// This function processes the submission of yes/no to the conf_delete form & returns strings
+//	fm_process_del($delfrom, $fromid)
+// This function deletes a shared attribute of a file for a user
+// 	fm_del_shared($id)
+// This func processes the submission from the admin_settings.php form
+//	fm_process_admin_settings($entry)
+// Returns the user's integer representation of their type (0=admin, 1=teacher, 2=student)
+// 	fm_get_user_int_type()
+/****************************************************************************/
+	
+// $delfrom		= table to delete record from
+// $fromid		= id(s) of the record(s) to delete
+function fm_process_del($delfrom, $fromid) {
+	global $USER;
+	
+	if (isset($_POST['yesdel'])) {
+		if (is_array($fromid)) {
+			foreach($fromid as $id) {
+				if (!delete_records($delfrom, "id", $id)) {
+					error(get_string("errnodelete","block_file_manager"));
+				}
+			} 
+		} else {
+			if (!delete_records($delfrom, "id", $fromid)) {
+				error(get_string("errnodelete","block_file_manager"));
+			}
+		}
+		return true;
+	} else if (isset($_POST['nodel'])) {
+		return true;
+	}
+}
+
+// $id 	= id of shared files to be removed
+function fm_del_shared($ids, $courseid) {
+	global $USER;
+	
+	if (isset($_POST['yesdel'])) {
+		if (is_array($ids)) {
+			foreach($ids as $id) {
+				// Ensures they can even view file to delete permission to view it
+				if ($id != 0) {
+					if (fm_user_has_shared_ind($id)) {
+						// Shared to the entire class
+						if ($t = get_record("fmanager_shared","id",$id,"userid",0)) {
+							// for courses with students/teachers
+							//DWT, make changes to work in Moodle 1.8
+							if ($courseid != 1) {
+								$course_context = get_context_instance(CONTEXT_COURSE, $courseid);
+								if ( !$course_context )
+									error("Invalid course ID $id.");
+									$students = get_records_sql("SELECT u.id AS userid, u.firstname, u.lastname " .
+											"FROM user AS u, role_assignments AS ra " .
+											"WHERE ra.contextid=$course_context->id AND ra.roleid=" .
+									 		STUDENT_ROLEID . " AND u.id=ra.userid");
+		
+									$teachers = get_records_sql("SELECT u.id AS userid, u.firstname, u.lastname " .
+									 	"FROM user AS u, role_assignments AS ra " .
+									 	"WHERE ra.contextid=$course_context->id AND ra.roleid in (" .
+									 	ADMIN_ROLEID . "," . COURSECREATOR_ROLEID . "," . TEACHER_ROLEID . "," .
+									 	NONEDITING_TEACHER_ROLEID . ") AND u.id=ra.userid" );
+								//if ($teachers = get_records("user_teachers","course",$courseid)) {
+								  if ($teachers) {
+									foreach ($teachers as $teacher) {
+										if ($teacher->userid != $USER->id) {
+											$t->userid = $teacher->userid;
+											insert_record('fmanager_shared',$t);
+										}
+									}
+								}
+								//if ($students = get_records("user_students","course",$courseid)) {
+								  if ( $students ) {
+									foreach ($students as $student) {
+										if ($student->userid != $USER->id) {
+											$t->userid = $student->userid;
+											insert_record('fmanager_shared',$t);
+										}
+									}
+								}
+								delete_records("fmanager_shared","id",$id);
+							} else {
+							//DWT, this is too expensive. For a school with say 20,000 students, this will take a long time
+							//Some one should change this.
+							// else share to all users sitewide
+								if ($users = get_records("user")) {
+									foreach($users as $user) {
+										if ($user->id != $USER->id  && $user->username != "guest") {
+											$t->userid = $user->id;
+											insert_record("fmanager_shared",$t);
+										}
+									}
+								}						
+								delete_records("fmanager_shared","id",$id);			
+							}
+						} else {
+							delete_records("fmanager_shared","id",$id);
+						}
+					}
+				}
+			}
+		}
+		return true;
+	} else if (isset($_POST['nodel'])) {
+		return true;
+	}
+}
+
+// $entry 		= object that contains all form data ($entry->usertype and any data required)
+function fm_process_admin_settings($entry) {
+	// Deals with all processing from the files section of admin
+	if (!$exist_record = get_record("fmanager_admin", "usertype", $entry->usertype)) {
+		$tmp = NULL;
+		$tmp->usertype = $entry->usertype;
+		if (!insert_record("fmanager_admin", $tmp)) {
+			$err = NULL;
+			$err->errtype = "insert";
+			$err->forhwho ="user";
+			error(get_string("errrecordmod","block_file_manager", $err), $_SERVER["HTTP_REFERER"]);
+		}
+	}
+	if ($exist_record = get_record("fmanager_admin", "usertype", $entry->usertype)) {
+		$entry->id = $exist_record->id;
+		if (!update_record("fmanager_admin", $entry)) {
+			$err = NULL;
+			$err->errtype = "update";
+			$err->forwho = "user";
+			error(get_string("errrecordmod", "block_file_manager", $err), $_SERVER["HTTP_REFERER"]);
+		}
+	}
+}
+
+function fm_get_user_int_type() {
+	if (isadmin()) {
+		return 0;
+	} else if (isteacherinanycourse("0", false)) {
+		return 1;
+	} else {
+		return 2;
+	}
+}
+
+/*************************** Zip Functions **********************************/
+// 	fm_zip_files($originalfiles, $destination)
+//  fm_unzip_file($zipfile, $destination = '', $showstatus = true)
+// Reorders a list of unzipped objects with folders first 
+//  fm_reorder_folders_list($obj1, $obj2)
+//  fm_unzip_cleanfilename($p_event, &$p_header)
+//  fm_unzip_show_status($list, $removepath)
+// Shows contents of target zipped file
+//  fm_view_zipped($file)
+/****************************************************************************/
+function fm_zip_files ($originalfiles, $destination, $zipname="zip01", $rootdir=0) {
+//Zip an array of files/dirs to a destination zip file
+//Both parameters must be FULL paths to the files/dirs
+// Modded for Myfiles 
+// Michael Avelar 1/19/06
+
+    global $CFG, $USER;
+
+    //Extract everything from destination
+    $path_parts = pathinfo(cleardoubleslashes($destination));
+    $destpath = $path_parts["dirname"];       //The path of the zip file
+    $destfilename = $path_parts["basename"];  //The name of the zip file
+    $extension = $path_parts["extension"];    //The extension of the file
+	// To put the zipped file into the current directory
+	$destpath = $destpath."/".$destfilename;
+	// To allow naming of zipfiles
+	$destfilename = $zipname;
+    //If no file, error
+    if (empty($destfilename)) {
+        return false;
+    }
+
+    //If no extension, add it
+    if (empty($extension)) {
+        $extension = 'zip';
+        $destfilename = $destfilename.'.'.$extension;
+    }
+
+    //Check destination path exists
+    if (!is_dir($destpath)) {
+        return false;
+    }
+
+    //Check destination path is writable. TODO!!
+
+    //Clean destination filename
+    $destfilename = clean_filename($destfilename);
+
+    //Now check and prepare every file
+    $files = array();
+    $origpath = NULL;
+
+    foreach ($originalfiles as $file) {  //Iterate over each file
+        //Check for every file
+        $tempfile = cleardoubleslashes($file); // no doubleslashes!
+        //Calculate the base path for all files if it isn't set
+        if ($origpath === NULL) {
+            $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
+        }
+        //See if the file is readable
+        if (!is_readable($tempfile)) {  //Is readable
+            continue;
+        }
+        //See if the file/dir is in the same directory than the rest
+        if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
+            continue;
+        }
+        //Add the file to the array
+        $files[] = $tempfile;
+    }
+
+    //Everything is ready:
+    //    -$origpath is the path where ALL the files to be compressed reside (dir).
+    //    -$destpath is the destination path where the zip file will go (dir).
+    //    -$files is an array of files/dirs to compress (fullpath)
+    //    -$destfilename is the name of the zip file (without path)
+
+    //print_object($files);                  //Debug
+
+    if (empty($CFG->zip)) {    // Use built-in php-based zip function
+
+        include_once("$CFG->libdir/pclzip/pclzip.lib.php");
+        $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
+        if (($list = $archive->create($files, PCLZIP_OPT_REMOVE_PATH,$origpath) == 0)) {
+            notice($archive->errorInfo(true));
+            return false;
+        }
+
+    } else {                   // Use external zip program
+
+        $filestozip = "";
+        foreach ($files as $filetozip) {
+            $filestozip .= escapeshellarg(basename($filetozip));
+            $filestozip .= " ";
+        }
+        //Construct the command
+        $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
+        $command = 'cd '.escapeshellarg($origpath).$separator.
+                    escapeshellarg($CFG->zip).' -r '.
+                    escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
+        //All converted to backslashes in WIN
+        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
+            $command = str_replace('/','\\',$command);
+        }
+        Exec($command);
+    }
+	// Adds an entry into myfiles api
+	$newentry = NULL;
+	$newentry->owner = $USER->id;
+	$newentry->type = TYPE_ZIP;
+	$newentry->folder = $rootdir;
+	$newentry->category = 0;
+	$newentry->name = substr($destfilename,0,-4);
+	$newentry->description = '';
+	$newentry->link = $destfilename;
+	$newentry->timemodified = time();
+	if (!fm_update_link($newentry)) {
+		error(get_string("errnoupdate","block_file_manager"));
+	}
+    return true;
+}
+
+function fm_unzip_file ($zipfile, $destination = '', $showstatus = false, $currentdir=0) {
+//Unzip one zip file to a destination dir
+//Both parameters must be FULL paths
+//If destination isn't specified, it will be the
+//SAME directory where the zip file resides.
+// Modded for Myfiles 
+// Michael Avelar 1/24/06 
+    global $CFG, $USER;
+
+    //Extract everything from zipfile
+    $path_parts = pathinfo(cleardoubleslashes($zipfile));
+    $zippath = $path_parts["dirname"];       //The path of the zip file
+    $zipfilename = $path_parts["basename"];  //The name of the zip file
+    $extension = $path_parts["extension"];    //The extension of the file
+
+    //If no file, error
+    if (empty($zipfilename)) {
+        return false;
+    }
+
+    //If no extension, error
+    if (empty($extension)) {
+        return false;
+    }
+
+    //If no destination, passed let's go with the same directory
+    if (empty($destination)) {
+        $destination = $zippath;
+    }
+
+    //Clear $destination
+    $destpath = rtrim(cleardoubleslashes($destination), "/");
+
+    //Check destination path exists
+    if (!is_dir($destpath)) {
+        return false;
+    }
+
+    //Check destination path is writable. TODO!!
+
+    //Everything is ready:
+    //    -$zippath is the path where the zip file resides (dir)
+    //    -$zipfilename is the name of the zip file (without path)
+    //    -$destpath is the destination path where the zip file will uncompressed (dir)
+
+    if (empty($CFG->unzip)) {    // Use built-in php-based unzip function
+
+        include_once("$CFG->libdir/pclzip/pclzip.lib.php");
+        $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
+        if (!$list = $archive->extract(PCLZIP_OPT_PATH, $destpath,
+                                       PCLZIP_CB_PRE_EXTRACT, 'unzip_cleanfilename')) {
+            notice($archive->errorInfo(true));
+            return false;
+        }
+
+    } else {                     // Use external unzip program
+
+        $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
+        $redirection = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '' : ' 2>&1';
+
+        $command = 'cd '.escapeshellarg($zippath).$separator.
+                    escapeshellarg($CFG->unzip).' -o '.
+                    escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
+                    escapeshellarg($destpath).$redirection;
+        //All converted to backslashes in WIN
+        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
+            $command = str_replace('/','\\',$command);
+        }
+        Exec($command,$list);
+    }
+	// Inserts unzipped objects into myfiles api
+	$afolder = $currentdir;
+	// Reorders list so that folders are inserted into database before links
+	$list2 = array();
+	foreach($list as $l) {
+		if ($l['folder'] == 1) {
+			$list2[] = $l;
+		}
+	}
+	// Reorders folders list to extract them in order, so the database has the folder before
+	// inserting stuff into that folder
+
+	usort($list2, 'fm_reorder_folders_list');
+	// Recompiles the completed list...with ordered folders first, then files
+	foreach($list as $l) {
+		if ($l['folder'] != 1) {
+			$list2[] = $l;
+		}
+	}
+	foreach($list2 as $l) {
+		if ($l['folder'] == 1) {	// is an unzipped folder
+			$newfolder = NULL;
+			$newfolder->owner = $USER->id;
+			$tmp = explode('/',$l['stored_filename']);
+			// compiles the path of the folder
+			$tmppath = '/';
+			foreach ($tmp as $t) {
+				if ($t != '') {
+					$tmppath .= $t."/";
+				}
+			}
+			$tmp = array_reverse($tmp);
+			$tmppath = substr($tmppath, 0, (strrpos($tmppath, $tmp[1])));
+			$newfolder->name = $tmp[1];
+			$newfolder->category = 0;
+			if ($tmp[2] == NULL) {			// Folder is root folder
+				$newfolder->path = '/';
+				$newfolder->pathid = 0;
+			} else {
+				// Puts all folders in their place :)
+				$pathtmp = '/';
+				$count = count($tmp);
+				while ($count > 3) {
+					$pathtmp .= $tmp[$count - 1].'/';
+					$count--;
+				}
+				$rec = get_record("fmanager_folders","name",$tmp[2],"path",$pathtmp);
+				$afolder = $rec->id;
+				$newfolder->path = fm_get_folder_path($afolder)."/";
+				$newfolder->pathid = $afolder;
+			}
+			$newfolder->timemodified = time();
+			if (!$afolder = insert_record('fmanager_folders',$newfolder)) {
+				error(get_string('errnoinsert','block_file_manager'));
+			}
+		} else {
+			$tmp = explode('/', $l['stored_filename']);
+			$newlink = NULL;
+			$newlink->owner = $USER->id;
+			$newlink->type = TYPE_FILE;	
+			$rootlinkstr = '';
+			// Compiles path string
+			$count = count($tmp);
+			$count = $count - 2;
+			foreach($tmp as $t) {
+				if ($count > 0) {
+					if ($t != '') {
+						$rootlinkstr .= '/'.$t;
+					}
+					$count--;
+				}
+			} 
+			if (substr($rootlinkstr,0,1) != '/') {
+				$rootlinkstr = '/'.$rootlinkstr;
+			}
+			if ($rootlinkstr != '/') {
+				$rootlinkstr = $rootlinkstr.'/';
+			}
+			$tmp = array_reverse($tmp);
+			if (!$foldstr = get_record("fmanager_folders","owner",$USER->id,"name",$tmp[1],"path",$rootlinkstr)) {
+				$foldstr->id = $currentdir;
+			}			
+			$newlink->folder = $foldstr->id;
+			$newlink->category = 0;
+			$newlink->name = substr($tmp[0],0,-4);
+			$newlink->description = '';
+			$newlink->link = $tmp[0];
+			$newlink->timemodified = time();
+			if (!$alink = insert_record('fmanager_link',$newlink)) {
+				error(get_string('errnoinsert','block_file_manager'));
+			}
+		}	
+	}
+    //Display some info about the unzip execution
+    if ($showstatus) {
+        fm_unzip_show_status($list,$destpath);
+    }
+
+    return $list;
+}
+
+// $list = list of the folders to be reordered
+function fm_reorder_folders_list($obj1, $obj2) {
+	$size1 = explode("/",$obj1['stored_filename']);
+	$size2 = explode("/",$obj2['stored_filename']);
+
+	if (count($size1) == count($size2)) {
+		return 0;
+	}
+	if (count($size1) > count($size2)) {
+		return 1;
+	}
+	if (count($size1) < count($size2)) {
+		return -1;
+	}
+}
+
+function fm_unzip_cleanfilename ($p_event, &$p_header) {
+//This function is used as callback in unzip_file() function
+//to clean illegal characters for given platform and to prevent directory traversal.
+//Produces the same result as info-zip unzip.
+    $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
+    $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
+    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
+        $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
+        $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
+    } else {
+        //Add filtering for other systems here
+        // BSD: none (tested)
+        // Linux: ??
+        // MacosX: ??
+    }
+    $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
+    return 1;
+}
+
+function fm_unzip_show_status ($list,$removepath) {
+//This function shows the results of the unzip execution
+//depending of the value of the $CFG->zip, results will be
+//text or an array of files.
+
+    global $CFG;
+
+    if (empty($CFG->unzip)) {    // Use built-in php-based zip function
+        $strname = get_string("name");
+        $strsize = get_string("size");
+        $strmodified = get_string("modified");
+        $strstatus = get_string("status");
+        echo "<table cellpadding=\"4\" cellspacing=\"2\" border=\"0\" width=\"640\">";
+        echo "<tr><th class=\"header\" align=\"left\">$strname</th>";
+        echo "<th class=\"header\" align=\"right\">$strsize</th>";
+        echo "<th class=\"header\" align=\"right\">$strmodified</th>";
+        echo "<th class=\"header\" align=\"right\">$strstatus</th></tr>";
+        foreach ($list as $item) {
+            echo "<tr>";
+            $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
+            print_cell("left", $item['filename']);
+            if (! $item['folder']) {
+                print_cell("right", display_size($item['size']));
+            } else {
+                echo "<td>&nbsp;</td>";
+            }
+            $filedate  = userdate($item['mtime'], get_string("strftimedatetime"));
+            print_cell("right", $filedate);
+            print_cell("right", $item['status']);
+            echo "</tr>";
+        }
+        echo "</table>";
+
+    } else {                   // Use external zip program
+        print_simple_box_start("center");
+        echo "<pre>";
+        foreach ($list as $item) {
+            echo str_replace(cleardoubleslashes($removepath.'/'), '', $item).'<br />';
+        }
+        echo "</pre>";
+        print_simple_box_end();
+    }
+}
+
+// $file = object of target zip file
+function fm_view_zipped($file) {
+	global $CFG, $USER;
+	
+	if ($file->folder == 0) {
+		$ziploc = $CFG->dataroot."/".fm_get_user_dir_space()."/".$file->link;
+	} else {
+		$ziploc = $CFG->dataroot."/".fm_get_user_dir_space().fm_get_folder_path($file->folder)."/".$file->link;
+	}
+
+	$filelist = array();
+	$zip = zip_open($ziploc);
+	if ($zip) {
+		$count = 0;
+		while ($zip_entry = zip_read($zip)) {
+		   $filelist[$count]->name = zip_entry_name($zip_entry);
+		   $filelist[$count]->actualsize = zip_entry_filesize($zip_entry);
+		   $filelist[$count]->compsize = zip_entry_compressedsize($zip_entry);
+		   $count++;
+		}
+		zip_close($zip);
+	}
+	return $filelist;
+}
+
+/*************************** Print Functions ********************************/
+// Located within print_lib.php
+/****************************************************************************/
+
+/*************************** JS Print Functions *****************************/
+// Located within print_lib.php
+/****************************************************************************/
+
+
+
+function shared_files_assignment_file_submission($entry, $assignment) {
+/// Copies a file to the teacher's assignment directory for that course
+	global $CFG, $USER;
+	$pathnew = "$assignment->course/moddata/assignment/$assignment->id/$USER->id";
+	$pathold = "$CFG->dataroot/shared_files/users/$entry->userid";
+
+	make_upload_directory($pathnew);
+
+	if (!copy("$pathold/$entry->attachment", "$CFG->dataroot/$pathnew/$entry->attachment")) {
+		error ("Failed to copy file!", "view.php?id=$id&rootdir=$rootdir");
+	}
+}
+
+
+// When called, outputs all groups and members of a course, using $listmembers and $listgroups defined in 
+// call to get_list_members()
+function show_visible_groups($course, $listmembers, $listgroups, $filerefphp) {	
+	// Print out the selection boxes and fill with groups/members
+	echo "<tr><td width=\"45%\" align=\"center\"><form name=\"form2\" id=\"form2\">
+		<input type=\"hidden\" name=\"id\" value=\"$course->id\"><select name=\"groups\" size=\"15\" onChange=\"updateMembers(this)\" multiple>";
+	if (!empty($listgroups)) {
+		foreach ($listgroups as $id => $listgroup) {
+			$selected = '';
+			if ($id == $selectedgroup) {
+			   $selected = 'selected="selected"';
+			}
+			echo "<option $selected value=\"$id\">$listgroup</option>";
+		}
+	}
+	echo "</select></form></td>";
+	$sharestring = get_string('share', 'block_shared_files');
+	echo "<td width=\"10%\" align=\"center\"><form name=\"formx\" id=\"formx\" method=\"post\" action=\"$filerefphp\">";
+	echo "<input type=\"hidden\" name=\"grpid\" value=\"\"><INPUT TYPE=\"hidden\" NAME=\"bookid\" VALUE=\"$bookid\"><input type=\"hidden\" name=\"id\" value=\"$course->id\"><input name=\"gshare\" type=\"submit\" value=\"$sharestring\"></form></td>";	
+	echo "<td width=\"45%\" align=\"center\"><form name=\"form3\" id=\"form3\">
+          <input type=\"hidden\" name=\"id\" value=\"$course->id\">
+          <select name=\"members[]\" size=\"15\">";
+    if (!empty($members)) {
+    	foreach ($members as $id => $membername) {
+        	echo "<option value=\"$id\">$membername</option>";
+    	}
+	}
+    echo "</select></form></td></tr>";
+}
+
+// called from share & sharefile.php to populate arrays passed by reference to pop js lists
+function get_list_members($course, &$nonmembers, &$listgroups)
+{
+/// First, get everyone into the nonmembers array
+    if ($students = get_course_students($course->id)) {
+        foreach ($students as $student) {
+            $nonmembers[$student->id] = fullname($student, true);
+        }
+        unset($students);
+    }
+
+    if ($teachers = get_course_teachers($course->id)) {
+        foreach ($teachers as $teacher) {
+            $prefix = '- ';
+            if (isteacheredit($course->id, $teacher->id)) {
+                $prefix = '# ';
+            }
+            $nonmembers[$teacher->id] = $prefix.fullname($teacher, true);
+        }
+        unset($teachers);
+    }
+
+/// Pull out all the members into little arrays
+	$groups = get_groups($course->id);
+    if ($groups) {
+        foreach ($groups as $group) {
+            $countusers = 0;
+            $listmembers[$group->id] = array();
+            if ($groupusers = get_group_users($group->id)) {
+                foreach ($groupusers as $groupuser) {
+                    $listmembers[$group->id][$groupuser->id] = $nonmembers[$groupuser->id];
+                    //unset($nonmembers[$groupuser->id]);
+                    $countusers++;
+                }
+                natcasesort($listmembers[$group->id]);
+            }
+            $listgroups[$group->id] = $group->name." ($countusers)";
+        }
+        natcasesort($listgroups);
+    }
+
+    natcasesort($nonmembers);
+	if (empty($selectedgroup)) {    // Choose the first group by default
+        if (!empty($listgroups) && ($selectedgroup = array_shift(array_keys($listgroups)))) {
+            $members = $listmembers[$selectedgroup];
+        }
+    } else {
+        $members = $listmembers[$selectedgroup];
+    }
+	return $listmembers;
+}
+
+/*********************** Moodle Required Functions **************************/
+//	upgrade_file_manager_db($continueto)  								
+/****************************************************************************/
+
+// This function upgrades the file_manager's tables, if necessary
+// It's called from admin/index.php
+function upgrade_file_manager_db($continueto) {
+    
+    global $CFG, $db;
+	$fmdir = fm_get_root_dir();
+
+    require_once ("$CFG->dirroot/$fmdir/version.php");  // Get code versions
+
+    if (empty($CFG->file_manager_version)) {                  // file_manager has never been installed.
+        $strdatabaseupgrades = get_string("databaseupgrades");
+        print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades, 
+                         "", "", false, "&nbsp;", "&nbsp;");
+
+        $db->debug=true;
+        if (modify_database("$CFG->dirroot/$fmdir/db/$CFG->dbtype.sql")) {
+            $db->debug = false;
+            if (set_config("file_manager_version", $file_manager_version) and set_config("file_manager_release", $file_manager_release)) {
+                notify(get_string("databasesuccess"), "green");
+                print_continue($continueto);
+                exit;
+            } else {
+                error("Upgrade of file_manager system failed! (Could not update version in config table)", "view.php?id=$id&rootdir=$rootdir");
+            }
+        } else {
+            error("file_manager tables could NOT be set up successfully!", "view.php?id=$id&rootdir=$rootdir");
+        }
+    }
+
+    if ($file_manager_version > $CFG->file_manager_version) {       // Upgrade tables
+        $strdatabaseupgrades = get_string("databaseupgrades");
+        print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades);
+
+        require_once ("$CFG->dirroot/$fmdir/db/$CFG->dbtype.php");
+
+        $db->debug=true;
+        if (file_manager_upgrade($CFG->file_manager_version)) {
+            $db->debug=false;
+            if (set_config("file_manager_version", $file_manager_version) and set_config("file_manager_release", $file_manager_release)) {
+                notify(get_string("databasesuccess"), "green");
+                notify(get_string("databaseupgradebackups", "", $file_manager_release));
+                print_continue($continueto);
+                exit;
+            } else {
+                error("Upgrade of file_manager system failed! (Could not update version in config table)", "view.php?id=$id&rootdir=$rootdir");
+            }
+        } else {
+            $db->debug=false;
+            error("Upgrade failed!  See file_manager/version.php", "view.php?id=$id&rootdir=$rootdir");
+        }
+
+    } else if ($file_manager_version < $CFG->file_manager_version) {
+        notify("WARNING!!!  The code you are using ($file_manager_version) is OLDER than the version that made the current database ($CFG->file_manager_version)!");
+    }
+}		 
+
+?>

