using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using CMS.CMSHelper;
using CMS.ExtendedControls;
using CMS.GlobalHelper;
using CMS.IO;
using CMS.MediaLibrary;
using CMS.SettingsProvider;
using CMS.SiteProvider;
using CMS.UIControls;
public partial class CMSModules_MediaLibrary_Controls_Dialogs_LinkMediaSelector : LinkMediaSelector
{
#region "Private variables"
private const string PERCENT_ESC_CHAR = "|";
// Media library variables
private string mFolderPath = string.Empty;
private string mMediaLibraryRootFolder = null;
private string mCurrentAction = null;
private MediaLibraryInfo mLibraryInfo = null;
private SiteInfo mLibrarySiteInfo = null;
private Hashtable mFileList = null;
private string mSortDirection = "ASC";
private string mSortColumns = "FileName";
private bool wasLoaded = false;
private bool mLibraryChanged = false;
#endregion
#region "Public properties"
///
/// Messages placeholder
///
public override MessagesPlaceHolder MessagesPlaceHolder
{
get
{
return plcMess;
}
}
///
/// Indicates if control is used on live site.
///
public override bool IsLiveSite
{
get
{
return base.IsLiveSite;
}
set
{
plcMess.IsLiveSite = value;
base.IsLiveSite = value;
}
}
#endregion
#region "Private properties"
///
/// Returns current properties (according to OutputFormat).
///
protected override ItemProperties Properties
{
get
{
switch (Config.OutputFormat)
{
case OutputFormatEnum.HTMLMedia:
return htmlMediaProp;
case OutputFormatEnum.HTMLLink:
return htmlLinkProp;
case OutputFormatEnum.BBMedia:
return bbMediaProp;
case OutputFormatEnum.BBLink:
return bbLinkProp;
case OutputFormatEnum.URL:
if (Config.OutputFormat == OutputFormatEnum.NodeGUID)
{
return nodeGuidProp;
}
return urlProp;
default:
return null;
}
}
}
///
/// Update panel where properties control resides.
///
protected override UpdatePanel PropertiesUpdatePanel
{
get
{
return pnlUpdateProperties;
}
}
///
/// Gets or sets last searched value.
///
private string LastSearchedValue
{
get
{
return hdnLastSearchedValue.Value;
}
set
{
hdnLastSearchedValue.Value = value;
}
}
///
/// Gets or sets last selected folder path.
///
private string LastFolderPath
{
get
{
return hdnLastSelectedPath.Value;
}
set
{
hdnLastSelectedPath.Value = value;
}
}
///
/// Gets or sets selected item to colorize.
///
private Guid ItemToColorize
{
get
{
return ValidationHelper.GetGuid(ViewState["ItemToColorize"], Guid.Empty);
}
set
{
ViewState["ItemToColorize"] = value;
}
}
///
/// Indicates if full listing mode is enabled. This mode enables navigation to child and parent folders/documents from current view.
///
private bool IsFullListingMode
{
get
{
return mediaView.IsFullListingMode;
}
set
{
mediaView.IsFullListingMode = value;
}
}
///
/// Current action name.
///
private string CurrentAction
{
get
{
return mCurrentAction ?? (mCurrentAction = hdnAction.Value.Trim().ToLowerCSafe());
}
}
///
/// Indicates whether the library has changed recently.
///
private bool LibraryChanged
{
get
{
return mLibraryChanged;
}
set
{
mLibraryChanged = value;
}
}
///
/// Gets or sets direction in which data should be ordered.
///
private string SortDirection
{
get
{
return mSortDirection;
}
set
{
mSortDirection = value;
}
}
///
/// Gets or sets sort columns data are ordered by.
///
public string SortColumns
{
get
{
return mSortColumns;
}
set
{
mSortColumns = value;
}
}
///
/// Gets or sets list of files from the currently selected folder.
///
private Hashtable FileList
{
get
{
return mFileList;
}
set
{
mFileList = value;
}
}
#endregion
#region "Library properties"
///
/// Gets or sets a folder path of the media library.
///
private string FolderPath
{
get
{
return mFolderPath;
}
set
{
mFolderPath = (value ?? string.Empty);
LastFolderPath = mFolderPath;
}
}
///
/// Gets or sets an ID of the media library.
///
private int LibraryID
{
get
{
return librarySelector.LibraryID;
}
set
{
librarySelector.LibraryID = value;
folderTree.MediaLibraryID = value;
menuElem.LibraryID = value;
menuElem.UpdateActionsMenu();
mLibraryInfo = null;
mediaView.LibraryInfo = null;
mLibrarySiteInfo = null;
mMediaLibraryRootFolder = null;
}
}
///
/// Current media library information.
///
private MediaLibraryInfo LibraryInfo
{
get
{
if ((mLibraryInfo == null) && (LibraryID > 0))
{
mLibraryInfo = MediaLibraryInfoProvider.GetMediaLibraryInfo(LibraryID);
}
return mLibraryInfo;
}
set
{
mLibraryInfo = value;
}
}
///
/// Gets info on site library is related to.
///
private SiteInfo LibrarySiteInfo
{
get
{
if ((mLibrarySiteInfo == null) && (LibraryInfo != null))
{
mLibrarySiteInfo = SiteInfoProvider.GetSiteInfo(LibraryInfo.LibrarySiteID);
}
return mLibrarySiteInfo;
}
}
///
/// Returns media library root folder path.
///
private string MediaLibraryRootFolder
{
get
{
if ((mMediaLibraryRootFolder == null) && (LibrarySiteInfo != null))
{
mMediaLibraryRootFolder = MediaLibraryHelper.GetMediaRootFolderPath(LibrarySiteInfo.SiteName);
}
return mMediaLibraryRootFolder;
}
}
///
/// Gets current starting path if set.
///
private string StartingPath
{
get
{
if (Config.LibStartingPath != string.Empty)
{
string startingPath = Config.LibStartingPath.Replace('\\', '/');
if (startingPath != "/")
{
startingPath = startingPath.Trim('/') + "/";
return MediaLibraryHelper.EnsurePath(startingPath);
}
}
return string.Empty;
}
}
#endregion
#region "Page events"
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
mediaView.OutputFormat = Config.OutputFormat;
mediaView.Config = Config;
}
protected override void OnPreRender(EventArgs e)
{
// High-light item being edited
if (ItemToColorize != Guid.Empty)
{
ColorizeRow(ItemToColorize.ToString());
}
// If full-listing mode is on
ProcessIsFullListingMode();
if (!wasLoaded && mediaView.Visible)
{
LoadData();
}
librarySelector.LoadLibraryData();
// Make sure properties are hidden for non-existing library
if (LibraryInfo == null)
{
ShowError(GetString("dialogs.libraries.nolibrary"));
}
base.OnPreRender(e);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!StopProcessing)
{
SetupControls();
SetupProperties();
InitializeDesignScripts();
if (!URLHelper.IsPostback())
{
InitializeControls();
LoadSelector();
// Is item selected in the editor MediaFile? Load it
if ((MediaSource != null) && (MediaSource.MediaFileID > 0))
{
LoadSelectedItem();
}
else
{
LoadUserConfiguration();
}
// Clear properties if link dialog is opened and no link is edited
bool isLink = (Config.OutputFormat == OutputFormatEnum.BBLink || Config.OutputFormat == OutputFormatEnum.HTMLLink);
if (isLink && !IsItemLoaded)
{
Properties.ClearProperties(true);
}
}
else
{
FolderPath = LastFolderPath;
mediaView.LibraryID = LibraryID;
mediaView.ViewMode = menuElem.SelectedViewMode;
}
}
else
{
Visible = false;
}
}
#endregion
#region "Public methods"
///
/// Displays error message.
///
/// Text of the error message
public override void ShowError(string text)
{
base.ShowError(text);
HideMediaElements();
}
///
/// Initializes its properties according to the URL parameters.
///
public void InitFromQueryString()
{
switch (Config.OutputFormat)
{
case OutputFormatEnum.HTMLMedia:
SelectableContent = SelectableContentEnum.OnlyMedia;
break;
case OutputFormatEnum.HTMLLink:
SelectableContent = SelectableContentEnum.AllContent;
break;
case OutputFormatEnum.BBMedia:
SelectableContent = SelectableContentEnum.OnlyImages;
break;
case OutputFormatEnum.BBLink:
SelectableContent = SelectableContentEnum.AllContent;
break;
case OutputFormatEnum.URL:
case OutputFormatEnum.NodeGUID:
string content = QueryHelper.GetString("content", string.Empty);
SelectableContent = CMSDialogHelper.GetSelectableContent(content);
break;
}
}
///
/// Returns selected item parameters as name-value collection.
///
public void GetSelectedItem()
{
// Clear unused information from the session
ClearSelectedItemInfo();
if (Properties.Validate())
{
// Store tab information in the user's dialogs configuration
StoreDialogsConfiguration();
Hashtable properties = Properties.GetItemProperties();
// Get JavaScript for inserting the item
string insertItemScript = GetInsertItem(properties);
if (!string.IsNullOrEmpty(insertItemScript))
{
ScriptHelper.RegisterStartupScript(Page, typeof(Page), "insertItemScript", ScriptHelper.GetScript(insertItemScript));
}
}
else
{
pnlUpdateProperties.Update();
}
}
#endregion
#region "Private methods"
///
/// Loads selector element.
///
private void LoadSelector()
{
librarySelector.LoadData();
}
///
/// Initializes properties controls.
///
private void SetupProperties()
{
htmlLinkProp.Visible = false;
htmlMediaProp.Visible = false;
bbLinkProp.Visible = false;
bbMediaProp.Visible = false;
urlProp.Visible = false;
if (Properties != null)
{
Properties.Visible = true;
}
htmlLinkProp.StopProcessing = !htmlLinkProp.Visible;
htmlMediaProp.StopProcessing = !htmlMediaProp.Visible;
bbLinkProp.StopProcessing = !bbLinkProp.Visible;
bbMediaProp.StopProcessing = !bbMediaProp.Visible;
urlProp.StopProcessing = !urlProp.Visible;
Properties.Config = Config;
}
///
/// Initializes additional controls.
///
private void SetupControls()
{
SourceType = MediaSourceEnum.MediaLibraries;
htmlMediaProp.SourceType = MediaSourceEnum.MediaLibraries;
bbMediaProp.SourceType = MediaSourceEnum.MediaLibraries;
urlProp.SourceType = MediaSourceEnum.MediaLibraries;
// Set editor client ID for the properties
Properties.EditorClientID = Config.EditorClientID;
Properties.IsLiveSite = IsLiveSite;
Properties.SourceType = MediaSourceEnum.MediaLibraries;
// Setup library selector
InitializeLibrarySelector();
// Set menu properties
InitializeMenuElem();
// Set media view properties
InitializeViewElem();
// Initialize helper scripts
InitializeControlScripts();
}
///
/// Performs actions necessary to select particular item from a list.
///
private void SelectMediaItem(string argument)
{
if (!string.IsNullOrEmpty(argument))
{
Hashtable argTable = CMSModules_MediaLibrary_Controls_Dialogs_MediaView.GetArgumentsTable(argument);
if (argTable.Count >= 2)
{
Guid fileGuid = ValidationHelper.GetGuid(argTable["fileguid"], Guid.Empty);
// Do not update properties when selecting recently edited image item
bool avoidPropUpdate = (IsEditImage && (ItemToColorize == fileGuid));
ItemToColorize = fileGuid;
// Get information from argument
string fileName = argTable["filename"].ToString();
string fileExt = argTable["fileextension"].ToString();
int imageWidth = ValidationHelper.GetInteger(argTable["fileimagewidth"], 0);
int imageHeight = ValidationHelper.GetInteger(argTable["fileimageheight"], 0);
long fileSize = ValidationHelper.GetLong(argTable["filesize"], 0);
string fileUrl = argTable["url"].ToString();
string fileNameWithouExtension = fileName;
fileName = UsePermanentUrls ? AttachmentHelper.GetFullFileName(fileName, fileExt) : fileName;
string filePermanentUrl = (LibrarySiteInfo.SiteID != CMSContext.CurrentSiteID) ? MediaFileInfoProvider.GetMediaFileAbsoluteUrl(LibrarySiteInfo.SiteName, fileGuid, fileName) : MediaFileInfoProvider.GetMediaFileUrl(fileGuid, fileName);
if (!fileUrl.StartsWithCSafe("~"))
{
filePermanentUrl = URLHelper.ResolveUrl(filePermanentUrl);
}
Properties.SiteDomainName = LibrarySiteInfo.DomainName;
if (!avoidPropUpdate)
{
SelectMediaItem(fileNameWithouExtension, fileExt, imageWidth, imageHeight, fileSize, fileUrl, filePermanentUrl);
}
}
}
}
#endregion
#region "Helper methods"
///
/// Returns file path without library root folder.
///
/// Original file path
private static string GetFilePath(string argument)
{
if (!string.IsNullOrEmpty(argument))
{
argument = argument.Replace('\\', '/');
int rootFolderNameIndex = argument.IndexOfCSafe('/');
argument = (rootFolderNameIndex > -1) ? argument.Substring(rootFolderNameIndex) : string.Empty;
return argument.TrimStart('/');
}
return string.Empty;
}
///
/// Returns folder path based on the given file path.
///
/// File path
private static string GetFolderPath(string filePath)
{
if (!string.IsNullOrEmpty(filePath))
{
int lastSlashIndex = filePath.LastIndexOfCSafe('/');
return (lastSlashIndex > -1) ? filePath.Substring(0, lastSlashIndex) : string.Empty;
}
return string.Empty;
}
///
/// Returns complete folder path including library folder.
///
/// Folder path.
private string GetCompletePath(string path)
{
// Include starting path if used
if (StartingPath != string.Empty)
{
path = StartingPath + path;
}
path = (LibraryInfo != null) ? String.Format("{0}/{1}", LibraryInfo.LibraryFolder, path) : path;
return path.TrimEnd('/');
}
///
/// Ensures folder path coming from JavaScript to keep normalized form.
///
/// Path to ensure
private string EnsureFolderPath(string path)
{
char separator = folderTree.PathSeparator;
return (!string.IsNullOrEmpty(path)) ? path.Replace('/', separator).Replace("\\\\", separator.ToString()).TrimStart(separator) : string.Empty;
}
///
/// Ensures that the text can be used in the WHERE condition.
///
/// Text to ensure
private static string NormalizeForSql(string text)
{
if (!String.IsNullOrEmpty(text) && text.Contains("%"))
{
text = text.Replace("%", PERCENT_ESC_CHAR + "%");
}
return text;
}
///
/// Ensures that menu element updates its information.
///
private void EnsureMenuInfo()
{
string updatedFolderDialog = URLHelper.UpdateParameterInUrl(menuElem.NewFolderDialogUrl, "libraryid", menuElem.LibraryID.ToString());
updatedFolderDialog = URLHelper.UpdateParameterInUrl(updatedFolderDialog, "path", Server.UrlEncode(menuElem.LibraryFolderPath).Replace("'", "\\'"));
string script = String.Format("$j(\"td[id$='menuLeft-000']\").attr('onclick', '').click(function () {{ modalDialog('{0}', 'NewFolder', 500, 350); return false; }});", URLHelper.ResolveUrl(updatedFolderDialog));
ScriptHelper.RegisterStartupScript(Page, typeof(Page), "DialogsEnsureMenuInfo", ScriptHelper.GetScript(script));
}
///
/// Clears hidden control elements for the future use.
///
private void ClearActionElems()
{
hdnAction.Value = string.Empty;
hdnArgument.Value = string.Empty;
}
///
/// Hides or displays media elements as required.
///
/// Indicates whether the elements should display content
private void HandleMediaElements(bool isDisplayed)
{
// Folder tree
folderTree.StopProcessing = !isDisplayed;
// Reload tree and hide it if not displayed (Ajax toolkit bug)
if (!isDisplayed)
{
folderTree.ReloadData();
pnlTree.CssClass = "Hidden";
}
else
{
pnlTree.CssClass = string.Empty;
}
pnlUpdateTree.Update();
// Media view
mediaView.StopProcessing = !isDisplayed;
mediaView.Visible = isDisplayed;
pnlUpdateView.Update();
// Properties
Properties.StopProcessing = !isDisplayed;
Properties.Visible = isDisplayed;
pnlUpdateProperties.Update();
lblEmpty.Text = CMSDialogHelper.GetSelectItemMessage(Config, MediaSourceEnum.MediaLibraries);
pnlEmpty.Visible = !isDisplayed;
}
///
/// Hides media elements.
///
private void HideMediaElements()
{
HandleMediaElements(false);
}
///
/// Displays media elements.
///
private void DisplayMediaElements()
{
HandleMediaElements(true);
}
///
/// Displays properties in full size.
///
private void DisplayFull()
{
// Change CSS class so properties are displayed in full size
if (divDialogView.Attributes["class"] == "DialogViewContent")
{
divDialogView.Attributes["class"] = "DialogElementHidden";
divDialogResizer.Attributes["class"] = "DialogElementHidden";
divDialogProperties.Attributes["class"] = "DialogPropertiesFullSize";
pnlUpdateContent.Update();
}
}
///
/// Displays properties in default size.
///
private void DisplayNormal()
{
// Change CSS class so properties are displayed in normal size
if (divDialogView.Attributes["class"] == "DialogElementHidden")
{
divDialogView.Attributes["class"] = "DialogViewContent";
divDialogResizer.Attributes["class"] = "DialogResizerVLine";
divDialogProperties.Attributes["class"] = "DialogProperties";
pnlUpdateContent.Update();
}
}
///
/// Ensures that filter is no more applied.
///
private void ResetSearchFilter()
{
mediaView.ResetSearch();
LastSearchedValue = string.Empty;
}
///
/// Ensures first page is displayed in the control displaying the content.
///
private void ResetPageIndex()
{
mediaView.ResetPageIndex();
}
///
/// Returns full file path including library folder.
///
/// File path to get full path for
private string GetFullFilePath(string path)
{
if (path != null)
{
return (String.Format("{0}/{1}", LibraryInfo.LibraryFolder, path)).TrimEnd('/');
}
return string.Empty;
}
///
/// Gets folder path of the parent of the folder specified by its path.
///
/// Path of the folder.
private string GetParentFullPath(string path)
{
return GetParentFullPath(path, true);
}
///
/// Gets folder path of the parent of the folder specified by its path.
///
/// Path of the folder.
private string GetParentFullPath(string path, bool includeRoot)
{
if (!string.IsNullOrEmpty(path))
{
path = MediaLibraryHelper.EnsurePath(path);
int lastSlash = path.LastIndexOfCSafe('/');
path = lastSlash > -1 ? path.Substring(0, lastSlash).Trim('/') : string.Empty;
if (includeRoot && (LibraryInfo != null))
{
path = String.Format("{0}/{1}", LibraryInfo.LibraryFolder, path);
}
}
return path.TrimEnd('/');
}
///
/// Ensures sorting of data set containing both files and folders.
///
/// DateSet to sort
/// Direction in which data should be sorted
/// Expression used to sort the data
private static void SortMixedDataSet(DataSet ds, string direction, string expression)
{
if ((ds != null) && !string.IsNullOrEmpty(direction) && !string.IsNullOrEmpty(expression) && !DataHelper.IsEmpty(ds))
{
string orderBy = String.Format("{0} {1}", expression.Trim(), direction);
DataHelper.SortDataTable(ds.Tables[0], orderBy);
DataTable sortedResult = ds.Tables[0].DefaultView.ToTable();
ds.Tables.RemoveAt(0);
ds.Tables.Add(sortedResult);
}
}
///
/// Imports folder details into given set of data.
///
/// DataSet folders information should be imported to
private void IncludeFolders(DataSet ds, string searchText)
{
// Data object specified
if ((ds != null) && (ds.Tables[0] != null))
{
// Get path to the currently selected folder
string dirPath = DirectoryHelper.CombinePath(MediaLibraryRootFolder, LibraryInfo.LibraryFolder) + ((StartingPath != string.Empty) ? "\\" + StartingPath : string.Empty) + ((LastFolderPath != string.Empty) ? "\\" + LastFolderPath : string.Empty);
dirPath = dirPath.TrimEnd('/').Replace('/', '\\');
if (Directory.Exists(dirPath))
{
// Get directories in the current path
string[] dirs = Directory.GetDirectories(dirPath);
if (dirs != null)
{
int lastFolderIndex = 0;
string hiddenFolder = MediaLibraryHelper.GetMediaFileHiddenFolder(LibrarySiteInfo.SiteName);
foreach (string folderPath in dirs)
{
if (!folderPath.EndsWithCSafe(hiddenFolder))
{
// Get directory info object to access additional information
DirectoryInfo dirInfo = DirectoryInfo.New(folderPath);
if (dirInfo != null)
{
DataRow dirRow = ds.Tables[0].NewRow();
bool includeFolder = true;
string fileName = Path.GetFileName(dirInfo.FullName);
if (!string.IsNullOrEmpty(searchText) && !fileName.ToLowerCSafe().Contains(searchText.ToLowerCSafe()))
{
includeFolder = false;
}
// Insert new row
if (includeFolder)
{
// Fill new row with data
dirRow["FileGuid"] = Guid.Empty;
dirRow["FileName"] = Path.GetFileName(dirInfo.FullName);
dirRow["FilePath"] = dirPath;
dirRow["FileExtension"] = "
";
dirRow["FileImageWidth"] = 0;
dirRow["FileImageHeight"] = 0;
dirRow["FileTitle"] = string.Empty;
dirRow["FileSize"] = 0;
dirRow["FileModifiedWhen"] = dirInfo.LastWriteTime;
dirRow["FileSiteID"] = LibrarySiteInfo.SiteID;
dirRow["FileID"] = 0;
ds.Tables[0].Rows.InsertAt(dirRow, lastFolderIndex);
lastFolderIndex++;
}
}
}
}
}
}
}
}
///
/// Gets file path based on its file name, recently selected folder path and library folder.
///
/// Name of the file (including extension)
private string CreateFilePath(string fileName)
{
return String.IsNullOrEmpty(LastFolderPath) ? fileName : DirectoryHelper.CombinePath(LastFolderPath, fileName);
}
///
/// Returns true if file information is not in database.
///
/// File name
private DataRow FileIsNotInDatabase(string fileName)
{
if (FileList == null)
{
string where = String.Format("FilePath LIKE N'{0}%' AND FilePath NOT LIKE N'{0}_%/%' AND FileLibraryID = {1}",
MediaLibraryHelper.EnsurePath(SqlHelperClass.GetSafeQueryString(LastFolderPath, false).Replace("[", "[[]").Replace("%", "[%]")).Trim('/'),
LibraryID);
if (!string.IsNullOrEmpty(LastSearchedValue))
{
where = SqlHelperClass.AddWhereCondition(where, String.Format("((FileName LIKE N'%{0}%' {{escape '{1}'}}) OR (FileExtension LIKE N'%{0}%' {{escape '{1}'}}))",
SqlHelperClass.GetSafeQueryString(LastSearchedValue, false),
PERCENT_ESC_CHAR));
}
const string columns = "FileID, FilePath, FileGUID, FileName, FileExtension, FileImageWidth, FileImageHeight, FileTitle, FileSize, FileLibraryID, FileSiteID, FileDescription";
// Get all files from current folder
DataSet ds = MediaFileInfoProvider.GetMediaFiles(where, "FileName", 0, columns);
if (ds != null)
{
FileList = new Hashtable();
foreach (DataRow row in ds.Tables[0].Rows)
{
FileList[row["FilePath"].ToString()] = row;
}
}
}
if (FileList != null)
{
if (String.IsNullOrEmpty(LastFolderPath))
{
if (FileList.Contains(fileName))
{
return (FileList[fileName] as DataRow);
}
}
else
{
string filePath = String.Format("{0}/{1}", MediaLibraryHelper.EnsurePath(LastFolderPath).Trim('/'), fileName);
if (FileList.Contains(filePath))
{
return (FileList[filePath] as DataRow);
}
}
}
return null;
}
#endregion
#region "Dialog configuration"
///
/// Loads selected item parameters into the selector.
///
public void LoadSelectedItem()
{
if (MediaSource != null)
{
IsItemLoaded = true;
// Try to pre-select media library
if ((MediaSource.MediaFileLibraryID > 0) && (LibraryInfo != null))
{
librarySelector.SelectedLibraryID = MediaSource.MediaFileLibraryID;
if (MediaSource.MediaFileLibraryGroupID > 0)
{
librarySelector.SelectedGroupID = MediaSource.MediaFileLibraryGroupID;
librarySelector.GroupLibraryName = LibraryInfo.LibraryName;
}
else
{
librarySelector.GlobalLibaryName = LibraryInfo.LibraryName;
}
}
// Try to pre-select path
if (!string.IsNullOrEmpty(MediaSource.MediaFilePath))
{
// Without library root
FolderPath = GetFolderPath(MediaSource.MediaFilePath);
if (StartingPath == string.Empty)
{
FolderPath = GetCompletePath(FolderPath);
}
else
{
folderTree.PathToSelect = FolderPath;
folderTree.StopProcessing = true;
// With library root
FolderPath = GetFullFilePath(FolderPath);
}
RequestStockHelper.Add("FolderPath", FolderPath);
}
// Reload HTML properties
if (Config.OutputFormat == OutputFormatEnum.HTMLMedia)
{
// Force media properties control to load selected item
htmlMediaProp.ViewMode = MediaSource.MediaType;
}
}
// Ensure inserted media file URL
string url = string.Empty;
if (Config.OutputFormat == OutputFormatEnum.URL)
{
url = ValidationHelper.GetString(Parameters[DialogParameters.URL_URL], string.Empty);
}
else if (ImageHelper.IsImage(MediaSource.Extension))
{
url = ValidationHelper.GetString(Parameters[DialogParameters.IMG_URL], string.Empty);
}
else
{
url = ValidationHelper.GetString(Parameters[DialogParameters.AV_URL], string.Empty);
}
// Get permanent URL for media file
if (url != string.Empty)
{
bool isDifferentSite = (MediaSource.SiteID != CMSContext.CurrentSiteID);
string siteName = LibrarySiteInfo.SiteName;
string fileName = UsePermanentUrls ? AttachmentHelper.GetFullFileName(MediaSource.FileName, MediaSource.Extension) : MediaSource.FileName;
string filePermanentUrl = isDifferentSite ? MediaFileInfoProvider.GetMediaFileAbsoluteUrl(siteName, MediaSource.MediaFileGuid, fileName) : MediaFileInfoProvider.GetMediaFileUrl(MediaSource.MediaFileGuid, fileName);
string fileDirectUrl = isDifferentSite ? MediaFileInfoProvider.GetMediaFileAbsoluteUrl(siteName, LibraryInfo.LibraryFolder, MediaSource.MediaFilePath) : MediaFileInfoProvider.GetMediaFileUrl(siteName, LibraryInfo.LibraryFolder, MediaSource.MediaFilePath);
Parameters[DialogParameters.URL_PERMANENT] = URLHelper.ResolveUrl(filePermanentUrl);
Parameters[DialogParameters.URL_DIRECT] = URLHelper.ResolveUrl(fileDirectUrl);
}
// Load properties
Properties.LoadItemProperties(Parameters);
pnlUpdateProperties.Update();
// Remember item being edited for later high-lighting
ItemToColorize = MediaSource.MediaFileGuid;
HandleMediaElements(true);
ClearSelectedItemInfo();
// Display properties in normal size
DisplayNormal();
}
///
/// Stores current tab's configuration for the user.
///
private void StoreDialogsConfiguration()
{
string path = GetCompletePath(LastFolderPath);
// Actualize configuration
UserInfo ui = CMSContext.CurrentUser;
ui.UserSettings.UserDialogsConfiguration["media.sitename"] = LibrarySiteInfo.SiteName;
ui.UserSettings.UserDialogsConfiguration["media.libraryname"] = LibraryInfo.LibraryName;
ui.UserSettings.UserDialogsConfiguration["media.path"] = path;
ui.UserSettings.UserDialogsConfiguration["media.viewmode"] = CMSDialogHelper.GetDialogViewMode(menuElem.SelectedViewMode);
ui.UserSettings.UserDialogsConfiguration["selectedtab"] = CMSDialogHelper.GetMediaSource(MediaSourceEnum.MediaLibraries);
// Update user info
UserInfoProvider.SetUserInfo(ui);
}
///
/// Loads dialogs according user's configuration.
///
private void LoadUserConfiguration()
{
if (CMSContext.CurrentUser.UserSettings.UserDialogsConfiguration != null)
{
XmlData dialogConfig = CMSContext.CurrentUser.UserSettings.UserDialogsConfiguration;
string libraryName = (dialogConfig.ContainsColumn("media.libraryname") ? (string)dialogConfig["media.libraryname"] : string.Empty);
string path = (dialogConfig.ContainsColumn("media.path") ? (string)dialogConfig["media.path"] : string.Empty);
string siteName = (dialogConfig.ContainsColumn("media.sitename") ? (string)dialogConfig["media.sitename"] : string.Empty);
// Set user dialogs configuration only if all sites available in selector or selected site is equal to users
if ((librarySelector.Sites == AvailableSitesEnum.All) || (librarySelector.SelectedSiteName == siteName))
{
if ((libraryName != string.Empty) && (siteName != string.Empty))
{
MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(libraryName, siteName);
if (mli != null)
{
librarySelector.SelectedSiteName = siteName;
librarySelector.SelectedLibraryID = mli.LibraryID;
librarySelector.SelectedGroupID = mli.LibraryGroupID;
}
}
if (path != string.Empty)
{
FolderPath = path;
if (StartingPath != string.Empty)
{
path = GetFilePath(path);
}
folderTree.PathToSelect = path;
RequestStockHelper.Add("FolderPath", FolderPath);
}
}
}
}
///
/// Ensures that full-listing mode is displayed when necessary.
///
private void ProcessIsFullListingMode()
{
bool rootHasMore = (LastFolderPath == string.Empty) && ((CurrentAction == "select") || ((!wasLoaded || LibraryChanged) && (CurrentAction == string.Empty))) && folderTree.RootHasMore;
if (IsFullListingMode || rootHasMore)
{
IsFullListingMode = (rootHasMore || IsFullListingMode);
string folderPath = LastFolderPath;
if (StartingPath != string.Empty)
{
folderPath = StartingPath + folderPath;
folderPath = GetFullFilePath(folderPath);
}
// Check path of the edited item
if (!URLHelper.IsPostback())
{
string editedPath = ValidationHelper.GetString(RequestStockHelper.GetItem("FolderPath"), string.Empty);
folderPath = (editedPath != string.Empty) ? editedPath : folderPath;
}
string closeLink = String.Format("{0}", GetString("general.close"));
string docNamePath = String.Format("{0}", folderPath.Replace('\\', '/'));
string listingMsg = string.Format(GetString("media.libraryui.listingInfo"), docNamePath, closeLink);
mediaView.DisplayListingInfo(listingMsg);
}
mediaView.ShowParentButton = (IsFullListingMode && (GetCompletePath(LastFolderPath) != GetFullFilePath(StartingPath)));
}
#endregion
#region "Initialization methods"
///
/// Initializes controls.
///
private void InitializeControls()
{
ViewMode = menuElem.SelectedViewMode;
// View mode obtained from the user's settings
XmlData dialogConfig = CMSContext.CurrentUser.UserSettings.UserDialogsConfiguration;
if (dialogConfig != null)
{
// Get user's view mode
string viewMode = (dialogConfig.ContainsColumn("media.viewmode") ? (string)dialogConfig["media.viewmode"] : string.Empty);
if (viewMode != string.Empty)
{
ViewMode = CMSDialogHelper.GetDialogViewMode(viewMode);
}
}
// Select default site
SelectSite();
mediaView.ViewMode = ViewMode;
menuElem.SelectedViewMode = ViewMode;
}
///
/// Selects site based on according dialogs configuration.
///
private void SelectSite()
{
// Select site based on dialog configuration
string siteName = !string.IsNullOrEmpty(Config.LibSelectedSite) ? Config.LibSelectedSite : CMSContext.CurrentSiteName;
if (Config.LibSites != AvailableSitesEnum.All)
{
librarySelector.SelectedSiteName = siteName;
}
// Select site based on selected item
if ((MediaSource != null) && (MediaSource.MediaFileLibraryID > 0))
{
LibraryInfo = MediaLibraryInfoProvider.GetMediaLibraryInfo(MediaSource.MediaFileLibraryID);
if (LibraryInfo != null)
{
siteName = SiteInfoProvider.GetSiteInfo(LibraryInfo.LibrarySiteID).SiteName;
}
}
// Select site based on user's configuration
else
{
// Select side based on the user's configuration
if (CMSContext.CurrentUser.UserSettings.UserDialogsConfiguration != null)
{
XmlData dialogConfig = CMSContext.CurrentUser.UserSettings.UserDialogsConfiguration;
// Get site name
string usersSiteName = (dialogConfig.ContainsColumn("media.sitename") ? (string)dialogConfig["media.sitename"] : string.Empty);
if (usersSiteName != string.Empty)
{
siteName = usersSiteName;
}
}
}
// Apply previously obtained sitename only when all sites are available
if (Config.LibSites == AvailableSitesEnum.All)
{
librarySelector.SelectedSiteName = siteName;
}
}
///
/// Initializes view element.
///
private void InitializeViewElem()
{
mediaView.LibraryID = LibraryID;
mediaView.IsLiveSite = IsLiveSite;
// Generate permanent URLs whenever node GUID output required
if (Config.OutputFormat != OutputFormatEnum.NodeGUID)
{
UsePermanentUrls = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSMediaUsePermanentURLs");
}
mediaView.UsePermanentUrls = UsePermanentUrls;
mediaView.ListViewControl.OnBeforeSorting += ListViewControl_OnBeforeSorting;
mediaView.ListReloadRequired += mediaView_ListReloadRequired;
mediaView.ListViewControl.DataSourceIsSorted = true;
mediaView.GetInformation += mediaView_GetInformation;
// Set media properties
mediaView.SelectableContent = SelectableContent;
mediaView.SourceType = SourceType;
mediaView.ViewMode = menuElem.SelectedViewMode;
// Set autoresize parameters
mediaView.ResizeToHeight = Config.ResizeToHeight;
mediaView.ResizeToMaxSideSize = Config.ResizeToMaxSideSize;
mediaView.ResizeToWidth = Config.ResizeToWidth;
// If folder was changed reset current page index for control displaying content
switch (CurrentAction)
{
case "folderselect":
case "clickformorefolder":
case "morefolderselect":
case "parentselect":
case "clickformorelink":
ResetPageIndex();
break;
}
}
///
/// Initializes menu element.
///
private void InitializeMenuElem()
{
menuElem.LibraryFolderPath = (StartingPath + LastFolderPath).Trim('/');
menuElem.ResizeToHeight = Config.ResizeToHeight;
menuElem.ResizeToMaxSideSize = Config.ResizeToMaxSideSize;
menuElem.ResizeToWidth = Config.ResizeToWidth;
menuElem.DisplayMode = DisplayMode;
menuElem.IsLiveSite = IsLiveSite;
menuElem.SourceType = SourceType;
menuElem.LibraryID = LibraryID;
menuElem.AllowFullscreen = false;
menuElem.UpdateViewMenu();
}
///
/// Initialize design jQuery scripts.
///
private void InitializeDesignScripts()
{
StringBuilder sb = new StringBuilder();
sb.Append("setTimeout('InitializeDesign();',200);");
sb.Append("$j(window).unbind('resize').resize(function() { InitializeDesign(); });");
ScriptHelper.RegisterStartupScript(Page, typeof(Page), "designScript", ScriptHelper.GetScript(sb.ToString()));
}
///
/// Loads folder tree.
///
private void InitializeTree()
{
// Initialize folder tree control
folderTree.CustomSelectFunction = "SetAction('folderselect', '##NODEVALUE##'); RaiseHiddenPostBack();";
folderTree.CustomClickForMoreFunction = "SetAction('clickformore##TYPE##', '##NODEVALUE##'); RaiseHiddenPostBack();";
folderTree.IsLiveSite = IsLiveSite;
// Set starting path
if (!string.IsNullOrEmpty(StartingPath))
{
folderTree.RootFolderPath = MediaLibraryRootFolder.TrimEnd('\\');
folderTree.MediaLibraryFolder = Path.GetFileNameWithoutExtension(StartingPath.Trim('/'));
folderTree.MediaLibraryPath = EnsureFolderPath(DirectoryHelper.CombinePath(LibraryInfo.LibraryFolder, StartingPath.Trim('/')));
}
else
{
folderTree.RootFolderPath = MediaLibraryRootFolder;
folderTree.MediaLibraryFolder = LibraryInfo.LibraryFolder;
}
folderTree.ReloadData();
pnlUpdateTree.Update();
}
///
/// Initializes library selector based on dialog configuration.
///
private void InitializeLibrarySelector()
{
librarySelector.IsLiveSite = IsLiveSite;
// Sites
librarySelector.Sites = Config.LibSites;
// Groups
librarySelector.Groups = Config.LibGroups;
librarySelector.GroupName = Config.LibGroupName;
librarySelector.GroupLibraries = Config.LibGroupLibraries;
librarySelector.GroupLibraryName = Config.LibGroupLibraryName;
// Libraries
librarySelector.GlobalLibraries = Config.LibGlobalLibraries;
librarySelector.GlobalLibaryName = Config.LibGlobalLibraryName;
}
///
/// Initializes all the script required for communication between controls.
///
private void InitializeControlScripts()
{
// Get reference causing postback to hidden button
string postBackRef = ControlsHelper.GetPostBackEventReference(hdnButton, string.Empty);
// Prepare for upload
string refreshType = CMSDialogHelper.GetMediaSource(MediaSourceEnum.MediaLibraries);
// SetAction function setting action name and passed argument
string setAction = String.Format(@"
function SetAction(action, argument) {{
var hdnAction = document.getElementById('{0}');
var hdnArgument = document.getElementById('{1}');
if ((hdnAction != null) && (hdnArgument != null)) {{
if (action != null) {{
hdnAction.value = action;
}}
if (argument != null) {{
hdnArgument.value = argument;
}}
}}
}}
function RaiseHiddenPostBack(){{
{2};
}}
function InitRefresh_{3}(message, fullRefresh, itemInfo, action) {{
if((message != null) && (message != ''))
{{
window.alert(message);
}}
else
{{
SetAction('libraryfilecreated', itemInfo);
RaiseHiddenPostBack();
}}
}}
function imageEdit_Refresh(guid){{
SetAction('edit', guid);
RaiseHiddenPostBack();
}}", hdnAction.ClientID, hdnArgument.ClientID, postBackRef, refreshType);
ltlScript.Text = ScriptHelper.GetScript(setAction);
}
#endregion
#region "Load object methods"
///
/// Loads library applying current library information.
///
private void SelectLibrary()
{
LibraryID = librarySelector.LibraryID;
if (LibraryID > 0)
{
// Reload data using new information
DisplayMediaElements();
// Initialize tree
InitializeTree();
// Reload view element
InitializeViewElem();
}
}
///
/// Checks permissions for the current user taking specified action.
///
private string CheckPermissions()
{
if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, PERMISSION_READ) &&
!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "LibraryAccess"))
{
return GetString("media.security.noaccess");
}
return string.Empty;
}
///
/// Loads all files for the view control.
///
private void LoadData()
{
LoadData(false);
}
///
/// Loads all files for the view control.
///
///
private void LoadData(bool forceSetup)
{
mediaView.StopProcessing = false;
LoadDataSource(LastSearchedValue);
mediaView.Reload(forceSetup);
wasLoaded = true;
}
///
/// Loads all files for the view control.
///
/// Text to filter loaded files
private void LoadDataSource(string searchText)
{
// Load media files data
if ((FolderPath != null) && (LibraryID > 0))
{
string err = CheckPermissions();
if (err == string.Empty)
{
string normFolderPath = NormalizeForSql(FolderPath);
string filePath = (StartingPath + MediaLibraryHelper.EnsurePath(normFolderPath)).Trim('/').Replace("'", "''");
// Create WHERE condition
string where = String.Format("FilePath LIKE N'{0}%' {{escape '{1}'}} AND FilePath NOT LIKE N'{2}_%/%' {{escape '{1}'}} AND FileLibraryID = {3}", (String.IsNullOrEmpty(filePath) ? string.Empty : filePath + "/"), PERCENT_ESC_CHAR, filePath, LibraryID);
if (!string.IsNullOrEmpty(searchText))
{
searchText = NormalizeForSql(searchText);
where = SqlHelperClass.AddWhereCondition(where, String.Format("(FileName LIKE N'%{0}%' {{escape '{1}'}}) OR (FileExtension LIKE N'%{0}%' {{escape '{1}'}})", SqlHelperClass.GetSafeQueryString(searchText, false), PERCENT_ESC_CHAR));
}
const string columns = "FileGUID, FileName, FilePath, FileExtension, FileImageWidth, FileImageHeight, FileTitle, FileSize, FileModifiedWhen, FileSiteID, FileID, FileLibraryID, FileDescription";
int topN = mediaView.CurrentTopN;
DataSet result = MediaFileInfoProvider.GetMediaFiles(where, null, topN, columns);
// Sort DataSet containing folders as well as files
SortMixedDataSet(result, SortDirection, SortColumns);
// If folders should be displayed as well include them in the DataSet
if (IsFullListingMode)
{
// Add folder
IncludeFolders(result, searchText);
}
// Get all files from current folder and pass it to the media view control
mediaView.DataSource = result;
}
else
{
// Display error
ShowError(err);
}
}
}
#endregion
#region "Common event methods"
///
/// Handles actions related to the media folder.
///
/// Path of folder
/// Indicates whether the action is related to the new folder created action
private void HandleFolderAction(string folderPath, bool isNewFolder)
{
HandleFolderAction(folderPath, isNewFolder, false);
}
///
/// Handles actions related to the media folder.
///
/// Path of folder
/// Indicates whether the action is related to the new folder created action
private void HandleFolderAction(string folderPath, bool isNewFolder, bool selectAndDisplay)
{
// Update information on currently selected folder path
FolderPath = GetFilePath(folderPath);
// Reload tree if new folder was created
if (isNewFolder)
{
InitializeTree();
ScriptHelper.RegisterStartupScript(Page, typeof(Page), "EnsureTopWindow", ScriptHelper.GetScript("if (self.focus) { self.focus(); }"));
}
// Bear in mind starting path
if (StartingPath != string.Empty)
{
if (isNewFolder)
{
folderPath = FolderPath;
}
// If action occurs as result of library changed - select root folder
else if (FolderPath == string.Empty)
{
folderPath = StartingPath.Trim('/').Trim('\\');
}
}
string selectPath = EnsureFolderPath(folderPath);
// Check if required folder exists
string folderToCheck = folderPath;
if (isNewFolder || StartingPath != string.Empty)
{
if (isNewFolder && (StartingPath == string.Empty))
{
folderToCheck = GetFilePath(folderPath);
}
else
{
if (!isNewFolder)
{
folderToCheck = String.Format("{0}/{1}", GetFolderPath(StartingPath.TrimEnd('/')), folderPath);
}
}
}
else
{
folderToCheck = GetFilePath(folderPath);
}
if (!folderTree.FolderExists(folderToCheck))
{
// Select root folder by default
FolderPath = string.Empty;
selectPath = StartingPath == string.Empty ? (LibraryInfo == null) ? string.Empty : LibraryInfo.LibraryFolder : folderTree.MediaLibraryFolder;
}
if (isNewFolder && (StartingPath != string.Empty))
{
//selectPath = GetFilePath(selectPath);
selectPath = EnsureFolderPath(selectPath);
}
if (selectAndDisplay)
{
// Make sure the path is expanded in the tree
folderTree.PathToSelect = selectPath;
folderTree.ReloadData();
pnlUpdateTree.Update();
}
// Select required folder if available
folderTree.SelectPath(selectPath);
// Update menu
menuElem.LibraryID = LibraryID;
menuElem.LibraryFolderPath = (!isNewFolder) ? (StartingPath + FolderPath).Trim('/') : FolderPath;
menuElem.UpdateActionsMenu();
// Load new data and reload view control's content
LoadData(true);
pnlUpdateView.Update();
DisplayNormal();
}
///
/// Handles actions occurring when some text is searched.
///
/// Argument holding information on searched text
private void HandleSearchAction(string argument)
{
LastSearchedValue = argument;
// Load new data filtered by searched text and reload view control's content
LoadData();
pnlUpdateView.Update();
// Keep focus in search text box
ScriptHelper.RegisterStartupScript(Page, typeof(Page), "SetSearchFocus", ScriptHelper.GetScript("SetSearchFocus();"));
}
///
/// Handles actions occurring when some item is selected.
///
/// Argument holding information on selected item
private void HandleSelectAction(string argument)
{
// Create new selected media item and pass it to the properties dialog
SelectMediaItem(argument);
ClearActionElems();
}
///
/// Handles display more action.
///
private void HandleDisplayMore(string argument)
{
// Set display mode
IsFullListingMode = true;
argument = argument.Replace('|', '/');
HandleFolderAction(argument, false);
pnlUpdateProperties.Update();
ClearActionElems();
}
///
/// Handles attachment edit action.
///
/// Media file GUID coming from the view control
private void HandleEdit(string argument)
{
IsEditImage = true;
if (!string.IsNullOrEmpty(argument))
{
string[] argArr = argument.Split('|');
string siteName = argArr[1];
Guid mediaFileGuid = ValidationHelper.GetGuid(argArr[0], Guid.Empty);
MediaFileInfo mfi = MediaFileInfoProvider.GetMediaFileInfo(mediaFileGuid, siteName);
if (mfi != null)
{
string url = mediaView.GetItemUrl(LibrarySiteInfo, mfi.FileGUID, mfi.FileName, mfi.FileExtension, mfi.FilePath, false, 0, 0, 0);
string permUrl = mediaView.GetItemUrl(LibrarySiteInfo, mfi.FileGUID, mfi.FileName, mfi.FileExtension, mfi.FilePath, true, 0, 0, 0);
if (ItemToColorize == mediaFileGuid)
{
SelectMediaItem(mfi.FileName, mfi.FileExtension, mfi.FileImageWidth, mfi.FileImageHeight, mfi.FileSize, url, permUrl);
}
// Load new data and reload view control's content
LoadData();
// Update content to reflect changes made during editing
pnlUpdateView.Update();
}
}
ClearActionElems();
}
///
/// Handles actions occurring when new library file was created.
///
/// Argument holding information on new file path
private void HandleFileCreatedAction(string argument)
{
string[] argArr = argument.Split('|');
if (argArr.Length == 2)
{
int mediaFileId = ValidationHelper.GetInteger(argArr[0], 0);
MediaFileInfo fileInfo = MediaFileInfoProvider.GetMediaFileInfo(mediaFileId);
if (fileInfo != null)
{
if (CMSDialogHelper.IsItemSelectable(SelectableContent, fileInfo.FileExtension))
{
// Get file URL
string fileUrl = mediaView.GetItemUrl(LibrarySiteInfo, fileInfo.FileGUID, fileInfo.FileName, fileInfo.FileExtension, fileInfo.FilePath, false, 0, 0, 0);
string permUrl = mediaView.GetItemUrl(LibrarySiteInfo, fileInfo.FileGUID, fileInfo.FileName, fileInfo.FileExtension, fileInfo.FilePath, true, 0, 0, 0);
SelectMediaItem(fileInfo.FileName, fileInfo.FileExtension, fileInfo.FileImageWidth,
fileInfo.FileImageHeight, fileInfo.FileSize, fileUrl, permUrl);
ItemToColorize = fileInfo.FileGUID;
ColorizeRow(fileInfo.FileGUID.ToString());
}
}
// Trim root folder when starting path is set
if (StartingPath != string.Empty)
{
string startingPath = StartingPath.Trim('/');
if (FolderPath.StartsWithCSafe(startingPath))
{
FolderPath = FolderPath.Substring(startingPath.Length);
}
}
InitializeMenuElem();
// Load new data and reload view control's content
LoadData();
pnlUpdateView.Update();
}
}
#endregion
#region "Event handlers"
///
/// Behaves as mediator in communication line between control taking action and the rest of the same level controls.
///
protected void hdnButton_Click(object sender, EventArgs e)
{
// Get information on action causing postback
string argument = hdnArgument.Value;
switch (CurrentAction)
{
case "insertitem":
GetSelectedItem();
break;
case "search":
HandleSearchAction(argument);
break;
case "select":
HandleSelectAction(argument);
break;
case "clickformorefolder":
case "clickformorelink":
mediaView.ResetListSelection();
ResetSearchFilter();
HandleDisplayMore(argument);
break;
case "morefolderselect":
string folderPath = CreateFilePath(argument);
folderPath = StartingPath != string.Empty ? StartingPath + folderPath : GetFullFilePath(folderPath);
ResetSearchFilter();
HandleFolderAction(folderPath, false, true);
ClearActionElems();
break;
case "libraryfilecreated":
HandleFileCreatedAction(argument);
break;
case "folderselect":
ResetSearchFilter();
argument = argument.Replace('|', '/');
HandleFolderAction(argument, false);
break;
case "parentselect":
string path = StartingPath != string.Empty ? GetParentFullPath(StartingPath + LastFolderPath, false) : GetParentFullPath(LastFolderPath);
ResetSearchFilter();
HandleFolderAction(path, false);
ClearActionElems();
break;
case "closelisting":
IsFullListingMode = false;
folderTree.CloseListing = true;
folderPath = StartingPath != string.Empty ? StartingPath + LastFolderPath : GetFullFilePath(LastFolderPath);
// Reload folder
HandleFolderAction(folderPath, false, false);
break;
case "newfolder":
argument = argument.Replace('|', '/').Replace("//", "/");
ResetSearchFilter();
HandleFolderAction(argument, true, true);
break;
case "cancelfolder":
ScriptHelper.RegisterStartupScript(Page, typeof(Page), "EnsureTopWindow", ScriptHelper.GetScript("if (self.focus) { self.focus(); }"));
ClearActionElems();
break;
case "edit":
HandleEdit(argument);
break;
default:
ColorizeLastSelectedRow();
pnlUpdateView.Update();
break;
}
}
protected void librarySelector_LibraryChanged(object sender, EventArgs e)
{
// Force control to reload library info
LibraryInfo = null;
FolderPath = string.Empty;
IsFullListingMode = false;
LibraryChanged = true;
// Do not clear item info when editing
if (URLHelper.IsPostback())
{
ItemToColorize = Guid.Empty;
}
if (LibraryInfo != null)
{
// Load selected library
SelectLibrary();
// Select folder tree path obtained from the configuration
string fullPath = !URLHelper.IsPostback() ? ValidationHelper.GetString(RequestStockHelper.GetItem("FolderPath"), string.Empty) : GetCompletePath(FolderPath);
if (fullPath.StartsWithCSafe(LibraryInfo.LibraryFolder))
{
// Remove library folder when tree starts at starting path different from the library root folder
if (StartingPath != string.Empty)
{
fullPath = fullPath.Replace(LibraryInfo.LibraryFolder, string.Empty).TrimStart('/');
}
}
else
{
fullPath = LibraryInfo.LibraryFolder;
}
ProcessIsFullListingMode();
HandleFolderAction(fullPath, false, true);
// If loaded for the first time make sure info on library and selected path
if (!URLHelper.IsPostback())
{
EnsureMenuInfo();
}
// Clear properties if library changed
if (URLHelper.IsPostback())
{
// High-light item being edited
if (ItemToColorize != Guid.Empty)
{
ColorizeRow(ItemToColorize.ToString());
}
Properties.ClearProperties(true);
}
}
else
{
ShowError(GetString("dialogs.libraries.nolibrary"));
}
// Update library selection
pnlUpdateSelectors.Update();
}
///
/// Handles event occurring when inner media view control requires load of the data.
///
private void mediaView_ListReloadRequired()
{
LoadData();
}
protected object mediaView_GetInformation(string type, object parameter)
{
switch (type.ToLowerCSafe())
{
case "fileisnotindatabase":
string fileName = ValidationHelper.GetString(parameter, string.Empty);
return FileIsNotInDatabase(fileName);
case "siteidrequired":
return LibrarySiteInfo.SiteID;
default:
return null;
}
}
protected void ListViewControl_OnBeforeSorting(object sender, EventArgs e)
{
GridViewSortEventArgs sortArg = (e as GridViewSortEventArgs);
if (sortArg != null)
{
SortDirection = (mediaView.ListViewControl.SortDirect.ToLowerCSafe().EndsWithCSafe("desc") ? "DESC" : "ASC");
SortColumns = sortArg.SortExpression;
}
}
#endregion
}