Compare commits

..

3 Commits

Author SHA1 Message Date
cf1212aae0 fix an issue with convert 2023-04-07 14:07:01 +03:00
81c0e25c9e minio license 2023-03-29 18:19:51 +03:00
c9dc7314d5 s3 2023-03-29 18:16:43 +03:00
134 changed files with 3479 additions and 5528 deletions

View File

@ -22,10 +22,8 @@ jobs:
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.2'
php-version: '8.1'
tools: cs2pr, phpcs
- name: Run phpcs
run: |
phpcs --version
phpcs -q --extensions=php,module,inc,install,test,profile,theme,info --ignore=node_modules,bower_components,vendor,css,js,lib --standard=./ruleset.xml ./
run: phpcs -q --extensions=php,module,inc,install,test,profile,theme,css,info,txt,md,yml --ignore=node_modules,bower_components,vendor ./

View File

@ -274,57 +274,6 @@ jQuery.UI - jQuery UI is an open source library of interface components —
License: MIT
License File: jQuery.UI.license
JWT - JSON Web Token implementation (https://github.com/firebase/php-jwt/blob/master/LICENSE)
License: BSD-3-Clause
License File: jwt.license
PHP_CodeSniffer - PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent. (https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt)
License: BSD-3-Clause
License File: PHP_CodeSniffer.license
web/documentserver-example/python
Django - Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Thanks for checking it out. (https://github.com/django/django/blob/main/LICENSE)
License: BSD-3-Clause
License File: Django.license
jQuery - jQuery is a new kind of JavaScript Library. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript. NOTE: This package is maintained on behalf of the library owners by the NuGet Community Packages project at https://nugetpackages.codeplex.com/ (https://jquery.org/license/)
License: MIT
License File: jQuery.license
jQuery.BlockUI - The jQuery BlockUI Plugin lets you simulate synchronous behavior when using AJAX, without locking the browser. (https://github.com/malsup/blockui/)
License: MIT, GPL
License File: jQuery.BlockUI.license
jQuery.FileUpload - File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads. (https://github.com/blueimp/jQuery-File-Upload/blob/master/LICENSE.txt)
License: MIT
License File: jQuery.FileUpload.license
jQuery.iframe-transport - jQuery Iframe Transport Plugin for File Upload (https://github.com/blueimp/jQuery-File-Upload/blob/master/LICENSE.txt)
License: MIT
License File: jQuery.iframe-transport.license
jQuery.Migrate - Upgrading libraries such as jQuery can be a lot of work, when breaking changes have been introduced. jQuery Migrate makes this easier, by restoring the APIs that were removed, and additionally shows warnings in the browser console (development version of jQuery Migrate only) when removed and/or deprecated APIs are used. (https://github.com/jquery/jquery-migrate/blob/main/LICENSE.txt)
License: OpenJS
License File: jQuery.Migrate.license
jQuery.UI - jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according to jQuery's event-driven architecture (find something, manipulate it) and is themeable, making it easy for developers of any skill level to integrate and extend into their own code. (https://jquery.org/license/)
License: MIT
License File: jQuery.UI.license
PyJWT - A Python implementation of RFC 7519. (https://github.com/jpadilla/pyjwt/blob/master/LICENSE)
License: MIT
License File: PyJWT.license
python-magic - python-magic is a Python interface to the libmagic file type identification library. (https://github.com/ahupp/python-magic/blob/master/LICENSE)
License: MIT
License File: python-magic.license
requests - Requests allows you to send HTTP/1.1 requests extremely easily. Theres no need to manually add query strings to your URLs, or to form-encode your PUT & POST data — but nowadays, just use the json method! (https://github.com/psf/requests/blob/main/LICENSE)
License: Apache 2.0
License File: requests.license
web/documentserver-example/python

View File

@ -1,17 +1,5 @@
# Change Log
- nodejs: setUsers for region protection
- si skin languages
- fix "no" skin languages
- anonymous can't change viewer to edit
- referenceData
- anonymous can't protect file
- separate setting for checking the token in requests
- php: linter refactoring
- horizontal scroll fix for Internet Explorer
- save file with extension from response after conversation
- conversation to ooxml
## 1.5.1
- update jquery

View File

@ -26,13 +26,13 @@
<RemoveDir Directories="$(To)" ContinueOnError="true" />
<ItemGroup>
<ZipFilesCSharp Include="$(DirCSharp)**" Exclude="$(DirCSharp).vs\**;$(DirCSharp)bin\*.pdb;$(DirCSharp)bin\*.xml;$(DirCSharp)obj\**;$(DirCSharp)packages\**;$(DirCSharp)**\.git" />
<ZipFilesCSharp Include="$(DirCSharp)**" Exclude="$(DirCSharp)obj\**;$(DirCSharp)**\.git" />
</ItemGroup>
<Copy SourceFiles="@(ZipFilesCSharp)" DestinationFiles="@(ZipFilesCSharp->'$(NameCSharp)\%(RecursiveDir)%(Filename)%(Extension)')" />
<Zip Files="$(NameCSharp)" WorkingDirectory="$(To)" ZipFileName="$(NameCSharp).zip" />
<ItemGroup>
<ZipFilesMVC Include="$(DirMvc)**" Exclude="$(DirMvc).vs\**;$(DirMvc)bin\*.pdb;$(DirMvc)bin\*.xml;$(DirMvc)obj\**;$(DirMvc)packages\**;$(DirMvc)**\.git" />
<ZipFilesMVC Include="$(DirMvc)**" Exclude="$(DirMvc)obj\**;$(DirMvc)**\.git" />
</ItemGroup>
<Copy SourceFiles="@(ZipFilesMVC)" DestinationFiles="@(ZipFilesMVC->'$(NameMvc)\%(RecursiveDir)%(Filename)%(Extension)')" />
<Zip Files="$(NameMvc)" WorkingDirectory="$(To)" ZipFileName="$(NameMvc).zip" />

View File

@ -36,6 +36,10 @@ Microsoft.Web.Infrastructure - This package contains the Microsoft.Web.Infrastru
License: MS-EULA License
License File: Microsoft.Web.Infrastructure.license
MinIO - MinIO Client SDK provides higher level APIs for MinIO and Amazon S3 compatible cloud storage services. (https://github.com/minio/minio-dotnet)
License: Apache-2.0 license
License File: MinIO.license
Newtonsoft.Json - Json.NET is a popular high-performance JSON framework for .NET (https://github.com/JamesNK/Newtonsoft.Json)
License: MIT
License File: Newtonsoft.Json.license

View File

@ -682,8 +682,3 @@
max-width:15%;
}
}
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.tableRow td:first-child{
max-width: none;
}
}

View File

@ -26,6 +26,8 @@ using System.Web.Configuration;
using System.Web.Script.Serialization;
using OnlineEditorsExampleMVC.Models;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Text;
namespace OnlineEditorsExampleMVC.Helpers
{
@ -80,21 +82,28 @@ namespace OnlineEditorsExampleMVC.Helpers
// get the storage path of the file
public static string StoragePath(string fileName, string userAddress = null)
{
var directory = "";
if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["storage-path"]) && Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]))
if (S3Helper.Instance.Enabled)
{
directory = WebConfigurationManager.AppSettings["storage-path"] + "\\";
return fileName;
}
else
{
directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(userAddress) + "\\";
var directory = "";
if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["storage-path"]) && Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]))
{
directory = WebConfigurationManager.AppSettings["storage-path"] + "\\";
}
else
{
directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(userAddress) + "\\";
}
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
return directory + (fileName.Contains("\\") ? fileName : Path.GetFileName(fileName));
}
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
return directory + (fileName.Contains("\\") ? fileName : Path.GetFileName(fileName));
}
// get the path to the forcesaved file version
@ -110,7 +119,7 @@ namespace OnlineEditorsExampleMVC.Helpers
{
directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(userAddress) + "\\";
}
if (!Directory.Exists(directory))
{
return "";
@ -146,13 +155,27 @@ namespace OnlineEditorsExampleMVC.Helpers
// get the history directory
public static string HistoryDir(string storagePath)
{
return storagePath += "-hist";
if (S3Helper.Instance.Enabled)
{
return storagePath + "-hist/";
}
else
{
return storagePath + "-hist";
}
}
// get the path to the file version by the history path and file version
public static string VersionDir(string histPath, int version)
{
return Path.Combine(histPath, version.ToString());
if (S3Helper.Instance.Enabled)
{
return histPath + version + "/";
}
else
{
return Path.Combine(histPath, version.ToString());
}
}
// get the path to the file version by the file name, user address and file version
@ -177,38 +200,62 @@ namespace OnlineEditorsExampleMVC.Helpers
// get a file name with an index if the file with such a name already exists
public static string GetCorrectName(string fileName, string userAddress = null)
{
var baseName = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName).ToLower();
var name = baseName + ext;
for (var i = 1; File.Exists(StoragePath(name, userAddress)); i++) // run through all the files with such a name in the storage directory
if (S3Helper.Instance.Enabled)
{
name = baseName + " (" + i + ")" + ext; // and add an index to the base name
}
return name;
}
var files = S3Helper.Instance.ListAllItemsSync().Select(file => file.Key);
var baseName = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName).ToLower();
var name = baseName + ext;
// get all the stored files from the user host address
public static List<FileInfo> GetStoredFiles()
{
var directory = "";
if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["storage-path"]) && Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]))
{
directory = WebConfigurationManager.AppSettings["storage-path"] + "\\";
for (var i = 1; files.Contains(name); i++) // run through all the files with such a name in the storage directory
{
name = baseName + " (" + i + ")" + ext; // and add an index to the base name
}
return name;
}
else
{
directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(null) + "\\";
var baseName = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName).ToLower();
var name = baseName + ext;
for (var i = 1; File.Exists(StoragePath(name, userAddress)); i++) // run through all the files with such a name in the storage directory
{
name = baseName + " (" + i + ")" + ext; // and add an index to the base name
}
return name;
}
if (!Directory.Exists(directory)) return new List<FileInfo>();
}
var directoryInfo = new DirectoryInfo(directory);
// get all the stored files from the user host address
public static IEnumerable<FileInfoModel> GetStoredFiles()
{
if (S3Helper.Instance.Enabled)
{
var files = S3Helper.Instance.ListAllItemsSync();
return files.Where(file => !file.IsDir).Select(file => FileInfoModel.FromS3(file));
}
else
{
var directory = "";
if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["storage-path"]) && Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]))
{
directory = WebConfigurationManager.AppSettings["storage-path"] + "\\";
}
else
{
directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(null) + "\\";
}
// take files from the root directory
List<FileInfo> storedFiles = directoryInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly).ToList();
if (!Directory.Exists(directory)) return new List<FileInfoModel>();
return storedFiles;
var directoryInfo = new DirectoryInfo(directory);
// take files from the root directory
List<FileInfo> storedFiles = directoryInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly).ToList();
return storedFiles.Select(file => FileInfoModel.FromFileInfo(file));
}
}
// create demo document
@ -219,7 +266,14 @@ namespace OnlineEditorsExampleMVC.Helpers
var fileName = GetCorrectName(demoName); // get a file name with an index if the file with such a name already exists
File.Copy(HttpRuntime.AppDomainAppPath + demoPath + demoName, StoragePath(fileName)); // copy file to the storage directory
if (S3Helper.Instance.Enabled)
{
S3Helper.Instance.UploadFileSync(StoragePath(fileName), HttpRuntime.AppDomainAppPath + demoPath + demoName);
}
else
{
File.Copy(HttpRuntime.AppDomainAppPath + demoPath + demoName, StoragePath(fileName)); // copy file to the storage directory
}
return fileName;
}
@ -228,26 +282,34 @@ namespace OnlineEditorsExampleMVC.Helpers
public static void CreateMeta(string fileName, string uid, string uname, string userAddress = null)
{
var histDir = HistoryDir(StoragePath(fileName, userAddress)); // create history directory
Directory.CreateDirectory(histDir);
// create createdInfo.json file with meta information in the history directory (creation time, user id and name)
File.WriteAllText(Path.Combine(histDir, "createdInfo.json"), new JavaScriptSerializer().Serialize(new Dictionary<string, object> {
{ "created", DateTime.Now.ToString("yyyy'-'MM'-'dd HH':'mm':'ss") },
{ "id", uid },
{ "name", uname }
}));
var content = new JavaScriptSerializer().Serialize(new Dictionary<string, object> {
{ "created", DateTime.Now.ToString("yyyy'-'MM'-'dd HH':'mm':'ss") },
{ "id", uid },
{ "name", uname }
});
if (S3Helper.Instance.Enabled)
{
S3Helper.Instance.UploadFileSync(histDir + "createdInfo.json", S3Helper.StringToStream(content));
}
else
{
Directory.CreateDirectory(histDir);
// create createdInfo.json file with meta information in the history directory (creation time, user id and name)
File.WriteAllText(Path.Combine(histDir, "createdInfo.json"), content);
}
}
// get file url
public static string GetFileUri(string fileName, Boolean forDocumentServer)
{
var uri = new UriBuilder(GetServerUrl(forDocumentServer))
{
Path = HttpRuntime.AppDomainAppVirtualPath
{
Path = HttpRuntime.AppDomainAppVirtualPath
+ (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
+ CurUserHostAddress() + "/"
+ fileName,
Query = ""
};
Query = ""
};
return uri.ToString();
}
@ -326,7 +388,7 @@ namespace OnlineEditorsExampleMVC.Helpers
+ "&fileName=" + HttpUtility.UrlEncode(filename)
+ userAddress
+ "&ver=" + version
+ "&file="+ file
+ "&file=" + file
};
return downloadUrl.ToString();
}
@ -397,14 +459,14 @@ namespace OnlineEditorsExampleMVC.Helpers
// write all the parameters to the map
var dictionary = new Dictionary<string, object>();
dictionary.Add("version", GetFileVersion(file.Name, null));
dictionary.Add("id", ServiceConverter.GenerateRevisionId(DocManagerHelper.CurUserHostAddress() + "/" + file.Name + "/" + File.GetLastWriteTime(DocManagerHelper.StoragePath(file.Name, null)).GetHashCode()));
dictionary.Add("id", ServiceConverter.GenerateRevisionId(DocManagerHelper.CurUserHostAddress() + "/" + file + "/" + file.LastModified.GetHashCode()));
dictionary.Add("contentLength", Math.Round(file.Length / 1024.0, 2) + " KB");
dictionary.Add("pureContentLength", file.Length);
dictionary.Add("title", file.Name);
dictionary.Add("updated", file.LastWriteTime.ToString());
dictionary.Add("title", file);
dictionary.Add("updated", file.LastModified.ToString());
// get file information by its id
if (fileId != null)
if (fileId != null)
{
if (fileId.Equals(dictionary["id"]))
{
@ -425,7 +487,8 @@ namespace OnlineEditorsExampleMVC.Helpers
public static void VerifySSL()
{
// hack. http://ubuntuforums.org/showthread.php?t=1841740
if(WebConfigurationManager.AppSettings["files.docservice.verify-peer-off"].Equals("true")) {
if (WebConfigurationManager.AppSettings["files.docservice.verify-peer-off"].Equals("true"))
{
ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
}
@ -436,9 +499,9 @@ namespace OnlineEditorsExampleMVC.Helpers
var languages = new Dictionary<string, string>();
String[] couples = (WebConfigurationManager.AppSettings["files.docservice.languages"] ?? "").Split('|');
foreach (string couple in couples)
{
{
String[] tmp = couple.Split(':');
languages.Add(tmp[0],tmp[1]);
languages.Add(tmp[0], tmp[1]);
}
return languages;
}

View File

@ -68,24 +68,24 @@ namespace OnlineEditorsExampleMVC.Helpers
/// <param name="toExtension">Extension to which to convert</param>
/// <param name="documentRevisionId">Key for caching on service</param>
/// <param name="isAsync">Perform conversions asynchronously</param>
/// <param name="convertedDocumentData">Uri and file type of the converted document</param>
/// <param name="convertedDocumentUri">Uri to the converted document</param>
/// <returns>The percentage of conversion completion</returns>
/// <example>
/// Dictionary<string, string> convertedDocumentData;
/// GetConvertedData("http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", ".pdf", ".docx", "http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", false, out convertedDocumentData);
/// string convertedDocumentUri;
/// GetConvertedUri("http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", ".pdf", ".docx", "http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", false, out convertedDocumentUri);
/// </example>
/// <exception>
/// </exception>
public static int GetConvertedData(string documentUri,
public static int GetConvertedUri(string documentUri,
string fromExtension,
string toExtension,
string documentRevisionId,
bool isAsync,
out Dictionary<string, string> convertedDocumentData,
out string convertedDocumentUri,
string filePass = null,
string lang = null)
{
convertedDocumentData = new Dictionary<string, string>();
convertedDocumentUri = string.Empty;
// check if the fromExtension parameter is defined; if not, get it from the document url
fromExtension = string.IsNullOrEmpty(fromExtension) ? Path.GetExtension(documentUri).ToLower() : fromExtension;
@ -119,7 +119,7 @@ namespace OnlineEditorsExampleMVC.Helpers
{ "region", lang }
};
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
if (JwtManager.Enabled)
{
// create payload object
var payload = new Dictionary<string, object>
@ -157,7 +157,7 @@ namespace OnlineEditorsExampleMVC.Helpers
}
}
return GetResponseData(dataResponse, out convertedDocumentData);
return GetResponseUri(dataResponse, out convertedDocumentUri);
}
/// <summary>
@ -181,9 +181,9 @@ namespace OnlineEditorsExampleMVC.Helpers
/// Processing document received from the editing service
/// </summary>
/// <param name="jsonDocumentResponse">The resulting json from editing service</param>
/// <param name="responseData">Uri and file type of the converted document</param>
/// <param name="responseUri">Uri to the converted document</param>
/// <returns>The percentage of conversion completion</returns>
private static int GetResponseData(string jsonDocumentResponse, out Dictionary<string, string> responseData)
private static int GetResponseUri(string jsonDocumentResponse, out string responseUri)
{
if (string.IsNullOrEmpty(jsonDocumentResponse)) throw new ArgumentException("Invalid param", "jsonDocumentResponse");
@ -197,20 +197,14 @@ namespace OnlineEditorsExampleMVC.Helpers
var isEndConvert = responseFromService.endConvert;
int resultPercent;
responseData = new Dictionary<string, string>();
var responseUri = string.Empty;
var responseFileType = string.Empty;
responseUri = string.Empty;
if (isEndConvert) // if the conversion is completed
{
responseUri = responseFromService.fileUrl; // get the file url
responseFileType = responseFromService.fileType; // get the file type
responseData.Add("fileUrl", responseUri);
responseData.Add("fileType", responseFileType);
resultPercent = 100;
}
else // if the conversion isn't completed
{
responseData.Add("fileUrl", "");
resultPercent = responseFromService.percent; // get the percentage value
if (resultPercent >= 100) resultPercent = 99;
}

View File

@ -29,13 +29,11 @@ namespace OnlineEditorsExampleMVC.Helpers
{
private static readonly string Secret;
public static readonly bool Enabled;
public static readonly bool SignatureUseForRequest;
static JwtManager()
{
Secret = WebConfigurationManager.AppSettings["files.docservice.secret"] ?? ""; // get token secret from the config parameters
Enabled = !string.IsNullOrEmpty(Secret); // check if the token is enabled
SignatureUseForRequest = bool.Parse(WebConfigurationManager.AppSettings["files.docservice.token.useforrequest"]);
}
// encode a payload object into a token using a secret key

View File

@ -0,0 +1,159 @@
using Minio;
using Minio.DataModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
namespace OnlineEditorsExampleMVC.Helpers
{
public class S3Helper
{
private S3Helper()
{
bool.TryParse(WebConfigurationManager.AppSettings["s3-enabled"], out var enable);
if (enable)
{
MinioClient = new MinioClient()
.WithEndpoint(WebConfigurationManager.AppSettings["s3-endpoint"])
.WithCredentials(WebConfigurationManager.AppSettings["s3-access-key"], WebConfigurationManager.AppSettings["s3-secret-key"])
.WithRegion(WebConfigurationManager.AppSettings["s3-region"]);
if (bool.Parse(WebConfigurationManager.AppSettings["s3-secure"]))
{
MinioClient.WithSSL();
}
MinioClient.Build();
}
}
private static S3Helper instance;
public static S3Helper Instance
{
get
{
if (instance == null)
{
instance = new S3Helper();
}
return instance;
}
}
private string Bucket { get { return WebConfigurationManager.AppSettings["s3-bucket"]; } }
private MinioClient MinioClient { get; set; }
public bool Enabled { get { return MinioClient != null; } }
public List<Item> ListAllItemsSync(string prefix = null)
{
return AwaitTaskSync(() => ListAllItems(prefix));
}
public void UploadFileSync(string name, string path)
{
AwaitTaskSync(() => UploadFile(name, path));
}
public void UploadFileSync(string name, Stream stream)
{
AwaitTaskSync(() => UploadFile(name, stream));
}
public void RemoveFilesSync(IEnumerable<string> names)
{
AwaitTaskSync(() => RemoveFiles(names));
}
public Stream DownloadFileSync(string name)
{
return AwaitTaskSync(() => DownloadFile(name));
}
public void CopyFileSync(string oldname, string newname)
{
AwaitTaskSync(() => CopyFile(oldname, newname));
}
private async Task<List<Item>> ListAllItems(string prefix = null)
{
var list = new List<Item>();
var shouldWait = true;
var args = new ListObjectsArgs().WithBucket(Bucket).WithRecursive(false);
if (!string.IsNullOrWhiteSpace(prefix))
{
args.WithPrefix(prefix).WithRecursive(true);
}
var observable = MinioClient.ListObjectsAsync(args);
var subscription = observable.Subscribe(item => list.Add(item), () => shouldWait = false);
while (shouldWait)
{
await Task.Delay(100);
}
return list;
}
private async Task UploadFile(string name, string path)
{
using (var stream = File.OpenRead(path))
{
await UploadFile(name, stream);
}
}
private async Task UploadFile(string name, Stream stream)
{
await MinioClient.PutObjectAsync(new PutObjectArgs().WithBucket(Bucket).WithObject(name).WithObjectSize(stream.Length).WithStreamData(stream));
}
private async Task RemoveFiles(IEnumerable<string> names)
{
await MinioClient.RemoveObjectsAsync(new RemoveObjectsArgs().WithBucket(Bucket).WithObjects(names.ToList()));
}
private async Task CopyFile(string oldname, string newname)
{
await MinioClient.CopyObjectAsync(new CopyObjectArgs().WithBucket(Bucket).WithObject(newname)
.WithCopyObjectSource(new CopySourceObjectArgs().WithBucket(Bucket).WithObject(oldname)));
}
private async Task<Stream> DownloadFile(string name)
{
Stream stream = null;
var shouldWait = true;
await MinioClient.GetObjectAsync(new GetObjectArgs().WithBucket(Bucket).WithObject(name).WithCallbackStream((s) =>
{
stream = s;
shouldWait = false;
}));
while (shouldWait)
{
await Task.Delay(100);
}
return stream;
}
private void AwaitTaskSync(Func<Task> f)
{
Task.Run(() => f()).GetAwaiter().GetResult();
}
private T AwaitTaskSync<T>(Func<Task<T>> f)
{
return Task.Run(() => f()).GetAwaiter().GetResult();
}
public static Stream StringToStream(string content)
{
return new MemoryStream(Encoding.UTF8.GetBytes(content ?? ""));
}
}
}

View File

@ -53,7 +53,7 @@ namespace OnlineEditorsExampleMVC.Helpers
var fileData = jss.Deserialize<Dictionary<string, object>>(body);
// check if the document token is enabled
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
if (JwtManager.Enabled)
{
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
@ -92,7 +92,8 @@ namespace OnlineEditorsExampleMVC.Helpers
// file saving process
public static int processSave(Dictionary<string, object> fileData, string fileName, string userAddress)
{
if (string.IsNullOrEmpty((string)fileData["url"])) {
if (string.IsNullOrEmpty((string)fileData["url"]))
{
throw new Exception("DownloadUrl is null");
}
var downloadUri = (string)fileData["url"];
@ -108,19 +109,18 @@ namespace OnlineEditorsExampleMVC.Helpers
try
{
// convert file and give url to a new file
Dictionary<string, string> newFileData;
var result = ServiceConverter.GetConvertedData(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileData);
var newFileUri = newFileData["fileUrl"];
string newFileUri;
var result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
if (string.IsNullOrEmpty(newFileUri))
{
// get the correct file name if it already exists
newFileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
}
else
else
{
downloadUri = newFileUri;
}
}
}
catch (Exception)
{
newFileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
@ -129,48 +129,57 @@ namespace OnlineEditorsExampleMVC.Helpers
DocManagerHelper.VerifySSL();
try
var storagePath = DocManagerHelper.StoragePath(newFileName, userAddress); // get the file path
var histDir = DocManagerHelper.HistoryDir(storagePath); // get the path to the history directory
if (!S3Helper.Instance.Enabled)
{
var bytesFile = DownloadFile(downloadUri); // download document file
var storagePath = DocManagerHelper.StoragePath(newFileName, userAddress); // get the file path
var histDir = DocManagerHelper.HistoryDir(storagePath); // get the path to the history directory
if (!Directory.Exists(histDir)) Directory.CreateDirectory(histDir);
}
var versionDir = DocManagerHelper.VersionDir(histDir, DocManagerHelper.GetFileVersion(histDir)); // get the path to the file version
var versionDir = DocManagerHelper.VersionDir(histDir, DocManagerHelper.GetFileVersion(histDir)); // get the path to the file version
if (!S3Helper.Instance.Enabled)
{
if (!Directory.Exists(versionDir)) Directory.CreateDirectory(versionDir); // if the path doesn't exist, create it
}
if (S3Helper.Instance.Enabled)
{
S3Helper.Instance.CopyFileSync(fileName, versionDir + "prev" + curExt);
}
else
{
// get the path to the previous file version and move it to the storage directory
File.Move(DocManagerHelper.StoragePath(fileName, userAddress), Path.Combine(versionDir, "prev" + curExt));
}
SaveFile(bytesFile, storagePath);// save document file
DownloadToFile(downloadUri, storagePath); // save file to the storage directory
DownloadToFile((string)fileData["changesurl"], S3Helper.Instance.Enabled ? versionDir + "diff.zip" : Path.Combine(versionDir, "diff.zip")); // save file changes to the diff.zip archive
byte[] bytesChanges = DownloadFile((string)fileData["changesurl"]); // download changes file
SaveFile(bytesChanges, Path.Combine(versionDir, "diff.zip")); // save file changes to the diff.zip archive
var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;
if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
{
var jss = new JavaScriptSerializer();
hist = jss.Serialize(fileData["history"]);
}
var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;
if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
if (!string.IsNullOrEmpty(hist))
{
if (S3Helper.Instance.Enabled)
{
var jss = new JavaScriptSerializer();
hist = jss.Serialize(fileData["history"]);
S3Helper.Instance.UploadFileSync(versionDir + "changes.json", S3Helper.StringToStream(hist));
}
if (!string.IsNullOrEmpty(hist))
else
{
File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist); // write the history changes to the changes.json file
}
}
File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]); // write the key value to the key.txt file
File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]); // write the key value to the key.txt file
string forcesavePath = DocManagerHelper.ForcesavePath(newFileName, userAddress, false); // get the path to the forcesaved file version
if (!forcesavePath.Equals("")) // if the forcesaved file version exists
{
File.Delete(forcesavePath); // remove it
}
} catch (Exception)
string forcesavePath = DocManagerHelper.ForcesavePath(newFileName, userAddress, false); // get the path to the forcesaved file version
if (!forcesavePath.Equals("")) // if the forcesaved file version exists
{
return 1;
File.Delete(forcesavePath); // remove it
}
return 0;
@ -179,7 +188,8 @@ namespace OnlineEditorsExampleMVC.Helpers
// file force saving process
public static int processForceSave(Dictionary<string, object> fileData, string fileName, string userAddress)
{
if ( string.IsNullOrEmpty((string)fileData["url"])) {
if (string.IsNullOrEmpty((string)fileData["url"]))
{
throw new Exception("DownloadUrl is null");
}
var downloadUri = (string)fileData["url"];
@ -196,18 +206,17 @@ namespace OnlineEditorsExampleMVC.Helpers
try
{
// convert file and give url to a new file
Dictionary<string, string> newFileData;
var result = ServiceConverter.GetConvertedData(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileData);
var newFileUri = newFileData["fileUrl"];
string newFileUri;
var result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
if (string.IsNullOrEmpty(newFileUri))
{
newFileName = true;
}
else
else
{
downloadUri = newFileUri;
}
}
}
catch (Exception)
{
newFileName = true;
@ -216,50 +225,43 @@ namespace OnlineEditorsExampleMVC.Helpers
DocManagerHelper.VerifySSL();
try
string forcesavePath = "";
Boolean isSubmitForm = fileData["forcesavetype"].ToString().Equals("3"); // SubmitForm
if (isSubmitForm) // if the form is submitted
{
var bytesFile = DownloadFile(downloadUri); // download document file
string forcesavePath = "";
Boolean isSubmitForm = fileData["forcesavetype"].ToString().Equals("3"); // SubmitForm
if (isSubmitForm) // if the form is submitted
if (newFileName)
{
if (newFileName)
{
fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress); // get the correct file name if it already exists
} else
{
fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + curExt, userAddress);
}
forcesavePath = DocManagerHelper.StoragePath(fileName, userAddress);
fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress); // get the correct file name if it already exists
}
else
{
if (newFileName)
{
fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
}
forcesavePath = DocManagerHelper.ForcesavePath(fileName, userAddress, false);
if (string.IsNullOrEmpty(forcesavePath)) // create forcesave path if it doesn't exist
{
forcesavePath = DocManagerHelper.ForcesavePath(fileName, userAddress, true);
}
fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + curExt, userAddress);
}
SaveFile(bytesFile, forcesavePath);// save document file
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
DocManagerHelper.CreateMeta(fileName, user, "Filling Form", userAddress); // create meta data for the forcesaved file
}
} catch (Exception)
forcesavePath = DocManagerHelper.StoragePath(fileName, userAddress);
}
else
{
return 1;
if (newFileName)
{
fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
}
forcesavePath = DocManagerHelper.ForcesavePath(fileName, userAddress, false);
if (string.IsNullOrEmpty(forcesavePath)) // create forcesave path if it doesn't exist
{
forcesavePath = DocManagerHelper.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
DocManagerHelper.CreateMeta(fileName, user, "Filling Form", userAddress); // create meta data for the forcesaved file
}
return 0;
@ -281,13 +283,13 @@ namespace OnlineEditorsExampleMVC.Helpers
{ "key", key }
};
if (meta != null)
if (meta != null)
{
body.Add("meta", meta);
}
// check if a secret key to generate token exists or not
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
if (JwtManager.Enabled)
{
var payload = new Dictionary<string, object>
{
@ -331,30 +333,34 @@ namespace OnlineEditorsExampleMVC.Helpers
}
}
// save file
private static void SaveFile(byte[] data, string path)
{
using (var fs = File.Open(path, FileMode.Create))
{
fs.Write(data, 0, data.Length);
}
}
// save file information from the url to the file specified
private static byte[] DownloadFile(string url)
private static void DownloadToFile(string url, string path)
{
if (string.IsNullOrEmpty(url)) throw new ArgumentException("url"); // url isn't specified
if (string.IsNullOrEmpty(path)) throw new ArgumentException("path"); // file isn't specified
var req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = 5000;
using (var stream = req.GetResponse().GetResponseStream()) // get input stream of the file information from the url
{
if (stream == null) throw new Exception("stream is null");
using (MemoryStream memoryStream = new MemoryStream())
if (S3Helper.Instance.Enabled)
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
S3Helper.Instance.UploadFileSync(path, stream);
}
else
{
const int bufferSize = 4096;
using (var fs = File.Open(path, 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
}
}
}
}
}

View File

