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

/BlogEngine/BlogEngine.NET/admin/Posts/Add_entry.aspx.cs

#
C# | 502 lines | 317 code | 73 blank | 112 comment | 37 complexity | 88b413048206fea8ad234491862d0276 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, BSD-3-Clause
  1. namespace Admin.Posts
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Web;
  8. using System.Web.Security;
  9. using System.Web.UI;
  10. using System.Web.UI.HtmlControls;
  11. using System.Web.UI.WebControls;
  12. using BlogEngine.Core;
  13. using Resources;
  14. using Page = System.Web.UI.Page;
  15. using App_Code;
  16. using BlogEngine.Core.Providers;
  17. /// <summary>
  18. /// The AddEntry.
  19. /// </summary>
  20. public partial class AddEntry : Page, ICallbackEventHandler
  21. {
  22. #region Constants and Fields
  23. /// <summary>
  24. /// The raw editor cookie.
  25. /// </summary>
  26. private const string RawEditorCookie = "useraweditor";
  27. /// <summary>
  28. /// The callback.
  29. /// </summary>
  30. private string callback;
  31. /// <summary>
  32. /// URL of the current post
  33. /// </summary>
  34. protected string PostUrl
  35. {
  36. get
  37. {
  38. if (!String.IsNullOrEmpty(Request.QueryString["id"]) && Request.QueryString["id"].Length == 36)
  39. {
  40. var id = new Guid(Request.QueryString["id"]);
  41. var p = Post.GetPost(id);
  42. return p.RelativeLink;
  43. }
  44. return string.Empty;
  45. }
  46. }
  47. #endregion
  48. #region Implemented Interfaces
  49. #region ICallbackEventHandler
  50. /// <summary>
  51. /// Returns the results of a callback event that targets a control.
  52. /// </summary>
  53. /// <returns>
  54. /// The result of the callback.
  55. /// </returns>
  56. public string GetCallbackResult()
  57. {
  58. return callback;
  59. }
  60. /// <summary>
  61. /// Processes a callback event that targets a control.
  62. /// </summary>
  63. /// <param name="eventArgument">
  64. /// A string that represents an event argument to pass to the event handler.
  65. /// </param>
  66. public void RaiseCallbackEvent(string eventArgument)
  67. {
  68. if (eventArgument.StartsWith("_autosave"))
  69. {
  70. var fields = eventArgument.Replace("_autosave", string.Empty).Split(
  71. new[] { ";|;" }, StringSplitOptions.None);
  72. Session["content"] = fields[0];
  73. Session["title"] = fields[1];
  74. Session["description"] = fields[2];
  75. Session["slug"] = fields[3];
  76. Session["tags"] = fields[4];
  77. }
  78. else
  79. {
  80. callback = Utils.RemoveIllegalCharacters(eventArgument.Trim());
  81. }
  82. }
  83. #endregion
  84. #endregion
  85. #region Methods
  86. /// <summary>
  87. /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
  88. /// </summary>
  89. /// <param name="e">
  90. /// The <see cref="T:System.EventArgs"/> object that contains the event data.
  91. /// </param>
  92. protected override void OnLoad(EventArgs e)
  93. {
  94. base.OnLoad(e);
  95. txtTitle.Focus();
  96. }
  97. /// <summary>
  98. /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event to initialize the page.
  99. /// </summary>
  100. /// <param name="e">
  101. /// An <see cref="T:System.EventArgs"/> that contains the event data.
  102. /// </param>
  103. protected override void OnInit(EventArgs e)
  104. {
  105. WebUtils.CheckRightsForAdminPostPages(false);
  106. MaintainScrollPositionOnPostBack = true;
  107. BindTags();
  108. BindUsers();
  109. Page.Title = labels.add_Entry;
  110. Page.ClientScript.GetCallbackEventReference(this, "title", "ApplyCallback", "slug");
  111. if (!String.IsNullOrEmpty(Request.QueryString["id"]) && Request.QueryString["id"].Length == 36)
  112. {
  113. var id = new Guid(Request.QueryString["id"]);
  114. Page.Title = string.Format("{0} {1}", labels.edit, labels.post);
  115. BindPost(id);
  116. BindCategories(id);
  117. }
  118. else
  119. {
  120. BindCategories(Guid.Empty);
  121. PreSelectAuthor(Page.User.Identity.Name);
  122. txtDate.Text = DateTime.Now.AddHours(BlogSettings.Instance.Timezone).ToString("yyyy-MM-dd");
  123. txtTime.Text = DateTime.Now.AddHours(BlogSettings.Instance.Timezone).ToString("HH\\:mm");
  124. cbEnableComments.Checked = BlogSettings.Instance.IsCommentsEnabled;
  125. cbPublish.Checked = Security.IsAuthorizedTo(Rights.PublishOwnPosts);
  126. if (Session["content"] != null)
  127. {
  128. txtContent.Text = Session["content"].ToString();
  129. txtRawContent.Text = txtContent.Text;
  130. txtTitle.Text = Session["title"].ToString();
  131. txtDescription.Text = Session["description"].ToString();
  132. txtSlug.Text = Session["slug"].ToString();
  133. txtTags.Text = Session["tags"].ToString();
  134. }
  135. BindBookmarklet();
  136. }
  137. if (!Security.IsAuthorizedTo(Rights.EditOtherUsersPosts))
  138. {
  139. ddlAuthor.Enabled = false;
  140. }
  141. cbEnableComments.Enabled = BlogSettings.Instance.IsCommentsEnabled;
  142. if (Request.Cookies[RawEditorCookie] != null)
  143. {
  144. txtRawContent.Visible = true;
  145. txtContent.Visible = false;
  146. cbUseRaw.Checked = true;
  147. }
  148. btnCategory.Click += BtnCategoryClick;
  149. btnUploadFile.Click += BtnUploadFileClick;
  150. btnUploadImage.Click += BtnUploadImageClick;
  151. btnUploadVideo.Click += BtnUploadVideoClick;
  152. valExist.ServerValidate += ValExistServerValidate;
  153. cbUseRaw.CheckedChanged += CbUseRawCheckedChanged;
  154. base.OnInit(e);
  155. }
  156. /// <summary>
  157. /// The bind bookmarklet.
  158. /// </summary>
  159. private void BindBookmarklet()
  160. {
  161. if (Request.QueryString["title"] == null || Request.QueryString["url"] == null)
  162. {
  163. return;
  164. }
  165. var title = Request.QueryString["title"];
  166. var url = Request.QueryString["url"];
  167. txtTitle.Text = title;
  168. txtContent.Text = string.Format("<p><a href=\"{0}\" title=\"{1}\">{1}</a></p>", url, title);
  169. }
  170. /// <summary>
  171. /// The bind categories.
  172. /// </summary>
  173. private void BindCategories(Guid postId)
  174. {
  175. string catHtml = "";
  176. var post = postId == Guid.Empty ? null : Post.GetPost(postId);
  177. foreach (var cat in Category.Categories)
  178. {
  179. string chk = "";
  180. if(post != null && post.Categories.Contains(cat))
  181. chk = "checked=\"checked\"";
  182. catHtml += string.Format("<input type=\"checkbox\" {0} id=\"{1}\">", chk, cat.Id);
  183. catHtml += string.Format("<label>{0}</label><br/>", Server.HtmlEncode(cat.Title));
  184. }
  185. cblCategories.InnerHtml = catHtml;
  186. }
  187. /// <summary>
  188. /// The bind post.
  189. /// </summary>
  190. /// <param name="postId">
  191. /// The post id.
  192. /// </param>
  193. private void BindPost(Guid postId)
  194. {
  195. var post = Post.GetPost(postId);
  196. if (post == null || !post.CanUserEdit)
  197. {
  198. Response.Redirect(Request.Path);
  199. }
  200. if (post != null)
  201. {
  202. txtTitle.Text = post.Title;
  203. txtContent.Text = post.Content;
  204. txtRawContent.Text = post.Content;
  205. txtDescription.Text = post.Description;
  206. txtDate.Text = post.DateCreated.ToString("yyyy-MM-dd");
  207. txtTime.Text = post.DateCreated.ToString("HH\\:mm");
  208. cbEnableComments.Checked = post.HasCommentsEnabled;
  209. cbPublish.Checked = post.IsPublished;
  210. txtSlug.Text = Utils.RemoveIllegalCharacters(post.Slug);
  211. PreSelectAuthor(post.Author);
  212. var tags = new string[post.Tags.Count];
  213. for (var i = 0; i < post.Tags.Count; i++)
  214. {
  215. tags[i] = post.Tags[i];
  216. }
  217. txtTags.Text = string.Join(",", tags);
  218. }
  219. }
  220. /// <summary>
  221. /// The bind tags.
  222. /// </summary>
  223. private void BindTags()
  224. {
  225. var col = new List<string>();
  226. foreach (var tag in from post in Post.Posts from tag in post.Tags where !col.Contains(tag) select tag)
  227. {
  228. col.Add(tag);
  229. }
  230. col.Sort(String.Compare);
  231. foreach (var a in col.Select(tag => new HtmlAnchor { HRef = "javascript:void(0)", InnerText = tag }))
  232. {
  233. a.Attributes.Add("onclick", "AddTag(this)");
  234. phTags.Controls.Add(a);
  235. }
  236. }
  237. /// <summary>
  238. /// The bind users.
  239. /// </summary>
  240. private void BindUsers()
  241. {
  242. foreach (MembershipUser user in Membership.GetAllUsers())
  243. {
  244. ddlAuthor.Items.Add(user.UserName);
  245. }
  246. }
  247. /// <summary>
  248. /// The pre select author.
  249. /// </summary>
  250. /// <param name="author">
  251. /// The author.
  252. /// </param>
  253. private void PreSelectAuthor(string author)
  254. {
  255. ddlAuthor.ClearSelection();
  256. foreach (ListItem item in
  257. ddlAuthor.Items.Cast<ListItem>().Where(item => item.Text.Equals(author, StringComparison.OrdinalIgnoreCase)))
  258. {
  259. item.Selected = true;
  260. break;
  261. }
  262. }
  263. /// <summary>
  264. /// Sizes the format.
  265. /// </summary>
  266. /// <param name="size">
  267. /// The string size.
  268. /// </param>
  269. /// <param name="formatString">
  270. /// The format string.
  271. /// </param>
  272. /// <returns>
  273. /// The string.
  274. /// </returns>
  275. private static string SizeFormat(float size, string formatString)
  276. {
  277. if (size < 1024)
  278. {
  279. return string.Format("{0} bytes", size.ToString(formatString));
  280. }
  281. if (size < Math.Pow(1024, 2))
  282. {
  283. return string.Format("{0} kb", (size / 1024).ToString(formatString));
  284. }
  285. if (size < Math.Pow(1024, 3))
  286. {
  287. return string.Format("{0} mb", (size / Math.Pow(1024, 2)).ToString(formatString));
  288. }
  289. if (size < Math.Pow(1024, 4))
  290. {
  291. return string.Format("{0} gb", (size / Math.Pow(1024, 3)).ToString(formatString));
  292. }
  293. return size.ToString(formatString);
  294. }
  295. /// <summary>
  296. /// Uploads the specified virtual folder.
  297. /// </summary>
  298. /// <param name="virtualFolder">The virtual folder.</param>
  299. /// <param name="control">The control.</param>
  300. /// <param name="fileName">Name of the file.</param>
  301. private void Upload(string virtualFolder, FileUpload control, string fileName)
  302. {
  303. return;
  304. }
  305. /// <summary>
  306. /// Handles the Click event of the btnCategory control.
  307. /// </summary>
  308. /// <param name="sender">The source of the event.</param>
  309. /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
  310. private void BtnCategoryClick(object sender, EventArgs e)
  311. {
  312. if (!Page.IsValid)
  313. {
  314. return;
  315. }
  316. var cat = new Category(txtCategory.Text, string.Empty);
  317. cat.Save();
  318. var item = new ListItem(Server.HtmlEncode(txtCategory.Text), cat.Id.ToString())
  319. {
  320. Selected = true
  321. };
  322. string catHtml = string.Format("<input type=\"checkbox\" id=\"{0}\">", cat.Id);
  323. catHtml += string.Format("<label>{0}</label><br/>", Server.HtmlEncode(cat.Title));
  324. cblCategories.InnerHtml += catHtml;
  325. string postId = Request.QueryString["id"];
  326. Post post = null;
  327. // Security Rights validation
  328. if (postId == null)
  329. {
  330. Security.DemandUserHasRight(Rights.CreateNewPosts, true);
  331. post = new Post();
  332. }
  333. else
  334. {
  335. post = Post.GetPost(new Guid(postId));
  336. if (post.CurrentUserOwns)
  337. {
  338. Security.DemandUserHasRight(Rights.EditOwnPosts, true);
  339. }
  340. else
  341. {
  342. Security.DemandUserHasRight(Rights.EditOtherUsersPosts, true);
  343. }
  344. }
  345. }
  346. /// <summary>
  347. /// Handles the Click event of the btnUploadFile control.
  348. /// </summary>
  349. /// <param name="sender">The source of the event.</param>
  350. /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
  351. private void BtnUploadFileClick(object sender, EventArgs e)
  352. {
  353. var dirName = string.Format("/{0}/{1}", DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"));
  354. var dir = BlogService.GetDirectory(dirName);
  355. var file = BlogService.UploadFile(txtUploadFile.PostedFile.InputStream, txtUploadFile.PostedFile.FileName, dir, true);
  356. txtContent.Text += string.Format("<p><a href=\"{0}\">{1}</a></p>", file.FileDownloadPath, file.FileDescription);
  357. txtRawContent.Text += string.Format("<p><a href=\"{0}\">{1}</a></p>", file.FileDownloadPath, file.FileDescription);
  358. }
  359. /// <summary>
  360. /// Handles the Click event of the btnUploadImage control.
  361. /// </summary>
  362. /// <param name="sender">The source of the event.</param>
  363. /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
  364. protected void BtnUploadImageClick(object sender, EventArgs e)
  365. {
  366. var dirName = string.Format("/{0}/{1}", DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"));
  367. var dir = BlogService.GetDirectory(dirName);
  368. var file = BlogService.UploadFile(txtUploadImage.PostedFile.InputStream, txtUploadImage.PostedFile.FileName, dir, true);
  369. txtContent.Text += string.Format("<img src=\"{0}\" />", file.AsImage.ImageUrl);
  370. txtRawContent.Text += string.Format("<img src=\"{0}\" />", file.AsImage.ImageUrl);
  371. }
  372. /// <summary>
  373. /// Handles the Click event of the btnUploadVideo control.
  374. /// </summary>
  375. /// <param name="sender">The source of the event.</param>
  376. /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
  377. protected void BtnUploadVideoClick(object sender, EventArgs e) {
  378. // default media folder
  379. var mediaFolder = "media";
  380. // get the mediaplayer extension and use it's folder
  381. var mediaPlayerExtension = BlogEngine.Core.Web.Extensions.ExtensionManager.GetExtension("MediaElementPlayer");
  382. mediaFolder = mediaPlayerExtension.Settings[0].GetSingleValue("folder");
  383. var folder = Utils.RelativeWebRoot + mediaFolder + "/";
  384. var fileName = txtUploadVideo.FileName;
  385. Upload(folder, txtUploadVideo, fileName);
  386. var shortCode = "[video src=\"" + fileName + "\"]";
  387. txtContent.Text += shortCode;
  388. txtRawContent.Text += shortCode;
  389. }
  390. /// <summary>
  391. /// Handles the CheckedChanged event of the cbUseRaw control.
  392. /// </summary>
  393. /// <param name="sender">The source of the event.</param>
  394. /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
  395. private void CbUseRawCheckedChanged(object sender, EventArgs e)
  396. {
  397. if (cbUseRaw.Checked)
  398. {
  399. txtRawContent.Text = txtContent.Text;
  400. var cookie = new HttpCookie(RawEditorCookie, "1") { Expires = DateTime.Now.AddYears(3) };
  401. Response.Cookies.Add(cookie);
  402. }
  403. else
  404. {
  405. txtContent.Text = txtRawContent.Text;
  406. if (Request.Cookies[RawEditorCookie] != null)
  407. {
  408. var cookie = new HttpCookie(RawEditorCookie) { Expires = DateTime.Now.AddYears(-3) };
  409. Response.Cookies.Add(cookie);
  410. }
  411. }
  412. txtRawContent.Visible = cbUseRaw.Checked;
  413. txtContent.Visible = !cbUseRaw.Checked;
  414. // Response.Redirect(Request.RawUrl);
  415. }
  416. /// <summary>
  417. /// Handles the ServerValidate event of the valExist control.
  418. /// </summary>
  419. /// <param name="source">The source of the event.</param>
  420. /// <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
  421. private void ValExistServerValidate(object source, ServerValidateEventArgs args)
  422. {
  423. args.IsValid =
  424. !Category.Categories.Any(
  425. cat => cat.Title.Equals(txtCategory.Text.Trim(), StringComparison.OrdinalIgnoreCase));
  426. }
  427. #endregion
  428. }
  429. }