public static string DoUpload(string fileUri, HttpRequest request)
        {
            _fileName = GetCorrectName(Path.GetFileName(fileUri));

            var curExt = (Path.GetExtension(_fileName) ?? "").ToLower();

            if (!FileExts.Contains(curExt))
            {
                throw new Exception("File type is not supported");
            }

            var req = (HttpWebRequest)WebRequest.Create(fileUri);

            try
            {
                // hack. http://ubuntuforums.org/showthread.php?t=1841740
                if (IsMono)
                {
                    ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                }

                using (var stream = req.GetResponse().GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(StoragePath(_fileName, null), FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);
                        }
                    }
                }

                DocEditor.CreateMeta(_fileName, request.Cookies.GetOrDefault("uid", "uid-1"), request.Cookies.GetOrDefault("uname", "John Smith"), null);
            }
            catch (Exception)
            {
            }
            return(_fileName);
        }
        // uploading a file by the file url and the request
        public static string DoUpload(string fileUri, HttpRequest request)
        {
            _fileName = GetCorrectName(Path.GetFileName(fileUri));  // get the correct file name if such a name already exists

            var curExt = (Path.GetExtension(_fileName) ?? "").ToLower();

            if (!FileExts.Contains(curExt))  // check if the file extension is supported by the editor
            {
                throw new Exception("File type is not supported");
            }

            var req = (HttpWebRequest)WebRequest.Create(fileUri);

            try
            {
                VerifySSL();

                using (var stream = req.GetResponse().GetResponseStream())  // get response stream of the uploading file
                {
                    if (stream == null)
                    {
                        throw new Exception("stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(StoragePath(_fileName, null), FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);  // write bytes to the output stream
                        }
                    }
                }

                // get file meta information or create the default one
                var id   = request.Cookies.GetOrDefault("uid", null);
                var user = Users.getUser(id);  // get the user
                DocEditor.CreateMeta(_fileName, user.id, user.name, null);
            }
            catch (Exception)
            {
            }
            return(_fileName);
        }
        // uploading a file by the HtthContext object
        public static string DoUpload(HttpContext context)
        {
            var httpPostedFile = context.Request.Files[0];

            if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")  // check from which browser the request came for
            {
                var files = httpPostedFile.FileName.Split(new char[] { '\\' });
                _fileName = files[files.Length - 1];  // get file name
            }
            else
            {
                _fileName = httpPostedFile.FileName;
            }

            var curSize = httpPostedFile.ContentLength;

            if (MaxFileSize < curSize || curSize <= 0)  // check if the file size exceeds the maximum file size
            {
                throw new Exception("File size is incorrect");
            }

            var curExt = (Path.GetExtension(_fileName) ?? "").ToLower();

            if (!FileExts.Contains(curExt))  // check if the file extension is supported by the editor
            {
                throw new Exception("File type is not supported");
            }

            _fileName = GetCorrectName(_fileName);            // get the correct file name if such a name already exists

            var savedFileName = StoragePath(_fileName, null); // get the storage path to the uploading file

            httpPostedFile.SaveAs(savedFileName);             // and save it

            // get file meta information or create the default one
            var id   = context.Request.Cookies.GetOrDefault("uid", null);
            var user = Users.getUser(id);  // get the user

            DocEditor.CreateMeta(_fileName, user.id, user.name, null);

            return(_fileName);
        }
        public static string DoUpload(HttpContext context)
        {
            var httpPostedFile = context.Request.Files[0];

            if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
            {
                var files = httpPostedFile.FileName.Split(new char[] { '\\' });
                _fileName = files[files.Length - 1];
            }
            else
            {
                _fileName = httpPostedFile.FileName;
            }

            var curSize = httpPostedFile.ContentLength;

            if (MaxFileSize < curSize || curSize <= 0)
            {
                throw new Exception("File size is incorrect");
            }

            var curExt = (Path.GetExtension(_fileName) ?? "").ToLower();

            if (!FileExts.Contains(curExt))
            {
                throw new Exception("File type is not supported");
            }

            _fileName = GetCorrectName(_fileName);

            var savedFileName = StoragePath(_fileName, null);

            httpPostedFile.SaveAs(savedFileName);

            DocEditor.CreateMeta(_fileName, context.Request.Cookies.GetOrDefault("uid", "uid-1"), context.Request.Cookies.GetOrDefault("uname", "John Smith"), null);

            return(_fileName);
        }
        // converting a file
        public static string DoConvert(HttpContext context)
        {
            string fileData;

            try
            {
                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        fileData = readStream.ReadToEnd();
                        if (string.IsNullOrEmpty(fileData))
                        {
                            context.Response.Write("{\"error\":1,\"message\":\"Request stream is empty\"}");
                        }
                    }
            }
            catch (Exception e)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            var jss  = new JavaScriptSerializer();
            var body = jss.Deserialize <Dictionary <string, object> >(fileData);

            _fileName = Path.GetFileName(body["filename"].ToString());
            var filePass = body["filePass"] != null ? body["filePass"].ToString() : null;
            var lang     = context.Request.Cookies.GetOrDefault("ulang", null);

            var extension         = (Path.GetExtension(_fileName).ToLower() ?? "").Trim('.');
            var internalExtension = FileType.GetInternalExtension(_fileName).Trim('.');

            // check if the file with such an extension can be converted
            if (ConvertExts.Contains("." + extension) &&
                !string.IsNullOrEmpty(internalExtension))
            {
                // generate document key
                var key = ServiceConverter.GenerateRevisionId(FileUri(_fileName, true));

                var fileUrl = new UriBuilder(_Default.GetServerUrl(true));
                fileUrl.Path = HttpRuntime.AppDomainAppVirtualPath
                               + (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
                               + "webeditor.ashx";
                fileUrl.Query = "type=download&fileName=" + HttpUtility.UrlEncode(_fileName)
                                + "&userAddress=" + HttpUtility.UrlEncode(HttpContext.Current.Request.UserHostAddress);

                // get the url to the converted file
                string newFileUri;
                var    result = ServiceConverter.GetConvertedUri(fileUrl.ToString(), extension, internalExtension, key, true, out newFileUri, filePass, lang);
                if (result != 100)
                {
                    return("{ \"step\" : \"" + result + "\", \"filename\" : \"" + _fileName + "\"}");
                }

                // get a file name of an internal file extension with an index if the file with such a name already exists
                var fileName = GetCorrectName(Path.GetFileNameWithoutExtension(_fileName) + "." + internalExtension);

                var req = (HttpWebRequest)WebRequest.Create(newFileUri);

                VerifySSL();

                using (var stream = req.GetResponse().GetResponseStream())  // get response stream of the converting file
                {
                    if (stream == null)
                    {
                        throw new Exception("Stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(StoragePath(fileName, null), FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);  // write bytes to the output stream
                        }
                    }
                }

                // remove the original file and its history if it exists
                var storagePath = StoragePath(_fileName, null);
                var histDir     = HistoryDir(storagePath);
                File.Delete(storagePath);
                if (Directory.Exists(histDir))
                {
                    Directory.Delete(histDir, true);
                }

                // create meta information about the converted file with user id and name specified
                _fileName = fileName;
                var id   = context.Request.Cookies.GetOrDefault("uid", null);
                var user = Users.getUser(id);  // get the user
                DocEditor.CreateMeta(_fileName, user.id, user.name, null);
            }

            return("{ \"filename\" : \"" + _fileName + "\"}");
        }
        public static string DoSaveAs(HttpContext context)
        {
            string fileData;

            try
            {
                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        fileData = readStream.ReadToEnd();
                        if (string.IsNullOrEmpty(fileData))
                        {
                            return("{\"error\":\"Request stream is empty\"}");
                        }
                    }
            }
            catch (Exception e)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            var jss       = new JavaScriptSerializer();
            var body      = jss.Deserialize <Dictionary <string, object> >(fileData);
            var fileUrl   = (string)body["url"];
            var title     = (string)body["title"];
            var fileName  = GetCorrectName(title);
            var extension = "." + (Path.GetExtension(fileName).ToLower() ?? "").Trim('.');

            var allExt = ConvertExts.Concat(EditedExts).Concat(ViewedExts).Concat(FillFormsExts).ToArray();

            if (!allExt.Contains(extension))
            {
                return("{\"error\":\"File type is not supported\"}");
            }

            var req = (HttpWebRequest)WebRequest.Create(fileUrl);

            VerifySSL();

            using (var stream = req.GetResponse().GetResponseStream())
            {
                if (stream == null || req.GetResponse().ContentLength <= 0 || req.GetResponse().ContentLength > MaxFileSize)
                {
                    return("{\"error\": \"File size is incorrect\"}");
                }
                const int bufferSize = 4096;

                using (var fs = File.Open(StoragePath(fileName, null), FileMode.Create))
                {
                    var buffer = new byte[bufferSize];
                    int readed;
                    while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                    {
                        fs.Write(buffer, 0, readed);  // write bytes to the output stream
                    }
                }
            }

            var id   = context.Request.Cookies.GetOrDefault("uid", null);
            var user = Users.getUser(id);  // get the user

            DocEditor.CreateMeta(fileName, user.id, user.name, null);

            return("{\"file\": \"" + fileName + "\"}");
        }
        public static int processForceSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            var downloadUri = (string)fileData["url"];

            string curExt      = Path.GetExtension(fileName);
            string downloadExt = Path.GetExtension(downloadUri);
            var    newFileName = fileName;

            if (!curExt.Equals(downloadExt))
            {
                try
                {
                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }
            }

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (_Default.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            string  forcesavePath = "";
            Boolean isSubmitForm  = fileData["forcesavetype"].ToString().Equals("3");

            if (isSubmitForm)
            {
                if (newFileName.Equals(fileName))
                {
                    newFileName = _Default.GetCorrectName(fileName, userAddress);
                }
                forcesavePath = _Default.StoragePath(newFileName, userAddress);
            }
            else
            {
                forcesavePath = _Default.ForcesavePath(newFileName, userAddress, false);
                if (forcesavePath.Equals(""))
                {
                    forcesavePath = _Default.ForcesavePath(newFileName, userAddress, true);
                }
            }

            DownloadToFile(downloadUri, forcesavePath);

            if (isSubmitForm)
            {
                var jss     = new JavaScriptSerializer();
                var actions = jss.Deserialize <List <object> >(jss.Serialize(fileData["actions"]));
                var action  = jss.Deserialize <Dictionary <string, object> >(jss.Serialize(actions[0]));
                var user    = action["userid"].ToString();
                DocEditor.CreateMeta(newFileName, user, "Filling Form", userAddress);
            }

            return(0);
        }
        // file force saving process
        public static int processForceSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            if (fileData["url"].Equals(null))
            {
                throw new Exception("DownloadUrl is null");
            }
            var downloadUri = (string)fileData["url"];

            string curExt = Path.GetExtension(fileName).ToLower();  // get current file extension

            var downloadExt = fileData.ContainsKey("filetype")
                ? "." + (string)fileData["filetype"]
                : Path.GetExtension(downloadUri).ToLower(); // TODO: Delete in version 7.0 or higher. Support for versions below 7.0

            Boolean newFileName = false;

            // convert downloaded file to the file with the current extension if these extensions aren't equal
            if (!curExt.Equals(downloadExt))
            {
                try
                {
                    // convert file and give url to a new file
                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        newFileName = true;
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = true;
                }
            }

            _Default.VerifySSL();

            string  forcesavePath = "";
            Boolean isSubmitForm  = fileData["forcesavetype"].ToString().Equals("3"); // SubmitForm

            if (isSubmitForm)                                                         // if the form is submitted
            {
                if (newFileName)
                {
                    fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress);  // get the correct file name if it already exists
                }
                else
                {
                    fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + curExt, userAddress);
                }
                forcesavePath = _Default.StoragePath(fileName, userAddress);
            }
            else
            {
                if (newFileName)
                {
                    fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }

                forcesavePath = _Default.ForcesavePath(fileName, userAddress, false);
                if (forcesavePath.Equals(""))  // create forcesave path if it doesn't exist
                {
                    forcesavePath = _Default.ForcesavePath(fileName, userAddress, true);
                }
            }

            DownloadToFile(downloadUri, forcesavePath);

            if (isSubmitForm)
            {
                var jss     = new JavaScriptSerializer();
                var actions = jss.Deserialize <List <object> >(jss.Serialize(fileData["actions"]));
                var action  = jss.Deserialize <Dictionary <string, object> >(jss.Serialize(actions[0]));
                var user    = action["userid"].ToString();                         // get the user id
                DocEditor.CreateMeta(fileName, user, "Filling Form", userAddress); // create meta data for the forcesaved file
            }

            return(0);
        }
        public static string DoConvert(HttpContext context)
        {
            _fileName = Path.GetFileName(context.Request["filename"]);

            var extension         = (Path.GetExtension(_fileName) ?? "").Trim('.');
            var internalExtension = FileType.GetInternalExtension(_fileName).Trim('.');

            if (ConvertExts.Contains("." + extension) &&
                !string.IsNullOrEmpty(internalExtension))
            {
                var key = ServiceConverter.GenerateRevisionId(FileUri(_fileName, true));

                string newFileUri;
                var    result = ServiceConverter.GetConvertedUri(FileUri(_fileName, true), extension, internalExtension, key, true, out newFileUri);
                if (result != 100)
                {
                    return("{ \"step\" : \"" + result + "\", \"filename\" : \"" + _fileName + "\"}");
                }

                var fileName = GetCorrectName(Path.GetFileNameWithoutExtension(_fileName) + "." + internalExtension);

                var req = (HttpWebRequest)WebRequest.Create(newFileUri);

                // hack. http://ubuntuforums.org/showthread.php?t=1841740
                if (IsMono)
                {
                    ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                }

                using (var stream = req.GetResponse().GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("Stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(StoragePath(fileName, null), FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);
                        }
                    }
                }

                var storagePath = StoragePath(_fileName, null);
                var histDir     = HistoryDir(storagePath);
                File.Delete(storagePath);
                if (Directory.Exists(histDir))
                {
                    Directory.Delete(histDir, true);
                }

                _fileName = fileName;
                DocEditor.CreateMeta(_fileName, context.Request.Cookies.GetOrDefault("uid", "uid-1"), context.Request.Cookies.GetOrDefault("uname", "John Smith"), null);
            }

            return("{ \"filename\" : \"" + _fileName + "\"}");
        }