@ -69,7 +69,6 @@ namespace OnlineEditorsExampleMVC.Helpers
"Cant see anyones information",
"Can't rename files from the editor",
"Can't view chat",
"Can't protect file",
"View file without collaboration",
};
@ -132,7 +131,7 @@ namespace OnlineEditorsExampleMVC.Helpers
new Dictionary<string,object>(),
new List<string>(),
null,
new List<string>() { "protect" },
new List<string>(),
descr_user_0,
false
)

View File

@ -0,0 +1,33 @@
using Minio.DataModel;
using System;
using System.IO;
namespace OnlineEditorsExampleMVC.Models
{
public class FileInfoModel
{
public string Name { get; set; }
public DateTime LastModified { get; set; }
public long Length { get; set; }
public static FileInfoModel FromFileInfo(FileInfo info)
{
return new FileInfoModel()
{
Name = info.Name,
LastModified = info.LastWriteTime,
Length = info.Length
};
}
public static FileInfoModel FromS3(Item info)
{
return new FileInfoModel()
{
Name = info.Key,
LastModified = info.LastModifiedDateTime.Value,
Length = (long)info.Size
};
}
}
}

View File

@ -24,6 +24,7 @@ using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using OnlineEditorsExampleMVC.Helpers;
namespace OnlineEditorsExampleMVC.Models
@ -75,8 +76,6 @@ namespace OnlineEditorsExampleMVC.Models
// get the document config
public string GetDocConfig(HttpRequest request, UrlHelper url)
{
var jss = new JavaScriptSerializer();
var ext = Path.GetExtension(FileName).ToLower(); // get file extension
var editorsMode = Mode ?? "edit"; // get editor mode
@ -96,7 +95,7 @@ namespace OnlineEditorsExampleMVC.Models
bool? favorite = user.favorite;
var actionLink = request.GetOrDefault("actionLink", null); // get the action link (comment or bookmark) if it exists
var actionData = string.IsNullOrEmpty(actionLink) ? null : jss.DeserializeObject(actionLink); // get action data for the action link
var actionData = string.IsNullOrEmpty(actionLink) ? null : JsonConvert.DeserializeObject(actionLink); // get action data for the action link
var directUrl = DocManagerHelper.GetDownloadUrl(FileName, false);
var createUrl = DocManagerHelper.GetCreateUrl(FileUtility.GetFileType(FileName));
@ -138,17 +137,6 @@ namespace OnlineEditorsExampleMVC.Models
{ "favorite", favorite}
}
},
{
"referenceData", new Dictionary<string, string>()
{
{ "fileKey", !user.id.Equals("uid-0") ?
jss.Serialize(new Dictionary<string, object>{
{"fileName", FileName},
{"userAddress", HttpUtility.UrlEncode(DocManagerHelper.CurUserHostAddress(HttpContext.Current.Request.UserHostAddress))}
}) : null },
{"instanceId", DocManagerHelper.GetServerUrl(false) }
}
},
{
// the permission for the document to be edited and downloaded or not
"permissions", new Dictionary<string, object>
@ -165,8 +153,7 @@ namespace OnlineEditorsExampleMVC.Models
{ "chat", !user.id.Equals("uid-0") },
{ "reviewGroups", user.reviewGroups },
{ "commentGroups", user.commentGroups },
{ "userInfoGroups", user.userInfoGroups },
{ "protect", !user.deniedPermissions.Contains("protect") }
{ "userInfoGroups", user.userInfoGroups }
}
}
}
@ -233,7 +220,7 @@ namespace OnlineEditorsExampleMVC.Models
config.Add("token", token);
}
return jss.Serialize(config);
return JsonConvert.SerializeObject(config, Formatting.Indented);
}
// get the document history

View File

@ -43,15 +43,92 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Crc32.NET, Version=1.0.0.0, Culture=neutral, PublicKeyToken=dc0b95cf99bf4e99, processorArchitecture=MSIL">
<HintPath>packages\Crc32.NET.1.2.0\lib\net20\Crc32.NET.dll</HintPath>
</Reference>
<Reference Include="JWT, Version=9.0.0.0, Culture=neutral, PublicKeyToken=6f98bca0f40f2ecf, processorArchitecture=MSIL">
<HintPath>packages\JWT.9.0.3\lib\net46\JWT.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.Web.Infrastructure, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Web.Infrastructure.2.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
</Reference>
<Reference Include="Minio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=348239ebd7debb4c, processorArchitecture=MSIL">
<HintPath>packages\Minio.4.0.0\lib\net46\Minio.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Net.Http" />
<Reference Include="System.IO, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\System.IO.4.3.0\lib\net462\System.IO.dll</HintPath>
<Private>True</Private>
<Private>True</Private>
</Reference>
<Reference Include="System.Net.Http, Version=4.1.1.3, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll</HintPath>
<Private>True</Private>
<Private>True</Private>
</Reference>
<Reference Include="System.Net.Http.Formatting, Version=5.2.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.WebApi.Client.5.2.9\lib\net45\System.Net.Http.Formatting.dll</HintPath>
</Reference>
<Reference Include="System.Reactive, Version=5.0.0.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263, processorArchitecture=MSIL">
<HintPath>packages\System.Reactive.5.0.0\lib\net472\System.Reactive.dll</HintPath>
</Reference>
<Reference Include="System.Reactive.Linq, Version=3.0.6000.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263, processorArchitecture=MSIL">
<HintPath>packages\System.Reactive.Linq.5.0.0\lib\net472\System.Reactive.Linq.dll</HintPath>
</Reference>
<Reference Include="System.Runtime, Version=4.1.1.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\System.Runtime.4.3.1\lib\net462\System.Runtime.dll</HintPath>
<Private>True</Private>
<Private>True</Private>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Security.Cryptography.Algorithms, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\System.Security.Cryptography.Algorithms.4.3.1\lib\net463\System.Security.Cryptography.Algorithms.dll</HintPath>
<Private>True</Private>
<Private>True</Private>
</Reference>
<Reference Include="System.Security.Cryptography.Encoding, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll</HintPath>
<Private>True</Private>
<Private>True</Private>
</Reference>
<Reference Include="System.Security.Cryptography.Primitives, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll</HintPath>
<Private>True</Private>
<Private>True</Private>
</Reference>
<Reference Include="System.Security.Cryptography.X509Certificates, Version=4.1.1.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\System.Security.Cryptography.X509Certificates.4.3.2\lib\net461\System.Security.Cryptography.X509Certificates.dll</HintPath>
<Private>True</Private>
<Private>True</Private>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.WebPages.3.2.9\lib\net45\System.Web.Helpers.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http, Version=5.2.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.WebApi.Core.5.2.9\lib\net45\System.Web.Http.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http.WebHost, Version=5.2.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.WebApi.WebHost.5.2.9\lib\net45\System.Web.Http.WebHost.dll</HintPath>
</Reference>
<Reference Include="System.Web.Mvc, Version=5.2.9.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.Mvc.5.2.9\lib\net45\System.Web.Mvc.dll</HintPath>
</Reference>
<Reference Include="System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.Razor.3.2.9\lib\net45\System.Web.Razor.dll</HintPath>
</Reference>
<Reference Include="System.Web.Services" />
<Reference Include="Antlr3.Runtime, Version=3.5.0.2, Culture=neutral, PublicKeyToken=eb42632606e9261f, processorArchitecture=MSIL">
<HintPath>packages\Antlr.3.5.0.2\lib\Antlr3.Runtime.dll</HintPath>
@ -59,45 +136,27 @@
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>packages\EntityFramework.6.4.4\lib\net45\EntityFramework.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System.Net.Http.Formatting, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.WebApi.Client.5.2.7\lib\net45\System.Net.Http.Formatting.dll</HintPath>
</Reference>
<Reference Include="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.WebPages.3.2.7\lib\net45\System.Web.Helpers.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.WebApi.Core.5.2.7\lib\net45\System.Web.Http.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http.WebHost, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.WebApi.WebHost.5.2.7\lib\net45\System.Web.Http.WebHost.dll</HintPath>
</Reference>
<Reference Include="System.Web.Mvc, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.Mvc.5.2.7\lib\net45\System.Web.Mvc.dll</HintPath>
</Reference>
<Reference Include="System.Web.Optimization, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.Web.Optimization.1.1.3\lib\net40\System.Web.Optimization.dll</HintPath>
</Reference>
<Reference Include="System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.Razor.3.2.7\lib\net45\System.Web.Razor.dll</HintPath>
</Reference>
<Reference Include="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.WebPages.3.2.7\lib\net45\System.Web.WebPages.dll</HintPath>
<HintPath>packages\Microsoft.AspNet.WebPages.3.2.9\lib\net45\System.Web.WebPages.dll</HintPath>
</Reference>
<Reference Include="System.Web.WebPages.Deployment, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.WebPages.3.2.7\lib\net45\System.Web.WebPages.Deployment.dll</HintPath>
<HintPath>packages\Microsoft.AspNet.WebPages.3.2.9\lib\net45\System.Web.WebPages.Deployment.dll</HintPath>
</Reference>
<Reference Include="System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.AspNet.WebPages.3.2.7\lib\net45\System.Web.WebPages.Razor.dll</HintPath>
<HintPath>packages\Microsoft.AspNet.WebPages.3.2.9\lib\net45\System.Web.WebPages.Razor.dll</HintPath>
</Reference>
<Reference Include="System.Windows" />
<Reference Include="System.Windows.Forms" />
<Reference Include="WebGrease, Version=1.6.5135.21930, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\WebGrease.1.6.0\lib\WebGrease.dll</HintPath>
</Reference>
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="App_Start\BundleConfig.cs" />
@ -108,12 +167,14 @@
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="Helpers\S3Helper.cs" />
<Compile Include="Helpers\TrackManager.cs" />
<Compile Include="Helpers\DocManagerHelper.cs" />
<Compile Include="Helpers\DocumentConverter.cs" />
<Compile Include="Helpers\JwtManager.cs" />
<Compile Include="Helpers\Users.cs" />
<Compile Include="Helpers\Utils.cs" />
<Compile Include="Models\FileInfoModel.cs" />
<Compile Include="Models\FileModel.cs" />
<Compile Include="Models\FileUtility.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />

View File

@ -31,7 +31,7 @@
-->
<link rel="icon" href="<%= "content/images/" + Model.DocumentType + ".ico" %>" type="image/x-icon" />
<title><%= Model.FileName + " - ONLYOFFICE" %></title>
<%: Styles.Render("~/Content/editor") %>
</head>
@ -40,7 +40,7 @@
<div id="iframeEditor">
</div>
</div>
<%: Scripts.Render(new []{ WebConfigurationManager.AppSettings["files.docservice.url.site"] + WebConfigurationManager.AppSettings["files.docservice.url.api"] }) %>
<script type="text/javascript" language="javascript">
@ -141,7 +141,7 @@
<% Model.GetMailMergeConfig(out dataMailMergeRecipients); %>
docEditor.setMailMergeRecipients(<%= dataMailMergeRecipients%>); // insert recipient data for mail merge into the file
};
var onRequestSaveAs = function (event) { // the user is trying to save file by clicking Save Copy as... button
var title = event.data.title;
var url = event.data.url;
@ -178,18 +178,6 @@
}
};
var onRequestReferenceData = function (event) { // user refresh external data source
event.data.directUrl = !!config.document.directUrl;
let xhr = new XMLHttpRequest();
xhr.open("POST", "webeditor.ashx?type=reference");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(event.data));
xhr.onload = function () {
console.log(xhr.responseText);
docEditor.setReferenceData(JSON.parse(xhr.responseText));
}
};
config = <%= Model.GetDocConfig(Request, Url) %>;
config.width = "100%";
@ -198,6 +186,7 @@
config.events = {
'onAppReady': onAppReady,
'onDocumentStateChange': onDocumentStateChange,
'onRequestEditRights': onRequestEditRights,
'onError': onError,
'onOutdatedVersion': onOutdatedVersion,
"onMakeActionLink": onMakeActionLink,
@ -227,7 +216,7 @@
docEditor.setHistoryData(histData[ver - 1]); // send the link to the document for viewing the version history
};
// the user is trying to go back to the document from viewing the document version history
config.events['onRequestHistoryClose'] = function () {
config.events['onRequestHistoryClose '] = function () {
document.location.reload();
};
<% } %>
@ -250,9 +239,6 @@
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
config.events['onRequestReferenceData'] = onRequestReferenceData;
// prevent switch the document from the viewing into the editing mode for anonymous users
config.events['onRequestEditRights'] = onRequestEditRights;
}
if (config.editorConfig.createUrl) {

View File

@ -53,6 +53,10 @@
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
@ -63,11 +67,27 @@
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
<bindingRedirect oldVersion="1.0.0.0-5.2.9.0" newVersion="5.2.9.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.9.0" newVersion="5.2.9.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Web.Infrastructure" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Reactive" publicKeyToken="94bc3704cddfc263" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>

View File

@ -74,9 +74,6 @@ namespace OnlineEditorsExampleMVC
case "rename":
Rename(context);
break;
case "reference":
Reference(context);
break;
}
}
@ -85,7 +82,7 @@ namespace OnlineEditorsExampleMVC
context.Response.ContentType = "text/plain";
try
{
string fileData;
string fileData;
try
{
using (var receiveStream = context.Request.InputStream)
@ -99,53 +96,60 @@ namespace OnlineEditorsExampleMVC
{
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 fileUrl = (string)body["url"];
var title = (string)body["title"];
var fileName = DocManagerHelper.GetCorrectName(title);
var extension = "." + (Path.GetExtension(fileName).ToLower() ?? "").Trim('.');
var allExt = DocManagerHelper.ConvertExts
.Concat(DocManagerHelper.EditedExts)
.Concat(DocManagerHelper.ViewedExts)
.Concat(DocManagerHelper.FillFormExts)
.ToArray();
if (!allExt.Contains(extension))
{
{
context.Response.Write("{\"error\":\"File type is not supported\"}");
}
var req = (HttpWebRequest)WebRequest.Create(fileUrl);
DocManagerHelper.VerifySSL();
using (var stream = req.GetResponse().GetResponseStream())
{
if (stream == null || req.GetResponse().ContentLength <= 0 || req.GetResponse().ContentLength > DocManagerHelper.MaxFileSize)
{
context.Response.Write("{\"error\": \"File size is incorrect\"}");
}
const int bufferSize = 4096;
using (var fs = File.Open(DocManagerHelper.StoragePath(fileName, null), FileMode.Create))
if (S3Helper.Instance.Enabled)
{
var buffer = new byte[bufferSize];
int readed;
while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
S3Helper.Instance.UploadFileSync(fileName, stream);
}
else
{
const int bufferSize = 4096;
using (var fs = File.Open(DocManagerHelper.StoragePath(fileName, null), FileMode.Create))
{
fs.Write(buffer, 0, readed); // write bytes to the output stream
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
DocManagerHelper.CreateMeta(fileName, user.id, user.name, null);
context.Response.Write("{ \"file\": \"" + fileName + "\"}");
}
catch (Exception e)
@ -161,7 +165,7 @@ namespace OnlineEditorsExampleMVC
try
{
DocManagerHelper.VerifySSL();
var httpPostedFile = context.Request.Files[0];
string fileName;
@ -191,8 +195,15 @@ namespace OnlineEditorsExampleMVC
fileName = DocManagerHelper.GetCorrectName(fileName); // get the correct file name if such a name already exists
var documentType = FileUtility.GetFileType(fileName).ToString().ToLower();
var savedFileName = DocManagerHelper.StoragePath(fileName); // get the storage path to the uploading file
httpPostedFile.SaveAs(savedFileName); // and save it
if (S3Helper.Instance.Enabled)
{
S3Helper.Instance.UploadFileSync(fileName, httpPostedFile.InputStream);
}
else
{
var savedFileName = DocManagerHelper.StoragePath(fileName); // 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);
@ -230,10 +241,11 @@ namespace OnlineEditorsExampleMVC
var fileUri = DocManagerHelper.GetDownloadUrl(fileName);
var extension = (Path.GetExtension(fileName).ToLower() ?? "").Trim('.');
var internalExtension = "ooxml";
var internalExtension = DocManagerHelper.GetInternalExtension(FileUtility.GetFileType(fileName)).Trim('.');
// check if the file with such an extension can be converted
if (DocManagerHelper.ConvertExts.Contains("." + extension))
if (DocManagerHelper.ConvertExts.Contains("." + extension)
&& !string.IsNullOrEmpty(internalExtension))
{
// generate document key
var key = ServiceConverter.GenerateRevisionId(fileUri);
@ -246,11 +258,9 @@ namespace OnlineEditorsExampleMVC
Query = "type=download&fileName=" + HttpUtility.UrlEncode(fileName)
};
// get the url and file type of the converted file
Dictionary<string, string> newFileData;
var result = ServiceConverter.GetConvertedData(downloadUri.ToString(), extension, internalExtension, key, true, out newFileData, filePass, lang);
var newFileUri = newFileData["fileUrl"];
var newFileType = "." + newFileData["fileType"];
// get the url to the converted file
string newFileUri;
var result = ServiceConverter.GetConvertedUri(downloadUri.ToString(), extension, internalExtension, key, true, out newFileUri, filePass, lang);
if (result != 100)
{
context.Response.Write("{ \"step\" : \"" + result + "\", \"filename\" : \"" + fileName + "\"}");
@ -258,7 +268,7 @@ namespace OnlineEditorsExampleMVC
}
// get a file name of an internal file extension with an index if the file with such a name already exists
var correctName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + newFileType);
var correctName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "." + internalExtension);
var req = (HttpWebRequest)WebRequest.Create(newFileUri);
@ -267,15 +277,29 @@ namespace OnlineEditorsExampleMVC
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(DocManagerHelper.StoragePath(correctName), FileMode.Create))
if (S3Helper.Instance.Enabled)
{
var buffer = new byte[bufferSize];
int readed;
while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
var path = Path.Combine(Path.GetTempPath(), $"temp-conv-upload-{DateTime.Now.Ticks}");
using (var file = File.Open(path, FileMode.Create))
{
fs.Write(buffer, 0, readed); // write bytes to the output stream
stream.CopyTo(file);
}
S3Helper.Instance.UploadFileSync(correctName, path);
File.Delete(path);
}
else
{
const int bufferSize = 4096;
using (var fs = File.Open(DocManagerHelper.StoragePath(correctName), 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
}
}
}
}
@ -316,7 +340,7 @@ namespace OnlineEditorsExampleMVC
var userAddress = context.Request["userAddress"];
var fileName = Path.GetFileName(context.Request["fileName"]);
var status = (TrackerStatus) (int) fileData["status"]; // get status from the request body
var status = (TrackerStatus)(int)fileData["status"]; // get status from the request body
var saved = 0;
switch (status)
{
@ -324,8 +348,8 @@ namespace OnlineEditorsExampleMVC
try
{
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 actions = jss.Deserialize<List<object>>(jss.Serialize(fileData["actions"]));
var action = jss.Deserialize<Dictionary<string, object>>(jss.Serialize(actions[0]));
if (action != null && action["type"].ToString().Equals("0")) // finished edit
{
var user = action["userid"].ToString(); // the user who finished editing
@ -400,8 +424,17 @@ namespace OnlineEditorsExampleMVC
var path = DocManagerHelper.StoragePath(fileName, null); // delete file
var histDir = DocManagerHelper.HistoryDir(path); // delete file history
if (File.Exists(path)) File.Delete(path);
if (Directory.Exists(histDir)) Directory.Delete(histDir, true);
if (S3Helper.Instance.Enabled)
{
var filesToRemove = S3Helper.Instance.ListAllItemsSync(histDir).Select(file => file.Key).ToList();
filesToRemove.Add(path);
S3Helper.Instance.RemoveFilesSync(filesToRemove);
}
else
{
if (File.Exists(path)) File.Delete(path);
if (Directory.Exists(histDir)) Directory.Delete(histDir, true);
}
}
// get files information
@ -460,26 +493,25 @@ namespace OnlineEditorsExampleMVC
{
try
{
var fileName = Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]) ? context.Request["fileName"]
var fileName = Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]) ? context.Request["fileName"]
: Path.GetFileName(context.Request["fileName"]);
var userAddress = context.Request["userAddress"];
var isEmbedded = context.Request["dmode"];
if (JwtManager.Enabled && isEmbedded == null && userAddress != null && JwtManager.SignatureUseForRequest)
if (JwtManager.Enabled && isEmbedded == null)
{
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
string token = "";
if (context.Request.Headers.AllKeys.Contains(JWTheader, StringComparer.InvariantCultureIgnoreCase))
{
var headerToken = context.Request.Headers.Get(JWTheader).Substring("Bearer ".Length);
token = JwtManager.Decode(headerToken);
}
if (string.IsNullOrEmpty(token))
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
context.Response.Write("JWT validation failed");
return;
string token = JwtManager.Decode(headerToken);
if (string.IsNullOrEmpty(token))
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
context.Response.Write("JWT validation failed");
return;
}
}
}
@ -490,7 +522,7 @@ namespace OnlineEditorsExampleMVC
}
download(filePath, context);
}
catch (Exception)
catch (Exception ex)
{
context.Response.Write("{ \"error\": \"File not found!\"}");
}
@ -499,13 +531,22 @@ namespace OnlineEditorsExampleMVC
// download data from the url to the file
private static void download(string filePath, HttpContext context)
{
var fileinf = new FileInfo(filePath);
context.Response.AddHeader("Content-Length", fileinf.Length.ToString()); // set headers to the response
context.Response.AddHeader("Content-Type", MimeMapping.GetMimeMapping(filePath));
var tmp = HttpUtility.UrlEncode(Path.GetFileName(filePath));
tmp = tmp.Replace("+", "%20");
context.Response.AddHeader("Content-Disposition", "attachment; filename*=UTF-8\'\'" + tmp);
context.Response.TransmitFile(filePath);
if (S3Helper.Instance.Enabled)
{
var stream = S3Helper.Instance.DownloadFileSync(filePath);
stream.CopyTo(context.Response.OutputStream);
}
else
{
var fileinf = new FileInfo(filePath);
context.Response.AddHeader("Content-Length", fileinf.Length.ToString()); // set headers to the response
context.Response.TransmitFile(filePath);
}
}
public bool IsReusable
@ -523,7 +564,7 @@ namespace OnlineEditorsExampleMVC
var version = System.Convert.ToInt32(context.Request["ver"]);
var file = Path.GetFileName(context.Request["file"]);
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
if (JwtManager.Enabled)
{
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
@ -547,7 +588,15 @@ namespace OnlineEditorsExampleMVC
}
}
var histPath = DocManagerHelper.HistoryDir(DocManagerHelper.StoragePath(fileName, userAddress));
var filePath = Path.Combine(DocManagerHelper.VersionDir(histPath, version), file); // get the path to document version
string filePath;
if (S3Helper.Instance.Enabled)
{
filePath = DocManagerHelper.VersionDir(histPath, version) + file;
}
else
{
filePath = Path.Combine(DocManagerHelper.VersionDir(histPath, version), file); // get the path to document version
}
download(filePath, context);
}
@ -579,112 +628,21 @@ namespace OnlineEditorsExampleMVC
var jss = new JavaScriptSerializer();
var body = jss.Deserialize<Dictionary<string, object>>(fileData);
var newFileName = (string) body["newfilename"];
var docKey = (string) body["dockey"];
var newFileName = (string)body["newfilename"];
var docKey = (string)body["dockey"];
var origExt = '.' + (string) body["ext"];
var origExt = '.' + (string)body["ext"];
var curExt = Path.GetExtension(newFileName).ToLower();
if (string.Compare(origExt, curExt, true) != 0)
{
newFileName += origExt;
}
var meta = new Dictionary<string, object>() {
var meta = new Dictionary<string, object>() {
{ "title", newFileName }
};
TrackManager.commandRequest("meta", docKey, meta);
context.Response.Write("{ \"result\": \"OK\"}");
}
private static void Reference(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;
}
}
catch (Exception e)
{
throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
}
var jss = new JavaScriptSerializer();
var body = jss.Deserialize<Dictionary<string, object>>(fileData);
Dictionary<string, object> referenceData = null;
var fileName = "";
var userAddress = "";
if (body.ContainsKey("referenceData"))
{
referenceData = jss.Deserialize<Dictionary<string, object>>(jss.Serialize(body["referenceData"]));
var instanceId = (string)referenceData["instanceId"];
var fileKey = (string)referenceData["fileKey"];
if (instanceId == DocManagerHelper.GetServerUrl(false))
{
var fileKeyObj = jss.Deserialize<Dictionary<string, object>>(fileKey);
userAddress = (string)fileKeyObj["userAddress"];
if (userAddress == HttpUtility.UrlEncode(DocManagerHelper.CurUserHostAddress(HttpContext.Current.Request.UserHostAddress)))
{
fileName = (string)fileKeyObj["fileName"];
}
}
}
if (fileName == "")
{
try
{
var path = (string)body["path"];
path = Path.GetFileName(path);
if (File.Exists(DocManagerHelper.StoragePath(path, null)))
{
fileName = path;
}
}
catch
{
context.Response.Write("{ \"error\": \"Path not found!\"}");
return;
}
}
if (fileName == "")
{
context.Response.Write("{ \"error\": \"File not found!\"}");
return;
}
var data = new Dictionary<string, object>() {
{ "fileType", (Path.GetExtension(fileName) ?? "").ToLower() },
{ "url", DocManagerHelper.GetDownloadUrl(fileName)},
{ "directUrl", DocManagerHelper.GetDownloadUrl(fileName) },
{ "referenceData", new Dictionary<string, string>()
{
{ "fileKey", jss.Serialize(new Dictionary<string, object>{
{"fileName", fileName},
{"userAddress", HttpUtility.UrlEncode(DocManagerHelper.CurUserHostAddress(HttpContext.Current.Request.UserHostAddress))}
})
},
{"instanceId", DocManagerHelper.GetServerUrl(false) }
}
},
{ "path", fileName }
};
if (JwtManager.Enabled)
{
var token = JwtManager.Encode(data);
data.Add("token", token);
}
context.Response.Write(jss.Serialize(data));
}
}
}

View File

@ -178,7 +178,7 @@
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -198,4 +198,4 @@
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
limitations under the License.

View File

@ -1,17 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Antlr" version="3.5.0.2" targetFramework="net48" />
<package id="Crc32.NET" version="1.2.0" targetFramework="net48" />
<package id="EntityFramework" version="6.4.4" targetFramework="net48" />
<package id="JWT" version="9.0.3" targetFramework="net48" />
<package id="Microsoft.AspNet.Mvc" version="5.2.7" targetFramework="net48" />
<package id="Microsoft.AspNet.Razor" version="3.2.7" targetFramework="net48" />
<package id="Microsoft.AspNet.Mvc" version="5.2.9" targetFramework="net48" />
<package id="Microsoft.AspNet.Razor" version="3.2.9" targetFramework="net48" />
<package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net48" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.7" targetFramework="net48" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.7" targetFramework="net48" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.7" targetFramework="net48" />
<package id="Microsoft.AspNet.WebPages" version="3.2.7" targetFramework="net48" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.9" targetFramework="net48" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.9" targetFramework="net48" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.9" targetFramework="net48" />
<package id="Microsoft.AspNet.WebPages" version="3.2.9" targetFramework="net48" />
<package id="Microsoft.CSharp" version="4.7.0" targetFramework="net48" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net48" />
<package id="Microsoft.Web.Infrastructure" version="2.0.0" targetFramework="net48" />
<package id="Minio" version="4.0.0" targetFramework="net48" />
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net48" />
<package id="System.IO" version="4.3.0" targetFramework="net48" />
<package id="System.Net.Http" version="4.3.4" targetFramework="net48" />
<package id="System.Net.Primitives" version="4.3.1" targetFramework="net48" />
<package id="System.Reactive" version="5.0.0" targetFramework="net48" />
<package id="System.Reactive.Linq" version="5.0.0" targetFramework="net48" />
<package id="System.Runtime" version="4.3.1" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="6.0.0" targetFramework="net48" />
<package id="System.Security.Cryptography.Algorithms" version="4.3.1" targetFramework="net48" />
<package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="net48" />
<package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="net48" />
<package id="System.Security.Cryptography.X509Certificates" version="4.3.2" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net48" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net48" />
<package id="WebGrease" version="1.6.0" targetFramework="net48" />
</packages>

View File

@ -5,20 +5,26 @@
<add key="filesize-max" value="52428800"/>
<add key="storage-path" value=""/>
<add key="s3-enabled" value="true"/>
<add key="s3-endpoint" value="s3.region.example"/>
<add key="s3-region" value="region"/>
<add key="s3-access-key" value="key"/>
<add key="s3-secret-key" value="secret"/>
<add key="s3-secure" value="false"/>
<add key="s3-bucket" value="bucket-name"/>
<add key="files.docservice.fillform-docs" value=".docx|.oform"/>
<add key="files.docservice.viewed-docs" value=".djvu|.oxps|.pdf|.xps"/>
<add key="files.docservice.edited-docs" value=".csv|.docm|.docx|.docxf|.dotm|.dotx|.epub|.fb2|.html|.odp|.ods|.odt|.otp|.ots|.ott|.potm|.potx|.ppsm|.ppsx|.pptm|.pptx|.rtf|.txt|.xlsm|.xlsx|.xltm|.xltx"/>
<add key="files.docservice.convert-docs" value=".doc|.dot|.dps|.dpt|.epub|.et|.ett|.fb2|.fodp|.fods|.fodt|.htm|.html|.mht|.mhtml|.odp|.ods|.odt|.otp|.ots|.ott|.pot|.pps|.ppt|.rtf|.stw|.sxc|.sxi|.sxw|.wps|.wpt|.xls|.xlsb|.xlt|.xml"/>
<add key="files.docservice.fillform-docs" value=".oform|.docx"/>
<add key="files.docservice.viewed-docs" value=".pdf|.djvu|.xps|.oxps"/>
<add key="files.docservice.edited-docs" value=".docx|.xlsx|.csv|.pptx|.txt|.docxf"/>
<add key="files.docservice.convert-docs" value=".docm|.dotx|.dotm|.dot|.doc|.odt|.fodt|.ott|.xlsm|.xlsb|.xltx|.xltm|.xlt|.xls|.ods|.fods|.ots|.pptm|.ppt|.ppsx|.ppsm|.pps|.potx|.potm|.pot|.odp|.fodp|.otp|.rtf|.mht|.html|.htm|.xml|.epub|.fb2"/>
<add key="files.docservice.timeout" value="120000" />
<add key="files.docservice.secret" value="" />
<add key="files.docservice.header" value="Authorization" />
<add key="files.docservice.token.useforrequest" value="true" />
<add key="files.docservice.verify-peer-off" value="true"/>
<add key="files.docservice.languages" value="en:English|hy:Armenian|az:Azerbaijani|eu:Basque|be:Belarusian|bg:Bulgarian|ca:Catalan|zh:Chinese|zh-TW:Chinese (Taiwan)|cs:Czech|da:Danish|nl:Dutch|fi:Finnish|fr:French|gl:Galego|de:German|el:Greek|hu:Hungarian|id:Indonesian|it:Italian|ja:Japanese|ko:Korean|lo:Lao|lv:Latvian|ms:Malay (Malaysia)|no:Norwegian|pl:Polish|pt:Portuguese (Brazil)|pt-PT:Portuguese (Portugal)|ro:Romanian|ru:Russian|si:Sinhala (Sri Lanka)|sk:Slovak|sl:Slovenian|es:Spanish|sv:Swedish|tr:Turkish|uk:Ukrainian|vi:Vietnamese|aa-AA: Test Language"/>
<add key="files.docservice.languages" value="en:English|hy:Armenian|az:Azerbaijani|eu:Basque|be:Belarusian|bg:Bulgarian|ca:Catalan|zh:Chinese (People's Republic of China)|zh-TW:Chinese (Traditional, Taiwan)|cs:Czech|da:Danish|nl:Dutch|fi:Finnish|fr:French|gl:Galego|de:German|el:Greek|hu:Hungarian|id:Indonesian|it:Italian|ja:Japanese|ko:Korean|lv:Latvian|lo:Lao|ms:Malay (Malaysia)|nb:Norwegian|pl:Polish|pt:Portuguese (Brazil)|pt-PT:Portuguese (Portugal)|ro:Romanian|ru:Russian|sk:Slovak|sl:Slovenian|es:Spanish|sv:Swedish|tr:Turkish|uk:Ukrainian|vi:Vietnamese|aa-AA: Test Language"/>
<add key="files.docservice.url.site" value="http://documentserver/"/>

