PageRenderTime 62ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/IZWebFileManager/FileManagerController.cs

http://izwebfilemanager.googlecode.com/
C# | 1580 lines | 1432 code | 118 blank | 30 comment | 154 complexity | a232e93a4fcc00a8f1f532991a27ff34 MD5 | raw file
  1. // Copyright (C) 2006 Igor Zelmanovich <izwebfilemanager@gmail.com>
  2. //
  3. // This program is free software; you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation; either version 2 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Text;
  19. using System.Web.UI;
  20. using System.ComponentModel;
  21. using System.Resources;
  22. using IZ.WebFileManager.Components;
  23. using System.Collections;
  24. using System.Web.UI.WebControls;
  25. using System.Collections.ObjectModel;
  26. using System.IO;
  27. using System.Web;
  28. using System.Security.Permissions;
  29. using System.Threading;
  30. using System.Drawing;
  31. using System.Globalization;
  32. using System.Text.RegularExpressions;
  33. using System.Runtime.Serialization;
  34. using System.Drawing.Design;
  35. using System.Web.Configuration;
  36. using System.Security;
  37. namespace IZ.WebFileManager
  38. {
  39. [PersistChildren (false)]
  40. [ParseChildren (true)]
  41. public sealed partial class FileManagerController : Control, ICallbackEventHandler, IPostBackEventHandler
  42. {
  43. #region Fields
  44. internal static readonly Unit SmallImageWidth = 16;
  45. internal static readonly Unit SmallImageHeight = 16;
  46. internal static readonly Unit LargeImageWidth = 32;
  47. internal static readonly Unit LargeImageHeight = 32;
  48. static readonly Hashtable _imageExtension;
  49. static readonly bool _supportThumbnails;
  50. const string ThumbnailHandler = "IZWebFileManagerThumbnailHandler.ashx";
  51. Hashtable _fileExtensions;
  52. Hashtable _specialFolderPaths;
  53. ArrayList _hiddenFilesArray;
  54. Style _hiddenItemStyle;
  55. ArrayList _prohibitedFilesArray;
  56. readonly FileTypeCollection _fileTypeCollection = new FileTypeCollection ();
  57. readonly NewDocumentTemplateCollection _templates = new NewDocumentTemplateCollection ();
  58. readonly RootDirectoryCollection _rootDirectories = new RootDirectoryCollection ();
  59. readonly SpecialFolderCollection _specialFolders = new SpecialFolderCollection ();
  60. string _defaultFolderSmallImage;
  61. string _defaultFolderLargeImage;
  62. string _defaultFileSmallImage;
  63. string _defaultFileLargeImage;
  64. string _defaultRootFolderSmallImage;
  65. string _defaultRootFolderLargeImage;
  66. Dictionary<ToolbarImages, string> _toolbarImages;
  67. bool _toolbarImagesInitialized;
  68. bool _defailtsInitialized;
  69. string _callbackResult;
  70. string _callbackCommandArgument;
  71. FileManagerCommands _callbackCommand;
  72. FileManagerControlBase _callbackControl;
  73. #endregion
  74. #region Properties
  75. internal bool SupportThumbnails {
  76. get { return _supportThumbnails; }
  77. }
  78. [Themeable (false)]
  79. [Localizable (false)]
  80. [DefaultValue (false)]
  81. [Category ("Behavior")]
  82. public bool AllowOverwrite {
  83. get { return ViewState ["AllowOverwrite"] == null ? false : (bool) ViewState ["AllowOverwrite"]; }
  84. set { ViewState ["AllowOverwrite"] = value; }
  85. }
  86. [Themeable (false)]
  87. [Localizable (false)]
  88. [DefaultValue (true)]
  89. [Category ("Behavior")]
  90. public bool AllowUpload {
  91. get { return ViewState ["AllowUpload"] == null ? true : (bool) ViewState ["AllowUpload"]; }
  92. set { ViewState ["AllowUpload"] = value; }
  93. }
  94. /// <summary>
  95. /// When is set true, Delete, Move and Rename are not allowed, Default value it true.
  96. /// </summary>
  97. [Themeable (false)]
  98. [Localizable (false)]
  99. [DefaultValue (true)]
  100. [Category ("Behavior")]
  101. public bool AllowDelete {
  102. get { return ViewState ["AllowDelete"] == null ? true : (bool) ViewState ["AllowDelete"]; }
  103. set { ViewState ["AllowDelete"] = value; }
  104. }
  105. [Themeable (false)]
  106. [Localizable (false)]
  107. [DefaultValue (false)]
  108. [Category ("Behavior")]
  109. public bool ReadOnly {
  110. get { return ViewState ["ReadOnly"] == null ? false : (bool) ViewState ["ReadOnly"]; }
  111. set { ViewState ["ReadOnly"] = value; }
  112. }
  113. [Themeable (false)]
  114. [Localizable (false)]
  115. [DefaultValue (false)]
  116. [Category ("Behavior")]
  117. public bool DownloadOnDoubleClick {
  118. get { return ViewState ["DownloadOnDoubleClick"] == null ? false : (bool) ViewState ["DownloadOnDoubleClick"]; }
  119. set { ViewState ["DownloadOnDoubleClick"] = value; }
  120. }
  121. [DefaultValue ("IZWebFileManagerResource")]
  122. [Category ("Data")]
  123. public string ResourceClassKey {
  124. get { return ((ViewState ["ResourceClassKey"] == null) ? "IZWebFileManagerResource" : (string) ViewState ["ResourceClassKey"]); }
  125. set { ViewState ["ResourceClassKey"] = value; }
  126. }
  127. [DefaultValue (null)]
  128. [Category ("Appearance")]
  129. [Themeable (true)]
  130. public CultureInfo Culture {
  131. get { return ((ViewState ["Culture"] == null) ? null : (CultureInfo) ViewState ["Culture"]); }
  132. set { ViewState ["Culture"] = value; }
  133. }
  134. public Boolean IsRightToLeft { get { return CurrentUICulture.TextInfo.IsRightToLeft; } }
  135. [Browsable (false)]
  136. public CultureInfo CurrentUICulture { get { return Culture == null ? CultureInfo.CurrentUICulture : Culture; } }
  137. [DefaultValue ("")]
  138. [Category ("Action")]
  139. [Themeable (false)]
  140. [Localizable (false)]
  141. public string ClientOpenItemFunction {
  142. get { return ((ViewState ["ClientOpenItemFunction"] == null) ? String.Empty : (string) ViewState ["ClientOpenItemFunction"]); }
  143. set { ViewState ["ClientOpenItemFunction"] = value; }
  144. }
  145. [DefaultValue ("")]
  146. [Category ("Behavior")]
  147. [Themeable (false)]
  148. [Localizable (false)]
  149. public string HiddenFiles {
  150. get { return ((ViewState ["HiddenFiles"] == null) ? String.Empty : (string) ViewState ["HiddenFiles"]); }
  151. set { ViewState ["HiddenFiles"] = value; }
  152. }
  153. [DefaultValue ("")]
  154. [Category ("Behavior")]
  155. [Themeable (false)]
  156. [Localizable (false)]
  157. public string HiddenFilesAndFoldersPrefix {
  158. get { return (string) (ViewState ["HiddenFolderPrefix"] ?? String.Empty); }
  159. set { ViewState ["HiddenFolderPrefix"] = value; }
  160. }
  161. [DefaultValue (false)]
  162. [Category ("Behavior")]
  163. [Themeable (false)]
  164. [Localizable (false)]
  165. public bool ShowHiddenFilesAndFolders {
  166. get { return (bool) (ViewState ["ShowHiddenFolders"] ?? false); }
  167. set { ViewState ["ShowHiddenFolders"] = value; }
  168. }
  169. internal ArrayList HiddenFilesArray {
  170. get {
  171. if (_hiddenFilesArray == null)
  172. _hiddenFilesArray = InitExtensionsArray (HiddenFiles);
  173. return _hiddenFilesArray;
  174. }
  175. }
  176. internal Style HiddenItemStyle {
  177. get {
  178. if (_hiddenItemStyle == null) {
  179. _hiddenItemStyle = new HiddenItemStyle ();
  180. }
  181. return _hiddenItemStyle;
  182. }
  183. }
  184. [DefaultValue ("")]
  185. [Category ("Behavior")]
  186. [Themeable (false)]
  187. [Localizable (false)]
  188. public string ProhibitedFiles {
  189. get { return ((ViewState ["ProhibitedFiles"] == null) ? String.Empty : (string) ViewState ["ProhibitedFiles"]); }
  190. set { ViewState ["ProhibitedFiles"] = value; }
  191. }
  192. internal ArrayList ProhibitedFilesArray {
  193. get {
  194. if (_prohibitedFilesArray == null)
  195. _prohibitedFilesArray = InitExtensionsArray (ProhibitedFiles);
  196. return _prohibitedFilesArray;
  197. }
  198. }
  199. [MergableProperty (false)]
  200. [Category ("Behavior")]
  201. [PersistenceMode (PersistenceMode.InnerProperty)]
  202. [Localizable (false)]
  203. [Themeable (false)]
  204. public RootDirectoryCollection RootDirectories {
  205. get { return _rootDirectories; }
  206. }
  207. [MergableProperty (false)]
  208. [Category ("Behavior")]
  209. [PersistenceMode (PersistenceMode.InnerProperty)]
  210. [Localizable (false)]
  211. [Themeable (false)]
  212. public SpecialFolderCollection SpecialFolders {
  213. get { return _specialFolders; }
  214. }
  215. [MergableProperty (false)]
  216. [PersistenceMode (PersistenceMode.InnerProperty)]
  217. [Category ("Behavior")]
  218. [Localizable (false)]
  219. [Themeable (false)]
  220. public NewDocumentTemplateCollection Templates {
  221. get { return _templates; }
  222. }
  223. [MergableProperty (false)]
  224. [PersistenceMode (PersistenceMode.InnerProperty)]
  225. [Category ("Behavior")]
  226. [Localizable (false)]
  227. [Themeable (false)]
  228. public FileTypeCollection FileTypes {
  229. get { return _fileTypeCollection; }
  230. }
  231. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  232. [DefaultValue ("")]
  233. [UrlProperty]
  234. [Bindable (true)]
  235. public string FileSmallImageUrl {
  236. get { return ViewState ["FileSmallIconUrl"] == null ? String.Empty : (string) ViewState ["FileSmallIconUrl"]; }
  237. set { ViewState ["FileSmallIconUrl"] = value; }
  238. }
  239. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  240. [DefaultValue ("")]
  241. [UrlProperty]
  242. [Bindable (true)]
  243. public string FileLargeImageUrl {
  244. get { return ViewState ["FileLargeIconUrl"] == null ? String.Empty : (string) ViewState ["FileLargeIconUrl"]; }
  245. set { ViewState ["FileLargeIconUrl"] = value; }
  246. }
  247. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  248. [DefaultValue ("")]
  249. [UrlProperty]
  250. [Bindable (true)]
  251. public string FolderSmallImageUrl {
  252. get { return ViewState ["FolderSmallIconUrl"] == null ? String.Empty : (string) ViewState ["FolderSmallIconUrl"]; }
  253. set { ViewState ["FolderSmallIconUrl"] = value; }
  254. }
  255. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  256. [DefaultValue ("")]
  257. [UrlProperty]
  258. [Bindable (true)]
  259. public string FolderLargeImageUrl {
  260. get { return ViewState ["FolderLargeIconUrl"] == null ? String.Empty : (string) ViewState ["FolderLargeIconUrl"]; }
  261. set { ViewState ["FolderLargeIconUrl"] = value; }
  262. }
  263. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  264. [DefaultValue ("")]
  265. [UrlProperty]
  266. [Bindable (true)]
  267. public string RootFolderSmallImageUrl {
  268. get { return ViewState ["RootFolderSmallIconUrl"] == null ? String.Empty : (string) ViewState ["RootFolderSmallIconUrl"]; }
  269. set { ViewState ["RootFolderSmallIconUrl"] = value; }
  270. }
  271. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  272. [DefaultValue ("")]
  273. [UrlProperty]
  274. [Bindable (true)]
  275. public string RootFolderLargeImageUrl {
  276. get { return ViewState ["RootFolderLargeIconUrl"] == null ? String.Empty : (string) ViewState ["RootFolderLargeIconUrl"]; }
  277. set { ViewState ["RootFolderLargeIconUrl"] = value; }
  278. }
  279. [DefaultValue ("")]
  280. [Bindable (true)]
  281. public string ImagesFolder {
  282. get { return ViewState ["IconsFolder"] == null ? String.Empty : (string) ViewState ["IconsFolder"]; }
  283. set { ViewState ["IconsFolder"] = value; }
  284. }
  285. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  286. [DefaultValue ("")]
  287. [UrlProperty]
  288. [Bindable (true)]
  289. public string CopyImageUrl {
  290. get { return ViewState ["CopyIconUrl"] == null ? String.Empty : (string) ViewState ["CopyIconUrl"]; }
  291. set { ViewState ["CopyIconUrl"] = value; }
  292. }
  293. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  294. [DefaultValue ("")]
  295. [UrlProperty]
  296. [Bindable (true)]
  297. public string MoveImageUrl {
  298. get { return ViewState ["MoveIconUrl"] == null ? String.Empty : (string) ViewState ["MoveIconUrl"]; }
  299. set { ViewState ["MoveIconUrl"] = value; }
  300. }
  301. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  302. [DefaultValue ("")]
  303. [UrlProperty]
  304. [Bindable (true)]
  305. public string DeleteImageUrl {
  306. get { return ViewState ["DeleteIconUrl"] == null ? String.Empty : (string) ViewState ["DeleteIconUrl"]; }
  307. set { ViewState ["DeleteIconUrl"] = value; }
  308. }
  309. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  310. [DefaultValue ("")]
  311. [UrlProperty]
  312. [Bindable (true)]
  313. public string RenameImageUrl {
  314. get { return ViewState ["RenameIconUrl"] == null ? String.Empty : (string) ViewState ["RenameIconUrl"]; }
  315. set { ViewState ["RenameIconUrl"] = value; }
  316. }
  317. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  318. [DefaultValue ("")]
  319. [UrlProperty]
  320. [Bindable (true)]
  321. public string FolderUpImageUrl {
  322. get { return ViewState ["FolderUpIconUrl"] == null ? String.Empty : (string) ViewState ["FolderUpIconUrl"]; }
  323. set { ViewState ["FolderUpIconUrl"] = value; }
  324. }
  325. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  326. [DefaultValue ("")]
  327. [UrlProperty]
  328. [Bindable (true)]
  329. public string NewFolderImageUrl {
  330. get { return ViewState ["NewFolderImageUrl"] == null ? String.Empty : (string) ViewState ["NewFolderImageUrl"]; }
  331. set { ViewState ["NewFolderImageUrl"] = value; }
  332. }
  333. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  334. [DefaultValue ("")]
  335. [UrlProperty]
  336. [Bindable (true)]
  337. public string ViewImageUrl {
  338. get { return ViewState ["ViewIconUrl"] == null ? String.Empty : (string) ViewState ["ViewIconUrl"]; }
  339. set { ViewState ["ViewIconUrl"] = value; }
  340. }
  341. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  342. [DefaultValue ("")]
  343. [UrlProperty]
  344. [Bindable (true)]
  345. public string ProcessImageUrl {
  346. get { return ViewState ["ProcessIconUrl"] == null ? String.Empty : (string) ViewState ["ProcessIconUrl"]; }
  347. set { ViewState ["ProcessIconUrl"] = value; }
  348. }
  349. [Editor ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))]
  350. [DefaultValue ("")]
  351. [UrlProperty]
  352. [Bindable (true)]
  353. public string RefreshImageUrl {
  354. get { return ViewState ["RefreshImageUrl"] == null ? String.Empty : (string) ViewState ["RefreshImageUrl"]; }
  355. set { ViewState ["RefreshImageUrl"] = value; }
  356. }
  357. #endregion
  358. static FileManagerController () {
  359. _imageExtension = new Hashtable (StringComparer.OrdinalIgnoreCase);
  360. object o = new object ();
  361. _imageExtension [".gif"] = o;
  362. _imageExtension [".jpg"] = o;
  363. _imageExtension [".jpeg"] = o;
  364. _imageExtension [".png"] = o;
  365. try {
  366. HttpHandlerActionCollection handlers = ((HttpHandlersSection) WebConfigurationManager.GetSection ("system.web/httpHandlers")).Handlers;
  367. foreach (HttpHandlerAction action in handlers)
  368. if (String.Compare (action.Path, ThumbnailHandler, StringComparison.OrdinalIgnoreCase) == 0) {
  369. _supportThumbnails = true;
  370. break;
  371. }
  372. }
  373. catch (SecurityException) {
  374. _supportThumbnails = true;
  375. }
  376. }
  377. protected override void OnPreRender (EventArgs e) {
  378. base.OnPreRender (e);
  379. Page.ClientScript.RegisterClientScriptBlock (typeof (FileManagerController), "WebFileManager_DoCallback", GetDoCallbackScript (), true);
  380. Page.ClientScript.RegisterClientScriptResource (typeof (FileManagerController), "IZ.WebFileManager.resources.FileManagerController.js");
  381. Page.ClientScript.RegisterStartupScript (typeof (FileManagerController), ClientID, GetInitInstanceScript (), true);
  382. RegisterResources ();
  383. EnsureDefaults ();
  384. // register hidden item style
  385. if (!String.IsNullOrEmpty (HiddenFilesAndFoldersPrefix) || !String.IsNullOrEmpty (HiddenFiles))
  386. if (Page.Header != null)
  387. Page.Header.StyleSheet.RegisterStyle (HiddenItemStyle, this);
  388. }
  389. internal void EnsureToolbarImages () {
  390. if (_toolbarImagesInitialized)
  391. return;
  392. _toolbarImagesInitialized = true;
  393. InitToolbarImages ();
  394. }
  395. private void InitToolbarImages () {
  396. bool isImagesFolder = ImagesFolder.Length > 0;
  397. string imagesFolder = EnsureEndsWithSlash (ImagesFolder);
  398. _toolbarImages = new Dictionary<ToolbarImages, string> ();
  399. // Copy icon
  400. if (CopyImageUrl.Length > 0)
  401. _toolbarImages [ToolbarImages.Copy] = ResolveUrl (CopyImageUrl);
  402. else if (isImagesFolder)
  403. _toolbarImages [ToolbarImages.Copy] = ResolveUrl (imagesFolder + "Copy.gif");
  404. else
  405. _toolbarImages [ToolbarImages.Copy] = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.Copy.gif");
  406. // Delete icon
  407. if (DeleteImageUrl.Length > 0)
  408. _toolbarImages [ToolbarImages.Delete] = ResolveUrl (DeleteImageUrl);
  409. else if (isImagesFolder)
  410. _toolbarImages [ToolbarImages.Delete] = ResolveUrl (imagesFolder + "Delete.gif");
  411. else
  412. _toolbarImages [ToolbarImages.Delete] = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.Delete.gif");
  413. // Move icon
  414. if (MoveImageUrl.Length > 0)
  415. _toolbarImages [ToolbarImages.Move] = ResolveUrl (MoveImageUrl);
  416. else if (isImagesFolder)
  417. _toolbarImages [ToolbarImages.Move] = ResolveUrl (imagesFolder + "Move.gif");
  418. else
  419. _toolbarImages [ToolbarImages.Move] = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.Move.gif");
  420. // Rename icon
  421. if (RenameImageUrl.Length > 0)
  422. _toolbarImages [ToolbarImages.Rename] = ResolveUrl (RenameImageUrl);
  423. else if (isImagesFolder)
  424. _toolbarImages [ToolbarImages.Rename] = ResolveUrl (imagesFolder + "Rename.gif");
  425. else
  426. _toolbarImages [ToolbarImages.Rename] = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.Rename.gif");
  427. // Rename icon
  428. if (NewFolderImageUrl.Length > 0)
  429. _toolbarImages [ToolbarImages.NewFolder] = ResolveUrl (NewFolderImageUrl);
  430. else if (isImagesFolder)
  431. _toolbarImages [ToolbarImages.NewFolder] = ResolveUrl (imagesFolder + "NewFolder.gif");
  432. else
  433. _toolbarImages [ToolbarImages.NewFolder] = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.NewFolder.gif");
  434. // View icon
  435. if (ViewImageUrl.Length > 0)
  436. _toolbarImages [ToolbarImages.View] = ResolveUrl (ViewImageUrl);
  437. else if (isImagesFolder)
  438. _toolbarImages [ToolbarImages.View] = ResolveUrl (imagesFolder + "View.gif");
  439. else
  440. _toolbarImages [ToolbarImages.View] = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.View.gif");
  441. // FolderUp icon
  442. if (FolderUpImageUrl.Length > 0)
  443. _toolbarImages [ToolbarImages.FolderUp] = ResolveUrl (FolderUpImageUrl);
  444. else if (isImagesFolder)
  445. _toolbarImages [ToolbarImages.FolderUp] = ResolveUrl (imagesFolder + "FolderUp.gif");
  446. else
  447. _toolbarImages [ToolbarImages.FolderUp] = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.FolderUp.gif");
  448. // Process icon
  449. if (ProcessImageUrl.Length > 0)
  450. _toolbarImages [ToolbarImages.Process] = ResolveUrl (ProcessImageUrl);
  451. else if (isImagesFolder)
  452. _toolbarImages [ToolbarImages.Process] = ResolveUrl (imagesFolder + "Process.gif");
  453. else
  454. _toolbarImages [ToolbarImages.Process] = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.Process.gif");
  455. // Refresh icon
  456. if (RefreshImageUrl.Length > 0)
  457. _toolbarImages [ToolbarImages.Refresh] = ResolveUrl (RefreshImageUrl);
  458. else if (isImagesFolder)
  459. _toolbarImages [ToolbarImages.Refresh] = ResolveUrl (imagesFolder + "Refresh.gif");
  460. else
  461. _toolbarImages [ToolbarImages.Refresh] = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.Refresh.gif");
  462. }
  463. internal void EnsureDefaults () {
  464. if (_defailtsInitialized)
  465. return;
  466. _defailtsInitialized = true;
  467. InitDefaults ();
  468. }
  469. private void InitDefaults () {
  470. bool isImagesFolder = ImagesFolder.Length > 0;
  471. string imagesFolder = EnsureEndsWithSlash (ImagesFolder);
  472. if (RootFolderSmallImageUrl.Length > 0)
  473. _defaultRootFolderSmallImage = ResolveUrl (RootFolderSmallImageUrl);
  474. else if (isImagesFolder)
  475. _defaultRootFolderSmallImage = ResolveUrl (imagesFolder + "RootFolderSmall.gif");
  476. else
  477. _defaultRootFolderSmallImage = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.RootFolderSmall.gif");
  478. if (RootFolderLargeImageUrl.Length > 0)
  479. _defaultRootFolderLargeImage = ResolveUrl (RootFolderLargeImageUrl);
  480. else if (isImagesFolder)
  481. _defaultRootFolderLargeImage = ResolveUrl (imagesFolder + "RootFolderLarge.gif");
  482. else
  483. _defaultRootFolderLargeImage = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.RootFolderLarge.gif");
  484. if (FolderSmallImageUrl.Length > 0)
  485. _defaultFolderSmallImage = ResolveUrl (FolderSmallImageUrl);
  486. else if (isImagesFolder)
  487. _defaultFolderSmallImage = ResolveUrl (imagesFolder + "FolderSmall.gif");
  488. else
  489. _defaultFolderSmallImage = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.FolderSmall.gif");
  490. if (FolderLargeImageUrl.Length > 0)
  491. _defaultFolderLargeImage = ResolveUrl (FolderLargeImageUrl);
  492. else if (isImagesFolder)
  493. _defaultFolderLargeImage = ResolveUrl (imagesFolder + "FolderLarge.gif");
  494. else
  495. _defaultFolderLargeImage = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.FolderLarge.gif");
  496. if (FileSmallImageUrl.Length > 0)
  497. _defaultFileSmallImage = ResolveUrl (FileSmallImageUrl);
  498. else if (isImagesFolder)
  499. _defaultFileSmallImage = ResolveUrl (imagesFolder + "FileSmall.gif");
  500. else
  501. _defaultFileSmallImage = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.FileSmall.gif");
  502. if (FileLargeImageUrl.Length > 0)
  503. _defaultFileLargeImage = ResolveUrl (FileLargeImageUrl);
  504. else if (isImagesFolder)
  505. _defaultFileLargeImage = ResolveUrl (imagesFolder + "FileLarge.gif");
  506. else
  507. _defaultFileLargeImage = Page.ClientScript.GetWebResourceUrl (typeof (FileManagerController), "IZ.WebFileManager.resources.FileLarge.gif");
  508. }
  509. string EnsureEndsWithSlash (string path) {
  510. if (!path.EndsWith ("/"))
  511. return path + "/";
  512. return path;
  513. }
  514. private void InitFileTypes () {
  515. _fileExtensions = new Hashtable (StringComparer.OrdinalIgnoreCase);
  516. foreach (FileType fileType in FileTypes) {
  517. string [] exts = fileType.Extensions.Split (new char [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  518. foreach (string ext in exts) {
  519. _fileExtensions [ext.Trim ().Trim ('.')] = fileType;
  520. }
  521. }
  522. }
  523. private void InitSpecialFolders () {
  524. _specialFolderPaths = new Hashtable (StringComparer.OrdinalIgnoreCase);
  525. foreach (SpecialFolder folder in SpecialFolders) {
  526. if (folder.DirectoryPath.Length > 0) {
  527. string path = Page.MapPath (folder.DirectoryPath);
  528. _specialFolderPaths [path] = folder;
  529. if (path.EndsWith ("/"))
  530. path.TrimEnd ('/');
  531. else
  532. path = path + "/";
  533. _specialFolderPaths [path] = folder;
  534. }
  535. }
  536. }
  537. private static ArrayList InitExtensionsArray (string extList) {
  538. string [] exts = extList.Split (',');
  539. ArrayList array = new ArrayList ();
  540. foreach (string ext in exts) {
  541. array.Add (ext.Trim ().ToLower (CultureInfo.InvariantCulture).TrimStart ('.'));
  542. }
  543. return array;
  544. }
  545. internal FileType GetFileType (FileInfo file) {
  546. if (_fileExtensions == null)
  547. InitFileTypes ();
  548. string ext = file.Extension.TrimStart ('.');
  549. return (FileType) _fileExtensions [ext];
  550. }
  551. public string GetResourceString (string name, string defaultValue) {
  552. try {
  553. string value = (string) HttpContext.GetGlobalResourceObject (ResourceClassKey, name, CurrentUICulture);
  554. if (value == null)
  555. return defaultValue;
  556. return value;
  557. }
  558. catch (MissingManifestResourceException) {
  559. return defaultValue;
  560. }
  561. }
  562. internal void AddDirectionAttribute (HtmlTextWriter writer) {
  563. writer.AddAttribute (HtmlTextWriterAttribute.Dir, IsRightToLeft ? "rtl" : "ltr");
  564. writer.AddStyleAttribute (HtmlTextWriterStyle.Direction, IsRightToLeft ? "rtl" : "ltr");
  565. }
  566. internal const string ClientScriptObjectNamePrefix = "WFM_";
  567. private string GetInitInstanceScript () {
  568. return "var " + ClientScriptObjectNamePrefix + ClientID + "=new FileManagerController('" + ClientID + "','" + UniqueID + "','" + EventArgumentSplitter + "');\r\n";
  569. }
  570. private string GetDoCallbackScript () {
  571. StringBuilder sb = new StringBuilder ();
  572. sb.AppendLine ("function WebFileManager_DoCallback(target, argument, clientCallback, context, clientErrorCallback) {");
  573. sb.AppendLine (Page.ClientScript.GetCallbackEventReference ("target", "argument", "clientCallback", "context", "clientErrorCallback", false) + ";");
  574. sb.AppendLine ("}");
  575. return sb.ToString ();
  576. }
  577. internal string GetCommandEventReference (Control control, string command, string arg) {
  578. return ClientScriptObjectNamePrefix + ClientID + ".On" + command + "(" + ClientScriptObjectNamePrefix + control.ClientID + "," + arg + ")";
  579. }
  580. #region ICallbackEventHandler Members
  581. string GetCallbackResult () {
  582. EnsureDefaults ();
  583. switch (_callbackCommand) {
  584. case FileManagerCommands.Refresh:
  585. _callbackResult = _callbackControl.RenderContents ();
  586. break;
  587. case FileManagerCommands.FileViewSort:
  588. _callbackResult = _callbackControl.RenderContents ();
  589. break;
  590. case FileManagerCommands.FileViewChangeView:
  591. _callbackResult = _callbackControl.RenderContents ();
  592. break;
  593. case FileManagerCommands.FileViewShowInGroups:
  594. _callbackResult = _callbackControl.RenderContents ();
  595. break;
  596. }
  597. return _callbackResult;
  598. }
  599. void RaiseCallbackEvent (string eventArgument) {
  600. if (eventArgument == null)
  601. return;
  602. // Parse eventArgument
  603. string [] args = eventArgument.Split (new char [] { EventArgumentSplitter }, 3);
  604. _callbackControl = (FileManagerControlBase) fileMangerControls [args [0]];
  605. _callbackCommand = (FileManagerCommands) Enum.Parse (typeof (FileManagerCommands), args [1]);
  606. _callbackCommandArgument = null;
  607. if (args.Length > 2)
  608. _callbackCommandArgument = args [2];
  609. switch (_callbackCommand) {
  610. case FileManagerCommands.Refresh:
  611. break;
  612. case FileManagerCommands.FileViewSort:
  613. break;
  614. case FileManagerCommands.FileViewChangeView:
  615. break;
  616. case FileManagerCommands.FileViewShowInGroups:
  617. break;
  618. case FileManagerCommands.FileViewNavigate:
  619. _callbackResult = ProcessFileViewNavigate (_callbackControl.ResolveFileManagerItemInfo (DecodeURIComponent (_callbackCommandArgument)));
  620. break;
  621. case FileManagerCommands.ExecuteCommand:
  622. string [] inds = _callbackCommandArgument.Split (':');
  623. _callbackResult = ProcessExecuteCommand (_callbackControl.SelectedItems, int.Parse (inds [0], null), int.Parse (inds [1], null));
  624. break;
  625. default:
  626. if (ReadOnly)
  627. _callbackResult = String.Empty;
  628. else {
  629. switch (_callbackCommand) {
  630. case FileManagerCommands.Rename:
  631. if (!AllowDelete) {
  632. _callbackResult = String.Empty;
  633. break;
  634. }
  635. string [] paths = _callbackCommandArgument.Split (EventArgumentSplitter);
  636. _callbackResult = ProcessRename (_callbackControl.ResolveFileManagerItemInfo (DecodeURIComponent (paths [0])), DecodeURIComponent (paths [1]));
  637. break;
  638. case FileManagerCommands.NewDocument:
  639. int index = int.Parse (_callbackCommandArgument, null);
  640. NewDocumentTemplate template = Templates [index];
  641. FileManagerItemInfo dir = _callbackControl.GetCurrentDirectory ();
  642. _callbackResult = ProcessNewDocument (dir, template);
  643. break;
  644. case FileManagerCommands.NewFolder:
  645. _callbackResult = ProcessNewFolder (_callbackControl.GetCurrentDirectory ());
  646. break;
  647. case FileManagerCommands.SelectedItemsDelete:
  648. if (!AllowDelete) {
  649. _callbackResult = String.Empty;
  650. break;
  651. }
  652. EvaluateSelectedItemsActionCommand (IZ.WebFileManager.SelectedItemsAction.Delete);
  653. break;
  654. case FileManagerCommands.SelectedItemsCopyTo:
  655. EvaluateSelectedItemsActionCommand (IZ.WebFileManager.SelectedItemsAction.Copy);
  656. break;
  657. case FileManagerCommands.SelectedItemsMoveTo:
  658. if (!AllowDelete) {
  659. _callbackResult = String.Empty;
  660. break;
  661. }
  662. EvaluateSelectedItemsActionCommand (IZ.WebFileManager.SelectedItemsAction.Move);
  663. break;
  664. default:
  665. String message = "Not Implemented Command \"{0}\"";
  666. throw new ArgumentException (String.Format (null, message, _callbackCommand));
  667. }
  668. }
  669. break;
  670. }
  671. }
  672. private void EvaluateSelectedItemsActionCommand (SelectedItemsAction action) {
  673. _callbackResult = ProcessSelectedItemsAction (_callbackControl.CurrentDirectory, _callbackControl.ResolveFileManagerItemInfo (DecodeURIComponent (_callbackCommandArgument)), _callbackControl.SelectedItems, action);
  674. }
  675. private string ProcessSelectedItemsAction (FileManagerItemInfo srcDir, FileManagerItemInfo destDir, FileManagerItemInfo [] items, SelectedItemsAction action) {
  676. if (items.Length == 0)
  677. return "";
  678. SelectedItemsActionCancelEventArgs cancelArg = new SelectedItemsActionCancelEventArgs (action);
  679. foreach (FileManagerItemInfo item in items) {
  680. if (item.Directory.Exists && destDir.Directory.FullName.StartsWith (item.Directory.FullName, StringComparison.InvariantCultureIgnoreCase))
  681. return ClientMessageEventReference (GetResourceString ("DestinationFolderIsSubfolder", "The destination folder is a subfolder of the source folder."));
  682. cancelArg.SelectedItems.Add (item);
  683. }
  684. cancelArg.DestinationDirectory = destDir;
  685. OnSelectedItemsAction (cancelArg);
  686. if (cancelArg.Cancel) {
  687. return ClientMessageEventReference (cancelArg.ClientMessage);
  688. }
  689. StringBuilder sb = new StringBuilder ();
  690. switch (action) {
  691. case IZ.WebFileManager.SelectedItemsAction.Delete:
  692. if (ProcessSelectedItemsDelete (items))
  693. AddFolderTreeRefreshEventReference (sb, srcDir);
  694. break;
  695. case IZ.WebFileManager.SelectedItemsAction.Move:
  696. destDir.EnsureDirectoryExists ();
  697. if (ProcessSelectedItemsMoveTo (destDir, items)) {
  698. AddFolderTreeRequireRefreshEventReference (sb, srcDir, destDir);
  699. AddFolderTreeNavigateEventReference (sb, srcDir);
  700. }
  701. break;
  702. case IZ.WebFileManager.SelectedItemsAction.Copy:
  703. destDir.EnsureDirectoryExists ();
  704. if (ProcessSelectedItemsCopyTo (destDir, items)) {
  705. AddFolderTreeRequireRefreshEventReference (sb, srcDir, destDir);
  706. AddFolderTreeNavigateEventReference (sb, srcDir);
  707. }
  708. break;
  709. }
  710. SelectedItemsActionEventArgs args = new SelectedItemsActionEventArgs ();
  711. OnSelectedItemsActionComplete (args);
  712. sb.AppendLine (ClientRefreshEventReference);
  713. return sb.ToString ();
  714. }
  715. private bool ProcessSelectedItemsMoveTo (FileManagerItemInfo destDir, FileManagerItemInfo [] items) {
  716. bool b = false;
  717. foreach (FileManagerItemInfo item in items) {
  718. if (item.Directory.Exists) {
  719. b = true;
  720. DirectoryInfo dir = item.Directory;
  721. if (String.Compare (dir.Parent.FullName.TrimEnd (Path.DirectorySeparatorChar), destDir.PhysicalPath.TrimEnd (Path.DirectorySeparatorChar), true) == 0)
  722. continue;
  723. string newName;
  724. if (AllowOverwrite)
  725. newName = dir.Name;
  726. else
  727. newName = GetNotDuplicatedFolderName (destDir, dir.Name);
  728. string newPath = Path.Combine (destDir.PhysicalPath, newName);
  729. xDirectory.Copy (dir.FullName, newPath, true);
  730. dir.Delete (true);
  731. }
  732. else if (item.File.Exists) {
  733. FileInfo file = item.File;
  734. if (String.Compare (file.Directory.FullName.TrimEnd (Path.DirectorySeparatorChar), destDir.PhysicalPath.TrimEnd (Path.DirectorySeparatorChar), true) == 0)
  735. continue;
  736. string newName;
  737. if (AllowOverwrite)
  738. newName = file.Name;
  739. else
  740. newName = GetNotDuplicatedFileName (destDir, Path.GetFileNameWithoutExtension (file.FullName), file.Extension);
  741. string newPath = Path.Combine (destDir.PhysicalPath, newName);
  742. file.CopyTo (newPath, AllowOverwrite);
  743. file.Delete ();
  744. }
  745. }
  746. return b;
  747. }
  748. private bool ProcessSelectedItemsCopyTo (FileManagerItemInfo destDir, FileManagerItemInfo [] items) {
  749. bool b = false;
  750. foreach (FileManagerItemInfo item in items) {
  751. if (item.Directory.Exists) {
  752. b = true;
  753. DirectoryInfo dir = item.Directory;
  754. string newName;
  755. if (AllowOverwrite && String.Compare (dir.Parent.FullName.TrimEnd (Path.DirectorySeparatorChar), destDir.PhysicalPath.TrimEnd (Path.DirectorySeparatorChar), true) != 0)
  756. newName = dir.Name;
  757. else
  758. newName = GetNotDuplicatedFolderName (destDir, dir.Name);
  759. string newPath = Path.Combine (destDir.PhysicalPath, newName);
  760. xDirectory.Copy (dir.FullName, newPath, true);
  761. }
  762. else if (item.File.Exists) {
  763. FileInfo file = item.File;
  764. string newName;
  765. if (AllowOverwrite && String.Compare (file.Directory.FullName.TrimEnd (Path.DirectorySeparatorChar), destDir.PhysicalPath.TrimEnd (Path.DirectorySeparatorChar), true) != 0)
  766. newName = file.Name;
  767. else
  768. newName = GetNotDuplicatedFileName (destDir, Path.GetFileNameWithoutExtension (file.FullName), file.Extension);
  769. string newPath = Path.Combine (destDir.PhysicalPath, newName);
  770. file.CopyTo (newPath, AllowOverwrite);
  771. }
  772. }
  773. return b;
  774. }
  775. private bool ProcessSelectedItemsDelete (FileManagerItemInfo [] items) {
  776. bool b = false;
  777. foreach (FileManagerItemInfo item in items) {
  778. if (item.File.Exists)
  779. item.File.Delete ();
  780. else if (item.Directory.Exists) {
  781. b = true;
  782. item.Directory.Delete (true);
  783. }
  784. }
  785. return b;
  786. }
  787. private String ClientRefreshEventReference { get { return ClientScriptObjectNamePrefix + ClientID + ".OnRefresh(context,null)"; } }
  788. private string ClientMessageEventReference (string message) {
  789. string clientMessage = message;
  790. if (clientMessage == null || clientMessage.Length == 0)
  791. clientMessage = GetResourceString ("CannotCompleteOperation", "Cannot Complete Operation.");
  792. return "alert(decodeURIComponent('" + EncodeURIComponent (clientMessage) + "'))";
  793. }
  794. private string ProcessRename (FileManagerItemInfo fileManagerItemInfo, string newName) {
  795. RenameCancelEventArgs cancelArg = new RenameCancelEventArgs ();
  796. cancelArg.FileManagerItem = fileManagerItemInfo;
  797. cancelArg.NewName = newName;
  798. OnItemRenaming (cancelArg);
  799. if (cancelArg.Cancel) {
  800. return ClientMessageEventReference (cancelArg.ClientMessage);
  801. }
  802. if (cancelArg.NewName == null || cancelArg.NewName.Length == 0 || cancelArg.NewName.StartsWith (".")) {
  803. return ClientMessageEventReference (GetResourceString ("MustTypeFileName", "You must type a file name."));
  804. }
  805. if (!Validate (cancelArg.NewName)) {
  806. return ClientMessageEventReference (GetResourceString ("NotAllowedCharacters", "A file name cannot contain any of the following characters: \\/:*?\"<>|"));
  807. }
  808. if (fileManagerItemInfo.File.Exists) {
  809. string newFileExt = Path.GetExtension (cancelArg.NewName).ToLower (CultureInfo.InvariantCulture).TrimStart ('.');
  810. if (newFileExt.Length == 0 ||
  811. HiddenFilesArray.Contains (newFileExt) ||
  812. ProhibitedFilesArray.Contains (newFileExt))
  813. cancelArg.NewName += fileManagerItemInfo.File.Extension;
  814. }
  815. FileManagerItemInfo renamedItem = ResolveFileManagerItemInfo (fileManagerItemInfo.FileManagerPath.Substring (0, fileManagerItemInfo.FileManagerPath.LastIndexOf ('/')) + "/" + cancelArg.NewName);
  816. if (renamedItem.Directory.Exists || renamedItem.File.Exists) {
  817. string fileExistsMessage = GetResourceString ("CannotRenameFile", "Cannot rename file: A file with the name you specified already exists. Specify a different file name.");
  818. return ClientMessageEventReference (fileExistsMessage);
  819. }
  820. bool b = false;
  821. if (fileManagerItemInfo.Directory.Exists) {
  822. b = true;
  823. fileManagerItemInfo.Directory.MoveTo (renamedItem.PhysicalPath);
  824. }
  825. else if (fileManagerItemInfo.File.Exists) {
  826. fileManagerItemInfo.File.MoveTo (renamedItem.PhysicalPath);
  827. }
  828. RenameEventArgs arg = new RenameEventArgs ();
  829. arg.FileManagerItem = renamedItem;
  830. OnItemRenamed (arg);
  831. StringBuilder sb = new StringBuilder ();
  832. if (b)
  833. AddFolderTreeRefreshEventReference (sb, _callbackControl.CurrentDirectory);
  834. sb.AppendLine (ClientRefreshEventReference);
  835. return sb.ToString ();
  836. }
  837. internal static bool Validate (string name) {
  838. // \/:*?"<>|
  839. return !name.Contains ("\\") &&
  840. !name.Contains ("/") &&
  841. !name.Contains (":") &&
  842. !name.Contains ("*") &&
  843. !name.Contains ("?") &&
  844. !name.Contains ("\"") &&
  845. !name.Contains ("<") &&
  846. !name.Contains (">") &&
  847. !name.Contains ("|");
  848. }
  849. internal static string DecodeURIComponent (string str) {
  850. string res = HttpUtility.UrlDecode (str);
  851. return res;
  852. }
  853. internal static string EncodeURIComponent (string str) {
  854. string res = HttpUtility.UrlEncode (str);
  855. res = res.Replace ("+", "%20");
  856. res = res.Replace ("'", "%27");
  857. return res;
  858. }
  859. internal static string DecodeURI (string str) {
  860. string res = HttpUtility.UrlDecode (str);
  861. return res;
  862. }
  863. internal static string EncodeURI (string str) {
  864. string res = HttpUtility.UrlPathEncode (str);
  865. res = res.Replace ("+", "%20");
  866. return res;
  867. }
  868. string ProcessFileViewNavigate (FileManagerItemInfo item) {
  869. if (item.Directory.Exists) {
  870. StringBuilder sb = new StringBuilder ();
  871. AddFolderTreeNavigateEventReference (sb, item);
  872. sb.AppendLine ("var dir = '" + EncodeURIComponent (item.FileManagerPath) + "'");
  873. sb.AppendLine ("WebForm_GetElementById(context.ClientID+'_Directory').value = dir;");
  874. sb.AppendLine ("var address = WebForm_GetElementById(context.ClientID+'_Address');");
  875. sb.AppendLine ("if(address) address.value = decodeURIComponent(dir);");
  876. sb.AppendLine (ClientRefreshEventReference);
  877. return sb.ToString ();
  878. }
  879. else if (item.File.Exists) {
  880. return ProcessExecuteCommand (new FileManagerItemInfo [] { item }, 0, 0);
  881. }
  882. else
  883. return ClientMessageEventReference (GetResourceString ("CannotFindFile", "Cannot find file, Make sure the path is correct."));
  884. }
  885. internal string [] GetPathHashCodes (string fileManagerPath) {
  886. fileManagerPath = VirtualPathUtility.RemoveTrailingSlash (fileManagerPath);
  887. List<string> list = new List<string> ();
  888. int index = fileManagerPath.IndexOf ('/', 1);
  889. while (index > 0) {
  890. list.Add (GetPathHashCode (fileManagerPath.Substring (0, index)));
  891. index = fileManagerPath.IndexOf ('/', index + 1);
  892. }
  893. list.Add (GetPathHashCode (fileManagerPath));
  894. return list.ToArray ();
  895. }
  896. internal string GetPathHashCode (string fileManagerPath) {
  897. return VirtualPathUtility.RemoveTrailingSlash (fileManagerPath).ToLower ().GetHashCode ().ToString ("x");
  898. }
  899. private string ProcessExecuteCommand (FileManagerItemInfo [] items, int group, int index) {
  900. if (items.Length == 0)
  901. return "";
  902. if (group == 0) {
  903. FileManagerItemInfo item = items [0];
  904. if (item.Directory.Exists)
  905. return ProcessFileViewNavigate (item);
  906. // Default Command
  907. if (index == -1)
  908. return ProcessOpenCommand (item);
  909. else if (index == -2)
  910. return ProcessDownloadCommand (item);
  911. FileType ft = GetFileType (item.File);
  912. if (ft == null || ft.Commands.Count <= index)
  913. return DownloadOnDoubleClick ? ProcessDownloadCommand (item) : ProcessOpenCommand (item);
  914. return ProcessCommand (item, ft.Commands [index]);
  915. }
  916. else {
  917. }
  918. return "";
  919. }
  920. private string ProcessDownloadCommand (FileManagerItemInfo item) {
  921. String script = Page.ClientScript.GetPostBackEventReference (this, "Download:" + EncodeURIComponent (item.FileManagerPath)) + ";" +
  922. "theForm.__EVENTTARGET.value = '';theForm.__EVENTARGUMENT.value = '';";
  923. return script;
  924. }
  925. private string ProcessCommand (FileManagerItemInfo item, FileManagerCommand fileManagerCommand) {
  926. ExecuteCommandEventArgs arg = new ExecuteCommandEventArgs (fileManagerCommand.CommandName, fileManagerCommand.CommandArgument);
  927. arg.Items.Add (item);
  928. //arg.Command = fileManagerCommand;
  929. OnExecuteCommand (arg);
  930. return arg.ClientScript;
  931. }
  932. private string ProcessOpenCommand (FileManagerItemInfo item) {
  933. StringBuilder sb = new StringBuilder ();
  934. if (ClientOpenItemFunction.Length > 0) {
  935. sb.AppendLine (ClientOpenItemFunction + "('" + EncodeURI (item.VirtualPath) + "')");
  936. }
  937. else {
  938. sb.AppendLine ("var href = '" + EncodeURIComponent (item.VirtualPath) + "';");
  939. sb.AppendLine ("window.open(decodeURIComponent(href),'_blank');");
  940. }
  941. return sb.ToString ();
  942. }
  943. string ResolveAbsolutePath (ref string fileManagerPath) {
  944. Regex reg = new Regex (@"^((?<rootPath>/[^/]+)|(\[(?<rootIndex>\d+)\]))(?<dirPath>/.*)?");
  945. Match match = reg.Match (fileManagerPath);
  946. if (!match.Success)
  947. goto _throw;
  948. RootDirectory rootDirectory;
  949. string dirPath = match.Groups ["dirPath"].Value;
  950. string rootPath = match.Groups ["rootPath"].Value;
  951. string rootIndex = match.Groups ["rootIndex"].Value;
  952. if (!String.IsNullOrEmpty (rootPath))
  953. rootDirectory = RootDirectories [rootPath.Substring (1)];
  954. else {
  955. int index = Int32.Parse (rootIndex);
  956. if (index >= RootDirectories.Count)
  957. goto _throw;
  958. rootDirectory = RootDirectories [index];
  959. rootPath = "/" + rootDirectory.TextInternal;
  960. }
  961. if (rootDirectory == null)
  962. goto _throw;
  963. dirPath = Normalize (dirPath);
  964. fileManagerPath = rootPath + dirPath;
  965. string rootVPath = VirtualPathUtility.RemoveTrailingSlash (ResolveUrl (rootDirectory.DirectoryPath));
  966. string vPath = rootVPath + dirPath;
  967. return vPath;
  968. _throw:
  969. throw new ArgumentException ("Invalid file manager path.");
  970. }
  971. public FileManagerItemInfo ResolveFileManagerItemInfo (string fileManagerPath) {
  972. string virtualPath = ResolveAbsolutePath (ref fileManagerPath);
  973. string phisicalPath = Page.MapPath (virtualPath);
  974. return new FileManagerItemInfo (fileManagerPath, virtualPath, phisicalPath);
  975. }
  976. internal string ProcessFileUpload (FileManagerItemInfo destDir, System.Web.HttpPostedFile uploadedFile) {
  977. string script;
  978. if (AllowUpload)
  979. ProcessFileUpload (destDir, uploadedFile, out script);
  980. else
  981. script = ClientMessageEventReference (null);
  982. return script;
  983. }
  984. internal bool ProcessFileUpload (FileManagerItemInfo destDir, System.Web.HttpPostedFile uploadedFile, out string script) {
  985. UploadFileCancelEventArgs cancelArg = new UploadFileCancelEventArgs ();
  986. cancelArg.DestinationDirectory = destDir;
  987. cancelArg.PostedFile = uploadedFile;
  988. OnFileUploading (cancelArg);
  989. if (cancelArg.Cancel) {
  990. script = ClientMessageEventReference (cancelArg.ClientMessage);
  991. return false;
  992. }
  993. string saveName = cancelArg.SaveName;
  994. string fileNameWithoutExtension = saveName.Substring (0, saveName.LastIndexOf ('.'));
  995. string extension = saveName.Substring (saveName.LastIndexOf ('.'));
  996. string ext = extension.ToLower (CultureInfo.InvariantCulture).TrimStart ('.');
  997. if (HiddenFilesArray.Contains (ext) ||
  998. ProhibitedFilesArray.Contains (ext)) {
  999. script = ClientMessageEventReference (null);
  1000. return false;
  1001. }
  1002. string newFileName = GetNotDuplicatedFileName (destDir, fileNameWithoutExtension, extension);
  1003. FileManagerItemInfo itemInfo = ResolveFileManagerItemInfo (VirtualPathUtility.AppendTrailingSlash (destDir.FileManagerPath) + newFileName);
  1004. uploadedFile.SaveAs (itemInfo.PhysicalPath);
  1005. UploadFileEventArgs arg = new UploadFileEventArgs ();
  1006. arg.UploadedFile = itemInfo;
  1007. OnFileUploaded (arg);
  1008. script = ClientRefreshEventReference;
  1009. return true;
  1010. }
  1011. private static string GetNotDuplicatedFileName (FileManagerItemInfo destDir, string fileNameWithoutExtension, string extension) {
  1012. string fileName = fileNameWithoutExtension;
  1013. int i = 1;
  1014. string originNewFileName = fileNameWithoutExtension;
  1015. while (File.Exists (Path.Combine (destDir.PhysicalPath, fileName + extension))) {
  1016. fileName = originNewFileName + "(" + i + ")";
  1017. i++;
  1018. }
  1019. return fileName + extension;
  1020. }
  1021. private static string GetNotDuplicatedFolderName (FileManagerItemInfo destDir, string folderName) {
  1022. string newFolderName = folderName;
  1023. int i = 1;
  1024. string originNewFolderName = folderName;
  1025. while (Directory.Exists (Path.Combine (destDir.PhysicalPath, newFolderName))) {
  1026. newFolderName = originNewFolderName + "(" + i + ")";
  1027. i++;
  1028. }
  1029. return newFolderName;
  1030. }
  1031. private string ProcessNewFolder (FileManagerItemInfo destDir) {
  1032. NewFolderCancelEventArgs cancelArg = new NewFolderCancelEventArgs ();
  1033. cancelArg.DestinationDirectory = destDir;
  1034. OnNewFolderCreating (cancelArg);
  1035. if (cancelArg.Cancel) {
  1036. return ClientMessageEventReference (cancelArg.ClientMessage);
  1037. }
  1038. string folderName = GetResourceString ("New_Folder_Name", "New Folder");
  1039. string newFolderName = GetNotDuplicatedFolderName (destDir, folderName);
  1040. FileManagerItemInfo itemInfo = ResolveFileManagerItemInfo (VirtualPathUtility.AppendTrailingSlash (destDir.FileManagerPath) + newFolderName);
  1041. itemInfo.EnsureDirectoryExists ();
  1042. NewFolderEventArgs arg = new NewFolderEventArgs ();
  1043. arg.NewFolder = itemInfo;
  1044. OnNewFolderCreated (arg);
  1045. StringBuilder sb = new StringBuilder ();
  1046. AddFolderTreeRefreshEventReference (sb, destDir);
  1047. sb.AppendLine (ClientRefreshEventReference);
  1048. return sb.ToString ();
  1049. }
  1050. void AddFolderTreeNavigateEventReference (StringBuilder sb, FileManagerItemInfo itemInfo) {
  1051. sb.AppendLine ("var folderTree = window['WFM_' + context.ClientID + '_FolderTree'];");
  1052. sb.AppendLine ("if(folderTree) {folderTree.Navigate (['" + String.Join ("','", GetPathHashCodes (itemInfo.FileManagerPath)) + "'],0);}");
  1053. }
  1054. void AddFolderTreeRefreshEventReference (StringBuilder sb, FileManagerItemInfo itemInfo) {
  1055. sb.AppendLine ("var folderTree = window['WFM_' + context.ClientID + '_FolderTree'];");
  1056. sb.AppendLine ("if(folderTree) {folderTree.Refresh ('" + GetPathHashCode (itemInfo.FileManagerPath) + "');}");
  1057. }
  1058. void AddFolderTreeRequireRefreshEventReference (StringBuilder sb, FileManagerItemInfo srcInfo, FileManagerItemInfo destInfo) {
  1059. sb.AppendLine ("var folderTree = window['WFM_' + context.ClientID + '_FolderTree'];");
  1060. sb.AppendLine ("if(folderTree) {folderTree.RequireRefresh (['" + GetPathHashCode (srcInfo.FileManagerPath) + "','" + String.Join ("','", GetPathHashCodes (destInfo.FileManagerPath)) + "']);}");
  1061. }
  1062. private string ProcessNewDocument (FileManagerItemInfo destDir, NewDocumentTemplate template) {
  1063. NewDocumentCancelEventArgs cancelArg = new NewDocumentCancelEventArgs ();
  1064. cancelArg.DestinationDirectory = destDir;
  1065. cancelArg.Template = template;
  1066. OnNewDocumentCreating (cancelArg);
  1067. if (cancelArg.Cancel) {
  1068. return ClientMessageEventReference (cancelArg.ClientMessage);
  1069. }
  1070. if (template.MasterFileUrl.Length == 0)
  1071. return "";
  1072. FileInfo masterFile = new FileInfo (Page.MapPath (template.MasterFileUrl));
  1073. if (!masterFile.Exists)
  1074. return "";
  1075. string newFileName = template.NewFileName;
  1076. if (newFileName.Length == 0)
  1077. newFileName = template.Name;
  1078. int i = 1;
  1079. string originNewFileName = newFileName;
  1080. while (File.Exists (Path.Combine (destDir.PhysicalPath, newFileName + masterFile.Extension))) {
  1081. newFileName = originNewFileName + "(" + i + ")";
  1082. i++;
  1083. }
  1084. newFileName = newFileName + masterFile.Extension;
  1085. FileManagerItemInfo itemInfo = ResolveFileManagerItemInfo (VirtualPathUtility.AppendTrailingSlash (destDir.FileManagerPath) + newFileName);
  1086. FileInfo newDocument = masterFile.CopyTo (itemInfo.PhysicalPath);
  1087. NewDocumentEventArgs arg = new NewDocumentEventArgs ();
  1088. arg.Template = template;
  1089. arg.NewDocument = itemInfo;
  1090. OnNewDocumentCreated (arg);
  1091. return ClientRefreshEventReference;
  1092. }
  1093. #endregion
  1094. Hashtable fileMangerControls = new Hashtable ();
  1095. internal void RegisterComponent (FileManagerControlBase control) {
  1096. fileMangerControls [control.ClientID] = control;
  1097. }
  1098. internal const char EventArgumentSplitter = ':';
  1099. internal string GetItemSmallImage (FileSystemInfo fsi) {
  1100. DirectoryInfo dir = fsi as DirectoryInfo;
  1101. if (dir != null)
  1102. return GetFolderSmallImage (dir);
  1103. else
  1104. return GetFileSmallImage ((FileInfo) fsi);
  1105. }
  1106. SpecialFolder GetSpecialFolder (DirectoryInfo dir) {
  1107. if (_specialFolderPaths == null)
  1108. InitSpecialFolders ();
  1109. return (SpecialFolder) _specialFolderPaths [dir.FullName];
  1110. }
  1111. [System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "dir")]
  1112. internal string GetFolderSmallImage (DirectoryInfo dir) {
  1113. if (dir == null)
  1114. return _defaultFolderSmallImage;
  1115. SpecialFolder folder = GetSpecialFolder (dir);
  1116. if (folder != null && folder.SmallImageUrl.Length > 0)
  1117. return ResolveUrl (folder.SmallImageUrl);
  1118. return _defaultFolderSmallImage;
  1119. }
  1120. internal string GetFolderSmallImage () {
  1121. return GetFolderSmallImage (null);
  1122. }
  1123. internal string GetFileSmallImage () {
  1124. return GetFileSmallImage (null);
  1125. }
  1126. internal string GetFileSmallImage (FileInfo file) {
  1127. if (file == null)
  1128. return _defaultFileSmallImage;
  1129. FileType fileType = GetFileType (file);
  1130. if (fileType != null && fileType.SmallImageUrl.Length > 0)
  1131. return ResolveUrl (fileType.SmallImageUrl);
  1132. return _defaultFileSmallImage;
  1133. }
  1134. internal string GetItemLargeImage (FileSystemInfo fsi) {
  1135. DirectoryInfo dir = fsi as DirectoryInfo;
  1136. if (dir != null)
  1137. return GetFolderLargeImage (dir);
  1138. else
  1139. return GetFileLargeImage ((FileInfo) fsi);
  1140. }
  1141. internal string GetItemThumbnailImage (FileSystemInfo fsi, FileManagerItemInfo currentDirectory) {
  1142. FileInfo file = fsi as FileInfo;
  1143. if (file == null)
  1144. return GetFolderLargeImage ((DirectoryInfo) fsi);
  1145. if (IsImage (file))
  1146. return ResolveUrl ("~/" + ThumbnailHandler + "?" + HttpUtility.UrlEncode (currentDirectory.VirtualPath + "/" + file.Name));
  1147. return GetFileLargeImage (file);
  1148. }
  1149. bool IsImage (FileInfo file) {
  1150. return _imageExtension [file.Extension] != null;
  1151. }
  1152. private string GetFileLargeImage (FileInfo file) {
  1153. if (file == null)
  1154. return _defaultFileLargeImage;
  1155. FileType fileType = GetFileType (file);
  1156. if (fileType != null && fileType.LargeImageUrl.Length > 0)
  1157. return ResolveUrl (fileType.LargeImageUrl);
  1158. return _defaultFileLargeImage;
  1159. }
  1160. private string GetFileLargeImage () {
  1161. return GetFileLargeImage (null);
  1162. }
  1163. [System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "dir")]
  1164. private string GetFolderLargeImage (DirectoryInfo dir) {
  1165. if (dir == null)
  1166. return _defaultFolderLargeImage;
  1167. SpecialFolder folder = GetSpecialFolder (dir);
  1168. if (folder != null && folder.LargeImageUrl.Length > 0)
  1169. return ResolveUrl (folder.LargeImageUrl);
  1170. return _defaultFolderLargeImage;
  1171. }
  1172. private string GetRootFolderLargeImage (RootDirectory rootDir) {
  1173. if (rootDir == null)
  1174. return _defaultRootFolderLargeImage;
  1175. if (rootDir.LargeImageUrl.Length > 0)
  1176. return rootDir.LargeImageUrl;
  1177. return _defaultRootFolderLargeImage;
  1178. }
  1179. internal string GetRootFolderSmallImage () {
  1180. return GetRootFolderSmallImage (null);
  1181. }
  1182. internal string GetRootFolderSmallImage (RootDirectory rootDir) {
  1183. if (rootDir == null)
  1184. return _defaultRootFolderSmallImage;
  1185. if (rootDir.SmallImageUrl.Length > 0)
  1186. return rootDir.SmallImageUrl;
  1187. return _defaultRootFolderSmallImage;
  1188. }
  1189. internal string GetToolbarImage (ToolbarImages image) {
  1190. EnsureToolbarImages ();
  1191. return _toolbarImages [image];
  1192. }
  1193. internal void RegisterResources () {
  1194. string initScript = "var " + ClientScriptObjectNamePrefix + ClientID + "DeleteConfirm" + "='" + EncodeURIComponent (GetResourceString ("DeleteConfirm", "Are you sure you want to delete selected items?")) + "';\r\n" +
  1195. "var " + ClientScriptObjectNamePrefix + ClientID + "SelectDestination" + "='" + EncodeURIComponent (GetResourceString ("SelectDestination", "Select destination directory")) + "';\r\n";
  1196. Page.ClientScript.RegisterStartupScript (typeof (FileManagerController), ClientID + "Resources", initScript, true);
  1197. }
  1198. #region IPostBackEventHandler Members
  1199. void IPostBackEventHandler.RaisePostBackEvent (string eventArgument) {
  1200. RaisePostBackEvent (eventArgument);
  1201. }
  1202. void RaisePostBackEvent (string eventArgument) {
  1203. string [] args = eventArgument.Split (new char [] { ':' }, 2);
  1204. switch (args [0]) {
  1205. case "Download":
  1206. FileManagerItemInfo fmi = ResolveFileManagerItemInfo (DecodeURIComponent (args [1]));
  1207. var e= new DownloadFileCancelEventArgs() {DownloadFile = fmi};
  1208. OFileDownload(e);
  1209. if (!e.Cancel)
  1210. {
  1211. string file = fmi.PhysicalPath;
  1212. if (File.Exists(file))
  1213. {
  1214. Page.Response.Clear();
  1215. Page.Response.ContentType = "application/octet-stream";
  1216. Page.Response.AddHeader("Content-Disposition",
  1217. "attachment;filename=" + EncodeURIComponent(Path.GetFileName(file)));
  1218. Page.Response.Flush();
  1219. Page.Response.WriteFile(file);
  1220. }
  1221. Page.Response.End ();
  1222. }
  1223. break;
  1224. }
  1225. }
  1226. private void OFileDownload(DownloadFileCancelEventArgs e)
  1227. {
  1228. if (FileDownload != null)
  1229. FileDownload(this, e);
  1230. }
  1231. #endregion
  1232. protected override object SaveViewState () {
  1233. object [] states = new object [5];
  1234. states [0] = base.SaveViewState ();
  1235. states [1] = ((IStateManager) RootDirectories).SaveViewState ();
  1236. states [2] = ((IStateManager) FileTypes).SaveViewState ();
  1237. states [3] = ((IStateManager) Templates).SaveViewState ();
  1238. states [4] = ((IStateManager) SpecialFolders).SaveViewState ();
  1239. for (int i = 0; i < states.Length; i++) {
  1240. if (states [i] != null)
  1241. return states;
  1242. }
  1243. return null;
  1244. }
  1245. protected override void LoadViewState (object savedState) {
  1246. if (savedState == null)
  1247. return;
  1248. object [] states = (object []) savedState;
  1249. base.LoadViewState (states [0]);
  1250. ((IStateManager) RootDirectories).LoadViewState (states [1]);
  1251. ((IStateManager) FileTypes).LoadViewState (states [2]);
  1252. ((IStateManager) Templates).LoadViewState (states [3]);
  1253. ((IStateManager) SpecialFolders).LoadViewState (states [4]);
  1254. }
  1255. protected override void TrackViewState () {
  1256. base.TrackViewState ();
  1257. ((IStateManager) RootDirectories).TrackViewState ();
  1258. ((IStateManager) FileTypes).TrackViewState ();
  1259. ((IStateManager) Templates).TrackViewState ();
  1260. ((IStateManager) SpecialFolders).TrackViewState ();
  1261. }
  1262. #region ICallbackEventHandler Members
  1263. string ICallbackEventHandler.GetCallbackResult () {
  1264. return GetCallbackResult ();
  1265. }
  1266. void ICallbackEventHandler.RaiseCallbackEvent (string eventArgument) {
  1267. RaiseCallbackEvent (eventArgument);
  1268. }
  1269. #endregion
  1270. static char [] path_sep = { '/' };
  1271. static string Normalize (string path) {
  1272. if (path.Length == 1) // '/'
  1273. return path;
  1274. path = Canonize (path);
  1275. int dotPos = path.IndexOf ('.');
  1276. while (dotPos >= 0) {
  1277. if (++dotPos == path.Length)
  1278. break;
  1279. char nextChar = path [dotPos];
  1280. if ((nextChar == '/') || (nextChar == '.'))
  1281. break;
  1282. dotPos = path.IndexOf ('.', dotPos);
  1283. }
  1284. if (dotPos < 0)
  1285. return path;
  1286. bool ends_with_slash = false;
  1287. if (path [path.Length - 1] == '/')
  1288. ends_with_slash = true;
  1289. string [] parts = path.Split (path_sep, StringSplitOptions.RemoveEmptyEntries);
  1290. int end = parts.Length;
  1291. int dest = 0;
  1292. for (int i = 0; i < end; i++) {
  1293. string current = parts [i];
  1294. if (current == ".")
  1295. continue;
  1296. if (current == "..") {
  1297. dest--;
  1298. if (dest < 0)
  1299. dest = 0;
  1300. continue;
  1301. }
  1302. parts [dest] = current;
  1303. dest++;
  1304. }
  1305. StringBuilder str = new StringBuilder ();
  1306. for (int i = 0; i < dest; i++) {
  1307. str.Append ('/');
  1308. str.Append (parts [i]);
  1309. }
  1310. if (str.Length > 0) {
  1311. if (ends_with_slash)
  1312. str.Append ('/');
  1313. }
  1314. else {
  1315. return "/";
  1316. }
  1317. return str.ToString ();
  1318. }
  1319. static string Canonize (string path) {
  1320. int index = -1;
  1321. for (int i = 0; i < path.Length; i++) {
  1322. if ((path [i] == '\\') || (path [i] == '/' && (i + 1) < path.Length && (path [i + 1] == '/' || path [i + 1] == '\\'))) {
  1323. index = i;
  1324. break;
  1325. }
  1326. }
  1327. if (index < 0)
  1328. return path;
  1329. StringBuilder sb = new StringBuilder (path.Length);
  1330. sb.Append (path, 0, index);
  1331. for (int i = index; i < path.Length; i++) {
  1332. if (path [i] == '\\' || path [i] == '/') {
  1333. int next = i + 1;
  1334. if (next < path.Length && (path [next] == '\\' || path [next] == '/'))
  1335. continue;
  1336. sb.Append ('/');
  1337. }
  1338. else {
  1339. sb.Append (path [i]);
  1340. }
  1341. }
  1342. return sb.ToString ();
  1343. }
  1344. }
  1345. }