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