View File

@ -682,8 +682,3 @@
max-width:15%;
}
}
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.tableRow td:first-child{
max-width: none;
}
}

View File

@ -471,10 +471,11 @@ namespace OnlineEditorsExample
var lang = context.Request.Cookies.GetOrDefault("ulang", null);
var extension = (Path.GetExtension(_fileName).ToLower() ?? "").Trim('.');
var internalExtension = "ooxml";
var internalExtension = FileType.GetInternalExtension(_fileName).Trim('.');
// check if the file with such an extension can be converted
if (ConvertExts.Contains("." + extension))
if (ConvertExts.Contains("." + extension)
&& !string.IsNullOrEmpty(internalExtension))
{
// generate document key
var key = ServiceConverter.GenerateRevisionId(FileUri(_fileName, true));
@ -486,18 +487,16 @@ namespace OnlineEditorsExample
fileUrl.Query = "type=download&fileName=" + HttpUtility.UrlEncode(_fileName)
+ "&userAddress=" + HttpUtility.UrlEncode(CurUserHostAddress(HttpContext.Current.Request.UserHostAddress));
// get the url and file type of the converted file
Dictionary<string, string> newFileData;
var result = ServiceConverter.GetConvertedData(fileUrl.ToString() , extension, internalExtension, key, true, out newFileData, filePass, lang);
var newFileUri = newFileData["fileUrl"];
var newFileType = "." + newFileData["fileType"];
// 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) + newFileType);
var fileName = GetCorrectName(Path.GetFileNameWithoutExtension(_fileName) + "." + internalExtension);
var req = (HttpWebRequest)WebRequest.Create(newFileUri);

View File

@ -153,7 +153,7 @@
var onRequestMailMergeRecipients = function (event) {
docEditor.setMailMergeRecipients(<%= DataMailMergeRecipients %>); // insert recipient data for mail merge into the file
};
var onRequestSaveAs = function (event) { // the user is trying to save file by clicking Save Copy as... button
var title = event.data.title;
var url = event.data.url;
@ -190,19 +190,6 @@
}
};
var onRequestReferenceData = function (event) { // user refresh external data source
event.data.directUrl = !!config.document.directUrl;
let xhr = new XMLHttpRequest();
xhr.open("POST", "webeditor.ashx?type=reference");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(event.data));
xhr.onload = function () {
console.log(xhr.responseText);
docEditor.setReferenceData(JSON.parse(xhr.responseText));
}
};
config = <%= DocConfig %>;
config.width = "100%";
@ -211,6 +198,7 @@
config.events = {
'onAppReady': onAppReady,
'onDocumentStateChange': onDocumentStateChange,
'onRequestEditRights': onRequestEditRights,
'onError': onError,
'onOutdatedVersion': onOutdatedVersion,
'onMakeActionLink': onMakeActionLink,
@ -231,7 +219,7 @@
var histData = <%= HistoryData %>;
docEditor.setHistoryData(histData[ver - 1]); // send the link to the document for viewing the version history
};
config.events['onRequestHistoryClose'] = function () { // the user is trying to go back to the document from viewing the document version history
config.events['onRequestHistoryClose '] = function () { // the user is trying to go back to the document from viewing the document version history
document.location.reload();
};
<% } %>
@ -254,9 +242,6 @@
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
config.events['onRequestReferenceData'] = onRequestReferenceData;
// prevent switch the document from the viewing into the editing mode for anonymous users
config.events['onRequestEditRights'] = onRequestEditRights;
}
if (config.editorConfig.createUrl) {

View File

@ -206,17 +206,6 @@ namespace OnlineEditorsExample
{ "favorite", favorite }
}
},
{
"referenceData", new Dictionary<string, string>()
{
{ "fileKey", !user.id.Equals("uid-0") ?
jss.Serialize(new Dictionary<string, object>{
{"fileName", FileName},
{"userAddress", HttpUtility.UrlEncode(_Default.CurUserHostAddress(HttpContext.Current.Request.UserHostAddress))}
}) : null },
{"instanceId", _Default.GetServerUrl(false) }
}
},
{
// the permission for the document to be edited and downloaded or not
"permissions", new Dictionary<string, object>
@ -233,8 +222,7 @@ namespace OnlineEditorsExample
{ "chat", !user.id.Equals("uid-0") },
{ "reviewGroups", user.reviewGroups },
{ "commentGroups", user.commentGroups },
{ "userInfoGroups", user.userInfoGroups },
{ "protect", !user.deniedPermissions.Contains("protect") }
{ "userInfoGroups", user.userInfoGroups }
}
}
}

View File

@ -70,24 +70,24 @@ namespace ASC.Api.DocumentConverter
/// <param name="toExtension">Extension to which to convert</param>
/// <param name="documentRevisionId">Key for caching on service</param>
/// <param name="isAsync">Perform conversions asynchronously</param>
/// <param name="convertedDocumentData">Uri and file type of the converted document</param>
/// <param name="convertedDocumentUri">Uri to the converted document</param>
/// <returns>The percentage of conversion completion</returns>
/// <example>
/// Dictionary<string, string> convertedDocumentData;
/// GetConvertedData("http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", ".pdf", ".docx", "http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", false, out convertedDocumentData);
/// string convertedDocumentUri;
/// GetConvertedUri("http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", ".pdf", ".docx", "http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", false, out convertedDocumentUri);
/// </example>
/// <exception>
/// </exception>
public static int GetConvertedData(string documentUri,
public static int GetConvertedUri(string documentUri,
string fromExtension,
string toExtension,
string documentRevisionId,
bool isAsync,
out Dictionary<string, string> convertedDocumentData,
out string convertedDocumentUri,
string filePass = null,
string lang = null)
{
convertedDocumentData = new Dictionary<string, string>();
convertedDocumentUri = string.Empty;
// check if the fromExtension parameter is defined; if not, get it from the document url
fromExtension = string.IsNullOrEmpty(fromExtension) ? Path.GetExtension(documentUri).ToLower() : fromExtension;
@ -121,7 +121,7 @@ namespace ASC.Api.DocumentConverter
{ "region", lang }
};
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
if (JwtManager.Enabled)
{
// create payload object
var payload = new Dictionary<string, object>
@ -159,7 +159,7 @@ namespace ASC.Api.DocumentConverter
}
}
return GetResponseData(dataResponse, out convertedDocumentData);
return GetResponseUri(dataResponse, out convertedDocumentUri);
}
/// <summary>
@ -183,9 +183,9 @@ namespace ASC.Api.DocumentConverter
/// Processing document received from the editing service
/// </summary>
/// <param name="jsonDocumentResponse">The resulting json from editing service</param>
/// <param name="responseData">Uri and file type of the converted document</param>
/// <param name="responseUri">Uri to the converted document</param>
/// <returns>The percentage of conversion completion</returns>
private static int GetResponseData(string jsonDocumentResponse, out Dictionary<string, string> responseData)
private static int GetResponseUri(string jsonDocumentResponse, out string responseUri)
{
if (string.IsNullOrEmpty(jsonDocumentResponse)) throw new ArgumentException("Invalid param", "jsonDocumentResponse");
@ -199,20 +199,14 @@ namespace ASC.Api.DocumentConverter
var isEndConvert = responseFromService.endConvert;
int resultPercent;
responseData = new Dictionary<string, string>();
var responseUri = string.Empty;
var responseFileType = string.Empty;
responseUri = string.Empty;
if (isEndConvert) // if the conversion is completed
{
responseUri = responseFromService.fileUrl; // get the file url
responseFileType = responseFromService.fileType; // get the file type
responseData.Add("fileUrl", responseUri);
responseData.Add("fileType", responseFileType);
resultPercent = 100;
}
else // if the conversion isn't completed
{
responseData.Add("fileUrl", "");
resultPercent = responseFromService.percent; // get the percentage value
if (resultPercent >= 100) resultPercent = 99;
}

View File

@ -29,13 +29,11 @@ namespace OnlineEditorsExample
{
private static readonly string Secret;
public static readonly bool Enabled;
public static readonly bool SignatureUseForRequest;
static JwtManager()
{
Secret = WebConfigurationManager.AppSettings["files.docservice.secret"] ?? ""; // get token secret from the config parameters
Enabled = !string.IsNullOrEmpty(Secret); // check if the token is enabled
SignatureUseForRequest = bool.Parse(WebConfigurationManager.AppSettings["files.docservice.token.useforrequest"]);
}
// encode a payload object into a token using a secret key

View File

@ -55,7 +55,7 @@ namespace OnlineEditorsExample
var fileData = jss.Deserialize<Dictionary<string, object>>(body);
// check if the document token is enabled
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
if (JwtManager.Enabled)
{
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
@ -110,9 +110,8 @@ namespace OnlineEditorsExample
try
{
// convert file and give url to a new file
Dictionary<string, string> newFileData;
ServiceConverter.GetConvertedData(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileData);
var newFileUri = newFileData["fileUrl"];
string newFileUri;
ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
if (string.IsNullOrEmpty(newFileUri))
{
// get the correct file name if it already exists
@ -131,48 +130,37 @@ namespace OnlineEditorsExample
_Default.VerifySSL();
try
var storagePath = _Default.StoragePath(newFileName, userAddress); // get the file path
var histDir = _Default.HistoryDir(storagePath); // get the path to the history directory
if (!Directory.Exists(histDir)) Directory.CreateDirectory(histDir);
var versionDir = _Default.VersionDir(histDir, _Default.GetFileVersion(histDir)); // get the path to the file version
if (!Directory.Exists(versionDir)) Directory.CreateDirectory(versionDir); // if the path doesn't exist, create it
// get the path to the previous file version and rename the storage path with it
File.Copy(_Default.StoragePath(fileName, userAddress), Path.Combine(versionDir, "prev" + curExt));
DownloadToFile(downloadUri, storagePath); // save file to the storage directory
DownloadToFile((string)fileData["changesurl"], Path.Combine(versionDir, "diff.zip")); // save file changes to the diff.zip archive
var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;
if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
{
var bytesFile = DownloadFile(downloadUri); // download document file
var storagePath = _Default.StoragePath(newFileName, userAddress); // get the file path
var histDir = _Default.HistoryDir(storagePath); // get the path to the history directory
if (!Directory.Exists(histDir)) Directory.CreateDirectory(histDir);
var versionDir = _Default.VersionDir(histDir, _Default.GetFileVersion(histDir)); // get the path to the file version
if (!Directory.Exists(versionDir)) Directory.CreateDirectory(versionDir); // if the path doesn't exist, create it
// get the path to the previous file version and rename the storage path with it
File.Copy(_Default.StoragePath(fileName, userAddress), Path.Combine(versionDir, "prev" + curExt));
SaveFile(bytesFile, storagePath);// save document file
var bytesChanges = DownloadFile((string)fileData["changesurl"]); // download changes file
SaveFile(bytesChanges, Path.Combine(versionDir, "diff.zip")); // save file changes to the diff.zip archive
var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;
if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
{
var jss = new JavaScriptSerializer();
hist = jss.Serialize(fileData["history"]);
}
if (!string.IsNullOrEmpty(hist))
{
File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist); // write the history changes to the changes.json file
}
File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]); // write the key value to the key.txt file
string forcesavePath = _Default.ForcesavePath(newFileName, userAddress, false); // get the path to the forcesaved file version
if (!string.IsNullOrEmpty(forcesavePath)) // if the forcesaved file version exists
{
File.Delete(forcesavePath); // remove it
}
var jss = new JavaScriptSerializer();
hist = jss.Serialize(fileData["history"]);
}
catch (Exception)
if (!string.IsNullOrEmpty(hist))
{
return 1;
File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist); // write the history changes to the changes.json file
}
File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]); // write the key value to the key.txt file
string forcesavePath = _Default.ForcesavePath(newFileName, userAddress, false); // get the path to the forcesaved file version
if (!string.IsNullOrEmpty(forcesavePath)) // if the forcesaved file version exists
{
File.Delete(forcesavePath); // remove it
}
return 0;
@ -198,9 +186,8 @@ namespace OnlineEditorsExample
try
{
// convert file and give url to a new file
Dictionary<string, string> newFileData;
var result = ServiceConverter.GetConvertedData(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileData);
var newFileUri = newFileData["fileUrl"];
string newFileUri;
var result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
if (string.IsNullOrEmpty(newFileUri))
{
newFileName = true;
@ -218,51 +205,43 @@ namespace OnlineEditorsExample
_Default.VerifySSL();
try
string forcesavePath = "";
Boolean isSubmitForm = fileData["forcesavetype"].ToString().Equals("3"); // SubmitForm
if (isSubmitForm) // if the form is submitted
{
var bytesFile = DownloadFile(downloadUri); // download document file
string forcesavePath = "";
Boolean isSubmitForm = fileData["forcesavetype"].ToString().Equals("3"); // SubmitForm
if (isSubmitForm) // if the form is submitted
if (newFileName)
{
if (newFileName)
{
fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress); // get the correct file name if it already exists
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);
}
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);
forcesavePath = _Default.ForcesavePath(fileName, userAddress, false);
if (string.IsNullOrEmpty(forcesavePath)) // create forcesave path if it doesn't exist
{
forcesavePath = _Default.ForcesavePath(fileName, userAddress, true);
}
}
SaveFile(bytesFile, forcesavePath);// save document file
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
forcesavePath = _Default.ForcesavePath(fileName, userAddress, true);
}
}
catch (Exception)
DownloadToFile(downloadUri, forcesavePath);
if (isSubmitForm)
{
return 1;
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;
@ -290,7 +269,7 @@ namespace OnlineEditorsExample
}
// check if a secret key to generate token exists or not
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
if (JwtManager.Enabled)
{
var payload = new Dictionary<string, object>
{
@ -334,29 +313,27 @@ namespace OnlineEditorsExample
}
}
private static void SaveFile(byte[] data, string path)
{
using (var fs = File.Open(path, FileMode.Create))
{
fs.Write(data, 0, data.Length);
}
}
// save file information from the url to the file specified
private static byte[] DownloadFile(string url)
private static void DownloadToFile(string url, string path)
{
if (string.IsNullOrEmpty(url)) throw new ArgumentException("url"); // url isn't specified
if (string.IsNullOrEmpty(path)) throw new ArgumentException("path"); // file isn't specified
var req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = 5000;
using (var stream = req.GetResponse().GetResponseStream()) // get input stream of the file information from the url
{
if (stream == null) throw new Exception("stream is null");
const int bufferSize = 4096;
using (MemoryStream memoryStream = new MemoryStream())
using (var fs = File.Open(path, FileMode.Create))
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
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
}
}
}
}

View File

@ -68,7 +68,6 @@ namespace OnlineEditorsExample
"Cant see anyones information",
"Can't rename files from the editor",
"Can't view chat",
"Can't protect file",
"View file without collaboration",
};
@ -131,7 +130,7 @@ namespace OnlineEditorsExample
new Dictionary<string, object>(),
new List<string>(),
null,
new List<string>() { "protect" },
new List<string>(),
descr_user_0,
false
)

View File

@ -26,7 +26,6 @@ using System.Diagnostics;
using System.Web.Configuration;
using System.Linq;
using System.Net;
using System.Net.Sockets;
namespace OnlineEditorsExample
{
@ -72,9 +71,6 @@ namespace OnlineEditorsExample
case "rename":
Rename(context);
break;
case "reference":
Reference(context);
break;
}
}
@ -285,21 +281,21 @@ namespace OnlineEditorsExample
var userAddress = Path.GetFileName(context.Request["userAddress"]);
var isEmbedded = context.Request["dmode"];
if (JwtManager.Enabled && isEmbedded == null && userAddress != null && JwtManager.SignatureUseForRequest)
if (JwtManager.Enabled && isEmbedded == null)
{
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
string token = "";
if (context.Request.Headers.AllKeys.Contains(JWTheader, StringComparer.InvariantCultureIgnoreCase))
{
var headerToken = context.Request.Headers.Get(JWTheader).Substring("Bearer ".Length);
token = JwtManager.Decode(headerToken);
}
if (string.IsNullOrEmpty(token))
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
context.Response.Write("JWT validation failed");
return;
string token = JwtManager.Decode(headerToken);
if (string.IsNullOrEmpty(token))
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
context.Response.Write("JWT validation failed");
return;
}
}
}
@ -342,7 +338,7 @@ namespace OnlineEditorsExample
var version = Path.GetFileName(context.Request["ver"]);
var file = Path.GetFileName(context.Request["file"]);
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
if (JwtManager.Enabled)
{
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
@ -413,94 +409,5 @@ namespace OnlineEditorsExample
TrackManager.commandRequest("meta", docKey, meta);
context.Response.Write("{ \"result\": \"OK\"}");
}
private static void Reference(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;
}
}
catch (Exception e)
{
throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
}
var jss = new JavaScriptSerializer();
var body = jss.Deserialize<Dictionary<string, object>>(fileData);
Dictionary<string, object> referenceData = null;
var fileName = "";
var userAddress = "";
if (body.ContainsKey("referenceData"))
{
referenceData = jss.Deserialize<Dictionary<string, object>>(jss.Serialize(body["referenceData"]));
var instanceId = (string)referenceData["instanceId"];
var fileKey = (string)referenceData["fileKey"];
if (instanceId == _Default.GetServerUrl(false))
{
var fileKeyObj = jss.Deserialize<Dictionary<string, object>>(fileKey);
userAddress = (string)fileKeyObj["userAddress"];
if (userAddress == HttpUtility.UrlEncode(_Default.CurUserHostAddress(HttpContext.Current.Request.UserHostAddress)))
{
fileName = (string)fileKeyObj["fileName"];
}
}
}
if (fileName == "")
{
try
{
var path = (string)body["path"];
path = Path.GetFileName(path);
if (File.Exists(_Default.StoragePath(path, null)))
{
fileName = path;
}
}
catch
{
context.Response.Write("{ \"error\": \"Path not found!\"}");
return;
}
}
if (fileName == "")
{
context.Response.Write("{ \"error\": \"File not found!\"}");
return;
}
var data = new Dictionary<string, object>() {
{ "fileType", (Path.GetExtension(fileName) ?? "").ToLower() },
{ "url", DocEditor.getDownloadUrl(fileName)},
{ "directUrl", DocEditor.getDownloadUrl(fileName) },
{ "referenceData", new Dictionary<string, string>()
{
{ "fileKey", jss.Serialize(new Dictionary<string, object>{
{"fileName", fileName},
{"userAddress", HttpUtility.UrlEncode(_Default.CurUserHostAddress(HttpContext.Current.Request.UserHostAddress))}
})
},
{"instanceId", _Default.GetServerUrl(false) }
}
},
{ "path", fileName }
};
if (JwtManager.Enabled)
{
var token = JwtManager.Encode(data);
data.Add("token", token);
}
context.Response.Write(jss.Serialize(data));
}
}
}

View File

@ -6,18 +6,16 @@
<add key="filesize-max" value="52428800"/>
<add key="storage-path" value=""/>
<add key="files.docservice.fillform-docs" value=".docx|.oform"/>
<add key="files.docservice.viewed-docs" value=".djvu|.oxps|.pdf|.xps"/>
<add key="files.docservice.edited-docs" value=".csv|.docm|.docx|.docxf|.dotm|.dotx|.epub|.fb2|.html|.odp|.ods|.odt|.otp|.ots|.ott|.potm|.potx|.ppsm|.ppsx|.pptm|.pptx|.rtf|.txt|.xlsm|.xlsx|.xltm|.xltx"/>
<add key="files.docservice.convert-docs" value=".doc|.dot|.dps|.dpt|.epub|.et|.ett|.fb2|.fodp|.fods|.fodt|.htm|.html|.mht|.mhtml|.odp|.ods|.odt|.otp|.ots|.ott|.pot|.pps|.ppt|.rtf|.stw|.sxc|.sxi|.sxw|.wps|.wpt|.xls|.xlsb|.xlt|.xml"/>
<add key="files.docservice.fillform-docs" value=".oform|.docx"/>
<add key="files.docservice.viewed-docs" value=".pdf|.djvu|.xps|.oxps"/>
<add key="files.docservice.edited-docs" value=".docx|.xlsx|.csv|.pptx|.txt|.docxf"/>
<add key="files.docservice.convert-docs" value=".docm|.dotx|.dotm|.dot|.doc|.odt|.fodt|.ott|.xlsm|.xlsb|.xltx|.xltm|.xlt|.xls|.ods|.fods|.ots|.pptm|.ppt|.ppsx|.ppsm|.pps|.potx|.potm|.pot|.odp|.fodp|.otp|.rtf|.mht|.html|.htm|.xml|.epub|.fb2"/>
<add key="files.docservice.timeout" value="120000" />
<add key="files.docservice.secret" value="" />
<add key="files.docservice.header" value="Authorization" />
<add key="files.docservice.verify-peer-off" value="true"/>
<add key="files.docservice.token.useforrequest" value="true" />
<add key="files.docservice.languages" value="en:English|hy:Armenian|az:Azerbaijani|eu:Basque|be:Belarusian|bg:Bulgarian|ca:Catalan|zh:Chinese|zh-TW:Chinese (Taiwan)|cs:Czech|da:Danish|nl:Dutch|fi:Finnish|fr:French|gl:Galego|de:German|el:Greek|hu:Hungarian|id:Indonesian|it:Italian|ja:Japanese|ko:Korean|lo:Lao|lv:Latvian|ms:Malay (Malaysia)|no:Norwegian|pl:Polish|pt:Portuguese (Brazil)|pt-PT:Portuguese (Portugal)|ro:Romanian|ru:Russian|si:Sinhala (Sri Lanka)|sk:Slovak|sl:Slovenian|es:Spanish|sv:Swedish|tr:Turkish|uk:Ukrainian|vi:Vietnamese|aa-AA: Test Language"/>
<add key="files.docservice.languages" value="en:English|hy:Armenian|az:Azerbaijani|eu:Basque|be:Belarusian|bg:Bulgarian|ca:Catalan|zh:Chinese (People's Republic of China)|zh-TW:Chinese (Traditional, Taiwan)|cs:Czech|da:Danish|nl:Dutch|fi:Finnish|fr:French|gl:Galego|de:German|el:Greek|hu:Hungarian|id:Indonesian|it:Italian|ja:Japanese|ko:Korean|lv:Latvian|lo:Lao|ms:Malay (Malaysia)|nb:Norwegian|pl:Polish|pt:Portuguese (Brazil)|pt-PT:Portuguese (Portugal)|ro:Romanian|ru:Russian|sk:Slovak|sl:Slovenian|es:Spanish|sv:Swedish|tr:Turkish|uk:Ukrainian|vi:Vietnamese|aa-AA: Test Language"/>
<add key="files.docservice.url.site" value="http://documentserver/"/>

View File

@ -45,7 +45,6 @@ public class ExampleData {
"Cant see anyones information",
"Can't rename files from the editor",
"Can't view chat",
"Can't protect file",
"View file without collaboration"
);
@ -93,23 +92,22 @@ public class ExampleData {
userService.createUser("John Smith", "smith@example.com", descriptionUserFirst,
"", List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
List.of(FilterState.NULL.toString()), null, true, true);
List.of(FilterState.NULL.toString()), null, true);
// create user 2 with the specified parameters
userService.createUser("Mark Pottato", "pottato@example.com", descriptionUserSecond,
"group-2", List.of("", "group-2"), List.of(FilterState.NULL.toString()),
List.of("group-2", ""), List.of("group-2"), List.of("group-2", ""), true, true,
true);
List.of("group-2", ""), List.of("group-2"), List.of("group-2", ""), true, true);
// create user 3 with the specified parameters
userService.createUser("Hamish Mitchell", "mitchell@example.com", descriptionUserThird,
"group-3", List.of("group-2"), List.of("group-2", "group-3"), List.of("group-2"),
new ArrayList<>(), List.of("group-2"), false, true, true);
new ArrayList<>(), List.of("group-2"), false, true);
// create user 0 with the specified parameters
userService.createUser("Anonymous", null, descriptionUserZero, "",
List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
new ArrayList<>(), null, false, false);
new ArrayList<>(), null, false);
}
}

View File

@ -19,14 +19,11 @@
package com.onlyoffice.integration.controllers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.onlyoffice.integration.documentserver.callbacks.CallbackHandler;
import com.onlyoffice.integration.documentserver.managers.jwt.JwtManager;
import com.onlyoffice.integration.documentserver.storage.FileStorageMutator;
import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
import com.onlyoffice.integration.dto.Converter;
import com.onlyoffice.integration.dto.ConvertedData;
import com.onlyoffice.integration.dto.Track;
import com.onlyoffice.integration.entities.User;
import com.onlyoffice.integration.documentserver.models.enums.DocumentType;
@ -54,10 +51,8 @@ import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@ -203,18 +198,15 @@ public class FileController {
// get document type (word, cell or slide)
DocumentType type = fileUtility.getDocumentType(fileName);
// convert to .ooxml
String internalFileExt = "ooxml";
// get an editor internal extension (".docx", ".xlsx" or ".pptx")
String internalFileExt = fileUtility.getInternalExtension(type);
try {
// check if the file with such an extension can be converted
if (fileUtility.getConvertExts().contains(fileExt)) {
String key = serviceConverter.generateRevisionId(fileUri); // generate document key
ConvertedData response = serviceConverter // get the URL to the converted file
.getConvertedData(fileUri, fileExt, internalFileExt, key, filePass, true, lang);
String newFileUri = response.getUri();
String newFileType = "." + response.getFileType();
String newFileUri = serviceConverter // get the URL to the converted file
.getConvertedUri(fileUri, fileExt, internalFileExt, key, filePass, true, lang);
if (newFileUri.isEmpty()) {
return "{ \"step\" : \"0\", \"filename\" : \"" + fileName + "\"}";
@ -222,7 +214,7 @@ public class FileController {
/* get a file name of an internal file extension with an index if the file
with such a name already exists */
String nameWithInternalExt = fileUtility.getFileNameWithoutExtension(fileName) + newFileType;
String nameWithInternalExt = fileUtility.getFileNameWithoutExtension(fileName) + internalFileExt;
String correctedName = documentManager.getCorrectName(nameWithInternalExt);
URL url = new URL(newFileUri);
@ -274,7 +266,7 @@ public class FileController {
@RequestParam("file") final String file) { // history file
try {
// check if a token is enabled or not
if (jwtManager.tokenEnabled() && jwtManager.tokenUseForRequest()) {
if (jwtManager.tokenEnabled()) {
String header = request.getHeader(documentJwtHeader == null // get the document JWT header
|| documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader);
if (header != null && !header.isEmpty()) {
@ -293,20 +285,16 @@ public class FileController {
@GetMapping(path = "${url.download}")
public ResponseEntity<Resource> download(final HttpServletRequest request, // download a file
@RequestParam("fileName") final String fileName,
@RequestParam(value = "userAddress", required = false)
final String userAddress) {
@RequestParam("fileName") final String fileName) {
try {
// check if a token is enabled or not
if (jwtManager.tokenEnabled() && userAddress != null && jwtManager.tokenUseForRequest()) {
String header = request.getHeader(documentJwtHeader == null // get the document JWT header
if (jwtManager.tokenEnabled()) {
String header = request.getHeader(documentJwtHeader == null // get the document JWT header
|| documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader);
if (header != null && !header.isEmpty()) {
String token = header
.replace("Bearer ", ""); // token is the header without the Bearer prefix
jwtManager.readToken(token); // read the token
} else {
return null;
}
}
return downloadFile(fileName); // download data from the specified file
@ -454,71 +442,4 @@ public class FileController {
return e.getMessage();
}
}
@PostMapping("/reference")
@ResponseBody
public String reference(@RequestBody final JSONObject body) {
try {
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String userAddress = "";
String fileName = "";
if (body.containsKey("referenceData")) {
JSONObject referenceDataObj = (JSONObject) body.get("referenceData");
String instanceId = (String) referenceDataObj.get("instanceId");
if (instanceId.equals(storagePathBuilder.getServerUrl(false))) {
JSONObject fileKey = (JSONObject) referenceDataObj.get("fileKey");
userAddress = (String) fileKey.get("userAddress");
if (userAddress.equals(InetAddress.getLocalHost().getHostAddress())) {
fileName = (String) fileKey.get("fileName");
}
}
}
if (fileName.equals("")) {
try {
String path = (String) body.get("path");
path = fileUtility.getFileName(path);
File f = new File(storagePathBuilder.getFileLocation(path));
if (f.exists()) {
fileName = path;
}
} catch (Exception e) {
return "{ \"error\" : 1, \"message\" : \"" + e.getMessage() + "\"}";
}
}
if (fileName.equals("")) {
return "{ \"error\": \"File not found\"}";
}
HashMap<String, Object> fileKey = new HashMap<>();
fileKey.put("fileName", fileName);
fileKey.put("userAddress", InetAddress.getLocalHost().getHostAddress());
HashMap<String, Object> referenceData = new HashMap<>();
referenceData.put("instanceId", storagePathBuilder.getServerUrl(true));
referenceData.put("fileKey", fileKey);
HashMap<String, Object> data = new HashMap<>();
data.put("fileType", fileUtility.getFileExtension(fileName));
data.put("url", documentManager.getDownloadUrl(fileName, true));
data.put("directUrl", documentManager.getDownloadUrl(fileName, true));
data.put("referenceData", referenceData);
data.put("path", fileName);
if (jwtManager.tokenEnabled()) {
String token = jwtManager.createToken(data);
data.put("token", token);
}
return gson.toJson(data);
} catch (Exception e) {
e.printStackTrace();
return "{ \"error\" : 1, \"message\" : \"" + e.getMessage() + "\"}";
}
}
}

View File

@ -35,7 +35,6 @@ import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
@ -76,12 +75,14 @@ public class DefaultCallbackManager implements CallbackManager {
@Autowired
private ServiceConverter serviceConverter;
// download file from url
@SneakyThrows
private byte[] getDownloadFile(final String url) {
// save file information from the URL to the file specified
private void downloadToFile(final String url, final Path path) throws Exception {
if (url == null || url.isEmpty()) {
throw new RuntimeException("Url argument is not specified"); // URL isn't specified
}
if (path == null) {
throw new RuntimeException("Path argument is not specified"); // file isn't specified
}
URL uri = new URL(url);
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) uri.openConnection();
@ -99,17 +100,7 @@ public class DefaultCallbackManager implements CallbackManager {
throw new RuntimeException("Input stream is null");
}
return stream.readAllBytes();
}
// file saving
@SneakyThrows
private void saveFile(final byte[] byteArray, final Path path) {
if (path == null) {
throw new RuntimeException("Path argument is not specified"); // file isn't specified
}
// update a file or create a new one
storageMutator.createOrUpdateFile(path, new ByteArrayInputStream(byteArray));
storageMutator.createOrUpdateFile(path, stream); // update a file or create a new one
}
@SneakyThrows
@ -127,9 +118,9 @@ public class DefaultCallbackManager implements CallbackManager {
if (!curExt.equals(downloadExt)) {
try {
String newFileUri = serviceConverter
.getConvertedData(downloadUri, downloadExt, curExt,
.getConvertedUri(downloadUri, downloadExt, curExt,
serviceConverter.generateRevisionId(downloadUri), null, false,
null).getUri(); // convert a file and get URL to a new file
null); // convert a file and get URL to a new file
if (newFileUri.isEmpty()) {
newFileName = documentManager
.getCorrectName(fileUtility.getFileNameWithoutExtension(fileName)
@ -143,8 +134,6 @@ public class DefaultCallbackManager implements CallbackManager {
}
}
byte[] byteArrayFile = getDownloadFile(downloadUri); // download document file
String storagePath = storagePathBuilder.getFileLocation(newFileName); // get the path to a new file
Path lastVersion = Paths.get(storagePathBuilder
.getFileLocation(fileName)); // get the path to the last file version
@ -163,11 +152,12 @@ public class DefaultCallbackManager implements CallbackManager {
storageMutator.createDirectory(ver); // create the file version directory
saveFile(byteArrayFile, toSave); // save document file
// move the last file version to the file version directory with the "prev" postfix
storageMutator.moveFile(lastVersion, Paths.get(versionDir + File.separator + "prev" + curExt));
byte[] byteArrayChanges = getDownloadFile(changesUri); // download file changes
saveFile(byteArrayChanges, Path
.of(versionDir + File.separator + "diff.zip")); // save file changes to the diff.zip archive
downloadToFile(downloadUri, toSave); // save file to the storage path
downloadToFile(changesUri, Path
.of(versionDir + File.separator + "diff.zip")); // save file changes to the diff.zip archive
JSONObject jsonChanges = new JSONObject(); // create a json object for document changes
jsonChanges.put("changes", body.getHistory().getChanges()); // put the changes to the json object
@ -211,8 +201,7 @@ public class DefaultCallbackManager implements CallbackManager {
}
String headerToken;
// check if a secret key to generate token exists or not
if (jwtManager.tokenEnabled() && jwtManager.tokenUseForRequest()) {
if (jwtManager.tokenEnabled()) { // check if a secret key to generate token exists or not
Map<String, Object> payloadMap = new HashMap<>();
payloadMap.put("payload", params);
headerToken = jwtManager.createToken(payloadMap); // encode a payload object into a header token
@ -257,8 +246,8 @@ public class DefaultCallbackManager implements CallbackManager {
break;
default:
throw new RuntimeException(response.toJSONString());
}
}
}
@SneakyThrows
public void processForceSave(final Track body, final String fileNameParam) { // file force saving process
@ -277,8 +266,8 @@ public class DefaultCallbackManager implements CallbackManager {
try {
// convert file and get URL to a new file
String newFileUri = serviceConverter
.getConvertedData(downloadUri, downloadExt, curExt, serviceConverter
.generateRevisionId(downloadUri), null, false, null).getUri();
.getConvertedUri(downloadUri, downloadExt, curExt, serviceConverter
.generateRevisionId(downloadUri), null, false, null);
if (newFileUri.isEmpty()) {
newFileName = true;
} else {
@ -289,7 +278,6 @@ public class DefaultCallbackManager implements CallbackManager {
}
}
byte[] byteArrayFile = getDownloadFile(downloadUri); // download document file
String forcesavePath = "";
// todo: Use ENUMS
@ -325,6 +313,6 @@ public class DefaultCallbackManager implements CallbackManager {
}
}
saveFile(byteArrayFile, Path.of(forcesavePath));
downloadToFile(downloadUri, Path.of(forcesavePath));
}
}

View File

@ -37,8 +37,6 @@ import java.util.Map;
public class DefaultJwtManager implements JwtManager {
@Value("${files.docservice.secret}")
private String tokenSecret;
@Value("${files.docservice.token-use-for-request}")
private String tokenUseForRequest;
@Autowired
private ObjectMapper objectMapper;
@Autowired
@ -64,10 +62,6 @@ public class DefaultJwtManager implements JwtManager {
return tokenSecret != null && !tokenSecret.isEmpty();
}
public boolean tokenUseForRequest() {
return Boolean.parseBoolean(tokenUseForRequest) && !tokenUseForRequest.isEmpty();
}
// read document token
public JWT readToken(final String token) {
try {
@ -90,7 +84,7 @@ public class DefaultJwtManager implements JwtManager {
} catch (Exception ex) {
throw new RuntimeException("{\"error\":1,\"message\":\"JSON Parsing error\"}");
}
if (tokenEnabled() && tokenUseForRequest()) { // check if the token is enabled
if (tokenEnabled()) { // check if the token is enabled
String token = (String) body.get("token"); // get token from the body
if (token == null) { // if token is empty
if (header != null && !header.isBlank()) { // and the header is defined

View File

@ -26,7 +26,6 @@ import java.util.Map;
// specify the jwt manager functions
public interface JwtManager {
boolean tokenEnabled(); // check if the token is enabled
boolean tokenUseForRequest(); // check if the token is enabled
String createToken(Map<String, Object> payloadClaims); // create document token
JWT readToken(String token); // read document token
JSONObject parseBody(String payload, String header); // parse the body

View File

@ -27,6 +27,5 @@ public enum Action {
comment,
chat,
fillForms,
blockcontent,
protect
blockcontent
}

View File

@ -25,8 +25,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.HashMap;
@Component
@Scope("prototype")
@Getter
@ -45,5 +43,4 @@ public class Document { // the parameters pertaining to the document (title, ur
as file name when the document is downloaded */
private String url; // the absolute URL where the source viewed or edited document is stored
private String directUrl;
private HashMap<String, Object> referenceData;
}

View File

@ -51,5 +51,4 @@ public class Permission extends AbstractModel { // the permission for the docum
private CommentGroup commentGroups; // the groups whose comments the user can edit, remove and/or view
@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = SerializerFilter.class)
private List<String> userInfoGroups;
private Boolean protect = true;
}

View File

@ -1,42 +0,0 @@
/**
*
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.onlyoffice.integration.documentserver.models.filemodel;
import java.util.HashMap;
import java.util.Map;
import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
import org.springframework.beans.factory.annotation.Autowired;
public class ReferenceData {
@Autowired
private FileStoragePathBuilder storagePathBuilder;
private final String instanceId;
private final Map<String, String> fileKey;
public ReferenceData(final String fileName, final String curUserHostAddress, final User user) {
instanceId = storagePathBuilder.getServerUrl(true);
Map<String, String> fileKeyList = new HashMap<>();
if (!user.getId().equals("uid-0")) {
fileKeyList.put("fileName", fileName);
fileKeyList.put("userAddress", curUserHostAddress);
} else {
fileKeyList = null;
}
fileKey = fileKeyList;
}
}

View File

@ -20,7 +20,6 @@ package com.onlyoffice.integration.documentserver.storage;
import org.springframework.core.io.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Path;
@ -38,5 +37,5 @@ public interface FileStorageMutator {
Resource loadFileAsResourceHistory(String fileName, String version, String file); // load file as a resource
File[] getStoredFiles(); // get a collection of all the stored files
void createMeta(String fileName, String uid, String uname); // create the file meta information
boolean createOrUpdateFile(Path path, ByteArrayInputStream stream); // create or update a file
boolean createOrUpdateFile(Path path, InputStream stream); // create or update a file
}

View File

@ -31,7 +31,6 @@ import org.springframework.stereotype.Component;
import org.springframework.util.FileSystemUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
@ -333,7 +332,7 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
}
// create or update a file
public boolean createOrUpdateFile(final Path path, final ByteArrayInputStream stream) {
public boolean createOrUpdateFile(final Path path, final InputStream stream) {
if (!Files.exists(path)) { // if the specified file does not exist
return createFile(path, stream); // create it in the specified directory
} else {
@ -373,7 +372,7 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
path = Paths.get(historyPath); // otherwise, get the path to the history directory
if (!Files.exists(path)) {
return 1; // if the history directory does not exist, then the file version is 1
}
}
}
// run through all the files in the history directory

View File

@ -23,7 +23,6 @@ import com.onlyoffice.integration.documentserver.managers.jwt.JwtManager;
import com.onlyoffice.integration.documentserver.models.enums.ConvertErrorType;
import com.onlyoffice.integration.documentserver.util.file.FileUtility;
import com.onlyoffice.integration.dto.Convert;
import com.onlyoffice.integration.dto.ConvertedData;
import lombok.SneakyThrows;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
@ -126,9 +125,9 @@ public class DefaultServiceConverter implements ServiceConverter {
}
// get the URL to the converted file
public ConvertedData getConvertedData(final String documentUri, final String fromExtension,
final String toExtension, final String documentRevisionId,
final String filePass, final Boolean isAsync, final String lang) {
public String getConvertedUri(final String documentUri, final String fromExtension,
final String toExtension, final String documentRevisionId,
final String filePass, final Boolean isAsync, final String lang) {
// check if the fromExtension parameter is defined; if not, get it from the document url
String fromExt = fromExtension == null || fromExtension.isEmpty()
? fileUtility.getFileExtension(documentUri) : fromExtension;
@ -156,7 +155,7 @@ public class DefaultServiceConverter implements ServiceConverter {
}
String headerToken = "";
if (jwtManager.tokenEnabled() && jwtManager.tokenUseForRequest()) {
if (jwtManager.tokenEnabled()) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("region", lang);
map.put("url", body.getUrl());
@ -180,7 +179,7 @@ public class DefaultServiceConverter implements ServiceConverter {
String jsonString = postToServer(body, headerToken);
return getResponseData(jsonString);
return getResponseUri(jsonString);
}
// generate document key
@ -204,7 +203,7 @@ public class DefaultServiceConverter implements ServiceConverter {
// get the response URL
@SneakyThrows
private ConvertedData getResponseData(final String jsonString) {
private String getResponseUri(final String jsonString) {
JSONObject jsonObj = convertStringToJSON(jsonString);
Object error = jsonObj.get("error");
@ -217,15 +216,10 @@ public class DefaultServiceConverter implements ServiceConverter {
Long resultPercent = 0L;
String responseUri = null;
String responseFileType = null;
ConvertedData convertedData = new ConvertedData("", "");
if (isEndConvert) { // if the conversion is completed
resultPercent = FULL_LOADING_IN_PERCENT;
responseUri = (String) jsonObj.get("fileUrl"); // get the file URL
responseFileType = (String) jsonObj.get("fileType"); // get the file type
convertedData.setUri(responseUri);
convertedData.setFileType(responseFileType);
} else { // if the conversion isn't completed
resultPercent = (Long) jsonObj.get("percent");
@ -233,7 +227,7 @@ public class DefaultServiceConverter implements ServiceConverter {
resultPercent = resultPercent >= FULL_LOADING_IN_PERCENT ? FULL_LOADING_IN_PERCENT - 1 : resultPercent;
}
return convertedData;
return resultPercent >= FULL_LOADING_IN_PERCENT ? responseUri : "";
}
// convert stream to string

View File

@ -18,16 +18,15 @@
package com.onlyoffice.integration.documentserver.util.service;
import com.onlyoffice.integration.dto.ConvertedData;
import org.json.simple.JSONObject;
import java.io.InputStream;
// specify the converter service functions
public interface ServiceConverter {
ConvertedData getConvertedData(String documentUri, String fromExtension, // get the URL to the converted file
String toExtension, String documentRevisionId,
String filePass, Boolean isAsync, String lang);
String getConvertedUri(String documentUri, String fromExtension, // get the URL to the converted file
String toExtension, String documentRevisionId,
String filePass, Boolean isAsync, String lang);
String generateRevisionId(String expectedKey); // generate document key
String convertStreamToString(InputStream stream); // convert stream to string
JSONObject convertStringToJSON(String jsonString); // convert string to json

View File

@ -1,33 +0,0 @@
/**
*
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.onlyoffice.integration.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ConvertedData {
private String uri;
private String fileType;
}

View File

@ -52,5 +52,4 @@ public class Permission extends AbstractEntity {
private List<Group> commentsRemoveGroups;
@ManyToMany
private List<Group> userInfoGroups;
private Boolean protect = true;
}

View File

@ -38,8 +38,7 @@ public class PermissionServices {
final List<Group> commentEditGroups,
final List<Group> commentRemoveGroups,
final List<Group> userInfoGroups,
final Boolean chat,
final Boolean protect) {
final Boolean chat) {
Permission permission = new Permission();
permission.setReviewGroups(reviewGroups); // define the groups whose changes the user can accept/reject
@ -49,7 +48,6 @@ public class PermissionServices {
whose comments the user can remove */
permission.setUserInfoGroups(userInfoGroups);
permission.setChat(chat);
permission.setProtect(protect);
permissionRepository.save(permission); // save new permissions

View File

@ -57,8 +57,7 @@ public class UserServices {
final List<String> editGroups,
final List<String> removeGroups,
final List<String> userInfoGroups, final Boolean favoriteDoc,
final Boolean chat,
final Boolean protect) {
final Boolean chat) {
User newUser = new User();
newUser.setName(name); // set the user name
newUser.setEmail(email); // set the user email
@ -82,8 +81,7 @@ public class UserServices {
commentGroupsEdit,
commentGroupsRemove,
usInfoGroups,
chat,
protect); // specify permissions for the current user
chat); // specify permissions for the current user
newUser.setPermissions(permission);
userRepository.save(newUser); // save a new user

View File

@ -18,7 +18,6 @@
package com.onlyoffice.integration.services.configurers.implementations;
import com.google.gson.Gson;
import com.onlyoffice.integration.documentserver.models.filemodel.Document;
import com.onlyoffice.integration.documentserver.models.filemodel.Permission;
import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
@ -32,8 +31,6 @@ import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import java.io.File;
import java.net.InetAddress;
import java.util.HashMap;
@Service
@Primary
@ -74,20 +71,7 @@ public class DefaultDocumentConfigurer implements DocumentConfigurer<DefaultDocu
+ "/" + fileName + "/"
+ new File(storagePathBuilder.getFileLocation(fileName)).lastModified());
Gson gson = new Gson();
HashMap<String, String> fileKey = new HashMap<>();
fileKey.put("fileName", fileName);
try {
fileKey.put("userAddress", InetAddress.getLocalHost().getHostAddress());
} catch (Exception e) {
e.printStackTrace();
}
HashMap<String, Object> referenceData = new HashMap<>();
referenceData.put("instanceId", storagePathBuilder.getServerUrl(true));
referenceData.put("fileKey", gson.toJson(fileKey));
document.setKey(key); // set the key to the document config
document.setPermissions(permission); // set the permission parameters to the document config
document.setReferenceData(referenceData);
}
}

View File

@ -19,7 +19,6 @@
package com.onlyoffice.integration.services.configurers.wrappers;
import com.onlyoffice.integration.documentserver.models.filemodel.Permission;
import com.onlyoffice.integration.documentserver.models.filemodel.ReferenceData;
import lombok.Builder;
import lombok.Getter;
@ -30,5 +29,4 @@ public class DefaultDocumentWrapper {
private String fileName;
private Boolean favorite;
private Boolean isEnableDirectUrl;
private ReferenceData referenceData;
}

View File

@ -8,10 +8,10 @@ filesize-max=5242880
files.storage=
files.storage.folder=documents
files.docservice.fillforms-docs=.docx|.oform
files.docservice.viewed-docs=.djvu|.oxps|.pdf|.xps
files.docservice.edited-docs=.csv|.docm|.docx|.docxf|.dotm|.dotx|.epub|.fb2|.html|.odp|.ods|.odt|.otp|.ots|.ott|.potm|.potx|.ppsm|.ppsx|.pptm|.pptx|.rtf|.txt|.xlsm|.xlsx|.xltm|.xltx
files.docservice.convert-docs=.doc|.dot|.dps|.dpt|.epub|.et|.ett|.fb2|.fodp|.fods|.fodt|.htm|.html|.mht|.mhtml|.odp|.ods|.odt|.otp|.ots|.ott|.pot|.pps|.ppt|.rtf|.stw|.sxc|.sxi|.sxw|.wps|.wpt|.xls|.xlsb|.xlt|.xml
files.docservice.fillforms-docs=.oform|.docx
files.docservice.viewed-docs=.pdf|.djvu|.xps|.oxps
files.docservice.edited-docs=.docx|.xlsx|.csv|.pptx|.txt|.docxf
files.docservice.convert-docs=.docm|.dotx|.dotm|.dot|.doc|.odt|.fodt|.ott|.xlsm|.xlsb|.xltx|.xltm|.xlt|.xls|.ods|.fods|.ots|.pptm|.ppt|.ppsx|.ppsm|.pps|.potx|.potm|.pot|.odp|.fodp|.otp|.rtf|.mht|.html|.htm|.xml|.epub|.fb2
files.docservice.timeout=120000
files.docservice.history.postfix=-hist
@ -24,11 +24,10 @@ files.docservice.url.example=
files.docservice.secret=
files.docservice.header=Authorization
files.docservice.token-use-for-request=true
files.docservice.verify-peer-off=true
files.docservice.languages=en:English|hy:Armenian|az:Azerbaijani|eu:Basque|be:Belarusian|bg:Bulgarian|ca:Catalan|zh:Chinese|zh-TW:Chinese (Taiwan)|cs:Czech|da:Danish|nl:Dutch|fi:Finnish|fr:French|gl:Galego|de:German|el:Greek|hu:Hungarian|id:Indonesian|it:Italian|ja:Japanese|ko:Korean|lo:Lao|lv:Latvian|ms:Malay (Malaysia)|no:Norwegian|pl:Polish|pt:Portuguese (Brazil)|pt-PT:Portuguese (Portugal)|ro:Romanian|ru:Russian|si:Sinhala (Sri Lanka)|sk:Slovak|sl:Slovenian|es:Spanish|sv:Swedish|tr:Turkish|uk:Ukrainian|vi:Vietnamese|aa-AA:Test Language
files.docservice.languages=en:English|hy:Armenian|az:Azerbaijani|eu:Basque|be:Belarusian|bg:Bulgarian|ca:Catalan|zh:Chinese (People's Republic of China)|zh-TW:Chinese (Traditional, Taiwan)|cs:Czech|da:Danish|nl:Dutch|fi:Finnish|fr:French|gl:Galego|de:German|el:Greek|hu:Hungarian|id:Indonesian|it:Italian|ja:Japanese|ko:Korean|lv:Latvian|lo:Lao|ms:Malay (Malaysia)|nb:Norwegian|pl:Polish|pt:Portuguese (Brazil)|pt-PT:Portuguese (Portugal)|ro:Romanian|ru:Russian|sk:Slovak|sl:Slovenian|es:Spanish|sv:Swedish|tr:Turkish|uk:Ukrainian|vi:Vietnamese|aa-AA:Test Language
spring.datasource.url=jdbc:h2:mem:usersdb
spring.datasource.driverClassName=org.h2.Driver

View File

@ -668,9 +668,4 @@
.main-panel > span{
max-width:15%;
}
}
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.tableRow td:first-child{
max-width: none;
}
}
}

View File

@ -160,23 +160,12 @@
}
};
var onRequestReferenceData = function(event) { // user refresh external data source
event.data.directUrl = !!config.document.directUrl;
let xhr = new XMLHttpRequest();
xhr.open("POST", "reference");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(event.data));
xhr.onload = function () {
innerAlert(xhr.responseText);
docEditor.setReferenceData(JSON.parse(xhr.responseText));
}
};
config.width = "100%";
config.height = "100%";
config.events = {
"onAppReady": onAppReady,
"onDocumentStateChange": onDocumentStateChange,
'onRequestEditRights': onRequestEditRights,
"onError": onError,
"onOutdatedVersion": onOutdatedVersion,
"onMakeActionLink": onMakeActionLink,
@ -222,9 +211,6 @@
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
config.events['onRequestReferenceData'] = onRequestReferenceData;
// prevent switch the document from the viewing into the editing mode for anonymous users
config.events['onRequestEditRights'] = onRequestEditRights;
}
if (config.editorConfig.createUrl) {

View File

@ -19,7 +19,6 @@
package controllers;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import entities.FileType;
import entities.User;
import helpers.ConfigManager;
@ -64,6 +63,7 @@ import java.util.Scanner;
import static utils.Constants.KILOBYTE_SIZE;
@WebServlet(name = "IndexServlet", urlPatterns = {"/IndexServlet"})
@MultipartConfig
public class IndexServlet extends HttpServlet {
@ -118,9 +118,6 @@ public class IndexServlet extends HttpServlet {
case "rename":
rename(request, response, writer);
break;
case "reference":
reference(request, response, writer);
break;
default:
break;
}
@ -265,18 +262,16 @@ public class IndexServlet extends HttpServlet {
String fileUri = DocumentManager.getDownloadUrl(fileName, true);
String fileExt = FileUtility.getFileExtension(fileName);
FileType fileType = FileUtility.getFileType(fileName);
String internalFileExt = "ooxml";
String internalFileExt = DocumentManager.getInternalExtension(fileType);
// check if the file with such an extension can be converted
if (DocumentManager.getConvertExts().contains(fileExt)) {
// generate document key
String key = ServiceConverter.generateRevisionId(fileUri);
// get the url and file type to the converted file
Map<String, String> newFileData = ServiceConverter
.getConvertedData(fileUri, fileExt, internalFileExt, key, filePass, true, lang);
String newFileUri = newFileData.get("fileUrl");
String newFileType = "." + newFileData.get("fileType");
// get the url to the converted file
String newFileUri = ServiceConverter
.getConvertedUri(fileUri, fileExt, internalFileExt, key, filePass, true, lang);
if (newFileUri.isEmpty()) {
writer.write("{ \"step\" : \"0\", \"filename\" : \"" + fileName + "\"}");
@ -286,7 +281,7 @@ public class IndexServlet extends HttpServlet {
/* get a file name of an internal file extension with an index if the file
with such a name already exists */
String correctName = DocumentManager.getCorrectName(FileUtility
.getFileNameWithoutExtension(fileName) + newFileType, null);
.getFileNameWithoutExtension(fileName) + internalFileExt, null);
URL url = new URL(newFileUri);
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
@ -477,7 +472,7 @@ public class IndexServlet extends HttpServlet {
final HttpServletResponse response,
final PrintWriter writer) {
try {
if (DocumentManager.tokenEnabled() && DocumentManager.tokenUseForRequest()) {
if (DocumentManager.tokenEnabled()) {
String documentJwtHeader = ConfigManager.getProperty("files.docservice.header");
@ -522,24 +517,22 @@ public class IndexServlet extends HttpServlet {
String userAddress = request.getParameter("userAddress");
String isEmbedded = request.getParameter("dmode");
if (DocumentManager.tokenEnabled() && isEmbedded == null && userAddress != null
&& DocumentManager.tokenUseForRequest()) {
if (DocumentManager.tokenEnabled() && isEmbedded == null) {
String documentJwtHeader = ConfigManager.getProperty("files.docservice.header");
String header = (String) request.getHeader(documentJwtHeader == null || documentJwtHeader.isEmpty()
? "Authorization" : documentJwtHeader);
String token = "";
if (header != null && !header.isEmpty()) {
String bearerPrefix = "Bearer ";
token = header.startsWith(bearerPrefix) ? header.substring(bearerPrefix.length()) : header;
}
try {
Verifier verifier = HMACVerifier.newVerifier(DocumentManager.getTokenSecret());
JWT jwt = JWT.getDecoder().decode(token, verifier);
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "JWT validation failed");
return;
String token = header.startsWith(bearerPrefix) ? header.substring(bearerPrefix.length()) : header;
try {
Verifier verifier = HMACVerifier.newVerifier(DocumentManager.getTokenSecret());
JWT jwt = JWT.getDecoder().decode(token, verifier);
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "JWT validation failed");
return;
}
}
}
@ -639,87 +632,6 @@ public class IndexServlet extends HttpServlet {
}
}
// reference data
private static void reference(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) {
try {
Scanner scanner = new Scanner(request.getInputStream());
scanner.useDelimiter("\\A");
String bodyString = scanner.hasNext() ? scanner.next() : "";
scanner.close();
String fileKeyValue = "";
String userAddress = "";
String fileName = "";
boolean incorrectFileKey = false;
JSONParser parser = new JSONParser();
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
JSONObject body = (JSONObject) parser.parse(bodyString);
if (body.containsKey("referenceData")) {
JSONObject referenceDataObj = (JSONObject) body.get("referenceData");
String instanceId = (String) referenceDataObj.get("instanceId");
if (instanceId.equals(DocumentManager.getServerUrl(false))) {
try {
JSONObject fileKey = (JSONObject) parser.parse((String) referenceDataObj.get("fileKey"));
userAddress = (String) fileKey.get("userAddress");
if (userAddress.equals(DocumentManager.curUserHostAddress(null))) {
fileName = (String) fileKey.get("fileName");
}
} catch (Exception e) {
incorrectFileKey = true; //data from DocEditor can give incorrect fileKey param in java Example
}
}
}
if (fileName.equals("")) {
try {
String path = (String) body.get("path");
path = FileUtility.getFileName(path);
File f = new File(DocumentManager.storagePath(path, null));
if (f.exists()) {
fileName = path;
}
} catch (Exception e) {
e.printStackTrace();
writer.write("{ \"error\" : 1, \"message\" : \"" + e.getMessage() + "\"}");
}
}
if (fileName.equals("")) {
writer.write("{ \"error\": \"File not found\"}");
return;
}
HashMap<String, Object> fileKey = new HashMap<>();
fileKey.put("fileName", fileName);
fileKey.put("userAddress", DocumentManager.curUserHostAddress(null));
HashMap<String, Object> referenceData = new HashMap<>();
referenceData.put("instanceId", DocumentManager.getServerUrl(false));
referenceData.put("fileKey", gson.toJson(fileKey));
HashMap<String, Object> data = new HashMap<>();
data.put("fileType", FileUtility.getFileExtension(fileName));
data.put("url", DocumentManager.getDownloadUrl(fileName, true));
data.put("directUrl", DocumentManager.getDownloadUrl(fileName, true));
data.put("referenceData", referenceData);
data.put("path", fileName);
if (DocumentManager.tokenEnabled()) {
String token = DocumentManager.createToken(data);
data.put("token", token);
}
writer.write(gson.toJson(data));
} catch (Exception e) {
e.printStackTrace();
writer.write("{ \"error\" : 1, \"message\" : \"" + e.getMessage() + "\"}");
}
}
// process get request
@Override

View File

@ -21,18 +21,6 @@ package entities;
import java.util.List;
public class CommentGroups {
public List<String> getView() {
return view;
}
public List<String> getEdit() {
return edit;
}
public List<String> getRemove() {
return remove;
}
private List<String> view;
private List<String> edit;
private List<String> remove;

View File

@ -77,7 +77,6 @@ public class FileModel {
.lastModified())));
document.setInfo(new Info());
document.getInfo().setFavorite(user.getFavorite());
document.setReferenceData(new ReferenceData(fileName, DocumentManager.curUserHostAddress(null), user));
String templatesImageUrl = DocumentManager.getTemplateImageUrl(FileUtility.getFileType(fileName));
List<Map<String, String>> templates = new ArrayList<>();
@ -124,26 +123,6 @@ public class FileModel {
changeType(mode, type, user, fileName);
}
public String getType() {
return type;
}
public String getMode() {
return mode;
}
public Document getDocument() {
return document;
}
public EditorConfig getEditorConfig() {
return editorConfig;
}
public String getToken() {
return token;
}
// change the document type
public void changeType(final String modeParam, final String typeParam, final User user, final String fileName) {
if (modeParam != null) {
@ -323,7 +302,6 @@ public class FileModel {
private String key;
private Info info;
private Permissions permissions;
private ReferenceData referenceData;
public String getTitle() {
return title;
@ -349,10 +327,6 @@ public class FileModel {
this.directUrl = directUrlParam;
}
public String getFileType() {
return fileType;
}
public void setFileType(final String fileTypeParam) {
this.fileType = fileTypeParam;
}
@ -380,13 +354,6 @@ public class FileModel {
public void setPermissions(final Permissions permissionsParam) {
this.permissions = permissionsParam;
}
public ReferenceData getReferenceData() {
return referenceData;
}
public void setReferenceData(final ReferenceData referenceDataParam) {
this.referenceData = referenceDataParam;
}
}
// the permissions parameters
@ -404,7 +371,6 @@ public class FileModel {
private final List<String> reviewGroups;
private final CommentGroups commentGroups;
private final List<String> userInfoGroups;
private final Boolean protect;
//public Gson gson = new Gson();
// defines what can be done with a document
@ -425,115 +391,23 @@ public class FileModel {
reviewGroups = user.getReviewGroups();
commentGroups = user.getCommentGroups();
userInfoGroups = user.getUserInfoGroups();
protect = !user.getDeniedPermissions().contains("protect");
}
public Boolean getComment() {
return comment;
}
public Boolean getCopy() {
return copy;
}
public Boolean getDownload() {
return download;
}
public Boolean getEdit() {
return edit;
}
public Boolean getPrint() {
return print;
}
public Boolean getFillForms() {
return fillForms;
}
public Boolean getModifyFilter() {
return modifyFilter;
}
public Boolean getModifyContentControl() {
return modifyContentControl;
}
public Boolean getReview() {
return review;
}
public Boolean getChat() {
return chat;
}
public List<String> getReviewGroups() {
return reviewGroups;
}
public CommentGroups getCommentGroups() {
return commentGroups;
}
public List<String> getUserInfoGroups() {
return userInfoGroups;
}
public Boolean getProtect() {
return protect;
}
}
public class ReferenceData {
private final String instanceId;
private final Map<String, String> fileKey;
public ReferenceData(final String fileName, final String curUserHostAddress, final User user) {
instanceId = DocumentManager.getServerUrl(true);
Map<String, String> fileKeyList = new HashMap<>();
if (!user.getId().equals("uid-0")) {
fileKeyList.put("fileName", fileName);
fileKeyList.put("userAddress", curUserHostAddress);
} else {
fileKeyList = null;
}
fileKey = fileKeyList;
}
public String getInstanceId() {
return instanceId;
}
public Map<String, String> getFileKey() {
return fileKey;
}
}
// the Favorite icon state
public class Info {
private String owner = "Me";
private Boolean favorite;
private String uploaded = getDate();
public String getOwner() {
return owner;
}
public Boolean getFavorite() {
return favorite;
private String getDate() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd yyyy", Locale.US);
return simpleDateFormat.format(new Date());
}
public void setFavorite(final Boolean favoriteParam) {
this.favorite = favoriteParam;
}
public String getUploaded() {
return uploaded;
}
private String getDate() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd yyyy", Locale.US);
return simpleDateFormat.format(new Date());
}
}
// the editor config parameters
public class EditorConfig {
@ -558,34 +432,6 @@ public class FileModel {
customization = new Customization();
}
public HashMap<String, Object> getActionLink() {
return actionLink;
}
public String getCallbackUrl() {
return callbackUrl;
}
public HashMap<String, Object> getCoEditing() {
return coEditing;
}
public String getLang() {
return lang;
}
public String getCreateUrl() {
return createUrl;
}
public List<Map<String, String>> getTemplates() {
return templates;
}
public Embedded getEmbedded() {
return embedded;
}
// set parameters for the embedded document
public void initDesktop(final String url) {
embedded = new Embedded();
@ -683,6 +529,10 @@ public class FileModel {
private Boolean comments;
private Boolean feedback;
public Goback getGoback() {
return goback;
}
public void setSubmitForm(final Boolean submitFormParam) {
this.submitForm = submitFormParam;
}
@ -695,30 +545,6 @@ public class FileModel {
goback = new Goback();
}
public Goback getGoback() {
return goback;
}
public Boolean getForcesave() {
return forcesave;
}
public Boolean getSubmitForm() {
return submitForm;
}
public Boolean getAbout() {
return about;
}
public Boolean getComments() {
return comments;
}
public Boolean getFeedback() {
return feedback;
}
public class Goback {
private String url;
@ -739,34 +565,18 @@ public class FileModel {
private String shareUrl;
private String toolbarDocked;
public String getSaveUrl() {
return saveUrl;
}
public void setSaveUrl(final String saveUrlParam) {
this.saveUrl = saveUrlParam;
}
public String getEmbedUrl() {
return embedUrl;
}
public void setEmbedUrl(final String embedUrlParam) {
this.embedUrl = embedUrlParam;
}
public String getShareUrl() {
return shareUrl;
}
public void setShareUrl(final String shareUrlParam) {
this.shareUrl = shareUrlParam;
}
public String getToolbarDocked() {
return toolbarDocked;
}
public void setToolbarDocked(final String toolbarDockedParam) {
this.toolbarDocked = toolbarDockedParam;
}

View File

@ -565,22 +565,11 @@ public final class DocumentManager {
return secret != null && !secret.isEmpty();
}
// check if the token is enabled for request
public static Boolean tokenUseForRequest() {
String tokenUseForRequest = getTokenUseForRequest();
return Boolean.parseBoolean(tokenUseForRequest) && !tokenUseForRequest.isEmpty();
}
// get token secret from the config parameters
public static String getTokenSecret() {
return ConfigManager.getProperty("files.docservice.secret");
}
// get config request jwt
public static String getTokenUseForRequest() {
return ConfigManager.getProperty("files.docservice.token-use-for-request");
}
// get languages
public static Map<String, String> getLanguages() {
String langs = ConfigManager.getProperty("files.docservice.languages");

View File

@ -137,10 +137,10 @@ public final class ServiceConverter {
}
// get the url of the converted file
public static Map<String, String> getConvertedData(final String documentUri, final String fromExtension,
final String toExtension, final String documentRevisionId,
final String filePass, final Boolean isAsync,
final String lang) throws Exception {
public static String getConvertedUri(final String documentUri, final String fromExtension,
final String toExtension, final String documentRevisionId,
final String filePass, final Boolean isAsync,
final String lang) throws Exception {
// check if the fromExtension parameter is defined; if not, get it from the document url
String fromExt = fromExtension == null || fromExtension.isEmpty()
? FileUtility.getFileExtension(documentUri) : fromExtension;
@ -168,7 +168,7 @@ public final class ServiceConverter {
}
String headerToken = "";
if (DocumentManager.tokenEnabled() && DocumentManager.tokenUseForRequest()) {
if (DocumentManager.tokenEnabled()) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("region", lang);
map.put("url", body.getUrl());
@ -233,7 +233,7 @@ public final class ServiceConverter {
connection.disconnect();
return getResponseData(jsonString);
return getResponseUri(jsonString);
}
// generate document key
@ -254,8 +254,8 @@ public final class ServiceConverter {
throw new Exception(errorMessage);
}
// get the response data
private static Map<String, String> getResponseData(final String jsonString) throws Exception {
// get the response url
private static String getResponseUri(final String jsonString) throws Exception {
JSONObject jsonObj = convertStringToJSON(jsonString);
Object error = jsonObj.get("error");
@ -268,23 +268,17 @@ public final class ServiceConverter {
Long resultPercent = 0L;
String responseUri = null;
String responseFileType = null;
Map<String, String> responseData = new HashMap<>();
if (isEndConvert) { // if the conversion is completed
resultPercent = FULL_LOADING_IN_PERCENT;
responseUri = (String) jsonObj.get("fileUrl"); // get the file url
responseFileType = (String) jsonObj.get("fileType"); // get the file type
responseData.put("fileUrl", responseUri);
responseData.put("fileType", responseFileType);
} else { // if the conversion isn't completed
resultPercent = (Long) jsonObj.get("percent");
responseData.put("fileUrl", "");
resultPercent = resultPercent >= FULL_LOADING_IN_PERCENT
? FULL_LOADING_IN_PERCENT - 1 : resultPercent; // get the percentage value
}
return responseData;
return resultPercent >= FULL_LOADING_IN_PERCENT ? responseUri : "";
}
// convert stream to string

View File

@ -26,26 +26,19 @@ import org.primeframework.jwt.domain.JWT;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import static utils.Constants.BUFFER_SIZE;
import static utils.Constants.FILE_SAVE_TIMEOUT;
import static utils.Constants.KILOBYTE_SIZE;
@ -87,7 +80,7 @@ public final class TrackManager {
}
// if the secret key to generate token exists
if (DocumentManager.tokenEnabled() && DocumentManager.tokenUseForRequest()) {
if (DocumentManager.tokenEnabled()) {
String token = (String) body.get("token"); // get the document token
if (token == null) { // if JSON web token is not received
@ -156,9 +149,9 @@ public final class TrackManager {
if (!curExt.equals(downloadExt)) {
try {
String newFileUri = ServiceConverter
.getConvertedData(downloadUri, downloadExt, curExt,
.getConvertedUri(downloadUri, downloadExt, curExt,
ServiceConverter.generateRevisionId(downloadUri),
null, false, null).get("fileUrl"); // convert file and get url to a new file
null, false, null); // convert file and get url to a new file
if (newFileUri.isEmpty()) {
// get the correct file name if it already exists
@ -174,8 +167,6 @@ public final class TrackManager {
}
}
byte[] byteArrayFile = getDownloadFile(downloadUri); // download document file
String storagePath = DocumentManager.storagePath(newFileName, userAddress); // get the file path
File histDir = new File(DocumentManager.historyDir(storagePath)); // get the path to the history direction
if (!histDir.exists()) {
@ -186,7 +177,7 @@ public final class TrackManager {
.getFileVersion(histDir.getAbsolutePath())); // get the path to the file version
File ver = new File(versionDir);
File lastVersion = new File(DocumentManager.storagePath(fileName, userAddress));
Path toSave = Paths.get(storagePath);
File toSave = new File(storagePath);
if (!ver.exists()) {
ver.mkdirs();
@ -195,10 +186,10 @@ public final class TrackManager {
// get the path to the previous file version and rename the last file version with it
lastVersion.renameTo(new File(versionDir + File.separator + "prev" + curExt));
saveFile(byteArrayFile, toSave); // save document file
downloadToFile(downloadUri, toSave); // save file to the storage path
byte[] byteArrayChanges = getDownloadFile(changesUri);
saveFile(byteArrayChanges, Paths.get(versionDir + File.separator + "diff.zip"));
// save file changes to the diff.zip archive
downloadToFile(changesUri, new File(versionDir + File.separator + "diff.zip"));
String history = (String) body.get("changeshistory");
if (history == null && body.containsKey("history")) {
@ -244,9 +235,9 @@ public final class TrackManager {
if (!curExt.equals(downloadExt)) {
try {
String newFileUri = ServiceConverter
.getConvertedData(downloadUri, downloadExt, curExt,
.getConvertedUri(downloadUri, downloadExt, curExt,
ServiceConverter.generateRevisionId(downloadUri), null,
false, null).get("fileUrl"); // convert file and get url to a new file
false, null); // convert file and get url to a new file
if (newFileUri.isEmpty()) {
newFileName = true;
} else {
@ -257,7 +248,6 @@ public final class TrackManager {
}
}
byte[] byteArrayFile = getDownloadFile(downloadUri); // download document file
String forcesavePath = "";
boolean isSubmitForm = body.get("forcesavetype").toString().equals("3"); // SubmitForm
@ -284,7 +274,8 @@ public final class TrackManager {
}
}
saveFile(byteArrayFile, Paths.get(forcesavePath));
File toSave = new File(forcesavePath);
downloadToFile(downloadUri, toSave);
if (isSubmitForm) {
JSONArray actions = (JSONArray) body.get("actions");
@ -296,79 +287,43 @@ public final class TrackManager {
}
}
// create a new file if it does not exist
private static boolean createFile(final byte[] byteArray, final Path path) {
if (Files.exists(path)) {
return true;
}
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray)) {
File file = Files.createFile(path).toFile(); // create a new file in the specified path
try (FileOutputStream out = new FileOutputStream(file)) {
int read;
final byte[] bytes = new byte[KILOBYTE_SIZE];
while ((read = byteArrayInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read); // write bytes to the output stream
}
out.flush(); // force write data to the output stream that can be cached in the current thread
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
// get byte array from stream
private static byte[] getAllBytes(final InputStream is) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
os.write(buffer, 0, len);
}
return os.toByteArray();
}
// save file
private static boolean saveFile(final byte[] byteArray, final Path path) {
if (path == null) {
throw new RuntimeException("Path argument is not specified"); // file isn't specified
}
if (!Files.exists(path)) { // if the specified file does not exist
return createFile(byteArray, path); // create it in the specified directory
} else {
try {
Files.write(path, byteArray); // otherwise, write new information in the bytes format to the file
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
// download file from url
private static byte[] getDownloadFile(final String url) throws Exception {
// save file information from the url to the file specified
private static void downloadToFile(final String url, final File file) throws Exception {
if (url == null || url.isEmpty()) {
throw new RuntimeException("Url argument is not specified"); // URL isn't specified
throw new Exception("argument url"); // url isn't specified
}
if (file == null) {
throw new Exception("argument path"); // file isn't specified
}
URL uri = new URL(url);
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) uri.openConnection();
connection.setConnectTimeout(FILE_SAVE_TIMEOUT);
InputStream stream = connection.getInputStream(); // get input stream of the file information from the URL
int statusCode = connection.getResponseCode();
if (statusCode != HttpServletResponse.SC_OK) { // checking status code
connection.disconnect();
throw new RuntimeException("Document editing service returned status: " + statusCode);
}
InputStream stream = connection.getInputStream(); // get input stream of the file information from the url
if (stream == null) {
connection.disconnect();
throw new RuntimeException("Input stream is null");
throw new Exception("Stream is null");
}
return getAllBytes(stream);
try (FileOutputStream out = new FileOutputStream(file)) {
int read;
final byte[] bytes = new byte[KILOBYTE_SIZE];
while ((read = stream.read(bytes)) != -1) {
out.write(bytes, 0, read); // write bytes to the output stream
}
// force write data to the output stream that can be cached in the current thread
out.flush();
}
connection.disconnect();
}
// create a command request
@ -388,8 +343,7 @@ public final class TrackManager {
}
String headerToken = "";
// check if a secret key to generate token exists or not
if (DocumentManager.tokenEnabled() && DocumentManager.tokenUseForRequest()) {
if (DocumentManager.tokenEnabled()) { // check if a secret key to generate token exists or not
Map<String, Object> payloadMap = new HashMap<String, Object>();
payloadMap.put("payload", params);
headerToken = DocumentManager.createToken(payloadMap); // encode a payload object into a header token

View File

@ -72,7 +72,6 @@ public final class Users {
add("Cant see anyones information");
add("Can't rename files from the editor");
add("Can't view chat");
add("Can't protect file");
add("View file without collaboration");
}};
@ -91,7 +90,7 @@ public final class Users {
descriptionUserThird, false));
add(new User("uid-0", null, null,
"", null, new CommentGroups(), new ArrayList<String>(),
null, Arrays.asList("protect"), descriptionUserZero, false));
null, new ArrayList<String>(), descriptionUserZero, false));
}};
private Users() { }

View File

@ -26,7 +26,6 @@ public final class Constants {
public static final Integer FILE_SAVE_TIMEOUT = 5000;
public static final Integer MAX_KEY_LENGTH = 20;
public static final Integer KILOBYTE_SIZE = 1024;
public static final Integer BUFFER_SIZE = 0xFFFF;
private Constants() { }
}

View File

@ -3,10 +3,10 @@ version=1.5.1
filesize-max=5242880
storage-folder=app_data
files.docservice.fill-docs=.docx|.oform
files.docservice.viewed-docs=.djvu|.oxps|.pdf|.xps
files.docservice.edited-docs=.csv|.docm|.docx|.docxf|.dotm|.dotx|.epub|.fb2|.html|.odp|.ods|.odt|.otp|.ots|.ott|.potm|.potx|.ppsm|.ppsx|.pptm|.pptx|.rtf|.txt|.xlsm|.xlsx|.xltm|.xltx
files.docservice.convert-docs=.doc|.dot|.dps|.dpt|.epub|.et|.ett|.fb2|.fodp|.fods|.fodt|.htm|.html|.mht|.mhtml|.odp|.ods|.odt|.otp|.ots|.ott|.pot|.pps|.ppt|.rtf|.stw|.sxc|.sxi|.sxw|.wps|.wpt|.xls|.xlsb|.xlt|.xml
files.docservice.fill-docs=.oform|.docx
files.docservice.viewed-docs=.pdf|.djvu|.xps|.oxps
files.docservice.edited-docs=.docx|.xlsx|.csv|.pptx|.txt|.docxf
files.docservice.convert-docs=.docm|.dotx|.dotm|.dot|.doc|.odt|.fodt|.ott|.xlsm|.xlsb|.xltx|.xltm|.xlt|.xls|.ods|.fods|.ots|.pptm|.ppt|.ppsx|.ppsm|.pps|.potx|.potm|.pot|.odp|.fodp|.otp|.rtf|.mht|.html|.htm|.xml|.epub|.fb2
files.docservice.timeout=120000
files.docservice.url.site=http://documentserver/
@ -16,10 +16,9 @@ files.docservice.url.api=web-apps/apps/api/documents/api.js
files.docservice.url.preloader=web-apps/apps/api/documents/cache-scripts.html
files.docservice.url.example=
files.docservice.languages=en:English|hy:Armenian|az:Azerbaijani|eu:Basque|be:Belarusian|bg:Bulgarian|ca:Catalan|zh:Chinese|zh-TW:Chinese (Taiwan)|cs:Czech|da:Danish|nl:Dutch|fi:Finnish|fr:French|gl:Galego|de:German|el:Greek|hu:Hungarian|id:Indonesian|it:Italian|ja:Japanese|ko:Korean|lo:Lao|lv:Latvian|ms:Malay (Malaysia)|no:Norwegian|pl:Polish|pt:Portuguese (Brazil)|pt-PT:Portuguese (Portugal)|ro:Romanian|ru:Russian|si:Sinhala (Sri Lanka)|sk:Slovak|sl:Slovenian|es:Spanish|sv:Swedish|tr:Turkish|uk:Ukrainian|vi:Vietnamese|aa-AA:Test Language
files.docservice.languages=en:English|hy:Armenian|az:Azerbaijani|eu:Basque|be:Belarusian|bg:Bulgarian|ca:Catalan|zh:Chinese (People's Republic of China)|zh-TW:Chinese (Traditional, Taiwan)|cs:Czech|da:Danish|nl:Dutch|fi:Finnish|fr:French|gl:Galego|de:German|el:Greek|hu:Hungarian|id:Indonesian|it:Italian|ja:Japanese|ko:Korean|lv:Latvian|lo:Lao|ms:Malay (Malaysia)|nb:Norwegian|pl:Polish|pt:Portuguese (Brazil)|pt-PT:Portuguese (Portugal)|ro:Romanian|ru:Russian|sk:Slovak|sl:Slovenian|es:Spanish|sv:Swedish|tr:Turkish|uk:Ukrainian|vi:Vietnamese|aa-AA:Test Language
files.docservice.secret=
files.docservice.header=Authorization
files.docservice.token-use-for-request=TRUE
files.docservice.verify-peer-off=TRUE

View File

@ -668,8 +668,3 @@
max-width:15%;
}
}
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.tableRow td:first-child{
max-width: none;
}
}

View File

@ -161,24 +161,13 @@
}
};
var onRequestReferenceData = function(event) { // user refresh external data source
event.data.directUrl = !!config.document.directUrl;
let xhr = new XMLHttpRequest();
xhr.open("POST", "IndexServlet?type=reference");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(event.data));
xhr.onload = function () {
innerAlert(xhr.responseText);
docEditor.setReferenceData(JSON.parse(xhr.responseText));
}
};
config = JSON.parse('<%= FileModel.serialize(Model) %>');
config.width = "100%";
config.height = "100%";
config.events = {
"onAppReady": onAppReady,
"onDocumentStateChange": onDocumentStateChange,
'onRequestEditRights': onRequestEditRights,
"onError": onError,
"onOutdatedVersion": onOutdatedVersion,
"onMakeActionLink": onMakeActionLink,
@ -226,9 +215,6 @@
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
config.events['onRequestReferenceData'] = onRequestReferenceData;
// prevent switch the document from the viewing into the editing mode for anonymous users
config.events['onRequestEditRights'] = onRequestEditRights;
}
if (config.editorConfig.createUrl) {

View File

@ -329,7 +329,7 @@ app.post("/convert", function (req, res) { // define a handler for converting f
var fileUri = req.docManager.getDownloadUrl(fileName, true);
var fileExt = fileUtility.getFileExtension(fileName);
var fileType = fileUtility.getFileType(fileName);
var internalFileExt = 'ooxml';
var internalFileExt = req.docManager.getInternalExtension(fileType);
var response = res;
var writeResult = function (filename, step, error) {
@ -361,17 +361,16 @@ app.post("/convert", function (req, res) { // define a handler for converting f
}
try {
var responseData = documentService.getResponseUri(res.toString());
var result = responseData.percent;
var newFileUri = responseData.uri; // get the callback url
var newFileType = "." + responseData.fileType; // get the file type
var responseUri = documentService.getResponseUri(res.toString());
var result = responseUri.key;
var newFileUri = responseUri.value; // get the callback url
if (result != 100) { // if the status isn't 100
writeResult(fileName, result, null); // write the origin file to the result object
return;
}
var correctName = req.docManager.getCorrectName(fileUtility.getFileName(fileName, true) + newFileType); // get the file name with a new extension
var correctName = req.docManager.getCorrectName(fileUtility.getFileName(fileName, true) + internalFileExt); // get the file name with a new extension
const {status, data} = await urllib.request(newFileUri, {method: "GET"});
@ -626,7 +625,7 @@ app.post("/track", async function (req, res) { // define a handler for tracking
}
try {
var res = documentService.getResponseUri(data);
await callbackProcessSave(res.uri, body, fileName, userAddress, fileName);
await callbackProcessSave(res.value, body, fileName, userAddress, fileName);
return;
} catch (ex) {
console.log(ex);
@ -712,7 +711,7 @@ app.post("/track", async function (req, res) { // define a handler for tracking
}
try {
var res = documentService.getResponseUri(data);
await callbackProcessForceSave(res.uri, body, fileName, userAddress, false);
await callbackProcessForceSave(res.value, body, fileName, userAddress, false);
return;
} catch (ex) {
console.log(ex);
@ -998,8 +997,7 @@ app.get("/editor", function (req, res) { // define a handler for editing docume
plugins: JSON.stringify(plugins),
actionData: actionData,
fileKey: userid != "uid-0" ? JSON.stringify({ fileName: fileName, userAddress: req.docManager.curUserHostAddress()}) : null,
instanceId: userid != "uid-0" ? req.docManager.getInstanceId() : null,
protect: !user.deniedPermissions.includes("protect")
instanceId: userid != "uid-0" ? req.docManager.getInstanceId() : null
},
history: history,
historyData: historyData,
@ -1019,7 +1017,6 @@ app.get("/editor", function (req, res) { // define a handler for editing docume
directUrl: !userDirectUrl ? null : req.docManager.getServerUrl() + "/csv",
},
usersForMentions: user.id != "uid-0" ? users.getUsersForMentions(user.id) : null,
usersForProtect: user.id != "uid-0" ? users.getUsersForProtect(user.id) : null,
};
if (cfgSignatureEnable) {

View File

@ -22,10 +22,10 @@
"apiUrl": "web-apps/apps/api/documents/api.js",
"preloaderUrl": "web-apps/apps/api/documents/cache-scripts.html",
"exampleUrl": null,
"viewedDocs": [".djvu", ".oxps", ".pdf", ".xps"],
"editedDocs": [".csv", ".docm", ".docx", ".docxf", ".dotm", ".dotx", ".epub", ".fb2", ".html", ".odp", ".ods", ".odt", ".otp", ".ots", ".ott", ".potm", ".potx", ".ppsm", ".ppsx", ".pptm", ".pptx", ".rtf", ".txt", ".xlsm", ".xlsx", ".xltm", ".xltx"],
"viewedDocs": [".pdf", ".djvu", ".xps", ".oxps"],
"editedDocs": [".docx", ".xlsx", ".csv", ".pptx", ".txt", ".docxf"],
"fillDocs": [".docx", ".oform"],
"convertedDocs": [".doc", ".dot", ".dps", ".dpt", ".epub", ".et", ".ett", ".fb2", ".fodp", ".fods", ".fodt", ".htm", ".html", ".mht", ".mhtml", ".odp", ".ods", ".odt", ".otp", ".ots", ".ott", ".pot", ".pps", ".ppt", ".rtf", ".stw", ".sxc", ".sxi", ".sxw", ".wps", ".wpt", ".xls", ".xlsb", ".xlt", ".xml"],
"convertedDocs": [".docm", ".doc", ".dotx", ".dotm", ".dot", ".odt", ".fodt", ".ott", ".xlsm", ".xlsb", ".xls", ".xltx", ".xltm", ".xlt", ".ods", ".fods", ".ots", ".pptm", ".ppt", ".ppsx", ".ppsm", ".pps", ".potx", ".potm", ".pot", ".odp", ".fodp", ".otp", ".rtf", ".mht", ".html", ".htm", ".xml", ".epub", ".fb2"],
"storageFolder": "./files",
"storagePath": "/files",
"maxFileSize": 1073741824,
@ -54,8 +54,8 @@
"be": "Belarusian",
"bg": "Bulgarian",
"ca": "Catalan",
"zh": "Chinese",
"zh-TW": "Chinese (Taiwan)",
"zh" : "Chinese (People's Republic of China)",
"zh-TW" : "Chinese (Traditional, Taiwan)",
"cs": "Czech",
"da": "Danish",
"nl": "Dutch",
@ -69,16 +69,15 @@
"it": "Italian",
"ja": "Japanese",
"ko": "Korean",
"lo": "Lao",
"lv": "Latvian",
"lo": "Lao",
"ms": "Malay (Malaysia)",
"no": "Norwegian",
"nb": "Norwegian",
"pl": "Polish",
"pt": "Portuguese (Brazil)",
"pt-PT": "Portuguese (Portugal)",
"pt" : "Portuguese (Brazil)",
"pt-PT" : "Portuguese (Portugal)",
"ro": "Romanian",
"ru": "Russian",
"si": "Sinhala (Sri Lanka)",
"sk": "Slovak",
"sl": "Slovenian",
"es": "Spanish",

View File

@ -150,23 +150,20 @@ documentService.getResponseUri = function (json) {
var percent = parseInt(fileResult.percent); // get the conversion percentage
var uri = null;
var fileType = null;
if (isEndConvert) { // if the conversion is completed
if (!fileResult.fileUrl) // and the file url doesn't exist
throw { message: "FileUrl is null" }; // the file url is null
uri = fileResult.fileUrl; // otherwise, get the file url
fileType = fileResult.fileType; // get the file type
percent = 100;
} else { // if the conversion isn't completed
percent = percent >= 100 ? 99 : percent; // get the percentage value
}
return {
percent : percent,
uri : uri,
fileType : fileType
key: percent,
value: uri
};
};

View File

@ -61,7 +61,6 @@ var descr_user_0 = [
"Cant see anyones information",
"Can't rename files from the editor",
"Can't view chat",
"Can't protect file",
"View file without collaboration",
//"Cant submit forms"
];
@ -77,7 +76,7 @@ var users = [
remove: ["group-2"]
}, ["group-2", ""],
true, [], descr_user_2, false), // own and without group
new User("uid-3", "Hamish Mitchell", null,
new User("uid-3", "Hamish Mitchell", "mitchell@example.com",
"group-3", ["group-2"], {
view: ["group-3", "group-2"],
edit: ["group-2"],
@ -86,7 +85,7 @@ var users = [
false, ["copy", "download", "print"], descr_user_3, false), // other group only
new User("uid-0", null, null,
null, null, {}, [],
null, ["protect"], descr_user_0, false),
null, [], descr_user_0, false),
];
function User(id, name, email, group, reviewGroups, commentGroups, userInfoGroups, favorite, deniedPermissions, descriptions, templates) {
@ -119,30 +118,12 @@ users.getUser = function (id) {
return result ? result : this[0];
};
// get a list of users with their name and email for mentions
// get a list of users with their names and emails for mentions
users.getUsersForMentions = function (id) {
var result = [];
this.forEach(user => {
if (user.id != id && user.name != null && user.email != null) {
result.push({
email: user.email,
name: user.name
});
}
});
return result;
};
// get a list of users with their name, id and email for protect
users.getUsersForProtect = function (id) {
var result = [];
this.forEach(user => {
if (user.id != id && user.name != null) {
result.push({
email: user.email,
id: user.id,
name: user.name
});
result.push({ name: user.name, email: user.email });
}
});
return result;

View File

@ -26,19 +26,6 @@ const configServer = config.get('server');
const siteUrl = configServer.get("siteUrl"); // the path to the editors installation
const users = require("../users");
getCustomWopiParams = function (query) {
let tokenParams = "";
let actionParams = "";
const userid = query.userid; // user id
tokenParams += (userid ? "&userid=" + userid : "");
const lang = query.lang; // language
actionParams += (lang ? "&ui=" + lang : "");
return { "tokenParams": tokenParams, "actionParams": actionParams };
};
exports.registerRoutes = function(app) {
// define a handler for the default wopi page
@ -128,7 +115,7 @@ exports.registerRoutes = function(app) {
actionUrl: utils.getActionUrl(req.docManager.getServerUrl(true), req.docManager.curUserHostAddress(), action, req.params['id']),
token: "test",
tokenTtl: Date.now() + 1000 * 60 * 60 * 10,
params: getCustomWopiParams(req.query),
params: req.docManager.getCustomParams(),
});
} catch (ex) {

View File

@ -1,4 +0,0 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M4 5C4 3.89543 4.89543 3 6 3H15C16.1046 3 17 3.89543 17 5V7H16V6H5V18H16V17H17V19C17 20.1046 16.1046 21 15 21H6C4.89543 21 4 20.1046 4 19V5ZM12 4H9V5H12V4ZM11 19.5C11 19.7761 10.7761 20 10.5 20C10.2239 20 10 19.7761 10 19.5C10 19.2239 10.2239 19 10.5 19C10.7761 19 11 19.2239 11 19.5Z" fill="#444444"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M12 16H14L14.6464 15.3536L12.6464 13.3536L12 14V16ZM15.3536 14.6464L21 9V8H20V7H19L13.3536 12.6464L15.3536 14.6464Z" fill="#444444"/>
</svg>

Before

Width:  |  Height:  |  Size: 638 B

View File

@ -1,4 +0,0 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M4 5C4 3.89543 4.89543 3 6 3H15C16.1046 3 17 3.89543 17 5V7H16V6H5V18H16V17H17V19C17 20.1046 16.1046 21 15 21H6C4.89543 21 4 20.1046 4 19V5ZM12 4H9V5H12V4ZM11 19.5C11 19.7761 10.7761 20 10.5 20C10.2239 20 10 19.7761 10 19.5C10 19.2239 10.2239 19 10.5 19C10.7761 19 11 19.2239 11 19.5Z" fill="#444444"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M14 8C11.3252 8 8.89946 9.40288 7.10954 11.6815C6.96349 11.8682 6.96349 12.129 7.10954 12.3157C8.89946 14.5971 11.3252 16 14 16C16.6748 16 19.1005 14.5971 20.8905 12.3185C21.0365 12.1318 21.0365 11.871 20.8905 11.6843C19.1005 9.40288 16.6748 8 14 8ZM14.1955 14.9939C12.3863 15.1077 10.8923 13.6166 11.0061 11.8045C11.0995 10.3105 12.3105 9.09949 13.8045 9.00611C15.6137 8.89231 17.1077 10.3834 16.9939 12.1955C16.8976 13.6866 15.6866 14.8976 14.1955 14.9939ZM14.0641 12.998C13.4609 13.0359 12.9625 12.5392 13.0022 11.9359C13.0329 11.4373 13.4375 11.0346 13.9359 11.002C14.5391 10.9641 15.0375 11.4608 14.9978 12.0641C14.9653 12.5645 14.5607 12.9673 14.0641 12.998Z" fill="#444444"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -245,7 +245,7 @@ if (typeof jQuery != "undefined") {
window.open(url, "_blank");
jq('#hiddenFileName').val("");
jq.unblockUI();
document.location.reload(true);
document.location.reload();
});
jq(document).on("click", "#beginView:not(.disable)", function () {
@ -258,7 +258,7 @@ if (typeof jQuery != "undefined") {
window.open(url, "_blank");
jq('#hiddenFileName').val("");
jq.unblockUI();
document.location.reload(true);
document.location.reload();
});
jq(document).on("click", "#beginEmbedded:not(.disable)", function () {
@ -272,13 +272,13 @@ if (typeof jQuery != "undefined") {
});
jq(document).on("click", ".reload-page", function () {
setTimeout(function () { document.location.reload(true); }, 1000);
setTimeout(function () { document.location.reload(); }, 1000);
return true;
});
jq(document).on("mouseup", ".reload-page", function (event) {
if (event.which == 2) {
setTimeout(function () { document.location.reload(true); }, 1000);
setTimeout(function () { document.location.reload(); }, 1000);
}
return true;
});
@ -288,7 +288,7 @@ if (typeof jQuery != "undefined") {
jq("#embeddedView").remove();
jq.unblockUI();
if (mustReload) {
document.location.reload(true);
document.location.reload();
}
});
@ -303,7 +303,7 @@ if (typeof jQuery != "undefined") {
type: "delete",
url: requestAddress,
complete: function (data) {
document.location.reload(true);
document.location.reload();
}
});
});

View File

@ -18,7 +18,7 @@
.tableRow td:first-child{
flex-grow: 1;
max-width: 50%;
max-width: 100%;
}
.downloadContentCells{
@ -55,9 +55,6 @@
.tableHeaderCellRemove{
padding-left: 7px;
}
.tableRow td:first-child {
max-width: 45%;
}
}
@media (max-width: 986px) and (min-width: 890px){
.tableHeaderCellRemove{
@ -71,19 +68,18 @@
width: 24%;
padding-right: 0;
}
.tableRow td:first-child {
max-width: 40%;
}
}
@media (max-width: 890px) and (min-width: 769px){
.tableRow td:first-child{
max-width: 30%;
max-width: 50%;
}
.contentCells-shift{
padding-right: 26px;
}
.contentCells-wopi{
width: unset;
}
@media (max-width: 769px) and (min-width: 593px){
.tableRow td:first-child{
max-width: 40%;
}
}
@media (max-width: 769px) {
@ -92,12 +88,7 @@
border: none;
}
.tableRow td:last-child:after{
top: 65px;
width: 100%;
height: 1%;
}
.tableRow td:first-child{
max-width: 100%;
width: 95%;
}
}
@media (max-width: 593px){
@ -110,28 +101,3 @@
height: 1%;
}
}
@media (max-width: 769px) and (min-width: 320px){
.contentCells-icon {
width: 1%;
}
}
@media (max-width: 508px) {
.downloadContentCells {
margin-left: unset;
}
.contentCells-wopi {
width: 100%;
}
.contentCells-icon {
width: 1%;
}
.contentCells-shift {
padding-right: 30px;
padding-left: 3px;
}
.tableRow td:last-child:after{
top: 95px;
height: 1%;
width: 100%;
}
}

View File

@ -682,8 +682,3 @@
max-width:15%;
}
}
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.tableRow td:first-child{
max-width: none;
}
}

View File

@ -605,7 +605,6 @@ footer table tr td:first-child {
.contentCells-wopi a {
text-decoration: none;
margin-right: 8px;
}
.select-user {

View File

@ -20,8 +20,7 @@
"review": <%- editor.review %>,
"reviewGroups": <%- editor.reviewGroups %>,
"commentGroups": <%- editor.commentGroups %>,
"userInfoGroups": <%- editor.userInfoGroups %>,
"protect": <%- editor.protect %>
"userInfoGroups": <%- editor.userInfoGroups %>
},
"referenceData": {
"fileKey": <%- JSON.stringify(editor.fileKey) %>,

View File

@ -139,22 +139,9 @@
docEditor.setMailMergeRecipients(<%- JSON.stringify(dataMailMergeRecipients) %>); // insert recipient data for mail merge into the file
};
var onRequestUsers = function (event) {
if (event && event.data){
var c = event.data.c;
}
switch (c) {
case "protect":
var users = <%- JSON.stringify(usersForProtect) %>;
break;
default:
users = <%- JSON.stringify(usersForMentions) %>;
}
docEditor.setUsers({
"c": c,
"users": users,
var onRequestUsers = function () { // add mentions for not anonymous users
docEditor.setUsers({ // set a list of users to mention in the comments
"users": <%- JSON.stringify(usersForMentions) %>
});
};
@ -221,6 +208,7 @@
config.events = {
"onAppReady": onAppReady,
"onDocumentStateChange": onDocumentStateChange,
"onRequestEditRights": onRequestEditRights,
"onError": onError,
"onOutdatedVersion": onOutdatedVersion,
"onMakeActionLink": onMakeActionLink,
@ -231,7 +219,6 @@
};
if (<%- JSON.stringify(editor.userid) %> != null) {
config.events.onRequestEditRights = onRequestEditRights;
config.events.onRequestHistory = onRequestHistory;
config.events.onRequestHistoryData = onRequestHistoryData;
config.events.onRequestHistoryClose = onRequestHistoryClose;
@ -245,10 +232,7 @@
config.events.onRequestSaveAs = onRequestSaveAs;
}
try {
var oformParam = new URL(window.location).searchParams.get("oform");
} catch (e) {}
if (oformParam == "false") {
if (new URL(window.location).searchParams.get("oform") == "false") {
config.document.options = config.document.options || {};
config.document.options["oform"] = false;
}
@ -267,9 +251,6 @@
// get the editor sizes
var fixSize = function () {
if (config.type !== "mobile") {
return;
}
var wrapEl = document.getElementsByClassName("form");
if (wrapEl.length) {
wrapEl[0].style.height = screen.availHeight + "px";

View File

@ -307,7 +307,7 @@
<a href="mailto:sales@onlyoffice.com">Submit your request</a>
</td>
<td class="copy">
&copy; Ascensio Systems SIA 2023. All rights reserved.
&copy; Ascensio Systems SIA 2021. All rights reserved.
</td>
</tr>
</tbody>

View File

@ -50,8 +50,8 @@
<body>
<form id="office_form" name="office_form" target="office_frame" action="<%= actionUrl %><%= params.actionParams %>" method="post">
<input name="access_token" value="<%= token %><%= params.tokenParams %>" type="hidden" />
<form id="office_form" name="office_form" target="office_frame" action="<%= actionUrl %>" method="post">
<input name="access_token" value="<%= token %><%= params %>" type="hidden" />
<input name="access_token_ttl" value="<%= tokenTtl %>" type="hidden" />
</form>

View File

@ -244,7 +244,7 @@
<a href="mailto:sales@onlyoffice.com">Submit your request</a>
</td>
<td class="copy">
&copy; Ascensio Systems SIA 2023. All rights reserved.
&copy; Ascensio Systems SIA 2021. All rights reserved.
</td>
</tr>
</tbody>
@ -252,8 +252,7 @@
</div>
</footer>
<script type="text/javascript" src="javascripts/jquery-3.6.4.min.js"></script>
<script type="text/javascript" src="javascripts/jquery-migrate-3.4.1.min.js"></script>
<script type="text/javascript" src="javascripts/jquery-1.8.2.js"></script>
<script type="text/javascript" src="javascripts/jquery-ui.js"></script>
<script type="text/javascript" src="javascripts/jquery.blockUI.js"></script>
<script type="text/javascript" src="javascripts/jquery.iframe-transport.js"></script>

View File

@ -25,9 +25,5 @@ License: MIT
License File: jQuery.UI.license
JWT - JSON Web Token implementation (https://github.com/firebase/php-jwt/blob/master/LICENSE)
License: BSD-3-Clause
License: BSD
License File: jwt.license
PHP_CodeSniffer - PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent. (https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt)
License: BSD-3-Clause
License File: PHP_CodeSniffer.license

View File

@ -16,14 +16,14 @@ See the detailed guide to learn how to [install Document Server for Windows](htt
Download the [PHP example](https://api.onlyoffice.com/editors/demopreview) from our site.
To connect the editors to your website, specify the path to the editors installation and the path to the storage folder in the *config.json* file:
To connect the editors to your website, specify the path to the editors installation and the path to the storage folder in the *config.php* file:
```
"storagePath" = "";
"docServSiteUrl" = "https://documentserver/";
$GLOBALS['STORAGE_PATH'] = "";
$GLOBALS['DOC_SERV_SITE_URL'] = "https://documentserver/";
```
where the **documentserver** is the name of the server with the ONLYOFFICE Document Server installed and the **storagePath** is the path where files will be created and stored. You can set an absolute path. For example, *D:\\\\folder*. Please note that on Windows OS the double backslash must be used as a separator.
where the **documentserver** is the name of the server with the ONLYOFFICE Document Server installed and the **STORAGE_PATH** is the path where files will be created and stored. You can set an absolute path. For example, *D:\\\\folder*. Please note that on Windows OS the double backslash must be used as a separator.
If you want to experiment with the editor configuration, modify the [parameters](https://api.onlyoffice.com/editors/advanced) in the *doceditor.php* file.
@ -39,60 +39,60 @@ You can use any web server capable of running PHP code to run the example. We wi
1. **PHP Manager for IIS** configuration.
After PHP Manager for IIS installation is complete, launch the **IIS Manager:**
After PHP Manager for IIS installation is complete, launch the **IIS Manager:**
**Start** -> **Control Panel** -> **System and Security** -> **Administrative Tools** -> **Internet Information Services (IIS) Manager**
**Start** -> **Control Panel** -> **System and Security** -> **Administrative Tools** -> **Internet Information Services (IIS) Manager**
and find the **PHP Manager** feature in the **Features View** in IIS.
and find the **PHP Manager** feature in the **Features View** in IIS.
![manager](screenshots/manager.png)
![manager](screenshots/manager.png)
You need to register the installed PHP version in IIS using PHP Manager.
You need to register the installed PHP version in IIS using PHP Manager.
Double-click **PHP Manager** to open it, click the **Register new PHP version** task and specify the full path to the main PHP executable file location. For example: *C:\Program Files\PHP\php-cgi.exe*.
Double-click **PHP Manager** to open it, click the **Register new PHP version** task and specify the full path to the main PHP executable file location. For example: *C:\Program Files\PHP\php-cgi.exe*.
![php-version-1](screenshots/php-version-1.jpg)
![php-version-1](screenshots/php-version-1.jpg)
After clicking **OK**, the new **PHP version** will be registered with IIS and will become active.
After clicking **OK**, the new **PHP version** will be registered with IIS and will become active.
![php-version-2](screenshots/php-version-2.jpg)
![php-version-2](screenshots/php-version-2.jpg)
2. Configure IIS to handle PHP requests.
For IIS to host PHP applications, you must add handler mapping that tells IIS to pass all the PHP-specific requests to the PHP application framework by using the **FastCGI** protocol.
For IIS to host PHP applications, you must add handler mapping that tells IIS to pass all the PHP-specific requests to the PHP application framework by using the **FastCGI** protocol.
Double-click the **Handler Mappings** feature:
Double-click the **Handler Mappings** feature:
![handlerclick](screenshots/handlerclick.png)
![handlerclick](screenshots/handlerclick.png)
In the **Action** panel, click **Add Module Mapping**. In the **Add Module Mapping** dialog box, specify the configuration settings as follows:
In the **Action** panel, click **Add Module Mapping**. In the **Add Module Mapping** dialog box, specify the configuration settings as follows:
* **Request path**: *.php,
* **Module**: FastCgiModule,
* **Executable**: "C:\[Path to your PHP installation]\php-cgi.exe",
* **Name**: PHP via FastCGI.
* **Request path**: *.php,
* **Module**: FastCgiModule,
* **Executable**: "C:\[Path to your PHP installation]\php-cgi.exe",
* **Name**: PHP via FastCGI.
Click **OK**.
![handler-add](screenshots/handler-add.png)
Click **OK**.
![handler-add](screenshots/handler-add.png)
After IIS manager configuration is complete, everything is ready for running the PHP example.
After IIS manager configuration is complete, everything is ready for running the PHP example.
### Step 5. Run your website with the editors
1. Add your website in the IIS Manager.
On the **Connections** panel right-click the **Sites** node in the tree, then click **Add Website**.
On the **Connections** panel right-click the **Sites** node in the tree, then click **Add Website**.
![add](screenshots/add.png)
![add](screenshots/add.png)
2. In the **Add Website** dialog box, specify the name of the folder with the PHP project in the **Site name** box.
Specify the path to the folder with your project in the **Physical path** box.
Specify the path to the folder with your project in the **Physical path** box.
Specify the unique value used only for this website in the **Port** box.
Specify the unique value used only for this website in the **Port** box.
![php-add](screenshots/php-add.png)
![php-add](screenshots/php-add.png)
3. Browse your website with the IIS manager:
@ -122,13 +122,7 @@ See the detailed guide to learn how to [install Document Server for Linux](https
apt-get install -y apache2 php7.0 libapache2-mod-php7.0
```
2. Install **Composer**:
```
instructions should be here
```
3. Download the archive with the PHP example and unpack the archive:
2. Download the archive with the PHP example and unpack the archive:
```
cd /var/www/html
@ -142,45 +136,40 @@ See the detailed guide to learn how to [install Document Server for Linux](https
unzip PHP\ Example.zip
```
4. Change the current directory for the project directory:
3. Change the current directory for the project directory:
```
cd PHP\ Example/
```
5. Edit the *config.json* configuration file. Specify the name of your local server with the ONLYOFFICE Document Server installed.
4. Edit the *config.php* configuration file. Specify the name of your local server with the ONLYOFFICE Document Server installed.
```
nano config.json
nano config.php
```
Edit the following lines:
Edit the following lines:
```
"storagePath" = "";
"docServSiteUrl" = "https://documentserver/";
$GLOBALS['STORAGE_PATH'] = "";
$GLOBALS['DOC_SERV_SITE_URL'] = "https://documentserver/";
```
where the **documentserver** is the name of the server with the ONLYOFFICE Document Server installed and the **STORAGE_PATH** is the path where files will be created and stored. You can set an absolute path.
where the **documentserver** is the name of the server with the ONLYOFFICE Document Server installed and the **STORAGE_PATH** is the path where files will be created and stored. You can set an absolute path.
6. Run *composer install*:
```
php composer.phar install
```
7. Set permission for site:
5. Set permission for site:
```
chown -R www-data:www-data /var/www/html
```
8. Restart apache:
6. Restart apache:
```
service apache2 restart
```
9. See the result in your browser using the address:
7. See the result in your browser using the address:
```
http://localhost/PHP%20Example/

View File

@ -1,5 +1,6 @@
<?php
/**
*
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
@ -13,597 +14,52 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace OnlineEditorsExamplePhp;
use Exception;
use OnlineEditorsExamplePhp\Helpers\ConfigManager;
use OnlineEditorsExamplePhp\Helpers\ExampleUsers;
use OnlineEditorsExamplePhp\Helpers\JwtManager;
/**
* Check if the request is an AJAX request
*
* @return bool
*/
function isAjax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& mb_strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
require( dirname(__FILE__) . '/config.php' );
// check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
/**
* Get the http origin
*
* @return string
*/
function getHttpOrigin()
{
$origin = '';
if (!empty($_SERVER['HTTP_ORIGIN'])) {
$origin = $_SERVER['HTTP_ORIGIN'];
}
return $origin;
// get the http origin
function get_http_origin() {
$origin = '';
if ( ! empty ( $_SERVER[ 'HTTP_ORIGIN' ] ) )
$origin = $_SERVER[ 'HTTP_ORIGIN' ];
return $origin;
}
/**
* Set headers that prevent caching in all the browsers
*
* @return void
*/
function nocacheHeaders()
{
$headers = [
'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
'Pragma' => 'no-cache',
];
$headers['Last-Modified'] = false;
// set headers that prevent caching in all the browsers
function nocache_headers() {
$headers = array(
'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
'Pragma' => 'no-cache',
);
$headers['Last-Modified'] = false;
unset($headers['Last-Modified']);
// In PHP 5.3+, make sure we are not sending a Last-Modified header.
if (function_exists('header_remove')) {
@header_remove('Last-Modified');
} else {
// In PHP 5.2, send an empty Last-Modified header, but only as a
// last resort to override a header already sent. #WP23021
foreach (headers_list() as $header) {
if (0 === mb_stripos($header, 'Last-Modified')) {
$headers['Last-Modified'] = '';
break;
}
}
}
unset( $headers['Last-Modified'] );
foreach ($headers as $name => $field_value) {
@header("{$name}: {$field_value}");
}
// In PHP 5.3+, make sure we are not sending a Last-Modified header.
if ( function_exists( 'header_remove' ) ) {
@header_remove( 'Last-Modified' );
} else {
// In PHP 5.2, send an empty Last-Modified header, but only as a
// last resort to override a header already sent. #WP23021
foreach ( headers_list() as $header ) {
if ( 0 === stripos( $header, 'Last-Modified' ) ) {
$headers['Last-Modified'] = '';
break;
}
}
}
foreach( $headers as $name => $field_value )
@header("{$name}: {$field_value}");
}
/**
* Save copy as...
*
* @return array
*/
function saveas()
{
try {
$post = json_decode(file_get_contents('php://input'), true);
$fileurl = $post["url"];
$title = $post["title"];
$extension = mb_strtolower(pathinfo($title, PATHINFO_EXTENSION));
$configManager = new ConfigManager();
$allexts = array_merge(
$configManager->getConfig("docServConvert"),
$configManager->getConfig("docServEdited"),
$configManager->getConfig("docServViewd"),
$configManager->getConfig("docServFillforms")
);
$filename = GetCorrectName($title);
if (!in_array("." . $extension, $allexts)) {
$result["error"] = "File type is not supported";
return $result;
}
$headers = get_headers($fileurl, 1);
$content_length = $headers["Content-Length"];
$data = file_get_contents(str_replace(" ", "%20", $fileurl));
if ($data === false || $content_length <= 0 || $content_length >
$configManager->getConfig("fileSizeMax")) {
$result["error"] = "File size is incorrect";
return $result;
}
file_put_contents(getStoragePath($filename), $data, LOCK_EX); // write data to the new file
$userList = new ExampleUsers();
$user = $userList->getUser($_GET["user"]);
createMeta($filename, $user->id, $user->name); // and create meta data for this file
$result["file"] = $filename;
return $result;
} catch (Exception $e) {
sendlog("SaveAs: ".$e->getMessage(), "webedior-ajax.log");
$result["error"] = "error: " . 1 . "message:" . $e->getMessage();
return $result;
}
}
/**
* Uploading a file
*
* @return array
*/
function upload()
{
$configManager = new ConfigManager();
if ($_FILES['files']['error'] > 0) {
$result["error"] = 'Error ' . json_encode($_FILES['files']['error']);
return $result;
}
// get the temporary name with which the received file was saved on the server
$tmp = $_FILES['files']['tmp_name'];
// if the temporary name doesn't exist, then an error occurs
if (empty($tmp)) {
$result["error"] = 'No file sent';
return $result;
}
// check if the file was uploaded using HTTP POST
if (is_uploaded_file($tmp)) {
$filesize = $_FILES['files']['size']; // get the file size
$ext = mb_strtolower('.' . pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION)); // get file extension
// check if the file size is correct (it should be less than the max file size, but greater than 0)
if ($filesize <= 0 || $filesize > $configManager->getConfig("fileSizeMax")) {
$result["error"] = 'File size is incorrect'; // if not, then an error occurs
return $result;
}
// check if the file extension is supported by the editor
if (!in_array($ext, getFileExts())) {
$result["error"] = 'File type is not supported'; // if not, then an error occurs
return $result;
}
// get the correct file name with an index if the file with such a name already exists
$filename = GetCorrectName($_FILES['files']['name']);
if (!move_uploaded_file($tmp, getStoragePath($filename))) {
$result["error"] = 'Upload failed'; // file upload error
return $result;
}
$userList = new ExampleUsers();
$user = $userList->getUser($_GET["user"]);
createMeta($filename, $user->id, $user->name); // create file meta data
} else {
$result["error"] = 'Upload failed';
return $result;
}
$result["filename"] = $filename;
$result["documentType"] = getDocumentType($filename);
return $result;
}
/**
* Tracking file changes
*
* @return array|int
*/
function track()
{
sendlog("Track START", "webedior-ajax.log");
sendlog(" _GET params: " . serialize($_GET), "webedior-ajax.log");
$result["error"] = 0;
// get the body of the post request and check if it is correct
$data = readBody();
if (!empty($data->error)) {
return $data;
}
global $_trackerStatus;
$status = $_trackerStatus[$data->status]; // get status from the request body
$userAddress = $_GET["userAddress"];
$fileName = basename($_GET["fileName"]);
sendlog(" CommandRequest status: " . $data->status, "webedior-ajax.log");
switch ($status) {
case "Editing": // status == 1
if ($data->actions && $data->actions[0]->type == 0) { // finished edit
$user = $data->actions[0]->userid; // the user who finished editing
if (array_search($user, $data->users) === false) {
// create a command request with the forcasave method
$commandRequest = commandRequest("forcesave", $data->key);
sendlog(" CommandRequest forcesave: " . serialize($commandRequest), "webedior-ajax.log");
}
}
break;
case "MustSave": // status == 2
case "Corrupted": // status == 3
$result = processSave($data, $fileName, $userAddress);
break;
case "MustForceSave": // status == 6
case "CorruptedForceSave": // status == 7
$result = processForceSave($data, $fileName, $userAddress);
break;
}
sendlog("Track RESULT: " . serialize($result), "webedior-ajax.log");
return $result;
}
/**
* Converting a file
*
* @return array
*/
function convert()
{
$post = json_decode(file_get_contents('php://input'), true);
$fileName = basename($post["filename"]);
$filePass = $post["filePass"];
$lang = $_COOKIE["ulang"];
$extension = mb_strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
$internalExtension = "ooxml";
$configManager = new ConfigManager();
// check if the file with such an extension can be converted
if (in_array("." . $extension, $configManager->getConfig("docServConvert")) &&
$internalExtension != "") {
$fileUri = $post["fileUri"];
if ($fileUri == null || $fileUri == "") {
$fileUri = serverPath(true) . '/'
. "webeditor-ajax.php"
. "?type=download"
. "&fileName=" . urlencode($fileName)
. "&userAddress=" . getClientIp();
}
$key = getDocEditorKey($fileName);
try {
// convert file and get the percentage of the conversion completion
$convertedData = getConvertedData(
$fileUri,
$extension,
$internalExtension,
$key,
true,
$newFileUri,
$filePass,
$lang
);
} catch (Exception $e) {
$result["error"] = "error: " . $e->getMessage();
return $result;
}
if ($convertedData["percent"] != 100) {
$result["step"] = $convertedData["percent"];
$result["filename"] = $fileName;
$result["fileUri"] = $fileUri;
return $result;
}
// get file name without extension
$baseNameWithoutExt = mb_substr($fileName, 0, mb_strlen($fileName) - mb_strlen($extension) - 1);
// get the correct file name with an index if the file with such a name already exists
$newFileName = GetCorrectName($baseNameWithoutExt . "." . $convertedData["fileType"]);
if (($data = file_get_contents(str_replace(" ", "%20", $newFileUri))) === false) {
$result["error"] = 'Bad Request';
return $result;
}
file_put_contents(getStoragePath($newFileName), $data, LOCK_EX); // write data to the new file
$userList = new ExampleUsers();
$user = $userList->getUser($_GET["user"]);
createMeta($newFileName, $user->id, $user->name); // and create meta data for this file
// delete the original file and its history
$stPath = getStoragePath($fileName);
unlink($stPath);
delTree(getHistoryDir($stPath));
$fileName = $newFileName;
}
$result["filename"] = $fileName;
return $result;
}
/**
* Removing a file
*
* @return array|void
*/
function delete()
{
try {
$fileName = basename($_GET["fileName"]);
$filePath = getStoragePath($fileName);
unlink($filePath); // delete a file
delTree(getHistoryDir($filePath)); // delete all the elements from the history directory
} catch (Exception $e) {
sendlog("Deletion ".$e->getMessage(), "webedior-ajax.log");
$result["error"] = "error: " . $e->getMessage();
return $result;
}
}
/**
* Get file information
*
* @return array
*/
function files()
{
try {
@header("Content-Type", "application/json");
$fileId = $_GET["fileId"];
$result = getFileInfo($fileId);
return $result;
} catch (Exception $e) {
sendlog("Files ".$e->getMessage(), "webedior-ajax.log");
$result["error"] = "error: " . $e->getMessage();
return $result;
}
}
/**
* Download assets
*
* @return void
*/
function assets()
{
$fileName = basename($_GET["name"]);
$filePath = dirname(__FILE__) .
DIRECTORY_SEPARATOR . "assets" . DIRECTORY_SEPARATOR . "sample" . DIRECTORY_SEPARATOR . $fileName;
downloadFile($filePath);
}
/**
* Download a csv file
*
* @return void
*/
function csv()
{
$fileName = "csv.csv";
$filePath = dirname(__FILE__) .
DIRECTORY_SEPARATOR . "assets" . DIRECTORY_SEPARATOR . "sample" . DIRECTORY_SEPARATOR . $fileName;
downloadFile($filePath);
}
/**
* Download a file from history
*
* @return array|void
*/
function historyDownload()
{
try {
$fileName = basename($_GET["fileName"]); // get the file name
$userAddress = $_GET["userAddress"];
$ver = $_GET["ver"];
$file = $_GET["file"];
$jwtManager = new JwtManager();
if ($jwtManager->isJwtEnabled()) {
$configManager = new ConfigManager();
$jwtHeader = $configManager->getConfig("docServJwtHeader") == "" ?
"Authorization" : $configManager->getConfig("docServJwtHeader");
if (!empty(apache_request_headers()[$jwtHeader])) {
$token = $jwtManager->jwtDecode(mb_substr(
apache_request_headers()[$jwtHeader],
mb_strlen("Bearer ")
));
if (empty($token)) {
http_response_code(403);
die("Invalid JWT signature");
}
} else {
http_response_code(403);
die("Invalid JWT signature");
}
}
$histDir = getHistoryDir(getStoragePath($fileName, $userAddress));
$filePath = getVersionDir($histDir, $ver) . DIRECTORY_SEPARATOR . $file;
;
downloadFile($filePath); // download this file
} catch (Exception $e) {
sendlog("Download ".$e->getMessage(), "webedior-ajax.log");
$result["error"] = "error: File not found";
return $result;
}
}
/**
* Download a file
*
* @return array|void
*/
function download()
{
try {
$configManager = new ConfigManager();
$fileName = realpath($configManager->getConfig("storagePath"))
=== $configManager->getConfig("storagePath") ?
$_GET["fileName"] : basename($_GET["fileName"]); // get the file name
$userAddress = $_GET["userAddress"];
$isEmbedded = $_GET["&dmode"];
$jwtManager = new JwtManager();
if ($jwtManager->isJwtEnabled() && $isEmbedded == null && $userAddress) {
$jwtHeader = $configManager->getConfig("docServJwtHeader") == "" ?
"Authorization" : $configManager->getConfig("docServJwtHeader");
if (!empty(apache_request_headers()[$jwtHeader])) {
$token = $jwtManager->jwtDecode(mb_substr(
apache_request_headers()[$jwtHeader],
mb_strlen("Bearer ")
));
if (empty($token)) {
http_response_code(403);
die("Invalid JWT signature");
}
}
}
$filePath = getForcesavePath($fileName, $userAddress, false); // get the path to the forcesaved file version
if ($filePath == "") {
$filePath = getStoragePath($fileName, $userAddress); // get file from the storage directory
}
downloadFile($filePath); // download this file
} catch (Exception $e) {
sendlog("Download ".$e->getMessage(), "webedior-ajax.log");
$result["error"] = "error: File not found";
return $result;
}
}
/**
* Download the specified file
*
* @param string $filePath
*
* @return void
*/
function downloadFile($filePath)
{
if (file_exists($filePath)) {
if (ob_get_level()) {
ob_end_clean();
}
// write headers to the response object
@header('Content-Length: ' . filesize($filePath));
@header('Content-Disposition: attachment; filename*=UTF-8\'\'' . urldecode(basename($filePath)));
@header('Content-Type: ' . mime_content_type($filePath));
if ($fd = fopen($filePath, 'rb')) {
while (!feof($fd)) {
echo fread($fd, 1024);
}
fclose($fd);
}
exit;
}
}
/**
* Delete all the elements from the directory
*
* @param string $dir
*
* @return void|bool
*/
function delTree($dir)
{
if (!file_exists($dir) || !is_dir($dir)) {
return;
}
$files = array_diff(scandir($dir), ['.', '..']);
foreach ($files as $file) {
(is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}
/**
* Rename file
*
* @return array
*/
function renamefile()
{
$post = json_decode(file_get_contents('php://input'), true);
$newfilename = $post["newfilename"];
$newfilenameArr = explode('.', $newfilename);
$curExt = mb_strtolower(array_pop($newfilenameArr));
$origExt = $post["ext"];
if ($origExt !== $curExt) {
$newfilename .= '.' . $origExt;
}
$dockey = $post["dockey"];
$meta = ["title" => $newfilename];
$commandRequest = commandRequest("meta", $dockey, $meta); // create a command request with the forcasave method
sendlog(" CommandRequest rename: " . serialize($commandRequest), "webedior-ajax.log");
return ["result" => $commandRequest];
}
/**
* Reference data
*
* @return array
*/
function reference()
{
$post = json_decode(file_get_contents('php://input'), true);
@header("Content-Type: application/json");
$referenceData = $post["referenceData"] ?? null;
$jwtManager = new JwtManager();
if ($referenceData) {
$instanceId = $referenceData["instanceId"];
if ($instanceId == serverPath()) {
$fileKey = json_decode(str_replace("'", "\"", $referenceData["fileKey"]));
$userAddress = $fileKey->userAddress;
if ($userAddress == getCurUserHostAddress()) {
$fileName = $fileKey->fileName;
}
}
}
if (!isset($filename) && isset($post["path"])) {
$path = basename($post["path"]);
if (file_exists(getStoragePath($path))) {
$fileName = $path;
}
}
if (!isset($fileName)) {
return ["error" => "File is not found"];
}
$data = [
"fileType" => getInternalExtension($fileName),
"url" => getDownloadUrl($fileName),
"directUrl" => $post["directUrl"] ? getDownloadUrl($fileName) : getDownloadUrl($fileName, false),
"referenceData" => [
"fileKey" => json_encode([
"fileName" => $fileName,
"userAddress" => getCurUserHostAddress()
]),
"instanceId" => serverPath(),
],
"path" => $fileName
];
if ($jwtManager->isJwtEnabled()) {
$data["token"] = $jwtManager->jwtEncode($data);
}
return $data;
}
?>

View File

@ -0,0 +1,441 @@
<?php
/**
*
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
require_once( dirname(__FILE__) . '/config.php' );
require_once( dirname(__FILE__) . '/functions.php' );
// put log files into the log folder
function sendlog($msg, $logFileName) {
$logsFolder = "logs/";
if (!file_exists($logsFolder)) { // if log folder does't exist, make it
mkdir($logsFolder);
}
file_put_contents($logsFolder . $logFileName, $msg . PHP_EOL, FILE_APPEND);
}
// create new uuid
function guid() {
if (function_exists('com_create_guid')) {
return com_create_guid();
} else {
mt_srand((double)microtime()*10000); // optional for php 4.2.0 and up
$charid = strtoupper(md5(uniqid(rand(), true)));
$hyphen = chr(45); // "-"
$uuid = chr(123) // "{"
.substr($charid, 0, 8).$hyphen
.substr($charid, 8, 4).$hyphen
.substr($charid,12, 4).$hyphen
.substr($charid,16, 4).$hyphen
.substr($charid,20,12)
.chr(125); // "}"
return $uuid;
}
}
if(!function_exists('mime_content_type')) {
function mime_content_type($filename) {
$mime_types = array(
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
);
// check if the file extension is in the mime type array
$ext = strtolower(array_pop(explode('.',$filename)));
if (array_key_exists($ext, $mime_types)) {
return $mime_types[$ext]; // get the mime type of this extension
}
// or get the mime type from the file information
elseif (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);
return $mimetype;
}
else {
return 'application/octet-stream';
}
}
}
// get ip address
function getClientIp() {
$ipaddress =
getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR')?:
'Storage';
$ipaddress = preg_replace("/[^0-9a-zA-Z.=]/", "_", $ipaddress);
return $ipaddress;
}
// get server url
function serverPath($forDocumentServer = NULL) {
return $forDocumentServer && isset($GLOBALS['EXAMPLE_URL']) && $GLOBALS['EXAMPLE_URL'] != ""
? $GLOBALS['EXAMPLE_URL']
: (getScheme() . '://' . $_SERVER['HTTP_HOST']);
}
// get current user host address
function getCurUserHostAddress($userAddress = NULL) {
if ($GLOBALS['ALONE']) {
if (empty($GLOBALS['STORAGE_PATH'])) {
return "Storage";
} else {
return "";
}
}
if (is_null($userAddress)) {$userAddress = getClientIp();}
return preg_replace("[^0-9a-zA-Z.=]", '_', $userAddress);
}
// get an internal file extension
function getInternalExtension($filename) {
$ext = strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION));
if (in_array($ext, $GLOBALS['ExtsDocument'])) return ".docx"; // .docx for text document extensions
if (in_array($ext, $GLOBALS['ExtsSpreadsheet'])) return ".xlsx"; // .xlsx for spreadsheet extensions
if (in_array($ext, $GLOBALS['ExtsPresentation'])) return ".pptx"; // .pptx for presentation extensions
return "";
}
// get image url for templates
function getTemplateImageUrl($filename) {
$ext = strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION));
$path = serverPath(true) . "/css/images/";
if (in_array($ext, $GLOBALS['ExtsDocument'])) return $path . "file_docx.svg"; // for text document extensions
if (in_array($ext, $GLOBALS['ExtsSpreadsheet'])) return $path . "file_xlsx.svg"; // for spreadsheet extensions
if (in_array($ext, $GLOBALS['ExtsPresentation'])) return $path . "file_pptx.svg"; // for presentation extensions
return $path . "file_docx.svg";
}
// get the document type
function getDocumentType($filename) {
$ext = strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION));
if (in_array($ext, $GLOBALS['ExtsDocument'])) return "word"; // word for text document extensions
if (in_array($ext, $GLOBALS['ExtsSpreadsheet'])) return "cell"; // cell for spreadsheet extensions
if (in_array($ext, $GLOBALS['ExtsPresentation'])) return "slide"; // slide for presentation extensions
return "word";
}
// get the protocol
function getScheme() {
return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
}
// get the storage path of the given file
function getStoragePath($fileName, $userAddress = NULL) {
$storagePath = trim(str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $GLOBALS['STORAGE_PATH']), DIRECTORY_SEPARATOR);
if (!empty($storagePath) && !file_exists($storagePath) && !is_dir($storagePath)) {
mkdir($storagePath);
}
if (realpath($storagePath) === $storagePath) {
$directory = $storagePath;
} else {
$directory = __DIR__ . DIRECTORY_SEPARATOR . $storagePath;
}
if ($storagePath != "")
{
$directory = $directory . DIRECTORY_SEPARATOR;
// if the file directory doesn't exist, make it
if (!file_exists($directory) && !is_dir($directory)) {
mkdir($directory);
}
}
if (realpath($storagePath) !== $storagePath) {
$directory = $directory . getCurUserHostAddress($userAddress) . DIRECTORY_SEPARATOR;
}
if (!file_exists($directory) && !is_dir($directory)) {
mkdir($directory);
}
sendlog("getStoragePath result: " . $directory . basename($fileName), "common.log");
return realpath($storagePath) === $storagePath ? $directory . $fileName : $directory . basename($fileName);
}
// get the path to the forcesaved file version
function getForcesavePath($fileName, $userAddress, $create) {
$storagePath = trim(str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $GLOBALS['STORAGE_PATH']), DIRECTORY_SEPARATOR);
// create the directory to this file version
if (realpath($storagePath) === $storagePath) {
$directory = $storagePath . DIRECTORY_SEPARATOR;
} else {
$directory = __DIR__ . DIRECTORY_SEPARATOR . $storagePath . getCurUserHostAddress($userAddress) . DIRECTORY_SEPARATOR;
}
if (!is_dir($directory)) return "";
// create the directory to the history of this file version
$directory = $directory . $fileName . "-hist" . DIRECTORY_SEPARATOR;
if (!$create && !is_dir($directory)) return "";
if (!file_exists($directory) && !is_dir($directory)) {
mkdir($directory);
}
$directory = $directory . $fileName;
if (!$create && !file_exists($directory)) return "";
return $directory;
}
// get the path to the file history
function getHistoryDir($storagePath) {
$directory = $storagePath . "-hist";
// if the history directory doesn't exist, make it
if (!file_exists($directory) && !is_dir($directory)) {
mkdir($directory);
}
return $directory;
}
// get the path to the specified file version
function getVersionDir($histDir, $version) {
return $histDir . DIRECTORY_SEPARATOR . $version;
}
// get a number of the last file version from the history directory
function getFileVersion($histDir) {
if (!file_exists($histDir) || !is_dir($histDir)) return 1; // check if the history directory exists
$cdir = scandir($histDir);
$ver = 1;
foreach($cdir as $key => $fileName) {
if (!in_array($fileName,array(".", ".."))) {
if (is_dir($histDir . DIRECTORY_SEPARATOR . $fileName)) {
$ver++;
}
}
}
return $ver;
}
// get all the stored files from the folder
function getStoredFiles() {
$storagePath = trim(str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $GLOBALS['STORAGE_PATH']), DIRECTORY_SEPARATOR);
if (!empty($storagePath) && !file_exists($storagePath) && !is_dir($storagePath)) {
mkdir($storagePath);
}
if (realpath($storagePath) === $storagePath) {
$directory = $storagePath;
} else {
$directory = __DIR__ . DIRECTORY_SEPARATOR . $storagePath;
}
// get the storage path and check if it exists
$result = array();
if ($storagePath != "")
{
$directory = $directory . DIRECTORY_SEPARATOR;
if (!file_exists($directory) && !is_dir($directory)) {
return $result;
}
}
if (realpath($storagePath) !== $storagePath) {
$directory = $directory . getCurUserHostAddress() . DIRECTORY_SEPARATOR;
}
if (!file_exists($directory) && !is_dir($directory)) {
return $result;
}
$cdir = scandir($directory); // get all the files and folders from the directory
$result = array();
foreach($cdir as $key => $fileName) { // run through all the file and folder names
if (!in_array($fileName,array(".", ".."))) {
if (!is_dir($directory . DIRECTORY_SEPARATOR . $fileName)) { // if an element isn't a directory
$ext = strtolower('.' . pathinfo($fileName, PATHINFO_EXTENSION));
$dat = filemtime($directory . DIRECTORY_SEPARATOR . $fileName); // get the time of element modification
$result[$dat] = (object) array( // and write the file to the result
"name" => $fileName,
"documentType" => getDocumentType($fileName),
"canEdit" => in_array($ext, $GLOBALS['DOC_SERV_EDITED']),
"isFillFormDoc" => in_array($ext, $GLOBALS['DOC_SERV_FILLFORMS'])
);
}
}
}
ksort($result); // sort files by the modification date
return array_reverse($result);
}
// get the virtual path
function getVirtualPath($forDocumentServer) {
$storagePath = trim(str_replace(array('/','\\'), '/', $GLOBALS['STORAGE_PATH']), '/');
$storagePath = $storagePath != "" ? $storagePath . '/' : "";
if (realpath($storagePath) === $storagePath) {
$virtPath = serverPath($forDocumentServer) . '/' . $storagePath . '/';
} else {
$virtPath = serverPath($forDocumentServer) . '/' . $storagePath . getCurUserHostAddress() . '/';
}
sendlog("getVirtualPath virtPath: " . $virtPath, "common.log");
return $virtPath;
}
// get a file with meta information
function createMeta($fileName, $uid, $uname, $userAddress = NULL) {
$histDir = getHistoryDir(getStoragePath($fileName, $userAddress)); // get the history directory
// turn the file information into the json format
$json = [
"created" => date("Y-m-d H:i:s"),
"uid" => $uid,
"name" => $uname,
];
// write the encoded file information to the createdInfo.json file
file_put_contents($histDir . DIRECTORY_SEPARATOR . "createdInfo.json", json_encode($json, JSON_PRETTY_PRINT));
}
// get the file url
function FileUri($file_name, $forDocumentServer = NULL) {
$uri = getVirtualPath($forDocumentServer) . rawurlencode($file_name); // add encoded file name to the virtual path
return $uri;
}
// get file information
function getFileInfo($fileId){
$storedFiles = getStoredFiles();
$result = array();
$resultID = array();
// run through all the stored files
foreach ($storedFiles as $key => $value){
$result[$key] = (object) array( // write all the parameters to the map
"version" => getFileVersion(getHistoryDir(getStoragePath($value->name))),
"id" => getDocEditorKey($value->name),
"contentLength" => number_format( filesize(getStoragePath($value->name)) / 1024, 2 )." KB",
"pureContentLength" => filesize(getStoragePath($value->name)),
"title" => $value->name,
"updated" => date( DATE_ATOM, filemtime(getStoragePath($value->name))),
);
// get file information by its id
if ($fileId != null){
if ($fileId == getDocEditorKey($value->name)){
$resultID[count($resultID)] = $result[$key];
}
}
}
if ($fileId != null){
if (count($resultID) != 0) return $resultID;
else return "File not found";
}
else {
return $result;
}
}
// get all the supported file extensions
function getFileExts() {
return array_merge($GLOBALS['DOC_SERV_VIEWD'], $GLOBALS['DOC_SERV_EDITED'], $GLOBALS['DOC_SERV_CONVERT'], $GLOBALS['DOC_SERV_FILLFORMS']);
}
// get the correct file name if such a name already exists
function GetCorrectName($fileName, $userAddress = NULL) {
$path_parts = pathinfo($fileName);
$ext = strtolower($path_parts['extension']);
$name = $path_parts['basename'];
$baseNameWithoutExt = substr($name, 0, strlen($name) - strlen($ext) - 1); // get file name from the basename without extension
$name = $baseNameWithoutExt . "." . $ext;
for ($i = 1; file_exists(getStoragePath($name, $userAddress)); $i++) // if a file with such a name already exists in this directory
{
$name = $baseNameWithoutExt . " (" . $i . ")." . $ext; // add an index after its base name
}
return $name;
}
// get document key
function getDocEditorKey($fileName) {
$key = getCurUserHostAddress() . FileUri($fileName); // get document key by adding local file url to the current user host address
$stat = filemtime(getStoragePath($fileName)); // get creation time
$key = $key . $stat; // and add it to the document key
return GenerateRevisionId($key); // generate the document key value
}
?>

View File

@ -1,26 +0,0 @@
{
"require-dev": {
"squizlabs/php_codesniffer": "*",
"ext-mbstring": "*"
},
"scripts": {
"code-sniffer": [
"./vendor/bin/phpcs --config-set default_standard ruleset.xml",
"./vendor/bin/phpcs --config-set colors 1"
],
"post-install-cmd": [
"@code-sniffer"
],
"post-update-cmd": [
"@code-sniffer"
]
},
"autoload-dev": {
"psr-4": {
"OnlineEditorsExamplePhp\\" : "",
"OnlineEditorsExamplePhp\\Helpers\\" : "helpers/",
"OnlineEditorsExamplePhp\\Views\\" : "views/",
"Firebase\\JWT\\" : "lib/jwt/"
}
}
}

View File

@ -1,75 +0,0 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "0ae1576e556ebadd2933ecd2483a4b26",
"packages": [],
"packages-dev": [
{
"name": "squizlabs/php_codesniffer",
"version": "3.7.1",
"source": {
"type": "git",
"url": "https://github.com/squizlabs/PHP_CodeSniffer.git",
"reference": "1359e176e9307e906dc3d890bcc9603ff6d90619"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/1359e176e9307e906dc3d890bcc9603ff6d90619",
"reference": "1359e176e9307e906dc3d890bcc9603ff6d90619",
"shasum": ""
},
"require": {
"ext-simplexml": "*",
"ext-tokenizer": "*",
"ext-xmlwriter": "*",
"php": ">=5.4.0"
},
"require-dev": {
"phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0"
},
"bin": [
"bin/phpcs",
"bin/phpcbf"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.x-dev"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Greg Sherwood",
"role": "lead"
}
],
"description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.",
"homepage": "https://github.com/squizlabs/PHP_CodeSniffer",
"keywords": [
"phpcs",
"standards"
],
"support": {
"issues": "https://github.com/squizlabs/PHP_CodeSniffer/issues",
"source": "https://github.com/squizlabs/PHP_CodeSniffer",
"wiki": "https://github.com/squizlabs/PHP_CodeSniffer/wiki"
},
"time": "2022-06-18T07:21:10+00:00"
}
],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform-dev": [],
"plugin-api-version": "2.2.0"
}

View File

@ -1,88 +0,0 @@
{
"version": "1.5.1",
"fileSizeMax": 5242880,
"storagePath": "",
"alone": false,
"docServFillforms": [".docx", ".oform"],
"docServViewd": [".djvu", ".oxps", ".pdf", ".xps"],
"docServEdited": [".csv", ".docm", ".docx", ".docxf", ".dotm", ".dotx", ".epub",
".fb2", ".html", ".odp", ".ods", ".odt", ".otp", ".ots", ".ott", ".potm", ".potx",
".ppsm", ".ppsx", ".pptm", ".pptx", ".rtf", ".txt", ".xlsm", ".xlsx", ".xltm", ".xltx"],
"docServConvert": [".doc", ".dot", ".dps", ".dpt", ".epub",
".et", ".ett", ".fb2", ".fodp", ".fods", ".fodt", ".htm", ".html",
".mht", ".mhtml", ".odp", ".ods", ".odt", ".otp", ".ots", ".ott", ".pot",
".pps", ".ppt", ".rtf", ".stw", ".sxc", ".sxi", ".sxw", ".wps", ".wpt", ".xls", ".xlsb", ".xlt", ".xml"],
"docServTimeout": "120000",
"docServSiteUrl": "https://documentserver/",
"docServConverterUrl": "ConvertService.ashx",
"docServApiUrl": "web-apps/apps/api/documents/api.js",
"docServPreloaderUrl": "web-apps/apps/api/documents/cache-scripts.html",
"docServCommandUrl": "coauthoring/CommandService.ashx",
"docServJwtSecret": "",
"docServJwtHeader": "Authorization",
"docServJwtUseForRequest": true,
"docServVerifyPeerOff": true,
"exampleUrl": "",
"mobileRegex": "android|avantgo|playbook|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino",
"extsSpreadsheet": [".xls", ".xlsx", ".xlsm", ".xlsb",
".xlt", ".xltx", ".xltm",
".ods", ".fods", ".ots", ".csv"],
"extsPresentation": [".pps", ".ppsx", ".ppsm",
".ppt", ".pptx", ".pptm",
".pot", ".potx", ".potm",
".odp", ".fodp", ".otp"],
"extsDocument": [".doc", ".docx", ".docm",
".dot", ".dotx", ".dotm",
".odt", ".fodt", ".ott", ".rtf", ".txt",
".html", ".htm", ".mht", ".xml",
".pdf", ".djvu", ".fb2", ".epub", ".xps", ".oxps", ".oform"],
"languages": {
"en": "English",
"hy": "Armenian",
"az": "Azerbaijani",
"eu": "Basque",
"be": "Belarusian",
"bg": "Bulgarian",
"ca": "Catalan",
"zh": "Chinese",
"zh-TW": "Chinese (Taiwan)",
"cs": "Czech",
"da": "Danish",
"nl": "Dutch",
"fi": "Finnish",
"fr": "French",
"gl": "Galego",
"de": "German",
"el": "Greek",
"hu": "Hungarian",
"id": "Indonesian",
"it": "Italian",
"ja": "Japanese",
"ko": "Korean",
"lo": "Lao",
"lv": "Latvian",
"ms": "Malay (Malaysia)",
"no": "Norwegian",
"pl": "Polish",
"pt": "Portuguese (Brazil)",
"pt-PT": "Portuguese (Portugal)",
"ro": "Romanian",
"ru": "Russian",
"si": "Sinhala (Sri Lanka)",
"sk": "Slovak",
"sl": "Slovenian",
"es": "Spanish",
"sv": "Swedish",
"tr": "Turkish",
"uk": "Ukrainian",
"vi": "Vietnamese",
"aa-AA": "Test Language"
}
}

View File

@ -0,0 +1,90 @@
<?php
$GLOBALS['version'] = "1.5.1";
$GLOBALS['FILE_SIZE_MAX'] = 5242880;
$GLOBALS['STORAGE_PATH'] = "";
$GLOBALS['ALONE'] = FALSE;
$GLOBALS['DOC_SERV_FILLFORMS'] = array(".oform", ".docx");
$GLOBALS['DOC_SERV_VIEWD'] = array(".pdf", ".djvu", ".xps", ".oxps");
$GLOBALS['DOC_SERV_EDITED'] = array(".docx", ".xlsx", ".csv", ".pptx", ".txt", ".docxf");
$GLOBALS['DOC_SERV_CONVERT'] = array(".docm", ".doc", ".dotx", ".dotm", ".dot", ".odt", ".fodt", ".ott", ".xlsm", ".xlsb", ".xls", ".xltx", ".xltm", ".xlt", ".ods", ".fods", ".ots", ".pptm", ".ppt", ".ppsx", ".ppsm", ".pps", ".potx", ".potm", ".pot", ".odp", ".fodp", ".otp", ".rtf", ".mht", ".html", ".htm", ".xml", ".epub", ".fb2");
$GLOBALS['DOC_SERV_TIMEOUT'] = "120000";
$GLOBALS['DOC_SERV_SITE_URL'] = "http://documentserver/";
$GLOBALS['DOC_SERV_CONVERTER_URL'] = "ConvertService.ashx";
$GLOBALS['DOC_SERV_API_URL'] = "web-apps/apps/api/documents/api.js";
$GLOBALS['DOC_SERV_PRELOADER_URL'] = "web-apps/apps/api/documents/cache-scripts.html";
$GLOBALS['DOC_SERV_COMMAND_URL'] = "coauthoring/CommandService.ashx";
$GLOBALS['DOC_SERV_JWT_SECRET'] = "";
$GLOBALS['DOC_SERV_JWT_HEADER'] = "Authorization";
$GLOBALS['DOC_SERV_VERIFY_PEER_OFF'] = TRUE;
$GLOBALS['EXAMPLE_URL'] = "";
$GLOBALS['MOBILE_REGEX'] = "android|avantgo|playbook|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino";
$GLOBALS['ExtsSpreadsheet'] = array(".xls", ".xlsx", ".xlsm", ".xlsb",
".xlt", ".xltx", ".xltm",
".ods", ".fods", ".ots", ".csv");
$GLOBALS['ExtsPresentation'] = array(".pps", ".ppsx", ".ppsm",
".ppt", ".pptx", ".pptm",
".pot", ".potx", ".potm",
".odp", ".fodp", ".otp");
$GLOBALS['ExtsDocument'] = array(".doc", ".docx", ".docm",
".dot", ".dotx", ".dotm",
".odt", ".fodt", ".ott", ".rtf", ".txt",
".html", ".htm", ".mht", ".xml",
".pdf", ".djvu", ".fb2", ".epub", ".xps", ".oxps", ".oform");
$GLOBALS['LANGUAGES'] = array(
'en' => 'English',
'hy' => 'Armenian',
'az' => 'Azerbaijani',
'eu' => 'Basque',
'be' => 'Belarusian',
'bg' => 'Bulgarian',
'ca' => 'Catalan',
'zh' => 'Chinese (People\'s Republic of China)',
'zh-TW' => 'Chinese (Traditional, Taiwan)',
'cs' => 'Czech',
'da' => 'Danish',
'nl' => 'Dutch',
'fi' => 'Finnish',
'fr' => 'French',
'gl' => 'Galego',
'de' => 'German',
'el' => 'Greek',
'hu' => 'Hungarian',
'id' => 'Indonesian',
'it' => 'Italian',
'ja' => 'Japanese',
'ko' => 'Korean',
'lv' => 'Latvian',
'lo' => 'Lao',
'ms' => 'Malay (Malaysia)',
'nb' => 'Norwegian',
'pl' => 'Polish',
'pt' => 'Portuguese (Brazil)',
'pt-PT' => 'Portuguese (Portugal)',
'ro' => 'Romanian',
'ru' => 'Russian',
'sk' => 'Slovak',
'sl' => 'Slovenian',
'es' => 'Spanish',
'sv' => 'Swedish',
'tr' => 'Turkish',
'uk' => 'Ukrainian',
'vi' => 'Vietnamese',
'aa-AA' => 'Test Language'
);
?>

View File

@ -684,8 +684,3 @@
max-width:15%;
}
}
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.tableRow td:first-child{
max-width: none;
}
}

View File

@ -366,9 +366,9 @@ footer {
color: #AAAAAA;
height: 64px;
width: 100%;
position: relative;
left: 0;
bottom: 0;
position: relative;
left: 0;
bottom: 0;
}
footer > .center{
width: 100%;
@ -390,7 +390,7 @@ footer table tr {
}
footer table td {
display: block;
display: block;
position: relative;
padding-left: 32px;
}
@ -467,8 +467,6 @@ footer table tr td:first-child {
.stored-edit span {
font-size: 12px;
line-height: 12px;
bottom: 35%;
position: relative;
}
.stored-edit:hover span {
@ -574,7 +572,7 @@ footer table tr td:first-child {
}
.contentCells {
display: block;
display: block;
border-bottom: 1px solid #EFEFEF;
font-family: 'Open Sans', sans-serif;
font-size: 16px;

View File

@ -1,26 +1,615 @@
<?php
/**
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace OnlineEditorsExamplePhp;
require_once( dirname(__FILE__) . '/config.php' );
require_once( dirname(__FILE__) . '/common.php' );
require_once( dirname(__FILE__) . '/functions.php' );
require_once( dirname(__FILE__) . '/jwtmanager.php' );
require_once( dirname(__FILE__) . '/users.php' );
use OnlineEditorsExamplePhp\Views\DocEditorView;
$filename;
require_once dirname(__FILE__) . '/functions.php';
require_once dirname(__FILE__) . '/vendor/autoload.php';
$user = getUser($_GET["user"]);
$isEnableDirectUrl = $_GET["directUrl"] != null ? filter_var($_GET["directUrl"], FILTER_VALIDATE_BOOLEAN) : false;
$docEditorView = new DocEditorView($_REQUEST);
$docEditorView->render();
// get the file url and upload it
$externalUrl = $_GET["fileUrl"];
if (!empty($externalUrl))
{
$filename = DoUpload($externalUrl);
}
// if the file url doesn't exist, get file name and file extension
else
{
$filename = basename($_GET["fileID"]);
}
$createExt = $_GET["fileExt"];
if (!empty($createExt))
{
// and get demo file name by the extension
$filename = tryGetDefaultByType($createExt, $user);
// create the demo file url
$new_url = "doceditor.php?fileID=" . $filename . "&user=" . $_GET["user"];
header('Location: ' . $new_url, true);
exit;
}
$fileuri = FileUri($filename, true);
$fileuriUser = realpath($GLOBALS['STORAGE_PATH']) === $GLOBALS['STORAGE_PATH'] ? getDownloadUrl($filename) . "&dmode=emb" : FileUri($filename);
$directUrl = getDownloadUrl($filename, FALSE);
$docKey = getDocEditorKey($filename);
$filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$ext = strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION));
$editorsMode = empty($_GET["action"]) ? "edit" : $_GET["action"]; // get the editors mode
$canEdit = in_array($ext, $GLOBALS['DOC_SERV_EDITED']); // check if the file can be edited
if ((!$canEdit && $editorsMode == "edit" || $editorsMode == "fillForms") && in_array($ext, $GLOBALS['DOC_SERV_FILLFORMS'])) {
$editorsMode = "fillForms";
$canEdit = true;
}
$submitForm = $editorsMode == "fillForms" && $user->id == "uid-1" && !1; // check if the Submit form button is displayed or not
$mode = $canEdit && $editorsMode != "view" ? "edit" : "view"; // define if the editing mode is edit or view
$type = empty($_GET["type"]) ? "desktop" : $_GET["type"];
$templatesImageUrl = getTemplateImageUrl($filename); // templates image url in the "From Template" section
$createUrl = getCreateUrl($filename, $user->id, $type);
$templates = array(
array (
"image" => "",
"title" => "Blank",
"url" => $createUrl
),
array (
"image" => $templatesImageUrl,
"title" => "With sample content",
"url" => $createUrl . "&sample=true"
)
);
// specify the document config
$config = [
"type" => $type,
"documentType" => getDocumentType($filename),
"document" => [
"title" => $filename,
"url" => getDownloadUrl($filename),
"directUrl" => $isEnableDirectUrl ? $directUrl : "",
"fileType" => $filetype,
"key" => $docKey,
"info" => [
"owner" => "Me",
"uploaded" => date('d.m.y'),
"favorite" => $user->favorite
],
"permissions" => [ // the permission for the document to be edited and downloaded or not
"comment" => $editorsMode != "view" && $editorsMode != "fillForms" && $editorsMode != "embedded" && $editorsMode != "blockcontent",
"copy" => !in_array("copy", $user->deniedPermissions),
"download" => !in_array("download", $user->deniedPermissions),
"edit" => $canEdit && ($editorsMode == "edit" || $editorsMode == "view" || $editorsMode == "filter" || $editorsMode == "blockcontent"),
"print" => !in_array("print", $user->deniedPermissions),
"fillForms" => $editorsMode != "view" && $editorsMode != "comment" && $editorsMode != "embedded" && $editorsMode != "blockcontent",
"modifyFilter" => $editorsMode != "filter",
"modifyContentControl" => $editorsMode != "blockcontent",
"review" => $canEdit && ($editorsMode == "edit" || $editorsMode == "review"),
"chat" => $user->id != "uid-0",
"reviewGroups" => $user->reviewGroups,
"commentGroups" => $user->commentGroups,
"userInfoGroups" => $user->userInfoGroups
]
],
"editorConfig" => [
"actionLink" => empty($_GET["actionLink"]) ? null : json_decode($_GET["actionLink"]),
"mode" => $mode,
"lang" => empty($_COOKIE["ulang"]) ? "en" : $_COOKIE["ulang"],
"callbackUrl" => getCallbackUrl($filename), // absolute URL to the document storage service
"coEditing" => $editorsMode == "view" && $user->id == "uid-0" ? [
"mode" => "strict",
"change" => false
] : null,
"createUrl" => $user->id != "uid-0" ? $createUrl : null,
"templates" => $user->templates ? $templates : null,
"user" => [ // the user currently viewing or editing the document
"id" => $user->id != "uid-0" ? $user->id : null,
"name" => $user->name,
"group" => $user->group
],
"embedded" => [ // the parameters for the embedded document type
"saveUrl" => $directUrl, // the absolute URL that will allow the document to be saved onto the user personal computer
"embedUrl" => $directUrl, // the absolute URL to the document serving as a source file for the document embedded into the web page
"shareUrl" => $directUrl, // the absolute URL that will allow other users to share this document
"toolbarDocked" => "top", // the place for the embedded viewer toolbar (top or bottom)
],
"customization" => [ // the parameters for the editor interface
"about" => true, // the About section display
"comments" => true,
"feedback" => true, // the Feedback & Support menu button display
"forcesave" => false, // adds the request for the forced file saving to the callback handler when saving the document
"submitForm" => $submitForm, // if the Submit form button is displayed or not
"goback" => [ // settings for the Open file location menu button and upper right corner button
"url" => serverPath(), // the absolute URL to the website address which will be opened when clicking the Open file location menu button
]
]
]
];
// an image for inserting
$dataInsertImage = $isEnableDirectUrl ? [
"fileType" => "png",
"url" => serverPath(true) . "/css/images/logo.png",
"directUrl" => serverPath(false) . "/css/images/logo.png"
] : [
"fileType" => "png",
"url" => serverPath(true) . "/css/images/logo.png"
];
// a document for comparing
$dataCompareFile = $isEnableDirectUrl ? [
"fileType" => "docx",
"url" => serverPath(true) . "/webeditor-ajax.php?type=assets&name=sample.docx",
"directUrl" => serverPath(false) . "/webeditor-ajax.php?type=assets&name=sample.docx"
] : [
"fileType" => "docx",
"url" => serverPath(true) . "/webeditor-ajax.php?type=assets&name=sample.docx"
];
// recipients data for mail merging
$dataMailMergeRecipients = $isEnableDirectUrl ? [
"fileType" =>"csv",
"url" => serverPath(true) . "/webeditor-ajax.php?type=csv",
"directUrl" => serverPath(false) . "/webeditor-ajax.php?type=csv"
] : [
"fileType" =>"csv",
"url" => serverPath(true) . "/webeditor-ajax.php?type=csv"
];
// users data for mentions
$usersForMentions = $user->id != "uid-0" ? getUsersForMentions($user->id) : null;
// check if the secret key to generate token exists
if (isJwtEnabled()) {
$config["token"] = jwtEncode($config); // encode config into the token
$dataInsertImage["token"] = jwtEncode($dataInsertImage); // encode the dataInsertImage object into the token
$dataCompareFile["token"] = jwtEncode($dataCompareFile); // encode the dataCompareFile object into the token
$dataMailMergeRecipients["token"] = jwtEncode($dataMailMergeRecipients); // encode the dataMailMergeRecipients object into the token
}
// get demo file name by the extension
function tryGetDefaultByType($createExt, $user) {
$demoName = ($_GET["sample"] ? "sample." : "new.") . $createExt;
$demoPath = "assets" . DIRECTORY_SEPARATOR . ($_GET["sample"] ? "sample" : "new") . DIRECTORY_SEPARATOR;
$demoFilename = GetCorrectName($demoName);
if(!@copy(dirname(__FILE__) . DIRECTORY_SEPARATOR . $demoPath . $demoName, getStoragePath($demoFilename)))
{
sendlog("Copy file error to ". getStoragePath($demoFilename), "common.log");
// Copy error!!!
}
// create demo file meta information
createMeta($demoFilename, $user->id, $user->name);
return $demoFilename;
}
// get the callback url
function getCallbackUrl($fileName) {
return serverPath(TRUE) . '/'
. "webeditor-ajax.php"
. "?type=track"
. "&fileName=" . urlencode($fileName)
. "&userAddress=" . getClientIp();
}
// get url to the created file
function getCreateUrl($fileName, $uid, $type) {
$ext = trim(getInternalExtension($fileName),'.');
return serverPath(false) . '/'
. "doceditor.php"
. "?fileExt=" . $ext
. "&user=" . $uid
. "&type=" . $type;
}
function getHistoryDownloadUrl($fileName, $version, $file, $isServer = TRUE) {
$userAddress = $isServer ? "&userAddress=" . getClientIp() : "";
return serverPath($isServer) . '/'
. "webeditor-ajax.php"
. "?type=history"
. "&fileName=" . urlencode($fileName)
. "&ver=" . $version
. "&file=" . urlencode($file)
. $userAddress;
}
// get url to download a file
function getDownloadUrl($fileName, $isServer = TRUE) {
$userAddress = $isServer ? "&userAddress=" . getClientIp() : "";
return serverPath($isServer) . '/'
. "webeditor-ajax.php"
. "?type=download"
. "&fileName=" . urlencode($fileName)
. $userAddress;
}
// get document history
function getHistory($filename, $filetype, $docKey, $fileuri, $isEnableDirectUrl) {
$storagePath = $GLOBALS['STORAGE_PATH'];
$histDir = getHistoryDir(getStoragePath($filename)); // get the path to the file history
if (getFileVersion($histDir) > 0) { // check if the file was modified (the file version is greater than 0)
$curVer = getFileVersion($histDir);
$hist = [];
$histData = [];
for ($i = 1; $i <= $curVer; $i++) { // run through all the file versions
$obj = [];
$dataObj = [];
$verDir = getVersionDir($histDir, $i); // get the path to the file version
$key = $i == $curVer ? $docKey : file_get_contents($verDir . DIRECTORY_SEPARATOR . "key.txt"); // get document key
$obj["key"] = $key;
$obj["version"] = $i;
if ($i == 1) { // check if the version number is equal to 1
$createdInfo = file_get_contents($histDir . DIRECTORY_SEPARATOR . "createdInfo.json"); // get meta data of this file
$json = json_decode($createdInfo, true); // decode the meta data from the createdInfo.json file
$obj["created"] = $json["created"];
$obj["user"] = [
"id" => $json["uid"],
"name" => $json["name"]
];
}
$fileExe = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$prevFileName = $verDir . DIRECTORY_SEPARATOR . "prev." . $filetype;
$prevFileName = substr($prevFileName, strlen(getStoragePath("")));
$dataObj["fileType"] = $fileExe;
$dataObj["key"] = $key;
$directUrl = $i == $curVer ? FileUri($filename, FALSE) : getHistoryDownloadUrl($filename, $i, "prev.".$fileExe, FALSE);
$prevFileUrl = $i == $curVer ? $fileuri : getHistoryDownloadUrl($filename, $i, "prev.".$fileExe);
if (realpath($storagePath) === $storagePath) {
$prevFileUrl = $i == $curVer ? getDownloadUrl($filename) : getHistoryDownloadUrl($filename, $i, "prev.".$fileExe);
if ($isEnableDirectUrl) {
$directUrl = $i == $curVer ? getDownloadUrl($filename, FALSE) : getHistoryDownloadUrl($filename, $i, "prev.".$fileExe, FALSE);
}
}
$dataObj["url"] = $prevFileUrl; // write file url to the data object
if ($isEnableDirectUrl) {
$dataObj["directUrl"] = $directUrl; // write direct url to the data object
}
$dataObj["version"] = $i;
if ($i > 1) { // check if the version number is greater than 1 (the document was modified)
$changes = json_decode(file_get_contents(getVersionDir($histDir, $i - 1) . DIRECTORY_SEPARATOR . "changes.json"), true); // get the path to the changes.json file
$change = $changes["changes"][0];
$obj["changes"] = $changes ? $changes["changes"] : null; // write information about changes to the object
$obj["serverVersion"] = $changes["serverVersion"];
$obj["created"] = $change ? $change["created"] : null;
$obj["user"] = $change ? $change["user"] : null;
$prev = $histData[$i - 2]; // get the history data from the previous file version
$dataObj["previous"] = $isEnableDirectUrl ? [ // write information about previous file version to the data object
"fileType" => $prev["fileType"],
"key" => $prev["key"],
"url" => $prev["url"],
"directUrl" => $prev["directUrl"]
] : [
"fileType" => $prev["fileType"],
"key" => $prev["key"],
"url" => $prev["url"]
];
// write the path to the diff.zip archive with differences in this file version
$dataObj["changesUrl"] = getHistoryDownloadUrl($filename, $i - 1, "diff.zip");
}
if (isJwtEnabled()) {
$dataObj["token"] = jwtEncode($dataObj);
}
array_push($hist, $obj); // add object dictionary to the hist list
$histData[$i - 1] = $dataObj; // write data object information to the history data
}
// write history information about the current file version
$out = [];
array_push($out, [
"currentVersion" => $curVer,
"history" => $hist
],
$histData);
return $out;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-capable" content="yes" />
<link rel="icon" href="css/images/<?php echo getDocumentType($filename) ?>.ico" type="image/x-icon" />
<title>ONLYOFFICE</title>
<style>
html {
height: 100%;
width: 100%;
}
body {
background: #fff;
color: #333;
font-family: Arial, Tahoma,sans-serif;
font-size: 12px;
font-weight: normal;
height: 100%;
margin: 0;
overflow-y: hidden;
padding: 0;
text-decoration: none;
}
form {
height: 100%;
}
div {
margin: 0;
padding: 0;
}
</style>
<script type="text/javascript" src="<?php echo $GLOBALS["DOC_SERV_SITE_URL"].$GLOBALS["DOC_SERV_API_URL"] ?>"></script>
<script type="text/javascript">
var docEditor;
var config;
var innerAlert = function (message, inEditor) {
if (console && console.log)
console.log(message);
if (inEditor && docEditor)
docEditor.showMessage(message);
};
// the application is loaded into the browser
var onAppReady = function () {
innerAlert("Document editor ready");
};
// the document is modified
var onDocumentStateChange = function (event) {
var title = document.title.replace(/\*$/g, "");
document.title = title + (event.data ? "*" : "");
};
// the user is trying to switch the document from the viewing into the editing mode
var onRequestEditRights = function () {
location.href = location.href.replace(RegExp("action=view\&?", "i"), "");
};
// an error or some other specific event occurs
var onError = function (event) {
if (event)
innerAlert(event.data);
};
// the document is opened for editing with the old document.key value
var onOutdatedVersion = function (event) {
location.reload(true);
};
// replace the link to the document which contains a bookmark
var replaceActionLink = function(href, linkParam) {
var link;
var actionIndex = href.indexOf("&actionLink=");
if (actionIndex != -1) {
var endIndex = href.indexOf("&", actionIndex + "&actionLink=".length);
if (endIndex != -1) {
link = href.substring(0, actionIndex) + href.substring(endIndex) + "&actionLink=" + encodeURIComponent(linkParam);
} else {
link = href.substring(0, actionIndex) + "&actionLink=" + encodeURIComponent(linkParam);
}
} else {
link = href + "&actionLink=" + encodeURIComponent(linkParam);
}
return link;
}
// the user is trying to get link for opening the document which contains a bookmark, scrolling to the bookmark position
var onMakeActionLink = function (event) {
var actionData = event.data;
var linkParam = JSON.stringify(actionData);
docEditor.setActionLink(replaceActionLink(location.href, linkParam)); // set the link to the document which contains a bookmark
};
// the meta information of the document is changed via the meta command
var onMetaChange = function (event) {
if (event.data.favorite) {
var favorite = !!event.data.favorite;
var title = document.title.replace(/^\☆/g, "");
document.title = (favorite ? "☆" : "") + title;
docEditor.setFavorite(favorite); // change the Favorite icon state
}
innerAlert("onMetaChange: " + JSON.stringify(event.data));
};
// the user is trying to insert an image by clicking the Image from Storage button
var onRequestInsertImage = function(event) {
docEditor.insertImage({ // insert an image into the file
"c": event.data.c,
<?php echo mb_strimwidth(json_encode($dataInsertImage), 1, strlen(json_encode($dataInsertImage)) - 2)?>
})
};
// the user is trying to select document for comparing by clicking the Document from Storage button
var onRequestCompareFile = function() {
docEditor.setRevisedFile(<?php echo json_encode($dataCompareFile)?>); // select a document for comparing
};
// the user is trying to select recipients data by clicking the Mail merge button
var onRequestMailMergeRecipients = function (event) {
docEditor.setMailMergeRecipients(<?php echo json_encode($dataMailMergeRecipients) ?>); // insert recipient data for mail merge into the file
};
var onRequestSaveAs = function (event) { // the user is trying to save file by clicking Save Copy as... button
var title = event.data.title;
var url = event.data.url;
var data = {
title: title,
url: url
};
let xhr = new XMLHttpRequest();
xhr.open("POST", "webeditor-ajax.php?type=saveas");
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
xhr.onload = function () {
innerAlert(xhr.responseText);
innerAlert(JSON.parse(xhr.responseText.substring(xhr.responseText.indexOf("{"))).file, true);
}
};
var onRequestRename = function(event) { // the user is trying to rename file by clicking Rename... button
innerAlert("onRequestRename: " + JSON.stringify(event.data));
var newfilename = event.data;
var data = {
newfilename: newfilename,
dockey: config.document.key,
ext: config.document.fileType
};
let xhr = new XMLHttpRequest();
xhr.open("POST", "webeditor-ajax.php?type=rename");
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
xhr.onload = function () {
innerAlert(xhr.responseText);
}
};
var сonnectEditor = function () {
<?php
if (!file_exists(getStoragePath($filename))) {
echo "alert('File not found'); return;";
}
?>
config = <?php echo json_encode($config) ?>;
config.width = "100%";
config.height = "100%";
config.events = {
'onAppReady': onAppReady,
'onDocumentStateChange': onDocumentStateChange,
'onRequestEditRights': onRequestEditRights,
'onError': onError,
'onOutdatedVersion': onOutdatedVersion,
'onMakeActionLink': onMakeActionLink,
'onMetaChange': onMetaChange,
'onRequestInsertImage': onRequestInsertImage,
'onRequestCompareFile': onRequestCompareFile,
'onRequestMailMergeRecipients': onRequestMailMergeRecipients,
};
<?php
$out = getHistory($filename, $filetype, $docKey, $fileuri, $isEnableDirectUrl);
$history = $out[0];
$historyData = $out[1];
?>
<?php if ($user->id != "uid-0"): ?>
<?php if ($history != null && $historyData != null): ?>
// the user is trying to show the document version history
config.events['onRequestHistory'] = function () {
docEditor.refreshHistory(<?php echo json_encode($history) ?>); // show the document version history
};
// the user is trying to click the specific document version in the document version history
config.events['onRequestHistoryData'] = function (event) {
var ver = event.data;
var histData = <?php echo json_encode($historyData) ?>;
docEditor.setHistoryData(histData[ver - 1]); // send the link to the document for viewing the version history
};
// the user is trying to go back to the document from viewing the document version history
config.events['onRequestHistoryClose'] = function () {
document.location.reload();
};
<?php endif; ?>
// add mentions for not anonymous users
config.events['onRequestUsers'] = function () {
docEditor.setUsers({ // set a list of users to mention in the comments
"users": <?php echo json_encode($usersForMentions) ?>
});
};
// the user is mentioned in a comment
config.events['onRequestSendNotify'] = function (event) {
event.data.actionLink = replaceActionLink(location.href, JSON.stringify(event.data.actionLink));
var data = JSON.stringify(event.data);
innerAlert("onRequestSendNotify: " + data);
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
<?php endif; ?>
if (config.editorConfig.createUrl) {
config.events.onRequestSaveAs = onRequestSaveAs;
};
if ((config.document.fileType === "docxf" || config.document.fileType === "oform")
&& DocsAPI.DocEditor.version().split(".")[0] < 7) {
innerAlert("Please update ONLYOFFICE Docs to version 7.0 to work on fillable forms online.");
return;
}
docEditor = new DocsAPI.DocEditor("iframeEditor", config);
};
if (window.addEventListener) {
window.addEventListener("load", сonnectEditor);
} else if (window.attachEvent) {
window.attachEvent("load", сonnectEditor);
}
</script>
</head>
<body>
<form id="form1">
<div id="iframeEditor">
</div>
</form>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@ -1,46 +0,0 @@
<?php
namespace OnlineEditorsExamplePhp\Helpers;
/**
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
final class ConfigManager
{
private mixed $config;
public function __construct()
{
$this->config = json_decode($this->getConfigurationJson());
}
private function getConfigurationJson(): bool|string
{
return file_exists("./config.json") ? file_get_contents("./config.json") : false;
}
/**
* @param string|null $configName
* @return mixed
*/
public function getConfig(string $configName = null): mixed
{
if ($configName) {
return $this->config->$configName ?? "";
}
return $this->config;
}
}

View File

@ -1,187 +0,0 @@
<?php
namespace OnlineEditorsExamplePhp\Helpers;
use function OnlineEditorsExamplePhp\sendlog;
/**
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
final class ExampleUsers
{
private array $descr_user_1;
private array $descr_user_2;
private array $descr_user_3;
private array $descr_user_0;
private array $users;
public function __construct()
{
$this->descr_user_1 = [
"File author by default",
"Doesnt belong to any group",
"Can review all the changes",
"Can perform all actions with comments",
"The file favorite state is undefined",
"Can create files from templates using data from the editor",
"Can see the information about all users",
];
$this->descr_user_2 = [
"Belongs to Group2",
"Can review only his own changes or changes made by users with no group",
"Can view comments, edit his own comments and comments left by users with no group.
Can remove his own comments only",
"This file is marked as favorite",
"Can create new files from the editor",
"Can see the information about users from Group2 and users who dont belong to any group",
];
$this->descr_user_3 = [
"Belongs to Group3",
"Can review changes made by Group2 users",
"Can view comments left by Group2 and Group3 users. Can edit comments left by the Group2 users",
"This file isnt marked as favorite",
"Cant copy data from the file to clipboard",
"Cant download the file",
"Cant print the file",
"Can create new files from the editor",
"Can see the information about Group2 users",
];
$this->descr_user_0 = [
"The name is requested when the editor is opened",
"Doesnt belong to any group",
"Can review all the changes",
"Can perform all actions with comments",
"The file favorite state is undefined",
"Can't mention others in comments",
"Can't create new files from the editor",
"Cant see anyones information",
"Can't rename files from the editor",
"Can't view chat",
"View file without collaboration",
];
$this->users = [
new Users(
"uid-1",
"John Smith",
"smith@example.com",
"",
null,
[],
null,
null,
[],
$this->descr_user_1,
true
),
new Users(
"uid-2",
"Mark Pottato",
"pottato@example.com",
"group-2",
["group-2", ""],
[
"view" => "",
"edit" => ["group-2", ""],
"remove" => ["group-2"],
],
["group-2", ""],
true,
[],
$this->descr_user_2,
false
),
new Users(
"uid-3",
"Hamish Mitchell",
"mitchell@example.com",
"group-3",
["group-2"],
[
"view" => ["group-3", "group-2"],
"edit" => ["group-2"],
"remove" => [],
],
["group-2"],
false,
["copy", "download", "print"],
$this->descr_user_3,
false
),
new Users(
"uid-0",
null,
null,
"",
null,
[],
[],
null,
["protect"],
$this->descr_user_0,
false
),
];
}
/**
* Get a list of all the users
*
* @return array
*/
public function getAllUsers(): array
{
return $this->users;
}
/**
* Get a user by id specified
*
* @param string|null $id
*
* @return Users
*/
public function getUser(?string $id): Users
{
foreach ($this->users as $user) {
if ($user->id == $id) {
sendlog("User ". $user->id, "common.log");
return $user;
}
}
return $this->users[0];
}
/**
* Get a list of users with their names and emails for mentions
*
* @param string|null $id
*
* @return array
*/
public function getUsersForMentions(?string $id): array
{
$usersData = [];
foreach ($this->users as $user) {
if ($user->id != $id && $user->name != null && $user->email != null) {
$usersData[] = [
"name" => $user->name,
"email" => $user->email,
];
}
}
return $usersData;
}
}

View File

@ -1,80 +0,0 @@
<?php
namespace OnlineEditorsExamplePhp\Helpers;
/**
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
final class JwtManager
{
/**
* Check if a secret key to generate token exists or not.
*
* @return bool
*/
public function isJwtEnabled(): bool
{
$configManager = new ConfigManager();
return !empty($configManager->getConfig("docServJwtSecret"));
}
/**
* Check if a secret key use for request
*
* @return bool
*/
public function tokenUseForRequest(): bool
{
$configManager = new ConfigManager();
return $configManager->getConfig("docServJwtUseForRequest") ?: false;
}
/**
* Encode a payload object into a token using a secret key
*
* @param array $payload
*
* @return string
*/
public function jwtEncode($payload)
{
$configManager = new ConfigManager();
return \Firebase\JWT\JWT::encode($payload, $configManager->getConfig("docServJwtSecret"));
}
/**
* Decode a token into a payload object using a secret key
*
* @param string $token
*
* @return string
*/
public function jwtDecode($token)
{
$configManager = new ConfigManager();
try {
$payload = \Firebase\JWT\JWT::decode(
$token,
$configManager->getConfig("docServJwtSecret"),
["HS256"]
);
} catch (\UnexpectedValueException $e) {
$payload = "";
}
return $payload;
}
}

View File

@ -1,77 +0,0 @@
<?php
namespace OnlineEditorsExamplePhp\Helpers;
/**
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
final class Users
{
public string $id;
public ?string $name;
public ?string $email;
public ?string $group;
public ?array $reviewGroups;
public ?array $commentGroups;
public ?bool $favorite;
public ?array $deniedPermissions;
public ?array $descriptions;
public ?bool $templates;
public ?array $userInfoGroups;
/**
* Constructor
*
* @param string $id
* @param string|null $name
* @param string|null $email
* @param string|null $group
* @param array|null $reviewGroups
* @param array|null $commentGroups
* @param array|null $userInfoGroups
* @param bool|null $favorite
* @param array|null $deniedPermissions
* @param array|null $descriptions
* @param bool|null $templates
*
* @return void
*/
public function __construct(
string $id,
?string $name,
?string $email,
?string $group,
?array $reviewGroups,
?array $commentGroups,
?array $userInfoGroups,
?bool $favorite,
?array $deniedPermissions,
?array $descriptions,
?bool $templates
) {
$this->id = $id;
$this->name = $name;
$this->email = $email;
$this->group = $group;
$this->reviewGroups = $reviewGroups;
$this->commentGroups = $commentGroups;
$this->favorite = $favorite;
$this->deniedPermissions = $deniedPermissions;
$this->descriptions = $descriptions;
$this->templates = $templates;
$this->userInfoGroups = $userInfoGroups;
}
}

View File

@ -1,26 +1,354 @@
<?php
/**
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace OnlineEditorsExamplePhp;
require_once( dirname(__FILE__) . '/config.php' );
require_once( dirname(__FILE__) . '/common.php' );
require_once( dirname(__FILE__) . '/functions.php' );
require_once( dirname(__FILE__) . '/users.php' );
use OnlineEditorsExamplePhp\Views\IndexView;
$user = $_GET["user"];
$directUrlArg = $_GET["directUrl"] != null ? "&directUrl=" . $_GET["directUrl"] : "";
?>
require_once dirname(__FILE__) . '/functions.php';
require_once dirname(__FILE__) . '/vendor/autoload.php';
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
$indexView = new IndexView($_REQUEST);
$indexView->render();
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
<title>ONLYOFFICE Document Editors</title>
<link rel="icon" href="./favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Open+Sans:900,800,700,600,500,400,300&subset=latin,cyrillic-ext,cyrillic,latin-ext" />
<link rel="stylesheet" type="text/css" href="css/stylesheet.css" />
<link rel="stylesheet" type="text/css" href="css/media.css">
<link rel="stylesheet" type="text/css" href="css/jquery-ui.css" />
</head>
<body>
<form id="form1">
<header>
<div class="center">
<a href="">
<img src ="css/images/logo.svg" alt="ONLYOFFICE" />
</a>
</div>
</header>
<div class="center main">
<table class="table-main">
<tbody>
<tr>
<td class="left-panel section">
<div class="help-block">
<span>Create new</span>
<div class="clearFix">
<div class="create-panel clearFix">
<ul class="try-editor-list clearFix">
<li>
<a class="try-editor word reload-page" target="_blank" href="doceditor.php?fileExt=docx&user=<?php echo htmlentities($user); ?>">Document</a>
</li>
<li>
<a class="try-editor cell reload-page" target="_blank" href="doceditor.php?fileExt=xlsx&user=<?php echo htmlentities($user); ?>">Spreadsheet</a>
</li>
<li>
<a class="try-editor slide reload-page" target="_blank" href="doceditor.php?fileExt=pptx&user=<?php echo htmlentities($user); ?>">Presentation</a>
</li>
<li>
<a class="try-editor form reload-page" target="_blank" href="doceditor.php?fileExt=docxf&user=<?php echo htmlentities($user); ?>">Form template</a>
</li>
</ul>
<label class="side-option">
<input type="checkbox" id="createSample" class="checkbox" />With sample content
</label>
</div>
<div class="upload-panel clearFix">
<a class="file-upload">Upload file
<input type="file" id="fileupload" name="files" data-url="webeditor-ajax.php?type=upload&user=<?php echo htmlentities($user); ?>" />
</a>
</div>
<table class="user-block-table" cellspacing="0" cellpadding="0">
<tr>
<td valign="middle">
<span class="select-user">Username</span>
<img id="info" class="info" src="css/images/info.svg" />
<select class="select-user" id="user">
<?php foreach(getAllUsers() as $user_l) {
$name = $user_l->name ? $user_l->name : "Anonymous";
echo '<option value="'.$user_l->id.'">'.$name.'</option>';
} ?>
</select>
</td>
</tr>
<tr>
<td valign="middle">
<span class="select-user">Language</span>
<img class="info info-tooltip" data-id="language"
data-tooltip="Choose the language for ONLYOFFICE editors interface"
src="css/images/info.svg" />
<select class="select-user" id="language">
<?php foreach ($GLOBALS['LANGUAGES'] as $key => $language) { ?>
<option value="<?=$key?>"><?=$language?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td valign="middle">
<label class="side-option">
<input id="directUrl" type="checkbox" class="checkbox" />Try opening on client
<img id="directUrlInfo" class="info info-tooltip" data-id="directUrlInfo" data-tooltip="Some files can be opened in the user's browser without connecting to the document server." src="css/images/info.svg" />
</label>
</td>
</tr>
</table>
</div>
</div>
</td>
<td class="section">
<div class="main-panel">
<?php
$storedFiles = getStoredFiles();
if (!empty($storedFiles)): ?>
<div id="portal-info" style="display: none">
<?php else: ?>
<div id="portal-info" style="display: table-cell">
<?php endif; ?>
<span class="portal-name">ONLYOFFICE Document Editors Welcome!</span>
<span class="portal-descr">
Get started with a demo-sample of ONLYOFFICE Document Editors, the first html5-based editors.
<br /> You may upload your own documents for testing using the "<b>Upload file</b>" button and <b>selecting</b> the necessary files on your PC.
</span>
<span class="portal-descr">Please do NOT use this integration example on your own server without proper code modifications, it is intended for testing purposes only. In case you enabled this test example, disable it before going for production.</span>
<span class="portal-descr">You can open the same document using different users in different Web browser sessions, so you can check out multi-user editing functions.</span>
<?php foreach(getAllUsers() as $user_l) {
$name = $user_l->name ? $user_l->name : "Anonymous";
echo '<div class="user-descr">';
echo '<b>'.$name.'</b>';
echo '<ul>';
foreach ($user_l->descriptions as $description) {
echo '<li>'.$description.'</li>';
}
echo '</ul>';
echo '</div>';
} ?>
</div>
<?php
if (!empty($storedFiles)) { ?>
<div class="stored-list">
<span class="header-list">Your documents</span>
<table class="tableHeader" cellspacing="0" cellpadding="0" width="100%">
<thead>
<tr>
<td class="tableHeaderCell tableHeaderCellFileName">Filename</td>
<td class="tableHeaderCell tableHeaderCellEditors contentCells-shift">Editors</td>
<td class="tableHeaderCell tableHeaderCellViewers">Viewers</td>
<td class="tableHeaderCell tableHeaderCellDownload">Download</td>
<td class="tableHeaderCell tableHeaderCellRemove">Remove</td>
</tr>
</thead>
</table>
<div class="scroll-table-body">
<table cellspacing="0" cellpadding="0" width="100%">
<tbody>
<?php foreach ($storedFiles as &$storeFile) {
echo '<tr class="tableRow" title="'.$storeFile->name.' ['.getFileVersion(getHistoryDir(getStoragePath($storeFile->name))).']">';
echo ' <td class="contentCells">';
echo ' <a class="stored-edit '.$storeFile->documentType.'" href="doceditor.php?fileID='.urlencode($storeFile->name).'&user='.htmlentities($user) . $directUrlArg .'" target="_blank">';
echo ' <span>'.$storeFile->name.'</span>';
echo ' </a>';
echo ' </td>';
if ($storeFile->canEdit) {
echo ' <td class="contentCells contentCells-icon">';
echo ' <a href="doceditor.php?fileID=' . urlencode($storeFile->name) . '&user=' . htmlentities($user) . $directUrlArg . '&action=edit&type=desktop" target="_blank">';
echo ' <img src="css/images/desktop.svg" alt="Open in editor for full size screens" title="Open in editor for full size screens" /></a>';
echo ' </td>';
echo ' <td class="contentCells contentCells-icon">';
echo ' <a href="doceditor.php?fileID=' . urlencode($storeFile->name) . '&user=' . htmlentities($user) . $directUrlArg . '&action=edit&type=mobile" target="_blank">';
echo ' <img src="css/images/mobile.svg" alt="Open in editor for mobile devices" title="Open in editor for mobile devices" /></a>';
echo ' </td>';
echo ' <td class="contentCells contentCells-icon">';
echo ' <a href="doceditor.php?fileID=' . urlencode($storeFile->name) . '&user=' . htmlentities($user) . $directUrlArg . '&action=comment&type=desktop" target="_blank">';
echo ' <img src="css/images/comment.svg" alt="Open in editor for comment" title="Open in editor for comment" /></a>';
echo ' </td>';
if ($storeFile->documentType == "word") {
echo ' <td class="contentCells contentCells-icon">';
echo ' <a href="doceditor.php?fileID=' . urlencode($storeFile->name) . '&user=' . htmlentities($user) . $directUrlArg . '&action=review&type=desktop" target="_blank">';
echo ' <img src="css/images/review.svg" alt="Open in editor for review" title="Open in editor for review" /></a>';
echo ' </td>';
} else if ($storeFile->documentType == "cell") {
echo ' <td class="contentCells contentCells-icon">';
echo ' <a href="doceditor.php?fileID=' . urlencode($storeFile->name) . '&user=' . htmlentities($user) . $directUrlArg . '&action=filter&type=desktop" target="_blank">';
echo ' <img src="css/images/filter.svg" alt="Open in editor without access to change the filter" title="Open in editor without access to change the filter" /></a>';
echo ' </td>';
}
if ($storeFile->documentType == "word") {
echo ' <td class="contentCells contentCells-icon ">';
echo ' <a href="doceditor.php?fileID=' . urlencode($storeFile->name) . '&user=' . htmlentities($user) . $directUrlArg . '&action=blockcontent&type=desktop" target="_blank">';
echo ' <img src="css/images/block-content.svg" alt="Open in editor without content control modification" title="Open in editor without content control modification" /></a>';
echo ' </td>';
} else{
echo ' <td class="contentCells contentCells-icon"></td> ';
}
if($storeFile->documentType!="word" && $storeFile->documentType!="cell"){
echo ' <td class="contentCells contentCells-icon"></td>';
}
if ($storeFile->isFillFormDoc) {
echo ' <td class="contentCells contentCells-shift contentCells-icon firstContentCellShift">';
echo ' <a href="doceditor.php?fileID=' . urlencode($storeFile->name) . '&user=' . htmlentities($user) . $directUrlArg . '&action=fillForms&type=desktop" target="_blank">';
echo ' <img src="css/images/fill-forms.svg" alt="Open in editor for filling in forms" title="Open in editor for filling in forms" /></a>';
echo ' </td>';
} else {
echo ' <td class="contentCells contentCells-shift contentCells-icon firstContentCellShift"></td> ';
}
} else if ($storeFile->isFillFormDoc) {
echo ' <td class="contentCells contentCells-icon"></td>';
echo ' <td class="contentCells contentCells-icon">';
echo ' <a href="doceditor.php?fileID=' . urlencode($storeFile->name) . '&user=' . htmlentities($user) . $directUrlArg . '&action=fillForms&type=desktop" target="_blank">';
echo ' <img src="css/images/mobile-fill-forms.svg" alt="Open in editor for filling in forms for mobile devices" title="Open in editor for filling in forms for mobile devices" /></a>';
echo ' </td>';
echo ' <td class="contentCells contentCells-icon"></td>';
echo ' <td class="contentCells contentCells-icon"></td>';
echo ' <td class="contentCells contentCells-icon"></td>';
echo ' <td class="contentCells contentCells-shift contentCells-icon firstContentCellShift">';
echo ' <a href="doceditor.php?fileID=' . urlencode($storeFile->name) . '&user=' . htmlentities($user) . $directUrlArg . '&action=fillForms&type=desktop" target="_blank">';
echo ' <img src="css/images/fill-forms.svg" alt="Open in editor for filling in forms" title="Open in editor for filling in forms" /></a>';
echo ' </td>';
} else {
echo '<td class="contentCells contentCells-shift contentCells-icon contentCellsEmpty" colspan="6"></td>';
}
echo ' <td class="contentCells contentCells-icon firstContentCellViewers">';
echo ' <a href="doceditor.php?fileID='.urlencode($storeFile->name).'&user='.htmlentities($user) . $directUrlArg . '&action=view&type=desktop" target="_blank">';
echo ' <img src="css/images/desktop.svg" alt="Open in viewer for full size screens" title="Open in viewer for full size screens" /></a>';
echo ' </td>';
echo ' <td class="contentCells contentCells-icon">';
echo ' <a href="doceditor.php?fileID='.urlencode($storeFile->name).'&user='.htmlentities($user) . $directUrlArg . '&action=view&type=mobile" target="_blank">';
echo ' <img src="css/images/mobile.svg" alt="Open in viewer for mobile devices" title="Open in viewer for mobile devices" /></a>';
echo ' </td>';
echo ' <td class="contentCells contentCells-icon contentCells-shift">';
echo ' <a href="doceditor.php?fileID='.urlencode($storeFile->name).'&user='.htmlentities($user) . $directUrlArg . '&action=embedded&type=embedded" target="_blank">';
echo ' <img src="css/images/embeded.svg" alt="Open in embedded mode" title="Open in embedded mode" /></a>';
echo ' </td>';
echo ' <td class="contentCells contentCells-icon contentCells-shift downloadContentCellShift">';
echo ' <a href="webeditor-ajax.php?type=download&fileName='.urlencode($storeFile->name).'">';
echo ' <img class="icon-download" src="css/images/download.svg" alt="Download" title="Download" /></a>';
echo ' </td>';
echo ' <td class="contentCells contentCells-icon contentCells-shift">';
echo ' <a class="delete-file" data="'.$storeFile->name.'">';
echo ' <img class="icon-delete" src="css/images/delete.svg" alt="Delete" title="Delete" /></a>';
echo ' </td>';
echo '</tr>';
} ?>
</tbody>
</table>
</div>
</div>
<?php
} ?>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="mainProgress">
<div id="uploadSteps">
<span id="uploadFileName" class="uploadFileName"></span>
<div class="describeUpload">After these steps are completed, you can work with your document.</div>
<span id="step1" class="step">1. Loading the file.</span>
<span class="step-descr">The loading speed depends on file size and additional elements it contains.</span>
<br />
<span id="step2" class="step">2. Conversion.</span>
<span class="step-descr">The file is converted to OOXML so that you can edit it.</span>
<br />
<div id="blockPassword">
<span class="descrFilePass">The file is password protected.</span>
<br />
<div>
<input id="filePass" type="password"/>
<div id="enterPass" class="button orange">Enter</div>
<div id="skipPass" class="button gray">Skip</div>
</div>
<span class="errorPass"></span>
<br />
</div>
<span id="step3" class="step">3. Loading editor scripts.</span>
<span class="step-descr">They are loaded only once, they will be cached on your computer.</span>
<input type="hidden" name="hiddenFileName" id="hiddenFileName" />
<br />
<span class="progress-descr">Note the speed of all operations depends on your connection quality and server location.</span>
<br />
<div class="error-message">
<b>Upload error: </b><span></span>
<br />
Please select another file and try again.
</div>
</div>
<iframe id="embeddedView" src="" height="345px" width="432px" frameborder="0" scrolling="no" allowtransparency></iframe>
<br />
<div class="buttonsMobile">
<?php if (($GLOBALS['MODE']) != "view") { ?>
<div id="beginEdit" class="button orange disable">Edit</div>
<?php } ?>
<div id="beginView" class="button gray disable">View</div>
<div id="beginEmbedded" class="button gray disable">Embedded view</div>
<div id="cancelEdit" class="button gray">Cancel</div>
</div>
</div>
<span id="loadScripts" data-docs="<?php echo $GLOBALS['DOC_SERV_SITE_URL'].$GLOBALS['DOC_SERV_PRELOADER_URL'] ?>"></span>
<footer>
<div class="center">
<table>
<tbody>
<tr>
<td>
<a href="http://api.onlyoffice.com/editors/howitworks" target="_blank">API Documentation</a>
</td>
<td>
<a href="mailto:sales@onlyoffice.com">Submit your request</a>
</td>
<td class="copy">
&copy; Ascensio Systems SIA <?php echo date("Y") ?>. All rights reserved.
</td>
</tr>
</tbody>
</table>
</div>
</footer>
</form>
<script type="text/javascript" src="js/jquery-3.6.4.min.js"></script>
<script type="text/javascript" src="js/jquery-migrate-3.4.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/jquery.blockUI.js"></script>
<script type="text/javascript" src="js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="js/jquery.fileupload.js"></script>
<script type="text/javascript" src="js/jquery.dropdownToggle.js"></script>
<script type="text/javascript" src="js/jscript.js"></script>
<script type="text/javascript">
var FillFormsExtList = '<?php echo implode(",", $GLOBALS["DOC_SERV_FILLFORMS"]) ?>';
var ConverExtList = '<?php echo implode(",", $GLOBALS["DOC_SERV_CONVERT"]) ?>';
var EditedExtList = '<?php echo implode(",", $GLOBALS["DOC_SERV_EDITED"]) ?>';
</script>
</body>
</html>

View File

@ -251,7 +251,7 @@ if (typeof jQuery != "undefined") {
window.open(url, "_blank");
jq('#hiddenFileName').val("");
jq.unblockUI();
document.location.reload(true);
document.location.reload();
});
jq(document).on("click", "#beginView:not(.disable)", function () {
@ -260,7 +260,7 @@ if (typeof jQuery != "undefined") {
window.open(url, "_blank");
jq('#hiddenFileName').val("");
jq.unblockUI();
document.location.reload(true);
document.location.reload();
});
jq(document).on("click", "#beginEmbedded:not(.disable)", function () {
@ -274,13 +274,13 @@ if (typeof jQuery != "undefined") {
});
jq(document).on("click", ".reload-page", function () {
setTimeout(function () { document.location.reload(true); }, 1000);
setTimeout(function () { document.location.reload(); }, 1000);
return true;
});
jq(document).on("mouseup", ".reload-page", function (event) {
if (event.which == 2) {
setTimeout(function () { document.location.reload(true); }, 1000);
setTimeout(function () { document.location.reload(); }, 1000);
}
return true;
});
@ -290,7 +290,7 @@ if (typeof jQuery != "undefined") {
jq("#embeddedView").attr("src", "");
jq.unblockUI();
if (mustReload) {
document.location.reload(true);
document.location.reload();
}
});
@ -305,7 +305,7 @@ if (typeof jQuery != "undefined") {
type: "get",
url: requestAddress,
complete: function (data) {
document.location.reload(true);
document.location.reload();
}
});
});

View File

@ -0,0 +1,46 @@
<?php
/**
*
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
require_once( dirname(__FILE__) . '/lib/jwt/BeforeValidException.php' );
require_once( dirname(__FILE__) . '/lib/jwt/ExpiredException.php' );
require_once( dirname(__FILE__) . '/lib/jwt/SignatureInvalidException.php' );
require_once( dirname(__FILE__) . '/lib/jwt/JWT.php' );
require_once( dirname(__FILE__) . '/config.php' );
// check if a secret key to generate token exists or not
function isJwtEnabled() {
return !empty($GLOBALS['DOC_SERV_JWT_SECRET']);
}
// encode a payload object into a token using a secret key
function jwtEncode($payload) {
return \Firebase\JWT\JWT::encode($payload, $GLOBALS["DOC_SERV_JWT_SECRET"]);
}
// decode a token into a payload object using a secret key
function jwtDecode($token) {
try {
$payload = \Firebase\JWT\JWT::decode($token, $GLOBALS["DOC_SERV_JWT_SECRET"], array("HS256"));
} catch (\UnexpectedValueException $e) {
$payload = "";
}
return $payload;
}
?>

View File

@ -25,9 +25,5 @@ License: MIT
License File: jQuery.UI.license
JWT - JSON Web Token implementation (https://github.com/firebase/php-jwt/blob/master/LICENSE)
License: BSD-3-Clause
License: BSD
License File: jwt.license
PHP_CodeSniffer - PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent. (https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt)
License: BSD-3-Clause
License File: PHP_CodeSniffer.license

Some files were not shown because too many files have changed in this diff Show More