Skip to content

Instantly share code, notes, and snippets.

@jammykam
Last active December 17, 2017 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jammykam/54d6af46593fa3b827b4 to your computer and use it in GitHub Desktop.
Save jammykam/54d6af46593fa3b827b4 to your computer and use it in GitHub Desktop.
Restrict Media Upload in Content Editor in Sitecore 7.2
using LaunchSitecore.Applications;
using Sitecore;
using Sitecore.Exceptions;
using Sitecore.Pipelines.Attach;
using System;
using System.Collections.Generic;
namespace LaunchSitecore.Pipelines.Attach
{
public class ImageCheckSize
{
public void Process(AttachArgs args)
{
if (!ImageSettings.IsRestrictedExtension(args.File.FileName))
return;
if (args.MediaItem.FileBased || args.File.InputStream.Length <= ImageSettings.MaxImageSizeInDatabase)
return;
// Unused, message displayed using Sheer.Alert from AttachPage.cs
throw new ClientAlertException(String.Format("The image is too big to be attached. The maximum size of a file that can be uploaded is {0}.", MainUtil.FormatSize(ImageSettings.MaxImageSizeInDatabase)));
}
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<xamlControls
xmlns:x="http://www.sitecore.net/xaml"
xmlns:ajax="http://www.sitecore.net/ajax"
xmlns:rest="http://www.sitecore.net/rest"
xmlns:javascript="http://www.sitecore.net/javascript"
xmlns:r="http://www.sitecore.net/renderings"
xmlns:xmlcontrol="http://www.sitecore.net/xmlcontrols"
xmlns:p="http://schemas.sitecore.net/Visual-Studio-Intellisense"
xmlns:asp="http://www.sitecore.net/microsoft/webcontrols"
xmlns:html="http://www.sitecore.net/microsoft/htmlcontrols"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- place this file in: /sitecore/shell/Applications/FlashUpload/Attach/Attach.xaml.xml -->
<Sitecore.Shell.Applications.FlashUpload.Attach x:inherits="LaunchSitecore.Applications.AttachPage,LaunchSitecore">
<Sitecore.Controls.DialogPage Header="Attach a File" Icon="Business/32x32/Paperclip.png" Text="Select a file. When done click the Upload button." OKButton="Upload" runat="server">
<AjaxScriptManager runat="server"/>
<ContinuationManager runat="server" />
<Script runat="server" Src="/sitecore/shell/controls/lib/YUIupload/yahoo-dom-event/yahoo-dom-event.js" />
<Script runat="server" Src="/sitecore/shell/controls/lib/YUIupload/element/element-beta-min.js" />
<Script runat="server" Src="/sitecore/shell/controls/lib/YUIupload/uploader/uploader-experimental-min.js" />
<Script runat="server" Src="/sitecore/shell/applications/flashupload/attach/attach.js" />
<Style runat="server">
.filename {
height: 22px;
width: 100%;
border: solid 1px #969696;
background: white;
margin-right: 4px;
position: relative;
}
#FilenameText {
padding: 2px;
padding-left: 4px;
display: block;
}
.progress {
width: 0%;
height: 20px;
position: absolute;
background: #eaeaea;
z-index: -1;
}
#Browse {
margin-left: 4px;
}
</Style>
<html:HtmlInputHidden class="uploadID" id="InputUploadID" runat="server" />
<html:HtmlInputHidden class="uploadSessionID" id="UploadSessionID" runat="server" />
<html:HtmlInputHidden class="uploadSessionID1" id="UploadSessionID1" runat="server" />
<GridPanel runat="server" Width="100%">
<Literal runat="server" Text="Filename:" />
<GridPanel runat="server" Columns="2">
<Border runat="server" class="filename" GridPanel.Width="100%">
<Border runat="server" class="progress" />
<ThemedImage runat="server" Src="People/16x16/clock.png" class="progressImage" style="position: absolute; right: 2px; top: 2px; display: none" />
<ThemedImage runat="server" Src="Applications/16x16/check2.png" class="doneImage" style="position: absolute; right: 2px; top: 2px; display: none" />
<span id="FilenameText"></span>
</Border>
<Border runat="server" id="BrowseContainer" GridPanel.Width="72px" style="position:relative">
<Button runat="server" Header="Browse" ID="Browse" style="z-index:1"/>
<div id="BrowseOverlay" style="width:82px;height:22px;position:absolute;top:0;left:0;z-index:2" />
</Border>
</GridPanel>
<Literal runat="server" ID="Message" />
</GridPanel>
</Sitecore.Controls.DialogPage>
</Sitecore.Shell.Applications.FlashUpload.Attach>
</xamlControls>
using Sitecore;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
using Sitecore.Web.UI.Sheer;
namespace LaunchSitecore.Applications
{
public class AttachPage : Sitecore.Shell.Applications.FlashUpload.Attach.AttachPage
{
protected new void OnQueued(string filename, string lengthString)
{
Assert.ArgumentNotNullOrEmpty(filename, "filename");
Assert.ArgumentNotNullOrEmpty(lengthString, "lengthString");
int num = int.Parse(lengthString);
long maximumImageUploadSize = ImageSettings.MaxImageSizeInDatabase;
if (ImageSettings.IsRestrictedExtension(filename) && num > maximumImageUploadSize)
{
string text = Translate.Text("The image \"{0}\" is too big to be uploaded.\n\nThe maximum image size that can be uploaded is {1}.", new object[] { filename, MainUtil.FormatSize(maximumImageUploadSize) });
this.WarningMessage = text;
SheerResponse.Alert(text, new string[0]);
}
else
{
base.OnQueued(filename, lengthString);
}
}
}
}
using LaunchSitecore.Applications;
using Sitecore;
using Sitecore.Diagnostics;
using Sitecore.Pipelines.Upload;
using System.Collections.Generic;
using System.Web;
namespace LaunchSitecore.Pipelines.Upload
{
public class ImageCheckSize : UploadProcessor
{
public void Process(UploadArgs args)
{
Assert.ArgumentNotNull((object) args, "args");
if (args.Destination == UploadDestination.File)
return;
foreach (string index in args.Files)
{
HttpPostedFile file = args.Files[index];
if (!string.IsNullOrEmpty(file.FileName) && ImageSettings.IsRestrictedExtension(file.FileName))
{
if ((long)file.ContentLength > ImageSettings.MaxImageSizeInDatabase)
{
// Unused, message displayed using Javascript from MediaFolderForm.cs
//HttpContext.Current.Response.Write("<html><head><script type=\"text/JavaScript\" language=\"javascript\">window.top.scForm.getTopModalDialog().frames[0].scForm.postRequest(\"\", \"\", \"\", 'ShowFileTooBig(" +StringUtil.EscapeJavascriptString(file.FileName) + ")')</script></head><body>Done</body></html>");
args.ErrorText = string.Format("The image \"{0}\" is too big to be uploaded. The maximum size for uploading images is {1}.", file.FileName, MainUtil.FormatSize(ImageSettings.MaxImageSizeInDatabase));
Log.Warn(args.ErrorText, this);
args.AbortPipeline();
break;
}
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace LaunchSitecore.Applications
{
public static class ImageSettings
{
private static List<string> restrictedExtensions = null;
public static bool IsRestrictedExtension(string filename)
{
if (restrictedExtensions == null)
{
restrictedExtensions = RestrictedImageExtensions.Split(new char[] { '|' }).ToList();
}
if (restrictedExtensions.Any())
return restrictedExtensions.Exists(restrictedExtension => string.Equals(restrictedExtension, Path.GetExtension(filename), StringComparison.CurrentCultureIgnoreCase));
return false;
}
public static string RestrictedImageExtensions
{
get
{
return Sitecore.Configuration.Settings.GetSetting("Media.RestrictedImageExtensions");
}
}
public static long MaxImageSizeInDatabase
{
get
{
return Sitecore.Configuration.Settings.GetLongSetting("Media.MaxImageSizeInDatabase", 524288000L);
}
}
}
}
<?xml version="1.0"?>
<!-- place this file in: /App_config/Include/Custom -->
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<processors>
<attachFile argsType="Sitecore.Pipelines.Attach.AttachArgs">
<processor mode="on" type="LaunchSitecore.Pipelines.Attach.ImageCheckSize, LaunchSitecore"
patch:before="processor[@type='Sitecore.Pipelines.Attach.CheckSize,Sitecore.Kernel']" />
</attachFile>
<uiUpload>
<processor mode="on" type="LaunchSitecore.Pipelines.Upload.ImageCheckSize, LaunchSitecore"
patch:before="processor[@type='Sitecore.Pipelines.Upload.CheckSize, Sitecore.Kernel']" />
</uiUpload>
</processors>
<settings>
<setting name="Media.MaxImageSizeInDatabase" value="1MB" />
<setting name="Media.RestrictedImageExtensions" value=".jpg|.jpeg|.png|.gif|.bmp|.tiff" />
</settings>
</sitecore>
</configuration>
<?xml version="1.0" encoding="utf-8" ?>
<!-- place this file in: /sitecore/shell/Override -->
<control xmlns:def="Definition" xmlns="http://schemas.sitecore.net/Visual-Studio-Intellisense">
<MediaFolder>
<FormPage>
<!-- BEGIN: Codebeside updated -->
<CodeBeside Type="LaunchSitecore.Applications.MediaFolderForm,LaunchSitecore"/>
<!-- END: Codebeside updated -->
<Stylesheet Src="Media Folder Viewer.css" DeviceDependant="true"/>
<Border id="SettingsContainer" style="display:none" />
<Script runat="server" Src="/sitecore/shell/controls/lib/YUIupload/yahoo-dom-event/yahoo-dom-event.js" />
<Script runat="server" Src="/sitecore/shell/controls/lib/YUIupload/element/element-beta-min.js" />
<Script runat="server" Src="/sitecore/shell/controls/lib/YUIupload/uploader/uploader-experimental-min.js" />
<Script type="text/JavaScript" language="javascript" src="/sitecore/shell/controls/lib/scriptaculous/scriptaculous.js?load=effects" />
<Script type="text/JavaScript" language="javascript" Src="/sitecore/shell/controls/SitecoreLightbox.js" />
<Script type="text/JavaScript" language="javascript" Src="/sitecore/shell/applications/media/mediafolder/mediafolder.js"/>
<!-- BEGIN: New JS override file added -->
<Script type="text/JavaScript" language="javascript" Src="/sitecore/shell/Override/mediafolderOverride.js"/>
<!-- END: New JS override file added -->
<div Class="scBackground" style="height:100%;">
<Scrollbox ID="FileList" Background="Transparent" Border="none" Padding="0px" ContextMenu="FileList_ContextMenu" />
</div>
<div id="UploadPanel" style="display:none; background: white">
<div id="UploadUI">
<Literal Text="These files are ready for uploading:" style="display: none; padding: 0px 0px 12px 4px; font-weight: 700" ID="Header" runat="server" />
<Scrollbox ID="Scrollbox" Style="border:none; padding:0">
<table style="display:none;" id="queue" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th class="filename">
<Literal runat="server" Text="Filename" />
</th>
<th class="size">
<Literal runat="server" Text="Size" />
</th>
<th class="alt">
<Literal runat="server" Text="Alternate Text" />
</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</Scrollbox>
</div>
<GridPanel id="AdvancedOptions" class="options" runat="server" Columns="2" Style="display:none">
<Checkbox Header="Unpack ZIP Archives" runat="server" ID="Unpack" />
<Checkbox Header="Make Uploaded Media Items Versionable" runat="server" ID="Versioned" />
<Checkbox Header="Overwrite Existing Media Items" runat="server" ID="Overwrite" />
<Checkbox Header="Upload as Files" runat="server" ID="AsFiles" />
</GridPanel>
<div id="buttons" style="display:none">
<img src="/sitecore/shell/themes/standard/images/loading15x15.gif" Class="closeProgress" style="display:none; margin-left: 8px" />
<Button id="UploadButton" runat="server" Click="OnStart" Header="Upload" style="display:none" />
<Button id="CancelButton" runat="server" Click="OnCancel" Header="Cancel" />
<Button id="CloseButton" runat="server" Click="" onclick="javascript:scMediaFolder.activeUploader.close()" Header="Close" style="display:none" />
</div>
</div>
</FormPage>
</MediaFolder>
</control>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Sitecore;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
using Sitecore.Configuration;
using Sitecore.Resources;
using Sitecore.StringExtensions;
using Sitecore.Web.Authentication;
using Sitecore.Text;
using Sitecore.Web.UI.Sheer;
namespace LaunchSitecore.Applications
{
public class MediaFolderForm : Sitecore.Shell.Applications.Media.MediaFolder.MediaFolderForm
{
protected override void OnLoad(System.EventArgs e)
{
Assert.ArgumentNotNull(e, "e");
base.OnLoad(e);
System.Collections.Generic.Dictionary<string, string> settings = new System.Collections.Generic.Dictionary<string, string>();
this.UploadID = System.Guid.NewGuid().ToString();
settings.Add("uploadID", this.UploadID);
if (UIUtil.IsFirefox() || UIUtil.IsWebkit())
{
string str = System.Web.HttpContext.Current.Session.SessionID;
Assert.IsNotNullOrEmpty(str, "session id");
settings.Add("uploadSessionID", str);
settings.Add("uploadSessionID1", TicketManager.GetCurrentTicketId());
}
this.Versioned.Checked = Settings.Media.UploadAsVersionableByDefault;
this.AsFiles.Visible = !Settings.Media.DisableFileMedia;
this.AsFiles.Checked = Settings.Media.UploadAsFiles;
if (!Settings.Upload.UserSelectableDestination)
{
this.AsFiles.Visible = false;
}
if (this.AsFiles.Checked)
{
settings.Add("uploadLimit", ((long)Settings.Runtime.EffectiveMaxRequestLengthBytes).ToString());
}
else
{
settings.Add("uploadLimit", ((long)System.Math.Min(Settings.Media.MaxSizeInDatabase, Settings.Runtime.EffectiveMaxRequestLengthBytes)).ToString());
}
settings.Add("uploadFileLimit", ((long)Settings.Runtime.EffectiveMaxRequestLengthBytes).ToString());
settings.Add("uploadingAsFilesMessage", Translate.Text("At least one of the files is too large to be uploaded to the database."));
// BEGIN Following settings have been added
settings.Add("uploadImageLimit", ((long)System.Math.Min(ImageSettings.MaxImageSizeInDatabase, Settings.Runtime.EffectiveMaxRequestLengthBytes)).ToString());
settings.Add("uploadImageRestrictedExtensions", ImageSettings.RestrictedImageExtensions);
// END Changed Code
this.RenderSettings(settings);
}
protected new void OnFilesCancelled(string packet)
{
Assert.ArgumentNotNullOrEmpty(packet, "packet");
ListString str = new ListString(packet);
Assert.IsTrue((bool)(str.Count > 0), "Zero cancelled files posted");
System.Text.StringBuilder builder = new System.Text.StringBuilder();
builder.Append("The following files are too big to be uploaded:");
builder.Append("\n\n");
string[] items = str.Items;
for (int i = 0; i < items.Length; i = (int)(i + 1))
{
builder.Append(items[i] + "\n");
}
string str3 = MainUtil.FormatSize(System.Math.Min(Settings.Media.MaxSizeInDatabase, Settings.Runtime.EffectiveMaxRequestLengthBytes));
builder.Append(Translate.Text("The maximum size of a file that can be uploaded is {0}.", new object[] { str3 }));
// BEGIN Following message has been added to be output to user
builder.Append("\n");
builder.Append(Translate.Text("The maximum image size that can be uploaded is {0}.", MainUtil.FormatSize(ImageSettings.MaxImageSizeInDatabase)));
// END Changed Code
SheerResponse.Alert(builder.ToString(), new string[0]);
}
// Copied directly from Sitecore code - private methods FTW!
private void RenderSettings(System.Collections.Generic.Dictionary<string, string> settings)
{
Assert.ArgumentNotNull(settings, "settings");
System.IO.StringWriter writer = new System.IO.StringWriter();
using (JsonWriter writer2 = new JsonTextWriter(writer))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new XmlNodeConverter());
serializer.Serialize(writer2, settings);
}
string str = writer.ToString();
this.SettingsContainer.InnerHtml = "<script type='text/javascript'>var scUploadSettings = {0};</script>".FormatWith(new object[] { str });
}
}
}
// This script extends the default MediaFolder.js class
// processSelectedFiles should match your Sitecore version, add in the additional check in Line 12, rest of function is copy+pasted
// <!-- place this file in: /sitecore/shell/Override -->
SitecoreMediaUploader.addMethods({
processSelectedFiles: function (files) {
for (var file in files) {
if (YAHOO.lang.hasOwnProperty(files, file)) {
file = files[file];
}
if (file.size > this.uploadLimit() || this.uploadImageLimitReached(file)) { // added image file size check here
if (this.simple || file.size > this.uploadFileLimit()) {
this.cancelledFiles.push(file);
return false;
}
else {
this.forcedFileUpload = true;
}
}
$("queue").show();
file.size = (file.size / 1000).toFixed(0) + " KB";
var html = "<tr id='#{id}' class='queued'><td class='name'>#{name}</td><td class='size'>#{size}</td><td class='alt'><input class='scFont alt' type='text' id='#{id}_alt' /></td><td class='progress'><img class='filler' style='width:0px' src='/sitecore/shell/Themes/Standard/Images/Progress/filler_media.png' alt='' /></td></tr>".interpolate(file);
$$("#queue tbody")[0].insert({ bottom: html });
if (!this.simple) {
$("UploadButton").show();
}
this.queue.push(file);
}
},
// BEGIN: New extended helper functions
uploadImageLimitReached: function (file) {
var maxImageSize = parseInt(this.settings.uploadImageLimit);
var arrayOfExtensions = this.settings.uploadImageRestrictedExtensions.split('|');
if (arrayOfExtensions.indexOf(this.getFileExtension(file.name)) > -1 && file.size > maxImageSize) {
return true;
}
return false;
},
getFileExtension: function(fileName) {
var ext = fileName.split(".");
if (ext.length === 1 || (ext[0] === "" && ext.length === 2)) {
return "";
}
return "." + ext.pop().toLowerCase();
}
// END: Extended helper functions
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment