Ejemplo n.º 1
0
	public bool SetCover()
	{
		if (Photo != null && Photo.DetailImage != null && AlbumId > 0)
		{
			try
			{
				var album = BXIBlockSection.GetById(AlbumId);

				if (album == null)
					return false;

				if (album.Image != null)
					album.Image.Delete();

                BXFile newImage = new BXFile();
                newImage.OwnerModuleId = "iblock";
                newImage.FileNameOriginal = Photo.DetailImage.FileNameOriginal;
                newImage.SetFile(
                    BXImageUtility.GetResizedImageStream(Photo.DetailImage, CoverWidth, CoverHeight),
                    "iblock");
                newImage.Save();

				album.ImageId = newImage.Id;
				album.Save();
			}
			catch
			{
				return false;
			}

			return true;
		}
		return false;
	}
Ejemplo n.º 2
0
	protected BXFile SaveFile()
	{
		FileUpload fu = aifImage.Upload;

		if (!fu.HasFile)
			return null;

		HttpPostedFile postedFile = fu.PostedFile;
		BXFileValidationResult result = BXFile.ValidateAsImage(
			postedFile.FileName,
			postedFile.ContentType,
			postedFile.InputStream,
			BXConfigurationUtility.Options.User.AvatarMaxSizeKB * 1024,
			BXConfigurationUtility.Options.User.AvatarMaxWidth,
			BXConfigurationUtility.Options.User.AvatarMaxHeight
			);

		if (result == BXFileValidationResult.Valid)
		{
			BXFile f = new BXFile(fu.PostedFile, "user", "main", null);
            f.DemandFileUpload();
			f.Save();
			return f;
		}

		if ((result & BXFileValidationResult.InvalidContentType) == 0
			&& (result & BXFileValidationResult.InvalidExtension) == 0
			&& (result & BXFileValidationResult.InvalidImage) == 0
			&& ((result & BXFileValidationResult.InvalidWidth) != 0 || (result & BXFileValidationResult.InvalidHeight) != 0)
			)
		{
			using (MemoryStream destinationStream = new MemoryStream())
			{
				string postedFileName = postedFile.FileName,
					postedFileMimeType = postedFile.ContentType;

				using (System.Drawing.Image image = System.Drawing.Image.FromStream(postedFile.InputStream))
				using (System.Drawing.Image scaledImage = BXImageUtility.Resize(image, BXConfigurationUtility.Options.User.AvatarMaxWidth, BXConfigurationUtility.Options.User.AvatarMaxHeight))
				{
					ImageFormat format = image.RawFormat;
					BXImageFormatInfo fInfo = new BXImageFormatInfo(format);
					/*
					 * GIF в PNG всегда - из-за возможной потери качества при преобразовании в 256 цветов
					 * JPG в PNG если площадь изображения не превышает 128x128
					 */
					if (format.Guid == ImageFormat.Gif.Guid || (format.Guid == ImageFormat.Jpeg.Guid && scaledImage.Width * scaledImage.Height <= 16384))
						fInfo = new BXImageFormatInfo(ImageFormat.Png);
					postedFileName = fInfo.AppendFileExtension(postedFileName);
					postedFileMimeType = fInfo.GetMimeType();
					scaledImage.Save(destinationStream, fInfo.Format);
				}

				BXFile f = new BXFile(null, destinationStream, postedFileName, "user", "main", null, postedFileMimeType);
				if ((result & BXFileValidationResult.InvalidSize) != 0 && f.FileSize <= BXConfigurationUtility.Options.User.AvatarMaxSizeKB * 1024)
					result &= ~BXFileValidationResult.InvalidSize;
				if ((result & BXFileValidationResult.InvalidWidth) != 0 && f.Width <= BXConfigurationUtility.Options.User.AvatarMaxWidth)
					result &= ~BXFileValidationResult.InvalidWidth;
				if ((result & BXFileValidationResult.InvalidHeight) != 0 && f.Height <= BXConfigurationUtility.Options.User.AvatarMaxHeight)
					result &= ~BXFileValidationResult.InvalidHeight;

				if (result == BXFileValidationResult.Valid)
				{
                    f.DemandFileUpload();
					f.Save();
					return f;
				}
			}
		}

		StringBuilder fError = new StringBuilder();
		if ((result & BXFileValidationResult.InvalidContentType) == BXFileValidationResult.InvalidContentType)
			fError.Append(GetMessageRaw("InvalidType"));

		if ((result & BXFileValidationResult.InvalidExtension) == BXFileValidationResult.InvalidExtension)
		{
			if (fError.Length != 0)
				fError.Append(", ");
			fError.Append(GetMessageRaw("InvalidExtension"));
		}

		if ((result & BXFileValidationResult.InvalidImage) == BXFileValidationResult.InvalidImage)
		{
			if (fError.Length != 0)
				fError.Append(", ");
			fError.Append(GetMessageRaw("InvalidImage"));
		}

		if ((result & BXFileValidationResult.InvalidSize) != 0)
		{
			if (fError.Length != 0)
				fError.Append(", ");
			fError.AppendFormat(GetMessageRaw("InvalidSize"), BXStringUtility.BytesToString(BXConfigurationUtility.Options.User.AvatarMaxSizeKB * 1024));
		}

		if ((result & BXFileValidationResult.InvalidWidth) != 0)
		{
			if (fError.Length != 0)
				fError.Append(", ");
			fError.AppendFormat(GetMessageRaw("InvalidWidth"), BXConfigurationUtility.Options.User.AvatarMaxWidth);
		}

		if ((result & BXFileValidationResult.InvalidHeight) != 0)
		{
			if (fError.Length != 0)
				fError.Append(", ");
			fError.AppendFormat(GetMessageRaw("InvalidHeight"), BXConfigurationUtility.Options.User.AvatarMaxHeight);
		}

		throw new Exception(string.Format(GetMessageRaw("Error.InvalidImage"), fError.ToString()));
	}
Ejemplo n.º 3
0
			public override bool Validate(string formFieldName, ICollection<string> errors)
			{
				HttpRequest request = HttpContext.Current.Request;

				// If the field is mandatory, then there is no checkbox
				store = file;
				if (!editor.field.Mandatory)
				{
					string save = request.Form[formFieldName + "$save"];
					int i;
					if (store != null && (!int.TryParse(save, out i) || store.Id != i))
					{
						delete = store;
						store = null;
					}
				}

				HttpPostedFile upload = request.Files[formFieldName];
				if (upload != null && upload.ContentLength != 0)
				{
					BXFile uploaded = editor.ValidateFile(upload, errors);
					if (uploaded == null)
						return false;

					save = uploaded;
				}

				if (editor.field.Mandatory && store == null && save == null)
				{
					errors.Add(HttpUtility.HtmlEncode(string.Format(BXLoc.GetMessage(editor.type, "Error.FieldIsRequired"), editor.field.TextEncoder.Decode(editor.field.EditFormLabel))));
					return false;
				}

				return true;
			}
Ejemplo n.º 4
0
	protected BXFile SaveFile(string type)
	{
		BXFile fImage = null;

		FileUpload fu;

		if ("detail".Equals(type, StringComparison.InvariantCultureIgnoreCase))
			fu = DetailImg.Upload;
		else
			fu = Img.Upload;

		if (fu.HasFile)
		{
			fImage = new BXFile(fu.PostedFile, "iblock", "iblock", null); 
			BXFileValidationResult fResult = fImage.ValidateAsImage(0, 0, 0);
			if (fResult != BXFileValidationResult.Valid)
			{
				string fError = "";
				if ((fResult & BXFileValidationResult.InvalidContentType) == BXFileValidationResult.InvalidContentType)
					fError += GetMessage("Error.InvalidType");
				if ((fResult & BXFileValidationResult.InvalidExtension) == BXFileValidationResult.InvalidExtension)
				{
					if (!String.IsNullOrEmpty(fError))
						fError += ", ";
					fError += GetMessage("Error.Invalid.Extension");
				}
				if ((fResult & BXFileValidationResult.InvalidImage) == BXFileValidationResult.InvalidImage)
				{
					if (!String.IsNullOrEmpty(fError))
						fError += ", ";
					fError += GetMessage("Error.InvalidImage");
				}
				throw new Exception(fError);
			}
			fImage.DemandFileUpload();
			fImage.Save();
		}

		return fImage;
	}
Ejemplo n.º 5
0
			public override void Load()
			{
				if (editor.property.Value == null)
					return;

				file = BXFile.GetById((int)editor.property.Value);
			}
Ejemplo n.º 6
0
			public override void Save(string formFieldName, BXCustomPropertyCollection storage)
			{
				if (delete != null)
				{
					delete.Delete();
					delete = null;
				}

				file = store;

				if (save != null)
				{
					save.Save();

					if (file != null)
						file.Delete();
					file = save;
				}

				BXCustomProperty p = new BXCustomProperty(editor.field.Name, editor.field.Id, editor.type.DbType, false, null, true);
				if (file != null)
					p.Values.Add(file.Id);
				storage[editor.field.Name] = p;
			}
Ejemplo n.º 7
0
		//METHODS
		private string RenderFile(BXFile file, string formName, string id, bool allowDelete, bool addPlaceholder, bool showUpload)
		{
			return
				(file != null
				? string.Format(
					allowDelete
						? string.Format(
							@"<input type=""checkbox"" name=""{0}$save"" id=""{1}"" value=""{2}"" checked=""checked"" /><label for=""{1}""> {{0}}</label><br/>",
							HttpUtility.HtmlEncode(formName),
							HttpUtility.HtmlEncode(id),
							file.Id
						)
						: @"{0}<br/>",
					string.Format(
						@"{0} ({1}) {2}",
						HttpUtility.HtmlEncode(file.FileNameOriginal ?? string.Empty),
						HttpUtility.HtmlEncode(file.ContentType ?? string.Empty),
						HttpUtility.HtmlEncode(BXStringUtility.BytesToString(file.FileSize))
					)
				)
				: string.Empty)
				+ (showUpload
					? string.Format(
						@"<input type=""file"" class=""bx-custom-field custom-field-file"" name=""{0}"" {1}/>",
						HttpUtility.HtmlEncode(formName),
						textboxSize > 0 ? (@"size=""" + textboxSize + @""" ") : string.Empty
					)
					: string.Empty)
				+ (addPlaceholder ? @" {0}" : null);
		}
Ejemplo n.º 8
0
		private BXFile ValidateFile(HttpPostedFile file, ICollection<string> errors)
		{
			bool result = true;
			if (maxSize > 0 && file.ContentLength > maxSize)
			{
				result = false;
				errors.Add(HttpUtility.HtmlEncode(string.Format(
					BXLoc.GetMessage(type, "Error.FileSizeExceeded"),
					file.FileName,
					BXStringUtility.BytesToString(maxSize)
				)));
			}
			if (allowedExtensions.Count != 0)
			{
				string ext = Path.GetExtension(file.FileName);
				if (ext != null)
					ext = ext.TrimStart('.').ToLowerInvariant();
				if (!allowedExtensions.Contains(ext))
				{
					result = false;
					errors.Add(HttpUtility.HtmlEncode(string.Format(
						BXLoc.GetMessage(type, "Error.InvalidFileExtension"),
						file.FileName,
						string.Join(", ", allowedExtensions.ToArray())
					)));
				}
			}
			if (!result)
				return null;

			BXFile f = new BXFile(file, "uf", "main", string.Empty);
			if (!BXSecureIO.CheckUpload(f.FileVirtualPath))
			{
				errors.Add(HttpUtility.HtmlEncode(string.Format(BXLoc.GetMessage(type, "Error.InsufficientRightsToUpload"), file.FileName)));
				return null;
			}
			return f;
		}
Ejemplo n.º 9
0
	private void RaiseFile()
	{
		if (raised)
			return;
		raised = true;

		if (!IsPostBack)
			return;

		var f = !string.IsNullOrEmpty(CachedId.Value) ? BXFile.GetByTempGuid(CachedId.Value, BXTextEncoder.EmptyTextEncoder) : null;
		
		if (StoredId.Value == "Y")
		{
			if (f != null)
				f.Delete();
			currentFile = originalFile;
		}
		else 
			currentFile = f;	
	}
Ejemplo n.º 10
0
	protected BXFile SaveFile(bitrix_ui_AdminImageField adminImageField, int currentImageId)
	{
		if (adminImageField == null)
			return null;

		BXFile image = null;
		FileUpload fileUpload = adminImageField.Upload;

		if (adminImageField.Upload.HasFile)
		{
			image = new BXFile(fileUpload.PostedFile, "iblock", "iblock", adminImageField.Description);
			BXFileValidationResult result = image.ValidateAsImage(0, 0, 0);
			if (result != BXFileValidationResult.Valid)
			{
				string errorMessage = "";
				if ((result & BXFileValidationResult.InvalidContentType) == BXFileValidationResult.InvalidContentType)
					errorMessage += GetMessageRaw("InvalidType");
				if ((result & BXFileValidationResult.InvalidExtension) == BXFileValidationResult.InvalidExtension)
				{
					if (!String.IsNullOrEmpty(errorMessage))
						errorMessage += ", ";
					errorMessage += GetMessageRaw("InvalidExtension");
				}
				if ((result & BXFileValidationResult.InvalidImage) == BXFileValidationResult.InvalidImage)
				{
					if (!String.IsNullOrEmpty(errorMessage))
						errorMessage += ", ";
					errorMessage += GetMessageRaw("InvalidImage");
				}
				throw new Exception(String.Format(GetMessageRaw("Error.InvalidImage"), errorMessage));
			}
            image.DemandFileUpload();
			image.Save();
			return image;
		}
		else if (currentImageId > 0 && (image = BXFile.GetById(currentImageId)) != null)
		{
			image.Description = adminImageField.Description;
			image.Save();
		}

		return null;
	}
Ejemplo n.º 11
0
	public void Save(BXCustomPropertyCollection storage)
	{
		if (field == null)
			return;
		
		RaiseFile();

		object value = null;
		BXCustomType t = BXCustomTypeManager.GetCustomType(field.CustomTypeId);
		
		if (currentFile != null)
		{
			value = currentFile.Id;
			
			if (addDescription)
				currentFile.Description = Description.Text;
			currentFile.TempGuid = "";
			currentFile.Save();
		}

		if (originalFile != null && (currentFile == null || originalFile.Id != currentFile.Id))
			originalFile.Delete();

		originalFile = currentFile;
		 
		if (value != null)
		{
			storage[field.Name] = new BXCustomProperty(field.Name, field.Id, t.DbType, t.IsClonable ? false : field.Multiple, value, true);			
		}
		else if (string.IsNullOrEmpty(StoredId.Value))
		{
			storage[field.Name] = new BXCustomProperty(field.Name, field.Id, t.DbType, t.IsClonable ? false : field.Multiple, null, true);			
		}
		else 
			storage[field.Name] = this.value;
	}
Ejemplo n.º 12
0
	public void Initialize(BXCustomField currentField, BXCustomProperty currentValue)
	{
		field = currentField;
		if (field == null)
			return;

		BXParamsBag<object> settings = new BXParamsBag<object>(currentField.Settings);

		RequiredValidator.Enabled = currentField.Mandatory;
		if (RequiredValidator.Enabled)
			RequiredValidator.ErrorMessage = GetMessageFormat("Error.Required", field.EditFormLabel);

		SizeValidator.Enabled = settings.ContainsKey("MaxSize");
		if (SizeValidator.Enabled)
		{
			maxSize = (int)settings["MaxSize"];
			SizeValidator.ErrorMessage = GetMessageFormat("Error.IllegalSize", field.EditFormLabel, settings["MaxSize"]);
		}

		if (settings.ContainsKey("AllowedExtensions"))
			extensions = settings["AllowedExtensions"] as string[];
		ExtensionValidator.Enabled = (extensions != null && extensions.Length > 0);
		if (ExtensionValidator.Enabled)
			ExtensionValidator.ErrorMessage = GetMessageFormat("Error.IllegalExtension", field.EditFormLabel, string.Join(", ", extensions));
		value = currentValue;

		RequiredValidator.Enabled = field.Mandatory;
		if (RequiredValidator.Enabled)
			RequiredValidator.ErrorMessage = GetMessageFormat("Error.Required", field.EditFormLabel);

		addDescription = settings.GetBool("AddDescription");
		DescriptionBlock.Visible = addDescription;

		BXFile f = null;
		if (currentValue != null && (currentValue.Value != null && (int)currentValue.Value != 0) && (f = BXFile.GetById((int)currentValue.Value, BXTextEncoder.EmptyTextEncoder)) != null)
		{
			currentFile = originalFile = f;
			StoredId.Value = "Y";
			//DisplayName.Value = f.FileNameOriginal;
			//DisplaySize.Value = BXStringUtility.BytesToString(f.FileSize);
			//ContentType.Value = f.ContentType;
			if (addDescription)
				Description.Text = f.Description;
		}
	}
Ejemplo n.º 13
0
	//protected string SavedName;
	//protected string DisplaySize;
	//protected string ContentType;

	
	private void ProcessUploadMode()
	{
		HasError = true;
		UploadMode = true;
		JSCodeMode = false;

		if (string.IsNullOrEmpty(Request.QueryString["id"]))
		{
			ErrorMessage += JSEncode(HtmlEncode(GetMessageRaw("Error.NoId")) + "<br/>");
			return;
		}

		OwnerId = Request.QueryString["id"];
		CachedId = Request.QueryString["old"];

		HttpPostedFile file = Request.Files[OwnerId + "_ValueUpload"];
		if (file == null || file.ContentLength == 0)
		{
			ErrorMessage += JSEncode(HtmlEncode(GetMessageRaw("Error.NoFile")) + "<br/>");
			return;
		}

		try
		{
			string cacheid = Guid.NewGuid().ToString("N");			
			bool success = false;
			try
			{
				Uploaded = new BXFile(BXTextEncoder.EmptyTextEncoder, file, "uf", "main", "");
				Uploaded.TempGuid = cacheid;
				Uploaded.DemandFileUpload();
				Uploaded.Save();
				success = true;				
			}
			catch(BXSecurityException)
			{
				ErrorMessage += JSEncode(HtmlEncode(GetMessageRaw("Error.InsufficientRights")) + "<br/>");
			}
			catch
			{
			}

			if (!success)
				return;
			
			//Delete Old File
			BXFile old;
			if (!string.IsNullOrEmpty(CachedId) && (old = BXFile.GetByTempGuid(CachedId, BXTextEncoder.EmptyTextEncoder)) != null)
			{
				try
				{
					old.Delete();
				}
				catch
				{
				}
			}

			//Set New File Params
			CachedId = cacheid;						
				
			HasError = false;
		}
		catch
		{
		}
	}
Ejemplo n.º 14
0
    protected BXFile SaveFile(HttpPostedFile postedFile)
    {
        BXFile image = new BXFile(postedFile, "iblock", "iblock", null);
		BXFileValidationResult fResult = image.ValidateAsImage(0, 0, 0);
        if (fResult != BXFileValidationResult.Valid)
        {
            string fError = "";
            if ((fResult & BXFileValidationResult.InvalidContentType) == BXFileValidationResult.InvalidContentType)
                fError += GetMessageRaw("Error.InvalidType");
            if ((fResult & BXFileValidationResult.InvalidExtension) == BXFileValidationResult.InvalidExtension)
            {
                if (!String.IsNullOrEmpty(fError))
                    fError += ", ";
                fError += GetMessageRaw("Error.Inavlid.extension");
            }
            if ((fResult & BXFileValidationResult.InvalidImage) == BXFileValidationResult.InvalidImage)
            {
                if (!String.IsNullOrEmpty(fError))
                    fError += ", ";
                fError += GetMessageRaw("Error.InvalidImage");
            }
            throw new FormatException(fError);
        }
        image.DemandFileUpload();
        image.Save();
        return image;
    }
Ejemplo n.º 15
0
	protected BXFile SaveFile()
	{
		BXFile fImage = null;

		if (Img.Upload.HasFile)
		{
			fImage = new BXFile(Img.Upload.PostedFile, "iblock", "iblock", null);
			BXFileValidationResult fResult = fImage.ValidateAsImage(0, 0, 0);
			if (fResult != BXFileValidationResult.Valid)
			{
				string fError = "";
				if ((fResult & BXFileValidationResult.InvalidContentType) == BXFileValidationResult.InvalidContentType)
					fError += GetMessage("Error.InvalidType");
				if ((fResult & BXFileValidationResult.InvalidExtension) == BXFileValidationResult.InvalidExtension)
				{
					if (!String.IsNullOrEmpty(fError))
						fError += ", ";
					fError += GetMessage("Error.InvalidExtension");
				}
				if ((fResult & BXFileValidationResult.InvalidImage) == BXFileValidationResult.InvalidImage)
				{
					if (!String.IsNullOrEmpty(fError))
						fError += ", ";
					fError += GetMessage("Error.InvalidImage");
				}
				throw new Exception(fError);
			}
            fImage.DemandFileUpload();
			fImage.Save();
		}

		return fImage;
	}