<?

/*
FlexCMS (http://www.flexcms.com)
Flexible, Powerful, Affordable.

Contents of this file are protected by the copyright
notice found at http://www.flexcms.com/flex/pages/copyright.html,
and its usage is subject to the terms of the licensing agreement 
available at http://www.flexcms.com/flex/pages/license.html
*/


		
	$PageTitle = '<img src="'.$ImagesURL.'/admin/admincp_settings.gif" width="23" height="20"> '.'File Manager';
	$BrowserTitle = $MsgText[0][685];
	$LocationBar = '<a href="'.$IndexURL.'">'.$MsgText[0][1].'</a> > <a href="'.$MainURL.'/options.html">'.$MsgText[0][4].'</a> > '.'File Manager';
	
	if ($LoggedIn == 'y') {
		
		ReadPermissions();
		Global $Permissions;
		
		ReadFormArguments();
		Global $FormArguments;
		
		
		
			$PHPMaxFileSize = ini_get('upload_max_filesize');
			if (strtoupper(substr($PHPMaxFileSize,strlen($PHPMaxFileSize)-1,1)) == 'K') {
				// number is Kbytes so convert it
				$PHPMaxFileSize = ($PHPMaxFileSize * 1024);
			}
			else if (strtoupper(substr($PHPMaxFileSize,strlen($PHPMaxFileSize)-1,1)) == 'M') {
				// number is Mbytes so convert it
				$PHPMaxFileSize = ($PHPMaxFileSize * 1024 * 1024);
			}
			else if (strtoupper(substr($PHPMaxFileSize,strlen($PHPMaxFileSize)-1,1)) == 'G') {
				// good luck uploading a gig through a browser lol ...
				$PHPMaxFileSize = ($PHPMaxFileSize * 1024 * 1024 * 1024);
			}
			
			
			if ($PHPMaxFileSize < $Settings['FileManagerMaxFileSize']*1024 && $PHPMaxFileSize > 0) {
				// PHP has a limit set, and it's smaller than Flex's
				$MaxFileSize = number_format($PHPMaxFileSize,0,'','');				
			}
			else if ($Settings['FileManagerMaxFileSize'] > 0) {
				// Flex's limit is the smaller one, but is > 0
				$MaxFileSize = number_format(($Settings['FileManagerMaxFileSize']*1024),0,'','');
			}
			else {
				// default to 2m if neither can be located
				$MaxFileSize = 2097152;				
			}
		
		
		
			// resizable images
			$FileTypes[3] = 'Resizable Image';
			$FileTypeExtensions['gif'] = 3;		//
			$FileTypeExtensions['jpg'] = 3;		//
			$FileTypeExtensions['jpeg'] = 3;	//
			$FileTypeExtensions['png'] = 3;		//
			
			// plain text
			$FileTypes[4] = 'Plain Text';
			$FileTypeExtensions['txt'] = 4;		//
			$FileTypeExtensions['log'] = 4;		//
			$FileTypeExtensions['csv'] = 4;		// Comma Separated Values
			
			// compressed & non-compressed archives
			$FileTypes[5] = 'Archives';	
			$FileTypeExtensions['zip'] = 5;		//
			$FileTypeExtensions['7z'] = 5;		// 7Zip
			$FileTypeExtensions['tar'] = 5;		// Tarball
			$FileTypeExtensions['gz'] = 5;		// GZip
			$FileTypeExtensions['tgz'] = 5;		// GZip
			$FileTypeExtensions['z'] = 5;		// 
			$FileTypeExtensions['sea'] = 5;		// Mac StuffIt
			$FileTypeExtensions['hqx'] = 5;		// Mac BinHex
			$FileTypeExtensions['rar'] = 5;		//
			$FileTypeExtensions['arj'] = 5;		//
			$FileTypeExtensions['cab'] = 5;		// Windows Cabinet
			
			// office documents
			$FileTypes[6] = 'Office Documents';
			$FileTypeExtensions['doc'] = 6;		// MS Word
			$FileTypeExtensions['docx'] = 6;	// MS Word New Format (2008)
			$FileTypeExtensions['xls'] = 6;		// MS Excel
			$FileTypeExtensions['xlsx'] = 6;	// MS Excel New Format (2008)
			$FileTypeExtensions['ppt'] = 6;		// MS PowerPoint
			$FileTypeExtensions['pps'] = 6;		// MS PowerPoint
			$FileTypeExtensions['mdb'] = 6;		// MS Access Database
			$FileTypeExtensions['pub'] = 6;		// MS Publisher
			$FileTypeExtensions['wps'] = 6;		// MS Works
			$FileTypeExtensions['wpd'] = 6;		// Corel WordPerfect
			$FileTypeExtensions['pdf'] = 6;		// Acrobat PDF
			$FileTypeExtensions['rtf'] = 6;		// Generic Rich Text
			// Open Office formats?
			
			// audio & video media
			$FileTypes[7] = 'Audio & Video Media';
			$FileTypeExtensions['swf'] = 7;		// Flash
			$FileTypeExtensions['flv'] = 7;		// Flash
			$FileTypeExtensions['avi'] = 7;		//
			$FileTypeExtensions['wmv'] = 7;		// Windows Media Video
			$FileTypeExtensions['wma'] = 7;		// Windows Media Audio
			$FileTypeExtensions['mov'] = 7;		// Apple QuickTime Video
			$FileTypeExtensions['m4v'] = 7;		// Apple iTunes Video
			$FileTypeExtensions['qt'] = 7;		// Apple QuickTime Video
			$FileTypeExtensions['qtm'] = 7;		// Apple QuickTime Video
			$FileTypeExtensions['ra'] = 7;		// Real
			$FileTypeExtensions['ram'] = 7;		// Real
			$FileTypeExtensions['rm'] = 7;		// Real
			$FileTypeExtensions['rmm'] = 7;		// Real
			$FileTypeExtensions['rv'] = 7;		// Real
			$FileTypeExtensions['mpg'] = 7;		// MPEG
			$FileTypeExtensions['mpeg'] = 7;	// MPEG
			$FileTypeExtensions['m1v'] = 7;		// MPEG
			$FileTypeExtensions['m3u'] = 7;		// MPEG
			$FileTypeExtensions['mpa'] = 7;		// MPEG
			$FileTypeExtensions['mp2'] = 7;		// MPEG
			$FileTypeExtensions['mp2v'] = 7;	// MPEG
			$FileTypeExtensions['mpe'] = 7;		// MPEG
			$FileTypeExtensions['mp3'] = 7;		// MPEG Audio
			$FileTypeExtensions['wav'] = 7;		// WAV Audio
			$FileTypeExtensions['mid'] = 7;		// MIDI Audio
		
			// non-resizable images
			$FileTypes[8] = 'Other Images';
			$FileTypeExtensions['bmp'] = 8;		// Windows Bitmap
			$FileTypeExtensions['tif'] = 8;		// TIFF
			$FileTypeExtensions['ai'] = 8;		// Adobe Illustrator
			$FileTypeExtensions['psd'] = 8;		// Adobe Photoshop
			$FileTypeExtensions['cdr'] = 8;		// Corel Draw
			$FileTypeExtensions['ico'] = 8;		// Windows Icon
			$FileTypeExtensions['ufo'] = 8;		// ULead
			
			// non-server scripts
			$FileTypes[9] = 'Non-Server Scripts';
			$FileTypeExtensions['htm'] = 9;		// 
			$FileTypeExtensions['html'] = 9;	// 
			$FileTypeExtensions['js'] = 9;		// Javascript
			$FileTypeExtensions['css'] = 9;		// CSS
			$FileTypeExtensions['jar'] = 9;		// Java Archive 
			$FileTypeExtensions['java'] = 9;	// Java
		
		
		
		
		if ($Arguments3 == 'upload') {
		
			if ($Permissions[80] == 'y' || $Permissions[81] == 'y' || $Permissions[82] == 'y' || $Permissions[83] == 'y' || $Permissions[84] == 'y' || $Permissions[85] == 'y' || $Permissions[86] == 'y' || $Permissions[87] == 'y') {
		
			
			
			
			if (count($FormArguments) > 0) {
			
						
				$CurrentLocation = $FormArguments['CurrentLocation'];
			
		
				$ThisFolderParent = substr($CurrentLocation,0,strrpos($CurrentLocation,'/')-1);
				
				$CLPieces = explode('/',$CurrentLocation);
				$ThisFolderParent = '/';
				for ($x = 1; $x < (count($CLPieces)-2); $x++) {
					$ThisFolderParent .= $CLPieces[$x].'/';
				}

				$ThisFolderName = $CLPieces[count($CLPieces)-2];
		
		
		
				if ($CurrentLocation == '/') {
					$query = "select * from `".$Settings['DBPrefix']."core-Folders` where Folder='/' and Location='' limit 1";
				}
				else {
					$query = "select * from `".$Settings['DBPrefix']."core-Folders` where Folder='".$ThisFolderName."' and Location='".$ThisFolderParent."' limit 1";
				}
		   		$result = mysql_query($query) or die (mysql_error());
				$row = mysql_fetch_array($result);
					
				if ($row['AddFilesLevel'] <= $UserLevel && $row['RecordNumber'] > 0) {
	
					// allowed to upload here, continue with processing
					
					
					$FileData = $_FILES['FileData']['tmp_name'];
					$FileSize = $_FILES['FileData']['size'];
					$FileType = $_FILES['FileData']['type'];
					$PreviousName = $_FILES['FileData']['name'];
					
					
								
					// take the previous file name and strip out any slashes
					// that windows may have allowed in the file name
					$NewFilename = str_replace('/','-',$PreviousName);
				
					$DestinationPath = '.'.$CurrentLocation;
					
					if ($FileSize == 0 || !is_file($FileData)) {
					
						$PageContents = 'File could not be uploaded (unknown reason) -- most likely it exceeds the limit of '.$MaxFileSize.' bytes ('.number_format($MaxFileSize/1024,0).' Kbytes) and couldn\'t be uploaded<br><br><a href="javascript:history.go(-1);">Go Back</a>';
						@unlink($FileData); // probably not needed, but
					
					}
					else if ($FileSize > $MaxFileSize) {
					
						$PageContents = 'File could not be uploaded (exceeds allowed size) -- size='.number_format($FileSize,0).', allowed='.number_format($MaxFileSize,0).'<br><br><a href="javascript:history.go(-1);">Go Back</a>';
						@unlink($FileData);
					
					}
					else {
						// file actually uploaded, keep going
					
						if (!is_file($DestinationPath.$NewFilename)) {
						
							move_uploaded_file($FileData, $DestinationPath.$NewFilename);
							
							if ($Settings['FilesCHMOD'] != '') {								
								chmod($DestinationPath.$NewFilename, $Settings['FilesCHMOD']);								
							}
						
							$FileData = $DestinationPath.$NewFilename;
					
												
							$FNPieces = explode('.',$NewFilename);
							$FileExtension = strtolower($FNPieces[count($FNPieces)-1]);
										
							$ImageWidth = 0;
							$ImageHeight = 0;
							$FileType = 0;
							if ($FileExtension == 'gif' || $FileExtension == 'png' || $FileExtension == 'jpg' || $FileExtension == 'jpeg') {
							
								$ImageInfo = @getimagesize($FileData);
							
								$ImageWidth = $ImageInfo[0];
								$ImageHeight = $ImageInfo[1];
								$FileType = $ImageInfo[2];
											
							}															
											
							$FileTypeGroup = 0;
							if ($FileTypeExtensions[$FileExtension] > 0) {
								$FileTypeGroup = $FileTypeExtensions[$FileExtension];
							}
							
							
							if ($Permissions[(77+$FileTypeGroup)] == 'y' || $Permissions[87] == 'y') {
								// allowed to upload file type, continue processing
								
																	
								
								$query = "insert into `".$Settings['DBPrefix']."core-Files` (Filename, Location, CreatedBy, CreationDate, ModifyLevel, ViewLevel, FileType, FileSize, ImageWidth, ImageHeight, ThumbnailExists, SystemFile) values ('".addslashes($NewFilename)."', '".$CurrentLocation."', '".$UserNumber."', '".GetTimestamp()."', '1', '1', '".$FileTypeGroup."', '".$FileSize."', '0', '0', '0', '0')";
								$result = mysql_query($query) or die (mysql_error());
								$RecordNumberCreated = mysql_insert_id();
								
								
								if ($FileTypeGroup == 3) {
									// image we can work with, so make a thumbnail
									
									if ($ImageWidth > 100 || $ImageHeight > 75) {
									
										$FileSource = $DestinationPath.$NewFilename;
										
										$NewWidth = 100;
										$NewHeight = 75;
									
										$WidthRatio = $ImageWidth / $NewWidth;
										$HeightRatio = $ImageHeight / $NewHeight;
						
										if ($WidthRatio >= $HeightRatio) {
								
											$NewWidthCalc = number_format($ImageWidth / $WidthRatio, 0);
											$NewHeightCalc = number_format($ImageHeight / $WidthRatio, 0);
									
										}	
										else {
									
											$NewWidthCalc = number_format($ImageWidth / $HeightRatio, 0);
											$NewHeightCalc = number_format($ImageHeight / $HeightRatio, 0);
										
										}
							
									
										if ($FileType == 1) {
											$SourceData = imagecreatefromgif($FileSource);
										}
										else if ($FileType == 2) {
											$SourceData = imagecreatefromjpeg($FileSource);
										}
										else if ($FileType == 3) {
											$SourceData = imagecreatefrompng($FileSource);
										} 
								
										$DestinationImage = imagecreatetruecolor($NewWidthCalc, $NewHeightCalc);
										imagecopyresampled($DestinationImage, $SourceData, 0, 0, 0, 0, $NewWidthCalc, $NewHeightCalc, $ImageWidth, $ImageHeight);
								
								
										if ($FileType == 1) {
											imagegif($DestinationImage, './thumbnails/'.$RecordNumberCreated.'_'.$NewFilename);
										}
										else if ($FileType == 2) {
											imagejpeg($DestinationImage, './thumbnails/'.$RecordNumberCreated.'_'.$NewFilename);
										}
										else if ($FileType == 3) {
											imagepng($DestinationImage, './thumbnails/'.$RecordNumberCreated.'_'.$NewFilename);
										}
										
										if ($Settings['FilesCHMOD'] != '') {
											@chmod('./thumbnails/'.$RecordNumberCreated.'_'.$NewFilename, $Settings['FilesCHMOD']);
										}
									
											
										imagedestroy($SourceData);
										imagedestroy($DestinationImage);
										
										
										$query = "update `".$Settings['DBPrefix']."core-Files` set ImageWidth='".$ImageWidth."', ImageHeight='".$ImageHeight."', ThumbnailExists=1 where RecordNumber='".$RecordNumberCreated."' limit 1";
										$result = mysql_query($query) or die (mysql_error());
										
									}
									else {
									
										$FileSource = $DestinationPath.$NewFilename;
											
										@copy($FileSource, './thumbnails/'.$RecordNumberCreated.'_'.$NewFilename);
										
										if ($Settings['FilesCHMOD'] != '') {
											@chmod('./thumbnails/'.$RecordNumberCreated.'_'.$NewFilename, $Settings['FilesCHMOD']);
										}
									
										$query = "update `".$Settings['DBPrefix']."core-Files` set ImageWidth='".$ImageWidth."', ImageHeight='".$ImageHeight."', ThumbnailExists=1 where RecordNumber='".$RecordNumberCreated."' limit 1";
										$result = mysql_query($query) or die (mysql_error());
											
									}
									
									
								
								}
								
							
								
								$PageContents = '<b>File successfully uploaded!</b><br><br><br><br>';
								
								if (strpos($Arguments4,'e') !== false) {
									$ImageMode = 'var ImageMode = false;';
									$ImageLinkMode = 'var ImageLinkMode = false;';
									
									if (strpos($Arguments4,'i') !== false) {
										$ImageMode = 'var ImageMode = true;';
										
										if ($FileTypeGroup != 3) {
											$PageContents .= '<b><font color="#ff0000">Warning!  File uploaded is not a website image type (GIF, JPEG, PNG), and will not be visible in the file manager when selecting an image to insert.</font></b><br><br><br>';
										}
									}
									else if (strpos($Arguments4,'l') !== false) {
										$ImageLinkMode = 'var ImageLinkMode = true;';
									}
									
									$PageContents .= '<script language="JavaScript">
										'.$ImageMode.'
										'.$ImageLinkMode.'
										
										// function to transfer selected file URL back to editor								
										function OpenFile( fileUrl ) {
											if (window.top.opener) {
												if (ImageMode == true) {
													window.top.opener.SetUrl(encodeURI( fileUrl ).replace( \'#\', \'%23\' ), "", "", "");
													window.top.opener.GetE("txtBorder").value = "0";
												}
												else if (ImageLinkMode == true) {
													window.top.opener.GetE("txtLnkUrl").value = encodeURI( fileUrl ).replace( \'#\', \'%23\' );
												}
												else {
													window.top.opener.GetE("txtUrl").value = "";
													window.top.opener.OnUrlChange();
													window.top.opener.GetE("txtUrl").value = encodeURI( fileUrl ).replace( \'#\', \'%23\' );
													window.top.opener.OnUrlChange();
												}
												
												window.top.close() ;
												window.top.opener.focus() ;
											}
											else {
												alert("Original window could not be located.  Please re-start the file manager from its original source and try again.");
											}
										}
										</script>
										
										<a href="javascript:OpenFile(\''.$BaseURL.$CurrentLocation.$NewFilename.'\');">Select This File and Return to Editor</a><br><br><br>';									
								}
								
								if (strpos($Arguments4,'u') !== false) {
									// return link should now go to file manager instead of back to uploader
									$Arguments4 = str_replace('u','',$Arguments4);
								}
								
								
								$PageContents .= '<a href="'.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$CurrentLocation).'">Return to File Manager</a>';
												
							
							}
							else {
								@unlink($FileData);
								$PageContents = 'Not allowed to upload file type<br><br><a href="javascript:history.go(-1);">Go Back</a>';
							}
																			
						
						}
						else {
							// file already exists with that name
							
										
						
							$ExistingFilename = $NewFilename;
							
							
							
							$FNPieces = explode('.',$NewFilename);
							$FileExtension = strtolower($FNPieces[count($FNPieces)-1]);
													
						
							$NewFilename = '-upload-renamed-'.rand(1000000,10000000).'.'.$FileExtension;
							$RenamedFile = $DestinationPath.$NewFilename;
							move_uploaded_file($FileData, $RenamedFile);
							
							if ($Settings['FilesCHMOD'] != '') {
								@chmod($RenamedFile, $Settings['FilesCHMOD']);
							}
							
							
							$FileData = $DestinationPath.$NewFilename;
																
					
										
							$ImageWidth = 0;
							$ImageHeight = 0;
							$FileType = 0;
							if ($FileExtension == 'gif' || $FileExtension == 'png' || $FileExtension == 'jpg' || $FileExtension == 'jpeg') {
							
								$ImageInfo = @getimagesize($FileData);
							
								$ImageWidth = $ImageInfo[0];
								$ImageHeight = $ImageInfo[1];
								$FileType = $ImageInfo[2];
											
							}															
											
							$FileTypeGroup = 0;
							if ($FileTypeExtensions[$FileExtension] > 0) {
								$FileTypeGroup = $FileTypeExtensions[$FileExtension];
							}													
							
							
							
							
							
							if ($Permissions[(77+$FileTypeGroup)] == 'y' || $Permissions[87] == 'y') {
								// allowed to upload file type, continue processing
																									
								
								$query = "insert into `".$Settings['DBPrefix']."core-Files` (Filename, Location, CreatedBy, CreationDate, ModifyLevel, ViewLevel, FileType, FileSize, ImageWidth, ImageHeight, ThumbnailExists, SystemFile) values ('".$NewFilename."', '".$CurrentLocation."', '".$UserNumber."', '".GetTimestamp()."', '1', '1', '".$FileTypeGroup."', '".$FileSize."', '0', '0', '0', '0')";
								$result = mysql_query($query) or die (mysql_error());
								$RecordNumberCreated = mysql_insert_id();
								
								
								if ($FileTypeGroup == 3) {
									// image we can work with, so make a thumbnail
																									
									$FileSource = $DestinationPath.$NewFilename;
									
									if ($ImageWidth > 100 || $ImageHeight > 75) {
									
										$NewWidth = 100;
										$NewHeight = 75;
							
										$WidthRatio = $ImageWidth / $NewWidth;
										$HeightRatio = $ImageHeight / $NewHeight;
							
										if ($WidthRatio >= $HeightRatio) {
								
											$NewWidthCalc = number_format($ImageWidth / $WidthRatio, 0);
											$NewHeightCalc = number_format($ImageHeight / $WidthRatio, 0);
								
										}	
										else {
									
											$NewWidthCalc = number_format($ImageWidth / $HeightRatio, 0);
											$NewHeightCalc = number_format($ImageHeight / $HeightRatio, 0);
										
										}
							
								
										if ($FileType == 1) {
											$SourceData = imagecreatefromgif($FileSource);
										}
										else if ($FileType == 2) {
											$SourceData = imagecreatefromjpeg($FileSource);
										}
										else if ($FileType == 3) {
											$SourceData = imagecreatefrompng($FileSource);
										} 
								
										$DestinationImage = imagecreatetruecolor($NewWidthCalc, $NewHeightCalc);
										imagecopyresampled($DestinationImage, $SourceData, 0, 0, 0, 0, $NewWidthCalc, $NewHeightCalc, $ImageWidth, $ImageHeight);
								
								
										if ($FileType == 1) {
											imagegif($DestinationImage, './thumbnails/'.$RecordNumberCreated.'_'.$NewFilename);
										}
										else if ($FileType == 2) {
											imagejpeg($DestinationImage, './thumbnails/'.$RecordNumberCreated.'_'.$NewFilename);
										}
										else if ($FileType == 3) {
											imagepng($DestinationImage, './thumbnails/'.$RecordNumberCreated.'_'.$NewFilename);
										}
										
										if ($Settings['FilesCHMOD'] != '') {
											@chmod('./thumbnails/'.$RecordNumberCreated.'_'.$NewFilename, $Settings['FilesCHMOD']);
										}
									
											
										imagedestroy($SourceData);
										imagedestroy($DestinationImage);
										
										
										$query = "update `".$Settings['DBPrefix']."core-Files` set ImageWidth='".$ImageWidth."', ImageHeight='".$ImageHeight."', ThumbnailExists=1 where RecordNumber='".$RecordNumberCreated."' limit 1";
										$result = mysql_query($query) or die (mysql_error());
										
									
									}
									else {
											
										@copy($FileSource, './thumbnails/'.$RecordNumberCreated.'_'.$NewFilename);
										
										if ($Settings['FilesCHMOD'] != '') {
											@chmod('./thumbnails/'.$RecordNumberCreated.'_'.$NewFilename, $Settings['FilesCHMOD']);
										}
									
										$query = "update `".$Settings['DBPrefix']."core-Files` set ImageWidth='".$ImageWidth."', ImageHeight='".$ImageHeight."', ThumbnailExists=1 where RecordNumber='".$RecordNumberCreated."' limit 1";
										$result = mysql_query($query) or die (mysql_error());
											
									}
									
															
								
								}
																			
								
								
								if (strpos($Arguments4,'i') !== false && $FileTypeGroup != 3) {
									$FileTypeWarning = '<b><font color="#ff0000">Warning!  File uploaded is not a website image type (GIF, JPEG, PNG), and will not be visible in the file manager when selecting an image to insert.</font></b><br><br><br>';
								}
								
								
								
								$query1 = "select * from `".$Settings['DBPrefix']."core-Files` where Filename='".$ExistingFilename."' and Location='".$CurrentLocation."' and ModifyLevel<='".$UserLevel."' limit 1";
								$result1 = mysql_query($query1) or die (mysql_error());
								if (mysql_num_rows($result1) > 0) {
									// if able to modify existing file
									
									$PageContents = $FileTypeWarning.'<b>A file named "'.$ExistingFilename.'" already exists in this folder.  Your upload has been temporarily renamed to "'.$NewFilename.'".<br><br>Select one of the actions below to continue:</b><br><br><br>
							
									<b>Rename Existing File</b><br><form name="RenameExistingForm" action="'.$MainURL.'/admin/filemanager-functions/upload_rename_existing/'.$Arguments4.'" method="post"><input type="hidden" id="ExistingFilename" name="ExistingFilename" value="'.$DestinationPath.$ExistingFilename.'"><input type="hidden" id="UploadedFilename" name="UploadedFilename" value="'.$DestinationPath.$NewFilename.'"><input type="text" name="NewFileName" id="NewFileName" value="'.$ExistingFilename.'" size="30"><br><input name="SubmitButton" type="submit" value="&nbsp;&nbsp;Rename Existing File&nbsp;&nbsp;"></form><br><br>
							
									<b>Rename Uploaded File</b><br><form name="RenameUploadedForm" action="'.$MainURL.'/admin/filemanager-functions/rename/'.$Arguments4.'" method="post"><input type="hidden" id="RenameFileID" name="RenameFileID" value="'.$RecordNumberCreated.'"><input type="text" name="NewFileName" id="NewFileName" value="'.$NewFilename.'" size="30"><br><input name="SubmitButton" type="submit" value="&nbsp;&nbsp;Rename Uploaded File&nbsp;&nbsp;"></form><br><br>
							
									<b>Replace Existing File</b><br><form name="ReplaceExistingForm" action="'.$MainURL.'/admin/filemanager-functions/upload_replace_existing/'.$Arguments4.'" method="post"><input type="hidden" id="ExistingFilename" name="ExistingFilename" value="'.$DestinationPath.$ExistingFilename.'"><input type="hidden" id="UploadedFilename" name="UploadedFilename" value="'.$DestinationPath.$NewFilename.'"><input name="SubmitButton" type="submit" value="&nbsp;&nbsp;Replace Existing File&nbsp;&nbsp;"></form><br><br>
							
									<b>Cancel Upload</b><br><form name="CancelUploadForm" action="'.$MainURL.'/admin/filemanager-functions/delete/'.$Arguments4.'" method="post"><input type="hidden" id="DeleteFileID" name="DeleteFileID" value="'.$RecordNumberCreated.'"><input name="SubmitButton" type="submit" value="&nbsp;&nbsp;Cancel File Upload&nbsp;&nbsp;"></form>';
									
									
								}
								else {
									// not able to modify existing
															
									$PageContents = $FileTypeWarning.'<b>A file named "'.$ExistingFilename.'" already exists in this folder.  Your upload has been temporarily renamed to "'.$NewFilename.'".<br><br>Select one of the actions below to continue:</b><br><br><br>
																						
									<b>Rename Uploaded File</b><br><form name="RenameUploadedForm" action="'.$MainURL.'/admin/filemanager-functions/rename/'.$Arguments4.'" method="post"><input type="hidden" id="RenameFileID" name="RenameFileID" value="'.$RecordNumberCreated.'"><input type="text" name="NewFileName" id="NewFileName" value="'.$NewFilename.'" size="30"><br><input name="SubmitButton" type="submit" value="&nbsp;&nbsp;Rename Uploaded File&nbsp;&nbsp;"></form><br><br>
																						
									<b>Cancel Upload</b><br><form name="CancelUploadForm" action="'.$MainURL.'/admin/filemanager-functions/delete/'.$Arguments4.'" method="post"><input type="hidden" id="DeleteFileID" name="DeleteFileID" value="'.$RecordNumberCreated.'"><input name="SubmitButton" type="submit" value="&nbsp;&nbsp;Cancel File Upload&nbsp;&nbsp;"></form>';
								}
								
												
							
							}
							else {
								$PageContents = 'Not allowed to upload file type<br><br><a href="javascript:history.go(-1);">Go Back</a>';
								@unlink($FileData);
							}
							
														
														
					
						}
					
					} // end if file actually uploaded
				
				}
				else {
							
					$PageContents = 'Not allowed to upload here!<br><br><a href="javascript:history.go(-1);">Go Back</a>';
					@unlink($FileData);
					
				}
				
	
							
			
			
			}
			else {
				// no form contents
				$PageContents = $MsgText[0][98];
			}
					

		}
		else {
			// insufficient permissions
			$PageContents = $MsgText[0][97];		
		}
		
		
		} // end if Arguments3 == 'upload'
		
		else if ($Arguments3 == 'upload_replace_existing') {
			// uploaded filename exists, user has chosen to replace existing
			
			if ($FormArguments['ExistingFilename'] != '' && $FormArguments['UploadedFilename'] != '') {
			
				$FNPieces = explode('/',$FormArguments['ExistingFilename']);
				$FileName = $FNPieces[count($FNPieces)-1];
				$FileLocation = substr($FormArguments['ExistingFilename'],1,(strlen($FormArguments['ExistingFilename'])-strlen($FileName)-1));
				
				$query = "select * from `".$Settings['DBPrefix']."core-Files` where Filename='".$FileName."' and Location='".$FileLocation."' and ModifyLevel<='".$UserLevel."' limit 1";
		   		$result = mysql_query($query) or die (mysql_error());
				$row = mysql_fetch_array($result);
				
				
				$FNPieces = explode('/',$FormArguments['UploadedFilename']);
				$FileName2 = $FNPieces[count($FNPieces)-1];
				$FileLocation2 = substr($FormArguments['UploadedFilename'],1,(strlen($FormArguments['UploadedFilename'])-strlen($FileName2)-1));
				
				$query2 = "select * from `".$Settings['DBPrefix']."core-Files` where Filename='".$FileName2."' and Location='".$FileLocation2."' and ModifyLevel<='".$UserLevel."' limit 1";
		   		$result2 = mysql_query($query2) or die (mysql_error());
				$row2 = mysql_fetch_array($result2);
				
				if ($row['RecordNumber'] > 0 && $row2['RecordNumber'] > 0) {
					
					@rename('.'.$FileLocation2.$FileName2, '.'.$FileLocation.$FileName);
					@rename('./thumbnails/'.$row2['RecordNumber'].'_'.$FileName2, './thumbnails/'.$row['RecordNumber'].'_'.$FileName);
					
					$query3 = "update `".$Settings['DBPrefix']."core-Files` set FileSize='".$row2['FileSize']."', ImageWidth='".$row2['ImageWidth']."', ImageHeight='".$row2['ImageHeight']."', CreationDate='".GetTimestamp()."', CreatedBy='".$UserNumber."' where RecordNumber='".$row['RecordNumber']."' limit 1";
		   			$result3 = mysql_query($query3) or die (mysql_error());
		   			
		   			$query3 = "delete from `".$Settings['DBPrefix']."core-Files` where RecordNumber='".$row2['RecordNumber']."' limit 1";
		   			$result3 = mysql_query($query3) or die (mysql_error());
					
					/*
					if (strpos($Arguments4,'e') !== false) {
						if (strpos($Arguments4,'i') === false) {
							$ImageMode = 'var ImageMode = false;';
						}
						else {
							$ImageMode = 'var ImageMode = true;';
							
							
							$FNPieces = explode('.',$FileName);
							$FileExtension = $FNPieces[count($FNPieces)-1];
													
							if ($FileTypeExtensions[strtolower($FileExtension)] > 0) {
								$FileTypeGroup = $FileTypeExtensions[strtolower($FileExtension)];
							}
							
							
							if ($FileTypeGroup != 3) {
								$PageContents .= '<b><font color="#ff0000">Warning!  File uploaded is not a website image type (GIF, JPEG, PNG), and will not be visible in the file manager when selecting an image to insert.</font></b><br><br><br>';
							}
						}
									
						$PageContents .= '<script language="JavaScript">
							'.$ImageMode.'
										
							// function to transfer selected file URL back to editor								
							function OpenFile( fileUrl ) {
								if (window.top.opener) {
									window.top.opener.GetE("txtUrl").value = "";
												
									if (ImageMode != true) {
										window.top.opener.OnUrlChange();
								
										window.top.opener.GetE("txtUrl").value = encodeURI( fileUrl ).replace( \'#\', \'%23\' );
								
										window.top.opener.OnUrlChange();
									}
									else {
										window.top.opener.SetUrl(encodeURI( fileUrl ).replace( \'#\', \'%23\' ), "", "", "");
										window.top.opener.GetE("txtBorder").value = "0";
									}
												
									window.top.close() ;
									window.top.opener.focus() ;
								}
								else {
									alert("Original window could not be located.  Please re-start the file manager from its original source and try again.");
								}
							}
							</script>
										
							File successfully replaced.<br><br><a href="'.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$FileLocation).'">Return to '.$FileLocation.'</a><br><br><a href="javascript:OpenFile(\''.$BaseURL.$FileLocation.$FileName.'\');">Select This File and Return to Editor</a>';			
						
					}
					else {
						$PageContents = 'File successfully replaced.<br><br><a href="'.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$FileLocation).'">Return to '.$FileLocation.'</a>';
					}
					*/
					
					header('Location: '.$MainURL.'/admin/filemanager/'.str_replace('u','',$Arguments4).'/'.str_replace('/','+++',$FileLocation));
					
					
				}
				else {
					$PageContents = 'Error locating original and/or replacement file<br><br><a href="javascript:history.go(-1);">Go Back</a>';
				}
				
			
			}
			else {
				
				$PageContents = 'Form data missing or incomplete<br><br><a href="javascript:history.go(-1);">Go Back</a>';
					
			}
		
		} // end if Arguments3 == 'upload_replace_existing'
		
		
		else if ($Arguments3 == 'upload_rename_existing') {
			// uploaded filename exists, user has chosen to rename existing to something else
			
			if ($FormArguments['ExistingFilename'] != '' && $FormArguments['UploadedFilename'] != '' && $FormArguments['NewFileName'] != '') {
			
				$FNPieces = explode('/',$FormArguments['ExistingFilename']);
				$FileName = $FNPieces[count($FNPieces)-1];
				$FileLocation = substr($FormArguments['ExistingFilename'],1,(strlen($FormArguments['ExistingFilename'])-strlen($FileName)-1));
				
				$query = "select * from `".$Settings['DBPrefix']."core-Files` where Filename='".$FileName."' and Location='".$FileLocation."' and ModifyLevel<='".$UserLevel."' limit 1";
		   		$result = mysql_query($query) or die (mysql_error());
				$row = mysql_fetch_array($result);
				
				
				$FNPieces = explode('/',$FormArguments['UploadedFilename']);
				$FileName2 = $FNPieces[count($FNPieces)-1];
				$FileLocation2 = substr($FormArguments['UploadedFilename'],1,(strlen($FormArguments['UploadedFilename'])-strlen($FileName2)-1));
				
				$query2 = "select * from `".$Settings['DBPrefix']."core-Files` where Filename='".$FileName2."' and Location='".$FileLocation2."' and ModifyLevel<='".$UserLevel."' limit 1";
		   		$result2 = mysql_query($query2) or die (mysql_error());
				$row2 = mysql_fetch_array($result2);
				
				if ($row['RecordNumber'] > 0 && $row2['RecordNumber'] > 0) {
				
					
					$FNPieces = explode('.',$row['Filename']);
					$OldFileExtension = $FNPieces[count($FNPieces)-1];
				
					$FNPieces = explode('.',$FormArguments['NewFileName']);
					$NewFileExtension = $FNPieces[count($FNPieces)-1];
				
				
					if (strpos($FormArguments['NewFileName'], '.') === false) {
						$NewFileExtension = $OldFileExtension;
						$FormArguments['NewFileName'] .= '.'.$OldFileExtension;
					}
						
					
					if ($row['ModifyLevel'] <= $UserLevel) {
						if ($Permissions[87] == 'y' || ($FileTypeExtensions[strtolower($OldFileExtension)] == $FileTypeExtensions[strtolower($NewFileExtension)] && $FileTypeExtensions[strtolower($NewFileExtension)] > 0)) {
							// if this is a recognized file type and the same group as previous, or permission to upload restricted files
					
							if ('.'.$row['Location'].$row['Filename'] == '.'.$row['Location'].$FormArguments['NewFileName']) {
								
								// filename hasn't actually changed
								$PageContents = 'Selected file name is identical to previous.  You must enter a new file name for the existing file.  <a href="javascript:history.go(-1);">Go Back</a>';
													
							}
							else if (!is_file('.'.$row['Location'].$FormArguments['NewFileName'])) {
						
								$query = "update `".$Settings['DBPrefix']."core-Files` set Filename='".$FormArguments['NewFileName']."', FileType='".$FileTypeExtensions[strtolower($NewFileExtension)]."' where RecordNumber='".$row['RecordNumber']."' limit 1";
								$result = mysql_query($query) or die (mysql_error());
					
						
								$MainRenameResult = rename('.'.$row['Location'].$row['Filename'], '.'.$row['Location'].$FormArguments['NewFileName']);
					
								if ($row['FileType'] == 3) {
									$ThumbRenameResult = rename('./thumbnails/'.$row['RecordNumber'].'_'.$row['Filename'], './thumbnails/'.$row['RecordNumber'].'_'.$FormArguments['NewFileName']);
								}
								else {
									$ThumbRenameResult = true;
								}
							
								if ($MainRenameResult == true && $ThumbRenameResult == true) {
									
																		
									@rename('.'.$FileLocation2.$FileName2, '.'.$FileLocation.$FileName);
									@rename('./thumbnails/'.$row2['RecordNumber'].'_'.$FileName2, './thumbnails/'.$row2['RecordNumber'].'_'.$FileName);
					
									$query3 = "update `".$Settings['DBPrefix']."core-Files` set Filename='".$FileName."', CreationDate='".GetTimestamp()."', CreatedBy='".$UserNumber."' where RecordNumber='".$row2['RecordNumber']."' limit 1";
		   							$result3 = mysql_query($query3) or die (mysql_error());
		   					   							
					
									/*
									if (strpos($Arguments4,'e') !== false) {
										if (strpos($Arguments4,'i') === false) {
											$ImageMode = 'var ImageMode = false;';
										}
										else {
											$ImageMode = 'var ImageMode = true;';
											
							
											$FNPieces = explode('.',$FileName);
											$FileExtension = $FNPieces[count($FNPieces)-1];
																	
											if ($FileTypeExtensions[strtolower($FileExtension)] > 0) {
												$FileTypeGroup = $FileTypeExtensions[strtolower($FileExtension)];
											}
															
											
											if ($FileTypeGroup != 3) {
												$PageContents .= '<b><font color="#ff0000">Warning!  File uploaded is not a website image type (GIF, JPEG, PNG), and will not be visible in the file manager when selecting an image to insert.</font></b><br><br><br>';
											}
										}
									
										$PageContents .= '<script language="JavaScript">
											'.$ImageMode.'
										
											// function to transfer selected file URL back to editor								
											function OpenFile( fileUrl ) {
												if (window.top.opener) {
													window.top.opener.GetE("txtUrl").value = "";
																
													if (ImageMode != true) {
														window.top.opener.OnUrlChange();
												
														window.top.opener.GetE("txtUrl").value = encodeURI( fileUrl ).replace( \'#\', \'%23\' );
												
														window.top.opener.OnUrlChange();
													}
													else {
														window.top.opener.SetUrl(encodeURI( fileUrl ).replace( \'#\', \'%23\' ), "", "", "");
														window.top.opener.GetE("txtBorder").value = "0";
													}
																
													window.top.close() ;
													window.top.opener.focus() ;
												}
												else {
													alert("Original window could not be located.  Please re-start the file manager from its original source and try again.");
												}
											}
											</script>
										
											File successfully replaced.<br><br><a href="'.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$FileLocation).'">Return to '.$FileLocation.'</a><br><br><a href="javascript:OpenFile(\''.$BaseURL.$FileLocation.$FileName.'\');">Select This File and Return to Editor</a>';			
						
									}
									else {
										$PageContents = 'File successfully replaced.<br><br><a href="'.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$FileLocation).'">Return to '.$FileLocation.'</a>';
									}
									*/
					
									header('Location: '.$MainURL.'/admin/filemanager/'.str_replace('u','',$Arguments4).'/'.str_replace('/','+++',$FileLocation));
									
									
									
								}
								else {
									$PageContents = 'Unknown error renaming file<br><br><a href="javascript:history.go(-1);">Go Back</a>';
								}					
								
							}
							else {
							
								$PageContents = 'Selected file name already exists.  <a href="javascript:history.go(-1);">Go Back</a>';
							
							}
							
						}
						else {
							$PageContents = 'Insufficient permissions to change file extension!<br><br><a href="javascript:history.go(-1);">Go Back</a>';
						}
					}
					else {
						$PageContents = 'Insufficient permissions to modify this file!<br><br><a href="javascript:history.go(-1);">Go Back</a>';
					}
				
					
				}
				else {
					$PageContents = 'Error locating original and/or new file<br><br><a href="javascript:history.go(-1);">Go Back</a>';
				}
				
			
			}
			else {
				
				if ($FormArguments['ExistingFilename'] != '' && $FormArguments['UploadedFilename'] != '') {
					$PageContents = 'Enter new file name for existing file.<br><br><a href="javascript:history.go(-1);">Go Back</a>';				
				}
				else {
					$PageContents = 'Form data missing or incomplete<br><br><a href="javascript:history.go(-1);">Go Back</a>';
				}
					
			}
		
		} // end if Arguments3 == 'upload_rename_existing'
		
		
		else if ($Arguments3 == 'rename') {
		
			if ($FormArguments['NewFileName'] != '') {
			
				$query = "select * from `".$Settings['DBPrefix']."core-Files` where RecordNumber='".$FormArguments['RenameFileID']."' limit 1";
		   		$result = mysql_query($query) or die (mysql_error());
				$row = mysql_fetch_array($result);
			
				
				$FNPieces = explode('.',$row['Filename']);
				$OldFileExtension = $FNPieces[count($FNPieces)-1];
				
				$FNPieces = explode('.',$FormArguments['NewFileName']);
				$NewFileExtension = $FNPieces[count($FNPieces)-1];
				
				
				if (strpos($FormArguments['NewFileName'], '.') === false) {
					$NewFileExtension = $OldFileExtension;
					$FormArguments['NewFileName'] .= '.'.$OldFileExtension;
				}
					
				
				if ($row['ModifyLevel'] <= $UserLevel) {
					if ($Permissions[87] == 'y' || ($FileTypeExtensions[strtolower($OldFileExtension)] == $FileTypeExtensions[strtolower($NewFileExtension)] && $FileTypeExtensions[strtolower($NewFileExtension)] > 0)) {
						// if this is a recognized file type and the same group as previous, or permission to upload restricted files
					
						if ('.'.$row['Location'].$row['Filename'] == '.'.$row['Location'].$FormArguments['NewFileName']) {
							
							// filename hasn't actually changed
							header('Location: '.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$row['Location']));
													
						}
						else if (!is_file('.'.$row['Location'].$FormArguments['NewFileName'])) {
					
							$query = "update `".$Settings['DBPrefix']."core-Files` set Filename='".$FormArguments['NewFileName']."', FileType='".$FileTypeExtensions[strtolower($NewFileExtension)]."' where RecordNumber='".$FormArguments['RenameFileID']."' limit 1";
							$result = mysql_query($query) or die (mysql_error());
					
						
							$MainRenameResult = rename('.'.$row['Location'].$row['Filename'], '.'.$row['Location'].$FormArguments['NewFileName']);
					
							if ($row['FileType'] == 3) {
								$ThumbRenameResult = rename('./thumbnails/'.$FormArguments['RenameFileID'].'_'.$row['Filename'], './thumbnails/'.$FormArguments['RenameFileID'].'_'.$FormArguments['NewFileName']);
							}
							else {
								$ThumbRenameResult = true;
							}
						
							if ($MainRenameResult == true && $ThumbRenameResult == true) {
								header('Location: '.$MainURL.'/admin/filemanager/'.str_replace('u','',$Arguments4).'/'.str_replace('/','+++',$row['Location']));
							}
							else {
								$PageContents = 'Unknown error renaming file<br><br><a href="javascript:history.go(-1);">Go Back</a>';
							}					
							
						}
						else {
						
							$PageContents = 'Selected file name already exists.  <a href="javascript:history.go(-1);">Go Back</a>';
						
						}
						
					}
					else {
						$PageContents = 'Insufficient permissions to change file extension!<br><br><a href="javascript:history.go(-1);">Go Back</a>';
					}
				}
				else {
					$PageContents = 'Insufficient permissions to modify this file!<br><br><a href="javascript:history.go(-1);">Go Back</a>';
				}
				
			} // end if $FormArguments['NewFileName'] != ''	
			else {
				$PageContents = 'No file name entered.  Enter the new name for the file you wish to rename.<br><br><a href="javascript:history.go(-1);">Go Back</a>';
			}
			
		} // end if Arguments3 == 'rename'
		
		
		else if ($Arguments3 == 'delete') {
		
			$query = "select * from `".$Settings['DBPrefix']."core-Files` where RecordNumber='".$FormArguments['DeleteFileID']."' limit 1";
	   		$result = mysql_query($query) or die (mysql_error());
			$row = mysql_fetch_array($result);
							
			
			if ($row['ModifyLevel'] <= $UserLevel) {
									
				if ($row['FileType'] == 3) {
					$ThumbDeleteResult = unlink('./thumbnails/'.$FormArguments['DeleteFileID'].'_'.$row['Filename']);
				}
				else {
					$ThumbDeleteResult = true;
				}
				
				$MainDeleteResult = unlink('.'.$row['Location'].$row['Filename']);
				
					
				if ($MainDeleteResult == true && $ThumbDeleteResult == true) {
				
					$query2 = "delete from `".$Settings['DBPrefix']."core-Files` where RecordNumber='".$FormArguments['DeleteFileID']."' limit 1";
	   				$result2 = mysql_query($query2) or die (mysql_error());
				
					header('Location: '.$MainURL.'/admin/filemanager/'.str_replace('u','',$Arguments4).'/'.str_replace('/','+++',$row['Location']));
				}
				else {
					$PageContents = 'Unknown error deleting file<br><br><a href="javascript:history.go(-1);">Go Back</a>';
				}					
								
			}
			else {
				$PageContents = 'Insufficient permissions to delete this file!<br><br><a href="javascript:history.go(-1);">Go Back</a>';
			}
			
		
		} // end if Arguments3 == 'delete'
		
		else if ($Arguments3 == 'download') {
		
			$query = "select * from `".$Settings['DBPrefix']."core-Files` where RecordNumber='".intval($Arguments5)."' limit 1";
	   		$result = mysql_query($query) or die (mysql_error());
			$row = mysql_fetch_array($result);
											
			
			if ($row['ViewLevel'] <= $UserLevel) {
				
				// disposition set to "inline" to view file in browser or "attachment" to download to hard disk
				header("Content-type:application/octet-stream");
				header("Content-Disposition: attachment; filename=\"".trim(htmlentities($row['Filename']))."\"");
				header("Content-Description: ".trim(htmlentities($row['Filename'])));
				header("Content-Length: ".(string)(filesize('.'.$row['Location'].$row['Filename'])));
		
		
				if (is_file('.'.$row['Location'].$row['Filename'])) {
					$fp = fopen('.'.$row['Location'].$row['Filename'], "rb");
					while (!feof($fp)) {
					    $buffer = fgets($fp, 4096);
					    echo $buffer;
					}
					fclose ($fp);
				}
				
				
				exit();				
				
				
			}
			else {
				$PageContents = 'Insufficient permissions to download this file!<br><br><a href="javascript:history.go(-1);">Go Back</a>';
			}
			
		
		} // end if Arguments3 == 'download'
		
		else if ($Arguments3 == 'createfolder') {
		
			if ($FormArguments['NewFolderName'] != '') {
		
				$CurrentLocation = $FormArguments['CurrentLocation'];
			
		
				$ThisFolderParent = substr($CurrentLocation,0,strrpos($CurrentLocation,'/')-1);
				
				$CLPieces = explode('/',$CurrentLocation);
				$ThisFolderParent = '/';
				for ($x = 1; $x < (count($CLPieces)-2); $x++) {
					$ThisFolderParent .= $CLPieces[$x].'/';
				}

				$ThisFolderName = $CLPieces[count($CLPieces)-2];
				
				
				$FormArguments['NewFolderName'] = str_replace('/','',$FormArguments['NewFolderName']);
				$FormArguments['NewFolderName'] = str_replace('..','',$FormArguments['NewFolderName']);
		
		
		
				if ($ThisFolderParent == '/') {
					$query = "select * from `".$Settings['DBPrefix']."core-Folders` where Folder='/' and Location='' limit 1";
				}
				else {
					$query = "select * from `".$Settings['DBPrefix']."core-Folders` where Folder='".$ThisFolderName."' and Location='".$ThisFolderParent."' limit 1";
				}
		   		$result = mysql_query($query) or die (mysql_error());
				$row = mysql_fetch_array($result);
					
				if ($row['AddFoldersLevel'] <= $UserLevel && $row['RecordNumber'] > 0) {	
					
					$CreateFolderResult = mkdir('.'.$FormArguments['CurrentLocation'].$FormArguments['NewFolderName']);
					
					if ($Settings['FoldersCHMOD'] != '') {
						@chmod('.'.$FormArguments['CurrentLocation'].$FormArguments['NewFolderName'], $Settings['FoldersCHMOD']);
					}
					
					if ($CreateFolderResult) {
					
						if ($ThisFolderParent == '/') {
							$ThisFolderParent = '';
						}					
					
						$query = "insert into `".$Settings['DBPrefix']."core-Folders` (Location, Folder, CreatedBy, CreationDate, ModifyLevel, ViewFilesLevel, AddFilesLevel, AddFoldersLevel, SystemFolder) values ('".$CurrentLocation."', '".$FormArguments['NewFolderName']."', '".$UserNumber."', '".GetTimestamp()."', '".$A."', '".$B."', '".$C."', '".$D."', '0')";
						$result = mysql_query($query) or die (mysql_error());
						
						header('Location: '.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$FormArguments['CurrentLocation']));
					}
					else {
						$PageContents = 'Folder could not be created (system error).<br><br><a href="javascript:history.go(-1);">Go Back</a>';
					}
					
				}
				else {
					$PageContents = 'Insufficient permissions to create folder!<br><br><a href="javascript:history.go(-1);">Go Back</a>';
				}
			
			} // end if $FormArguments['NewFolderName'] != ''
			else {
				$PageContents = 'No folder name entered.  Enter the name for the folder you wish to create.<br><br><a href="javascript:history.go(-1);">Go Back</a>';
			}
		
		} // end if Arguments3 == 'createfolder'
		
		
		else if ($Arguments3 == 'move') {
		
			if ($FormArguments['MoveFileID'] != '' && $FormArguments['FileDestination'] != '') {
		
								
				$FormArguments['FileDestination'] = str_replace('..','',$FormArguments['FileDestination']);
				
				
				//$ThisFolderParent = substr($FormArguments['FileDestination'],0,strrpos($FormArguments['FileDestination'],'/')-1);
				
				$CLPieces = explode('/',$FormArguments['FileDestination']);
				$ThisFolderParent = '/';
				for ($x = 1; $x < (count($CLPieces)-2); $x++) {
					$ThisFolderParent .= $CLPieces[$x].'/';
				}

				$ThisFolderName = $CLPieces[count($CLPieces)-2];
				
				//print '$ThisFolderName>>'.$ThisFolderName.'<br>$ThisFolderParent>>'.$ThisFolderParent.'<br><br>';
				//var_dump($CLPieces);
				
		
				if ($FormArguments['FileDestination'] == '/') {
					$query = "select * from `".$Settings['DBPrefix']."core-Folders` where Folder='/' and Location='' limit 1";
				}
				else {
					$query = "select * from `".$Settings['DBPrefix']."core-Folders` where Folder='".$ThisFolderName."' and Location='".$ThisFolderParent."' limit 1";
				}
		   		$result = mysql_query($query) or die (mysql_error());
				$row = mysql_fetch_array($result);
				
				
				$query2 = "select * from `".$Settings['DBPrefix']."core-Files` where RecordNumber='".intval($FormArguments['MoveFileID'])."' limit 1";
				$result2 = mysql_query($query2) or die (mysql_error());
				$row2 = mysql_fetch_array($result2);
				
					
				if ($row['AddFilesLevel'] <= $UserLevel && $row['RecordNumber'] > 0 && $row2['ModifyLevel'] <= $UserLevel) {
				
					//if ($FormArguments['FileDestination'] != '/') {
					//	$FormArguments['FileDestination'] .= '/';
					//}
					
					$MoveFileResult = rename('.'.$row2['Location'].$row2['Filename'], '.'.$FormArguments['FileDestination'].$row2['Filename']);
					
					if ($Settings['FilesCHMOD'] != '') {
						@chmod('.'.$FormArguments['FileDestination'].$row2['Filename'], $Settings['FilesCHMOD']);
					}
					
					if ($MoveFileResult) {
					
						// update db
						$query3 = "update `".$Settings['DBPrefix']."core-Files` set Location='".$FormArguments['FileDestination']."' where RecordNumber='".intval($FormArguments['MoveFileID'])."' limit 1";
						$result3 = mysql_query($query3) or die (mysql_error());
						
						// display status message
						$PageContents = '<b>File successfully moved.</b><br><br><br>Go to <a href="'.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$FormArguments['FileDestination']).'">'.$FormArguments['FileDestination'].'</a><br><br><br>Return to <a href="'.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$row2['Location']).'">'.$row2['Location'].'</a>';

					}
					else {
						$PageContents = '<b>File could not be moved (system error).</b><br><br><br><a href="javascript:history.go(-1);">Go Back</a>';
					}
					
				}
				else {
								
					$PageContents = '<b>Insufficient permissions to move file to this folder!</b><br><br><br><a href="javascript:history.go(-1);">Go Back</a>';
				}
			
			} // end if $FormArguments['FileDestination'] != ''
			else {
				$PageContents = '<b>No destination folder selected.</b><br><br><br><a href="javascript:history.go(-1);">Go Back</a>';
			}
		
		} // end if Arguments3 == 'move'
		
		else if ($Arguments3 == 'permissions') {
		
			if ($FormArguments['PermissionFileID'] != '' && $FormArguments['ModifyLevel'] != '' && $FormArguments['ViewLevel'] != '') {
		
								
				$query2 = "select * from `".$Settings['DBPrefix']."core-Files` where RecordNumber='".intval($FormArguments['PermissionFileID'])."' limit 1";
				$result2 = mysql_query($query2) or die (mysql_error());
				$row2 = mysql_fetch_array($result2);
									
				if ($row2['ModifyLevel'] <= $UserLevel) {
				
					$query3 = "update `".$Settings['DBPrefix']."core-Files` set ModifyLevel='".intval($FormArguments['ModifyLevel'])."', ViewLevel='".intval($FormArguments['ViewLevel'])."' where RecordNumber='".intval($FormArguments['PermissionFileID'])."' limit 1";
					$result3 = mysql_query($query3) or die (mysql_error());
						
					// display status message
					$PageContents = 'File permissions successfully updated.  Return to <a href="'.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$row2['Location']).'">'.$row2['Location'].'</a>';

				}				
				else {
								
					$PageContents = 'Insufficient permissions to modify this file!<br><br><a href="javascript:history.go(-1);">Go Back</a>';
				}
			}			
		
		} // end if Arguments3 == 'permissions'
		
		
		
		
		else if ($Arguments3 == 'folderpermissions') {
		
			if ($FormArguments['PermissionFolderID'] != '' && $FormArguments['FolderModifyLevel'] != '' && $FormArguments['FolderViewLevel'] != '' && $FormArguments['FolderAddFilesLevel'] != '' && $FormArguments['FolderAddFoldersLevel'] != '') {
		
								
				$query2 = "select * from `".$Settings['DBPrefix']."core-Folders` where RecordNumber='".intval($FormArguments['PermissionFolderID'])."' limit 1";
				$result2 = mysql_query($query2) or die (mysql_error());
				$row2 = mysql_fetch_array($result2);
									
				if ($row2['ModifyLevel'] <= $UserLevel) {
				
					$query3 = "update `".$Settings['DBPrefix']."core-Folders` set ModifyLevel='".intval($FormArguments['FolderModifyLevel'])."', ViewFilesLevel='".intval($FormArguments['FolderViewLevel'])."', AddFilesLevel='".intval($FormArguments['FolderAddFilesLevel'])."', AddFoldersLevel='".intval($FormArguments['FolderAddFoldersLevel'])."' where RecordNumber='".intval($FormArguments['PermissionFolderID'])."' limit 1";
					$result3 = mysql_query($query3) or die (mysql_error());
						
					// display status message
					$PageContents = 'Folder permissions successfully updated.  Return to <a href="'.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$row2['Location']).'">'.$row2['Location'].'</a>';

				}				
				else {
								
					$PageContents = 'Insufficient permissions to modify this folder!<br><br><a href="javascript:history.go(-1);">Go Back</a>';
				}
			}		
		
		} // end if Arguments3 == 'folderpermissions'
		
		
		
		else if ($Arguments3 == 'folderrename') {
		
			$FormArguments['RenameNewFolderName'] = str_replace('..','',$FormArguments['RenameNewFolderName']);
			$FormArguments['RenameNewFolderName'] = str_replace('/','',$FormArguments['RenameNewFolderName']);
			$FormArguments['RenameNewFolderName'] = str_replace('\\','',$FormArguments['RenameNewFolderName']);
			$FormArguments['RenameNewFolderName'] = str_replace('?','',$FormArguments['RenameNewFolderName']);
			$FormArguments['RenameNewFolderName'] = str_replace('#','',$FormArguments['RenameNewFolderName']);
			
		
			if ($FormArguments['RenameFolderID'] > 0) {
			
				if ($FormArguments['RenameNewFolderName'] != '') {
					// new name entered
				
					$query2 = "select * from `".$Settings['DBPrefix']."core-Folders` where RecordNumber='".intval($FormArguments['RenameFolderID'])."' limit 1";
					$result2 = mysql_query($query2) or die (mysql_error());
					if (mysql_num_rows($result2) > 0) {
						// folder found in db
						$row2 = mysql_fetch_array($result2);
						
						if ($row2['Folder'] != $FormArguments['RenameNewFolderName']) {
							// name entered is different than existing
						
							if ($row2['ModifyLevel'] <= $UserLevel) {
								// has permission to modify this folder
								
								
								// switch for whether anything un-editable has been found below this level
								$FoundHigherNumber = false;
								
								// recursive function to spider the directory tree
								function ReadDirectory2($dir) {
															
									//Global $DirectoriesArray, $FilesArray, $FileSizesArray;
									Global $Settings, $FoundHigherNumber, $UserLevel;

									if (is_dir($dir)) {
										if ($dh[$dir] = opendir($dir)) {
								   			while (($file = readdir($dh[$dir])) !== false) {
												if ($file != '' && $file != '.' && $file != '..' && $file != 'error_log' && $file != 'settings.php' && $file != '.htaccess' && $dir.$file != './thumbnails' && substr($file,0,1) != '.') {
																						
													if (filetype($dir . $file) == 'dir') {
																							
														if ($dir != './') {
															$FolderName = '/'.substr($dir,2).'';
														}
														else {
															$FolderName = '/';
														}
														
														$query = "select * from `".$Settings['DBPrefix']."core-Folders` where Folder='".$file."' and Location='".$FolderName."' and ModifyLevel>'".$UserLevel."' limit 1";
						   								$result = mysql_query($query) or die (mysql_error());
														if (mysql_num_rows($result) > 0) {
															$FoundHigherNumber = true;
														}

														ReadDirectory2($dir . $file.'/');
													}
													else {
																							
														if ($dir != './') {
															$FolderName = '/'.substr($dir,2);
														}
														else {
															$FolderName = '/';
														}
																		
														$query = "select * from `".$Settings['DBPrefix']."core-Files` where Filename='".$file."' and Location='".$FolderName."' and ModifyLevel>'".$UserLevel."' limit 1";
		   												$result = mysql_query($query) or die (mysql_error());
														if (mysql_num_rows($result) > 0) {
															$FoundHigherNumber = true;
														}
									
									
													}
								
								
												}
											}
											closedir($dh[$dir]);
										}
									}
			
								}
					
								// start the spider process
								ReadDirectory2('.'.$row2['Location'].$row2['Folder'].'/');
								
								
								if ($FoundHigherNumber == false) {
									// allowed to modify everything in this folder
									
									
									$query = "select * from `".$Settings['DBPrefix']."core-Folders` where Folder='".$FormArguments['RenameNewFolderName']."' and Location='".$row2['Location']."' limit 1";
						   			$result = mysql_query($query) or die (mysql_error());
									if (mysql_num_rows($result) == 0) {
										// new name doesn't already exist
									
										$RenameResult = @rename('.'.$row2['Location'].$row2['Folder'], '.'.$row2['Location'].$FormArguments['RenameNewFolderName']);										
										
										if ($RenameResult == true) {
											// actual folder moved, now update dbs
											
											$query = "update `".$Settings['DBPrefix']."core-Folders` set Folder='".$FormArguments['RenameNewFolderName']."' where RecordNumber='".$row2['RecordNumber']."' limit 1";
						   					$result = mysql_query($query) or die (mysql_error());
						   											   					
						   					
						   					$query3 = "select * from `".$Settings['DBPrefix']."core-Folders` where Location like '".$row2['Location'].$row2['Folder']."%'";
						   					$result3 = mysql_query($query3) or die (mysql_error());
						   					while ($row3 = mysql_fetch_array($result3)) {
						   						$NewLocation = $row2['Location'].$FormArguments['RenameNewFolderName'].substr($row3['Location'],(strlen($row2['Location'].$row2['Folder'])));
						   						$query4 = "update `".$Settings['DBPrefix']."core-Folders` set Location='".$NewLocation."' where RecordNumber='".$row3['RecordNumber']."' limit 1";
						   						$result4 = mysql_query($query4) or die (mysql_error());
						   					}
						   					
						   					
						   					$query3 = "select * from `".$Settings['DBPrefix']."core-Files` where Location like '".$row2['Location'].$row2['Folder']."%'";
						   					$result3 = mysql_query($query3) or die (mysql_error());
						   					while ($row3 = mysql_fetch_array($result3)) {
						   						$NewLocation = $row2['Location'].$FormArguments['RenameNewFolderName'].substr($row3['Location'],(strlen($row2['Location'].$row2['Folder'])));
						   						$query4 = "update `".$Settings['DBPrefix']."core-Files` set Location='".$NewLocation."' where RecordNumber='".$row3['RecordNumber']."' limit 1";
						   						$result4 = mysql_query($query4) or die (mysql_error());
						   					}
						   					
						   					
						   					header('Location: '.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$row2['Location']));
						   					
										
										}
										else {
											$PageContents = 'System error moving folder.<br><br><a href="javascript:history.go(-1);">Go Back</a>';
										}
									
									}
									else {
										$PageContents = 'Error, new folder name entered already exists!<br><br><a href="javascript:history.go(-1);">Go Back</a>';									
									}
								
								}
								else {
									$PageContents = 'Error, insufficient permission to modify this folder!  This folder contains one or more items you do not have permission to modify.<br><br><a href="javascript:history.go(-1);">Go Back</a>';
								}
													
							
							}
							else {
								$PageContents = 'Error, insufficient permission to modify this folder!<br><br><a href="javascript:history.go(-1);">Go Back</a>';						
							}						
						}
						else {
							$PageContents = 'Error, folder name is identical to previous.  Enter the new name for this folder.<br><br><a href="javascript:history.go(-1);">Go Back</a>';						
						}					
					}
					else {					
						$PageContents = 'Error, folder could not be located.<br><br><a href="javascript:history.go(-1);">Go Back</a>';
					}				
				}
				else {				
					$PageContents = 'No folder name entered.  Enter the new name for this folder.<br><br><a href="javascript:history.go(-1);">Go Back</a>';				
				}			
			}
			else {
				$PageContents = 'Form data error.<br><br><a href="javascript:history.go(-1);">Go Back</a>';			
			}	
				
		} // end if Arguments3 == 'folderrename'	



		else if ($Arguments3 == 'folderdelete') {
					
		
			if ($FormArguments['DeleteFolderID'] > 0) {
				
				$query2 = "select * from `".$Settings['DBPrefix']."core-Folders` where RecordNumber='".intval($FormArguments['DeleteFolderID'])."' limit 1";
				$result2 = mysql_query($query2) or die (mysql_error());
				if (mysql_num_rows($result2) > 0) {
					// folder found in db
					$row2 = mysql_fetch_array($result2);
					
										
					if ($row2['ModifyLevel'] <= $UserLevel) {
						// has permission to modify this folder
						
						
						// switch for whether anything un-editable has been found below this level
						$FoundHigherNumber = false;
						
						// recursive function to spider the directory tree
						function ReadDirectory2($dir) {
													
							//Global $DirectoriesArray, $FilesArray, $FileSizesArray;
							Global $Settings, $FoundHigherNumber, $UserLevel;
								if (is_dir($dir)) {
								if ($dh[$dir] = opendir($dir)) {
						   			while (($file = readdir($dh[$dir])) !== false) {
										if ($file != '' && $file != '.' && $file != '..' && $file != 'error_log' && $file != 'settings.php' && $file != '.htaccess' && $dir.$file != './thumbnails' && substr($file,0,1) != '.') {
																				
											if (filetype($dir . $file) == 'dir') {
																					
												if ($dir != './') {
													$FolderName = '/'.substr($dir,2).'';
												}
												else {
													$FolderName = '/';
												}
												
												$query = "select * from `".$Settings['DBPrefix']."core-Folders` where Folder='".$file."' and Location='".$FolderName."' and ModifyLevel>'".$UserLevel."' limit 1";
					  							$result = mysql_query($query) or die (mysql_error());
												if (mysql_num_rows($result) > 0) {
													$FoundHigherNumber = true;
												}
													ReadDirectory2($dir . $file.'/');
											}
											else {
																					
												if ($dir != './') {
													$FolderName = '/'.substr($dir,2);
												}
												else {
													$FolderName = '/';
												}
																
												$query = "select * from `".$Settings['DBPrefix']."core-Files` where Filename='".$file."' and Location='".$FolderName."' and ModifyLevel>'".$UserLevel."' limit 1";
   												$result = mysql_query($query) or die (mysql_error());
												if (mysql_num_rows($result) > 0) {
													$FoundHigherNumber = true;
												}
							
							
											}
						
						
										}
									}
									closedir($dh[$dir]);
								}
							}
	
						}
			
						// start the spider process
						ReadDirectory2('.'.$row2['Location'].$row2['Folder'].'/');
								
								
						if ($FoundHigherNumber == false) {
							// allowed to modify everything in this folder
								
								
			   				$query3 = "select * from `".$Settings['DBPrefix']."core-Folders` where Location like '".$row2['Location'].$row2['Folder']."%'";
			   				$result3 = mysql_query($query3) or die (mysql_error());
			   				while ($row3 = mysql_fetch_array($result3)) {
			   				
			   					$query5 = "select * from `".$Settings['DBPrefix']."core-Files` where Location like '".$row3['Location'].$row3['Folder']."%'";
			   					$result5 = mysql_query($query5) or die (mysql_error());
			   					while ($row5 = mysql_fetch_array($result5)) {
			   						
			   						$DeleteResult = @unlink('.'.$row5['Location'].$row5['Filename']);						
								
									if ($DeleteResult == true) {
			   							$query4 = "delete from `".$Settings['DBPrefix']."core-Files` where RecordNumber='".$row5['RecordNumber']."' limit 1";
			   							$result4 = mysql_query($query4) or die (mysql_error());
			   						}
			   					}
			   						
			   					$DeleteResult = @rmdir('.'.$row3['Location'].$row3['Folder']);						
								
								if ($DeleteResult == true) {
			   						$query4 = "delete from `".$Settings['DBPrefix']."core-Folders` where RecordNumber='".$row3['RecordNumber']."' limit 1";
				   					$result4 = mysql_query($query4) or die (mysql_error());
				   				}
			   				}
					   		
					   		
					   		$query5 = "select * from `".$Settings['DBPrefix']."core-Files` where Location like '".$row2['Location'].$row2['Folder']."%'";
			   				$result5 = mysql_query($query5) or die (mysql_error());
			   				while ($row5 = mysql_fetch_array($result5)) {
			   						
			   					$DeleteResult = @unlink('.'.$row5['Location'].$row5['Filename']);						
								
								if ($DeleteResult == true) {
			   						$query4 = "delete from `".$Settings['DBPrefix']."core-Files` where RecordNumber='".$row5['RecordNumber']."' limit 1";
			   						$result4 = mysql_query($query4) or die (mysql_error());
			   					}
			   				}
			   				
			   					
			   					
			   				$DeleteResult = @rmdir('.'.$row2['Location'].$row2['Folder']);
			   				
			   				if ($DeleteResult == true) {
			   					
			   					$query = "delete from `".$Settings['DBPrefix']."core-Folders` where RecordNumber='".$row2['RecordNumber']."' limit 1";
			   					$result = mysql_query($query) or die (mysql_error());
			   					
			   					header('Location: '.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.str_replace('/','+++',$row2['Location']));
				   											
							}
							else {
								$PageContents = 'System error deleting folder.<br><br><a href="javascript:history.go(-1);">Go Back</a>';
							}
										
						}
						else {
							$PageContents = 'Error, insufficient permission to modify this folder!  This folder contains one or more items you do not have permission to modify.<br><br><a href="javascript:history.go(-1);">Go Back</a>';
						}
													
					
					}
					else {
						$PageContents = 'Error, insufficient permission to modify this folder!<br><br><a href="javascript:history.go(-1);">Go Back</a>';						
					}						
										
				}
				else {					
					$PageContents = 'Error, folder could not be located.<br><br><a href="javascript:history.go(-1);">Go Back</a>';
				}										
			}
			else {
				$PageContents = 'Form data error.<br><br><a href="javascript:history.go(-1);">Go Back</a>';			
			}	
				
		} // end if Arguments3 == 'folderdelete'
		
		
		
		else if ($Arguments3 == 'scan') {
			// function to scan for new files not already in file manager
		
		
			@mkdir('./thumbnails');
			if (is_writable('./thumbnails')) {
			
			
			
			
			//@unlink('./color_picker.html');
			@unlink('./editor.html');
			@unlink('./image.html');
			@unlink('./link.html');
			@unlink('./table.html');
			
			@unlink('./images/buttons.gif');
			@unlink('./images/cheque.gif');
			//@unlink('./images/color_chart.jpg');
			@unlink('./images/creditcards.gif');
			@unlink('./images/fbc_center.gif');
			@unlink('./images/fbc_hr.gif');
			@unlink('./images/fbc_left.gif');
			@unlink('./images/fbc_right.gif');
			@unlink('./images/icon_email.gif');
			@unlink('./images/icon_print.gif');
			
			
			
			
			$query = "select * from `".$Settings['DBPrefix']."core-Folders` where Location='' and Folder='/' limit 1";
			$result = mysql_query($query) or die (mysql_error());
			if (mysql_num_rows($result) == 0) {
				$query = "insert into `".$Settings['DBPrefix']."core-Folders` (Location, Folder, ModifyLevel) values ('','/','101')";
				$result = mysql_query($query) or die (mysql_error());
			}
			
			
			
			
			$MaxExecTime = ini_get('max_execution_time');
			if ($MaxExecTime < 10) {
				$MaxExecTime = 30;
			}
			
			$StartTime = GetTimestamp();
			
			$StopTime = $StartTime + ($MaxExecTime*.8);
			
			$LoopCounter = intval($Arguments6);
						
			
			// recursive function to spider the directory tree
			function ReadDirectory1($dir) {
						
				//Global $DirectoriesArray, $FilesArray, $FileSizesArray;
				Global $Settings, $FileTypeExtensions, $StopTime, $LoopCounter, $MainURL, $Arguments4, $Arguments5, $MsgText;

				if (is_dir($dir)) {
					if ($dh[$dir] = opendir($dir)) {
			   			while (($file = readdir($dh[$dir])) !== false) {
							if ($file != '' && $file != '.' && $file != '..' && $file != 'error_log' && $file != 'settings.php' && $file != '.htaccess' && $dir.$file != './thumbnails' && substr($file,0,1) != '.' && $file != 'v2.5.data' && $file != 'v2.5.sql' && $file != 'v2.5.map' && $file != 'v3.0.data' && $file != 'v3.0.sql' && $file != 'v3.0.map' && $file != 'install.php' && $file != 'upgrade.php' && $file != 'pack.php') {
								
															
								if ($StopTime <= GetTimestamp()) {
									if ($LoopCounter < 100) {
										$LoopCounter++;
										header('Location: '.$MainURL.'/admin/filemanager-functions/scan/'.$Arguments4.'/'.$Arguments5.'/'.$LoopCounter);
										sleep(1);
									}
									else {
										print $MsgText[0][710].'<br><br><a href="javascript:history.go(-1);">Go Back</a>';
										exit();
									}
								}
																
															
																
								if (filetype($dir . $file) == 'dir') {
																		
									if ($dir != './') {
										$FolderName = '/'.substr($dir,2).'';
									}
									else {
										$FolderName = '/';
									}
									
									$query = "select * from `".$Settings['DBPrefix']."core-Folders` where Folder='".addslashes($file)."' and Location='".addslashes($FolderName)."' limit 1";
	   								$result = mysql_query($query) or die (mysql_error());
									if (mysql_num_rows($result) == 0) {
										$query = "insert into `".$Settings['DBPrefix']."core-Folders` (Folder, Location, CreatedBy, CreationDate, ModifyLevel, ViewFilesLevel, AddFilesLevel, AddFoldersLevel, SystemFolder) values ('".addslashes($file)."', '".addslashes($FolderName)."', '0', '".GetTimestamp()."', '1', '1', '1', '1', '0')";
	   									$result = mysql_query($query) or die (mysql_error());
									}

									ReadDirectory1($dir . $file.'/');
								}
								else {
																		
									if ($dir != './') {
										$FolderName = '/'.substr($dir,2);
									}
									else {
										$FolderName = '/';
									}
																		
									$query = "select * from `".$Settings['DBPrefix']."core-Files` where Filename='".addslashes($file)."' and Location='".addslashes($FolderName)."' limit 1";
		   							$result = mysql_query($query) or die (mysql_error());
									if (mysql_num_rows($result) == 0) {
									
										$FileSize = filesize($dir.$file);
									
										$FNPieces = explode('.',$file);
										$FileExtension = strtolower($FNPieces[count($FNPieces)-1]);
										
										$ImageWidth = 0;
										$ImageHeight = 0;
										$FileType = 0;
										if ($FileExtension == 'gif' || $FileExtension == 'png' || $FileExtension == 'jpg' || $FileExtension == 'jpeg') {
										
											$ImageInfo = @getimagesize($dir.$file);
										
											$ImageWidth = $ImageInfo[0];
											$ImageHeight = $ImageInfo[1];
											$FileType = $ImageInfo[2];
											
										}															
											
										$FileTypeGroup = 0;
										if ($FileTypeExtensions[$FileExtension] > 0) {
											$FileTypeGroup = $FileTypeExtensions[$FileExtension];
										}
										
										
										$query = "insert into `".$Settings['DBPrefix']."core-Files` (Filename, Location, CreatedBy, CreationDate, ModifyLevel, ViewLevel, FileType, FileSize, SystemFile) values ('".addslashes($file)."', '".addslashes($FolderName)."', '0', '".GetTimestamp()."', '1', '1', '".$FileTypeGroup."', '".$FileSize."', '0')";
	   									$result = mysql_query($query) or die (mysql_error());
										$RecordNumberCreated = mysql_insert_id();
										
										
										if ($FileTypeGroup == 3 && $ImageWidth > 0 && $ImageHeight > 0) {
											// image we can work with, so make a thumbnail
									
											$FileSource = $dir.$file;										
										
											if ($ImageWidth > 100 || $ImageHeight > 75) {
																					
												$NewWidth = 100;
												$NewHeight = 75;
								
												$WidthRatio = $ImageWidth / $NewWidth;
												$HeightRatio = $ImageHeight / $NewHeight;
							
												if ($WidthRatio >= $HeightRatio) {
								
													$NewWidthCalc = number_format($ImageWidth / $WidthRatio, 0);
													$NewHeightCalc = number_format($ImageHeight / $WidthRatio, 0);
										
												}	
												else {
										
													$NewWidthCalc = number_format($ImageWidth / $HeightRatio, 0);
													$NewHeightCalc = number_format($ImageHeight / $HeightRatio, 0);
										
												}
							
								
												if ($FileType == 1) {
													$SourceData = @imagecreatefromgif($FileSource);
												}
												else if ($FileType == 2) {
													$SourceData = @imagecreatefromjpeg($FileSource);
												}
												else if ($FileType == 3) {
													$SourceData = @imagecreatefrompng($FileSource);
												} 
										
												$DestinationImage = @imagecreatetruecolor($NewWidthCalc, $NewHeightCalc);
												@imagecopyresampled($DestinationImage, $SourceData, 0, 0, 0, 0, $NewWidthCalc, $NewHeightCalc, $ImageWidth, $ImageHeight);
							
							
												if ($FileType == 1) {
													@imagegif($DestinationImage, './thumbnails/'.$RecordNumberCreated.'_'.$file);
												}
												else if ($FileType == 2) {
													@imagejpeg($DestinationImage, './thumbnails/'.$RecordNumberCreated.'_'.$file);
												}
												else if ($FileType == 3) {
													@imagepng($DestinationImage, './thumbnails/'.$RecordNumberCreated.'_'.$file);
												}
												
												
												if ($Settings['FilesCHMOD'] != '') {
													@chmod('./thumbnails/'.$RecordNumberCreated.'_'.$file, $Settings['FilesCHMOD']);
												}
									
											
												if ($SourceData) {
													imagedestroy($SourceData);
												}
												if ($DestinationImage) {
													imagedestroy($DestinationImage);
												}
										
										
												$query = "update `".$Settings['DBPrefix']."core-Files` set ImageWidth='".$ImageWidth."', ImageHeight='".$ImageHeight."', ThumbnailExists=1 where RecordNumber='".$RecordNumberCreated."' limit 1";
												$result = mysql_query($query) or die (mysql_error());
																	
											}
											else {
											
												@copy($FileSource, './thumbnails/'.$RecordNumberCreated.'_'.$file);
												
												if ($Settings['FilesCHMOD'] != '') {
													@chmod('./thumbnails/'.$RecordNumberCreated.'_'.$file, $Settings['FilesCHMOD']);
												}
												
											
												$query = "update `".$Settings['DBPrefix']."core-Files` set ImageWidth='".$ImageWidth."', ImageHeight='".$ImageHeight."', ThumbnailExists=1 where RecordNumber='".$RecordNumberCreated."' limit 1";
												$result = mysql_query($query) or die (mysql_error());
											
											}
									
								
										}
																		
										   									
									}
									else {
									
										$row = mysql_fetch_array($result);
										
										$FNPieces = explode('.',$row['Filename']);
										$FileExtension = strtolower($FNPieces[count($FNPieces)-1]);
										
										$ImageWidth = 0;
										$ImageHeight = 0;
										$FileType = 0;
										if ($row['ThumbnailExists'] == 0 && ($FileExtension == 'gif' || $FileExtension == 'png' || $FileExtension == 'jpg' || $FileExtension == 'jpeg')) {
											
											$FileSource = '.'.$row['Location'].$row['Filename'];
										
											$ImageInfo = @getimagesize($dir.$file);
										
											$ImageWidth = $ImageInfo[0];
											$ImageHeight = $ImageInfo[1];
											$FileType = $ImageInfo[2];
											
											
											if ($ImageWidth > 100 || $ImageHeight > 75) {
																					
												$NewWidth = 100;
												$NewHeight = 75;
								
												$WidthRatio = $ImageWidth / $NewWidth;
												$HeightRatio = $ImageHeight / $NewHeight;
							
												if ($WidthRatio >= $HeightRatio) {
								
													$NewWidthCalc = number_format($ImageWidth / $WidthRatio, 0);
													$NewHeightCalc = number_format($ImageHeight / $WidthRatio, 0);
										
												}	
												else {
										
													$NewWidthCalc = number_format($ImageWidth / $HeightRatio, 0);
													$NewHeightCalc = number_format($ImageHeight / $HeightRatio, 0);
										
												}
							
								
												if ($FileType == 1) {
													$SourceData = @imagecreatefromgif($FileSource);
												}
												else if ($FileType == 2) {
													$SourceData = @imagecreatefromjpeg($FileSource);
												}
												else if ($FileType == 3) {
													$SourceData = @imagecreatefrompng($FileSource);
												} 
										
												$DestinationImage = @imagecreatetruecolor($NewWidthCalc, $NewHeightCalc);
												@imagecopyresampled($DestinationImage, $SourceData, 0, 0, 0, 0, $NewWidthCalc, $NewHeightCalc, $ImageWidth, $ImageHeight);
							
							
												if ($FileType == 1) {
													@imagegif($DestinationImage, './thumbnails/'.$row['RecordNumber'].'_'.$row['Filename']);
												}
												else if ($FileType == 2) {
													@imagejpeg($DestinationImage, './thumbnails/'.$row['RecordNumber'].'_'.$row['Filename']);
												}
												else if ($FileType == 3) {
													@imagepng($DestinationImage, './thumbnails/'.$row['RecordNumber'].'_'.$row['Filename']);
												}
												
												
												if ($Settings['FilesCHMOD'] != '') {
													@chmod('./thumbnails/'.$row['RecordNumber'].'_'.$row['Filename'], $Settings['FilesCHMOD']);
												}
									
											
												if ($SourceData) {
													imagedestroy($SourceData);
												}
												if ($DestinationImage) {
													imagedestroy($DestinationImage);
												}
										
										
												$query = "update `".$Settings['DBPrefix']."core-Files` set ImageWidth='".$ImageWidth."', ImageHeight='".$ImageHeight."', ThumbnailExists=1 where RecordNumber='".$row['RecordNumber']."' limit 1";
												$result = mysql_query($query) or die (mysql_error());
																	
											}
											else {
											
												@copy($FileSource, './thumbnails/'.$row['RecordNumber'].'_'.$row['Filename']);
												
												if ($Settings['FilesCHMOD'] != '') {
													@chmod('./thumbnails/'.$row['RecordNumber'].'_'.$row['Filename'], $Settings['FilesCHMOD']);
												}
												
											
												$query = "update `".$Settings['DBPrefix']."core-Files` set ImageWidth='".$ImageWidth."', ImageHeight='".$ImageHeight."', ThumbnailExists=1 where RecordNumber='".$row['RecordNumber']."' limit 1";
												$result = mysql_query($query) or die (mysql_error());
											
											}
											
										}										
									
									}								
									
								}
									
								
							}
						}
						closedir($dh[$dir]);
					}
				}
			
			}
					
			// start the spider process
			ReadDirectory1('./');
			
			
			
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101',ViewFilesLevel='101' where Location='/' and Folder='thumbnails' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101',ViewFilesLevel='101' where Location='/' and Folder='pg_images' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101',ViewFilesLevel='101' where Location='/' and Folder='languages' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101',ViewFilesLevel='101' where Location='/' and Folder='fckeditor' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101' where Location='/' and Folder='backups' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ViewFilesLevel='100' where Location='/' and Folder='cgi-bin' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ViewFilesLevel='100',ModifyLevel='101' where Location='/' and Folder='templates' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101',ViewFilesLevel='101' where Location='/images/' and Folder='admin' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101' where Location='/images/' and Folder='smilies' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101' where Location='/images/' and Folder='store' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101' where Location='/images/' and Folder='articles' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101' where Location='/images/' and Folder='avatars' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101',ViewFilesLevel='101' where Location='/images/' and Folder='user_avatars' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101' where Location='/images/' and Folder='uploaded' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101' where Location='/images/' and Folder='menu' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		
		
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Files` set SystemFile='1',ViewLevel='101',ModifyLevel='101' where Location='/' and Filename like 'inc-%.php'";
		$result3 = mysql_query($query3) or die (mysql_error());				
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Files` set SystemFile='1',ViewLevel='101',ModifyLevel='101' where Location='/' and Filename='flex_cs.js' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Files` set SystemFile='1',ViewLevel='101',ModifyLevel='101' where Location='/' and Filename='index.php' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Files` set SystemFile='1',ViewLevel='101',ModifyLevel='101' where Location='/' and Filename='settings.php' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Files` set SystemFile='1',ViewLevel='100',ModifyLevel='100' where Location='/' and Filename='0.htaccess' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		
		
		
		// frontpage junk
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101',ViewFilesLevel='101' where Location='/' and Folder='_private' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());		
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Folders` set SystemFolder='1',ModifyLevel='101',ViewFilesLevel='101' where Location='/' and Folder like '_vti%'";
		$result3 = mysql_query($query3) or die (mysql_error());
		
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Files` set SystemFile='1',ViewLevel='101',ModifyLevel='101' where Location='/' and Filename='postinfo.html' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		$query3 = "UPDATE `".$Settings['DBPrefix']."core-Files` set SystemFile='1',ViewLevel='101',ModifyLevel='101' where Location='/' and Filename='_vti_inf.html' limit 1";
		$result3 = mysql_query($query3) or die (mysql_error());
		
		
		
		
		
			
			
			
			
			
			
			// and remove anything that no longer exists
			$query = "select * from `".$Settings['DBPrefix']."core-Folders`";
	   		$result = mysql_query($query) or die (mysql_error());
			while ($row = mysql_fetch_array($result)) {
				if (!is_dir('.'.$row['Location'].$row['Folder'])) {
					$query2 = "delete from `".$Settings['DBPrefix']."core-Folders` where RecordNumber='".$row['RecordNumber']."' limit 1";
		   			$result2 = mysql_query($query2) or die (mysql_error());		   			
		   		}
			}
			
			$query = "select * from `".$Settings['DBPrefix']."core-Files`";
	   		$result = mysql_query($query) or die (mysql_error());
			while ($row = mysql_fetch_array($result)) {
				if (!is_file('.'.$row['Location'].$row['Filename'])) {
					$query2 = "delete from `".$Settings['DBPrefix']."core-Files` where RecordNumber='".$row['RecordNumber']."' limit 1";
		   			$result2 = mysql_query($query2) or die (mysql_error());
		   		}
			}
			
			
						
			
			header('Location: '.$MainURL.'/admin/filemanager/'.$Arguments4.'/'.$Arguments5);
			
			
			
			} // end if thumbs folder writable
			else {
			
				$PageContents = '<b>"thumbnails" folder could not be created or written to.</b>  Ensure that your base folder can be written to, or create a "thumbnails" folder with write permissions within it.  If a one already exists, ensure it has sufficient permissions to be written to.';			
			
			}
			

		} // end if $Arguments3 == 'scan'

	} // end if logged in	
	else {
	
		RedirectToLogin();
	
	}
	
	
	
								
		print '<html><head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<title>File Manager</title>
		<meta name="Description" content="">
		<meta name="Keywords" content="">
		<meta name="Author" content="FlexCMS">
		<meta name="Generator" content="FlexCMS">
		<META NAME="Robots" CONTENT="INDEX,FOLLOW">
		<META NAME="Rating" CONTENT="General">
		<meta name="MSSmartTagsPreventParsing" content="TRUE"></head>
		<body bgcolor="#ffffff" text="#000000" link="#000000" vlink="#000000" alink="#000000" leftmargin="0" marginwidth="0" topmargin="0" marginheight="0" rightmargin="0" style="margin:0"><br><br><br><div align="center"><table width="400" cellpadding="0" cellspacing="0" border="0"><tr><td align="center"><font face="'.$FontFace.'" size="'.$FontSize.'">'.$PageContents.'</td></tr></table></div></body></html>';
				
		exit();
				
	
	

	// ========================================================================================


?>