Compare commits

..

1 Commits

Author SHA1 Message Date
1ac382d3c0 java-spring: https 2023-02-10 10:39:03 +03:00
123 changed files with 2949 additions and 4616 deletions

View File

@ -6,7 +6,7 @@ on:
branches: [master, main]
paths: ['web/documentserver-example/java/**']
pull_request:
branches: [master, main, develop]
branches: [master, main]
paths: ['web/documentserver-example/java/**']
jobs:

View File

@ -6,7 +6,7 @@ on:
branches: [master, main]
paths: ['web/documentserver-example/nodejs/**']
pull_request:
branches: [master, main, develop]
branches: [master, main]
paths: ['web/documentserver-example/nodejs/**']
env:

View File

@ -6,7 +6,7 @@ on:
branches: [master, main]
paths: ['web/documentserver-example/php/**']
pull_request:
branches: [master, main, develop]
branches: [master, main]
paths: ['web/documentserver-example/php/**']
jobs:

View File

@ -6,7 +6,7 @@ on:
branches: [master, main]
paths: ['web/documentserver-example/python/**']
pull_request:
branches: [master, main, develop]
branches: [master, main]
paths: ['web/documentserver-example/python/**']
jobs:

View File

@ -6,7 +6,7 @@ on:
branches: [master, main]
paths: ['web/documentserver-example/ruby/**']
pull_request:
branches: [master, main, develop]
branches: [master, main]
paths: ['web/documentserver-example/ruby/**']
jobs:

View File

@ -6,7 +6,7 @@ on:
branches: [master, main]
paths: ['web/documentserver-example/java-spring/**']
pull_request:
branches: [master, main, develop]
branches: [master, main]
paths: ['web/documentserver-example/java-spring/**']
jobs:

View File

@ -259,45 +259,6 @@ 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.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/ruby
byebug - Byebug is a Ruby debugger. (https://github.com/deivid-rodriguez/byebug/blob/master/LICENSE)

View File

@ -1,8 +1,5 @@
# Change Log
- referenceData
- anonymous can't protect file
- separate setting for checking the token in requests
- php: linter refactoring
## 1.5.0

View File

@ -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>

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

@ -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"];
@ -285,7 +285,7 @@ namespace OnlineEditorsExampleMVC.Helpers
}
// 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>
{

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

@ -138,17 +138,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 +154,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 }
}
}
}

View File

@ -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%";
@ -251,7 +239,6 @@
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
config.events['onRequestReferenceData'] = onRequestReferenceData;
}
if (config.editorConfig.createUrl) {

View File

@ -74,9 +74,6 @@ namespace OnlineEditorsExampleMVC
case "rename":
Rename(context);
break;
case "reference":
Reference(context);
break;
}
}
@ -464,7 +461,7 @@ namespace OnlineEditorsExampleMVC
var userAddress = context.Request["userAddress"];
var isEmbedded = context.Request["dmode"];
if (JwtManager.Enabled && isEmbedded == null && userAddress != null && JwtManager.SignatureUseForRequest)
if (JwtManager.Enabled && isEmbedded == null && userAddress != null)
{
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
@ -522,7 +519,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"];
@ -594,96 +591,5 @@ namespace OnlineEditorsExampleMVC
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

@ -6,16 +6,14 @@
<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.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 (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

@ -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%";
@ -255,7 +242,6 @@
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
config.events['onRequestReferenceData'] = onRequestReferenceData;
}
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

@ -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>

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"];
@ -288,7 +288,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>
{

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,7 +281,7 @@ 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 && userAddress != null)
{
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
@ -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,17 +6,15 @@
<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 (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

@ -35,6 +35,14 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>

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

@ -0,0 +1,37 @@
/**
*
* (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.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(final HttpSecurity http) throws Exception {
return http
.requiresChannel(channel -> channel.anyRequest().requiresSecure())
.authorizeRequests(authorize -> authorize.anyRequest().permitAll())
.build();
}
}

View File

@ -19,8 +19,6 @@
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;
@ -53,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;
@ -270,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,7 +289,7 @@ public class FileController {
@RequestParam(value = "userAddress", required = false) final String userAddress){
try {
// check if a token is enabled or not
if (jwtManager.tokenEnabled() && userAddress != null && jwtManager.tokenUseForRequest()) {
if (jwtManager.tokenEnabled() && userAddress != null) {
String header = request.getHeader(documentJwtHeader == null // get the document JWT header
|| documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader);
if (header != null && !header.isEmpty()) {
@ -449,71 +445,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

@ -211,8 +211,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

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

@ -18,7 +18,6 @@
package com.onlyoffice.integration.documentserver.models.filemodel;
import com.onlyoffice.integration.documentserver.managers.document.DocumentManager;
import com.onlyoffice.integration.documentserver.models.configurations.Info;
import lombok.Getter;
import lombok.Setter;
@ -26,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
@ -46,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,24 +0,0 @@
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

@ -155,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());

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,10 +18,8 @@
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.models.filemodel.ReferenceData;
import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
import com.onlyoffice.integration.services.configurers.DocumentConfigurer;
import com.onlyoffice.integration.services.configurers.wrappers.DefaultDocumentWrapper;
@ -33,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
@ -56,7 +52,6 @@ public class DefaultDocumentConfigurer implements DocumentConfigurer<DefaultDocu
final DefaultDocumentWrapper wrapper) { // define the document configurer
String fileName = wrapper.getFileName(); // get the fileName parameter from the document wrapper
Permission permission = wrapper.getPermission(); // get the permission parameter from the document wrapper
//ReferenceData referenceData = wrapper.getReferenceData();
document.setTitle(fileName); // set the title to the document config
@ -76,21 +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

@ -1,17 +1,21 @@
server.version=1.5.0
server.address=
server.port=4000
server.port=8443
server.ssl.key-store=classpath:springboot.p12
server.ssl.key-store-password=111111
server.ssl.key-alias=springboot
server.ssl.key-password=111111
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,7 +28,6 @@ files.docservice.url.example=
files.docservice.secret=
files.docservice.header=Authorization
files.docservice.token-use-for-request=true
files.docservice.verify-peer-off=true

View File

@ -160,18 +160,6 @@
}
};
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 = {
@ -223,7 +211,6 @@
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
config.events['onRequestReferenceData'] = onRequestReferenceData;
}
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;
}
@ -475,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");
@ -520,8 +517,7 @@ 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 && userAddress != null) {
String documentJwtHeader = ConfigManager.getProperty("files.docservice.header");
@ -637,87 +633,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

@ -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<>();
@ -303,7 +302,6 @@ public class FileModel {
private String key;
private Info info;
private Permissions permissions;
private ReferenceData referenceData;
public String getTitle() {
return title;
@ -356,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
@ -380,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
@ -401,25 +391,9 @@ public class FileModel {
reviewGroups = user.getReviewGroups();
commentGroups = user.getCommentGroups();
userInfoGroups = user.getUserInfoGroups();
protect = !user.getDeniedPermissions().contains("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;
}
}
// the Favorite icon state
public class Info {
private String owner = "Me";

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

@ -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());

View File

@ -87,7 +87,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
@ -388,8 +388,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

@ -3,10 +3,10 @@ version=1.5.0
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/
@ -20,6 +20,5 @@ files.docservice.languages=en:English|hy:Armenian|az:Azerbaijani|eu:Basque|be:Be
files.docservice.secret=
files.docservice.header=Authorization
files.docservice.token-use-for-request=TRUE
files.docservice.verify-peer-off=TRUE

View File

@ -161,18 +161,6 @@
}
};
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%";
@ -227,7 +215,6 @@
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
config.events['onRequestReferenceData'] = onRequestReferenceData;
}
if (config.editorConfig.createUrl) {

View File

@ -997,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,

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,

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"
];
@ -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) {

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

@ -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

@ -232,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;
}

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>

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

@ -15,12 +15,7 @@
* limitations under the License.
*/
namespace OnlineEditorsExamplePhp;
use Exception;
use OnlineEditorsExamplePhp\Helpers\ConfigManager;
use OnlineEditorsExamplePhp\Helpers\ExampleUsers;
use OnlineEditorsExamplePhp\Helpers\JwtManager;
require dirname(__FILE__) . '/config.php';
/**
* Check if the request is an AJAX request
@ -81,529 +76,3 @@ function nocacheHeaders()
@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 = trim(getInternalExtension($fileName), '.');
$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
$percent = getConvertedUri(
$fileUri,
$extension,
$internalExtension,
$key,
true,
$newFileUri,
$filePass,
$lang
);
} catch (Exception $e) {
$result["error"] = "error: " . $e->getMessage();
return $result;
}
if ($percent != 100) {
$result["step"] = $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 . "." . $internalExtension);
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,626 @@
<?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
*
* @param string $msg
* @param integer $logFileName
*
* @return void
*/
function sendlog($msg, $logFileName)
{
$logsFolder = "logs/";
if (!file_exists($logsFolder)) { // if log folder doesn't exist, make it
mkdir($logsFolder);
}
file_put_contents($logsFolder . $logFileName, $msg . PHP_EOL, FILE_APPEND);
}
/**
* Create new uuid
*
* @return string
*/
function guid()
{
if (function_exists('com_create_guid')) {
return com_create_guid();
}
mt_srand((float) microtime() * 10000); // optional for php 4.2.0 and up
$charid = mb_strtoupper(md5(uniqid(rand(), true)));
$hyphen = chr(45); // "-"
$uuid = chr(123) // "{"
.mb_substr($charid, 0, 8).$hyphen
.mb_substr($charid, 8, 4).$hyphen
.mb_substr($charid, 12, 4).$hyphen
.mb_substr($charid, 16, 4).$hyphen
.mb_substr($charid, 20, 12)
.chr(125); // "}"
return $uuid;
}
if (!function_exists('mime_content_type')) {
/**
* Create new uuid
*
* @param string $filename
*
* @return string
*/
function mime_content_type($filename)
{
$mime_types = [
'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 = mb_strtolower(array_pop(explode('.', $filename)));
if (array_key_exists($ext, $mime_types)) {
return $mime_types[$ext]; // get the mime type of this extension
} elseif (function_exists('finfo_open')) { // or get the mime type from the file information
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);
return $mimetype;
}
return 'application/octet-stream';
}
}
/**
* Get ip address
*
* @return string
*/
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
*
* @param string $forDocumentServer
*
* @return string
*/
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
*
* @param string $userAddress
*
* @return string
*/
function getCurUserHostAddress($userAddress = null)
{
if ($GLOBALS['ALONE']) {
if (empty($GLOBALS['STORAGE_PATH'])) {
return "Storage";
}
return "";
}
if (is_null($userAddress)) {
$userAddress = getClientIp();
}
return preg_replace("[^0-9a-zA-Z.=]", '_', $userAddress);
}
/**
* Get an internal file extension
*
* @param string $filename
*
* @return string
*/
function getInternalExtension($filename)
{
$ext = mb_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
*
* @param string $filename
*
* @return string
*/
function getTemplateImageUrl($filename)
{
$ext = mb_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
*
* @param string $filename
*
* @return string
*/
function getDocumentType($filename)
{
$ext = mb_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
*
* @return string
*/
function getScheme()
{
return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
}
/**
* Get the storage path of the given file
*
* @param string $fileName
* @param string $userAddress
*
* @return string
*/
function getStoragePath($fileName, $userAddress = null)
{
$storagePath = trim(str_replace(['/', '\\'], 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
*
* @param string $fileName
* @param string $userAddress
* @param bool $create
*
* @return string
*/
function getForcesavePath($fileName, $userAddress, $create)
{
$storagePath = trim(str_replace(['/', '\\'], 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
*
* @param string $storagePath
*
* @return string
*/
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
*
* @param string $histDir
* @param string $version
*
* @return string
*/
function getVersionDir($histDir, $version)
{
return $histDir . DIRECTORY_SEPARATOR . $version;
}
/**
* Get a number of the last file version from the history directory
*
* @param string $histDir
*
* @return int
*/
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, [".", ".."])) {
if (is_dir($histDir . DIRECTORY_SEPARATOR . $fileName)) {
$ver++;
}
}
}
return $ver;
}
/**
* Get all the stored files from the folder
*
* @return array
*/
function getStoredFiles()
{
$storagePath = trim(str_replace(['/', '\\'], 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 = [];
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 = [];
foreach ($cdir as $key => $fileName) { // run through all the file and folder names
if (!in_array($fileName, [".", ".."])) {
if (!is_dir($directory . DIRECTORY_SEPARATOR . $fileName)) { // if an element isn't a directory
$ext = mb_strtolower('.' . pathinfo($fileName, PATHINFO_EXTENSION));
$dat = filemtime($directory . DIRECTORY_SEPARATOR . $fileName); // get the time of element modification
$result[$dat] = (object) [ // 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
*
* @param string $forDocumentServer
*
* @return string
*/
function getVirtualPath($forDocumentServer)
{
$storagePath = trim(str_replace(['/', '\\'], '/', $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
*
* @param string $fileName
* @param string $uid
* @param string $uname
* @param string $userAddress
*
* @return void
*/
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
*
* @param string $file_name
* @param string $forDocumentServer
*
* @return string
*/
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
*
* @param string $fileId
*
* @return array|string
*/
function getFileInfo($fileId)
{
$storedFiles = getStoredFiles();
$result = [];
$resultID = [];
// run through all the stored files
foreach ($storedFiles as $key => $value) {
$result[$key] = (object) [ // 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;
}
return "File not found";
}
return $result;
}
/**
* Get all the supported file extensions
*
* @return array
*/
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
*
* @param string $fileName
* @param string $userAddress
*
* @return string
*/
function GetCorrectName($fileName, $userAddress = null)
{
$path_parts = pathinfo($fileName);
$ext = mb_strtolower($path_parts['extension']);
$name = $path_parts['basename'];
// get file name from the basename without extension
$baseNameWithoutExt = mb_substr($name, 0, mb_strlen($name) - mb_strlen($ext) - 1);
$name = $baseNameWithoutExt . "." . $ext;
// if a file with such a name already exists in this directory
for ($i = 1; file_exists(getStoragePath($name, $userAddress)); $i++) {
$name = $baseNameWithoutExt . " (" . $i . ")." . $ext; // add an index after its base name
}
return $name;
}
/**
* Get document key
*
* @param string $fileName
*
* @return string
*/
function getDocEditorKey($fileName)
{
// get document key by adding local file url to the current user host address
$key = getCurUserHostAddress() . fileUri($fileName);
$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,7 +1,6 @@
{
"require-dev": {
"squizlabs/php_codesniffer": "*",
"ext-mbstring": "*"
"squizlabs/php_codesniffer": "*"
},
"scripts": {
"code-sniffer": [
@ -14,13 +13,5 @@
"post-update-cmd": [
"@code-sniffer"
]
},
"autoload-dev": {
"psr-4": {
"OnlineEditorsExamplePhp\\" : "",
"OnlineEditorsExamplePhp\\Helpers\\" : "helpers/",
"OnlineEditorsExamplePhp\\Views\\" : "views/",
"Firebase\\JWT\\" : "lib/jwt/"
}
}
}

View File

@ -1,87 +0,0 @@
{
"version": "1.5.0",
"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 (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

@ -0,0 +1,108 @@
<?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.
*/
$GLOBALS['version'] = "1.5.0";
$GLOBALS['FILE_SIZE_MAX'] = 5242880;
$GLOBALS['STORAGE_PATH'] = "";
$GLOBALS['ALONE'] = false;
$GLOBALS['DOC_SERV_FILLFORMS'] = [".oform", ".docx"];
$GLOBALS['DOC_SERV_VIEWD'] = [".pdf", ".djvu", ".xps", ".oxps"];
$GLOBALS['DOC_SERV_EDITED'] = [".docx", ".xlsx", ".csv", ".pptx", ".txt", ".docxf"];
$GLOBALS['DOC_SERV_CONVERT'] = [".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'] = [".xls", ".xlsx", ".xlsm", ".xlsb",
".xlt", ".xltx", ".xltm",
".ods", ".fods", ".ots", ".csv"];
$GLOBALS['ExtsPresentation'] = [".pps", ".ppsx", ".ppsm",
".ppt", ".pptx", ".pptm",
".pot", ".potx", ".potm",
".odp", ".fodp", ".otp"];
$GLOBALS['ExtsDocument'] = [".doc", ".docx", ".docm",
".dot", ".dotx", ".dotm",
".odt", ".fodt", ".ott", ".rtf", ".txt",
".html", ".htm", ".mht", ".xml",
".pdf", ".djvu", ".fb2", ".epub", ".xps", ".oxps", ".oform"];
$GLOBALS['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',
];

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,4 +1,7 @@
<?php
namespace PhpExample;
/**
* (c) Copyright Ascensio System SIA 2023
*
@ -15,12 +18,684 @@
* limitations under the License.
*/
namespace OnlineEditorsExamplePhp;
use OnlineEditorsExamplePhp\Views\DocEditorView;
require_once dirname(__FILE__) . '/config.php';
require_once dirname(__FILE__) . '/common.php';
require_once dirname(__FILE__) . '/functions.php';
require_once dirname(__FILE__) . '/vendor/autoload.php';
require_once dirname(__FILE__) . '/jwtmanager.php';
require_once dirname(__FILE__) . '/users.php';
$docEditorView = new DocEditorView($_REQUEST);
$docEditorView->render();
$user = getUser($_GET["user"]);
$isEnableDirectUrl = isset($_GET["directUrl"]) ? filter_var($_GET["directUrl"], FILTER_VALIDATE_BOOLEAN) : false;
// get the file url and upload it
$externalUrl = $_GET["fileUrl"] ?? "";
if (!empty($externalUrl)) {
$filename = doUpload($externalUrl);
} else { // if the file url doesn't exist, get file name and file extension
$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 = mb_strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$ext = mb_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;
}
// check if the Submit form button is displayed or not
$submitForm = $editorsMode == "fillForms" && $user->id == "uid-1" && !1;
$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 = [
[
"image" => "",
"title" => "Blank",
"url" => $createUrl,
],
[
"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
// the absolute URL that will allow the document to be saved onto the user personal computer
"saveUrl" => $directUrl,
// the absolute URL to the document serving as a source file for the document embedded into the web page
"embedUrl" => $directUrl,
// the absolute URL that will allow other users to share this document
"shareUrl" => $directUrl,
"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
// adds the request for the forced file saving to the callback handler when saving the document
"forcesave" => false,
"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
// the absolute URL to the website address which will be opened
// when clicking the Open file location menu button
"url" => serverPath(),
],
],
],
];
// 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
// encode the dataMailMergeRecipients object into the token
$dataMailMergeRecipients["token"] = jwtEncode($dataMailMergeRecipients);
}
/**
* Get demo file name by the extension
*
* @param string $createExt
* @param string $user
*
* @return string
*/
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
*
* @param string $fileName
*
* @return string
*/
function getCallbackUrl($fileName)
{
return serverPath(true) . '/'
. "webeditor-ajax.php"
. "?type=track"
. "&fileName=" . urlencode($fileName)
. "&userAddress=" . getClientIp();
}
/**
* Get url to the created file
*
* @param string $fileName
* @param string $uid
* @param string $type
*
* @return string
*/
function getCreateUrl($fileName, $uid, $type)
{
$ext = trim(getInternalExtension($fileName), '.');
return serverPath(false) . '/'
. "doceditor.php"
. "?fileExt=" . $ext
. "&user=" . $uid
. "&type=" . $type;
}
/**
* Get url for history download
*
* @param string $fileName
* @param string $version
* @param string $file
* @param bool $isServer
*
* @return string
*/
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
*
* @param string $fileName
* @param bool $isServer
*
* @return string
*/
function getDownloadUrl($fileName, $isServer = true)
{
$userAddress = $isServer ? "&userAddress=" . getClientIp() : "";
return serverPath($isServer) . '/'
. "webeditor-ajax.php"
. "?type=download"
. "&fileName=" . urlencode($fileName)
. $userAddress;
}
/**
* Get document history
*
* @param string $filename
* @param string $filetype
* @param string $docKey
* @param string $fileuri
* @param bool $isEnableDirectUrl
*
* @return array
*/
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
// get document key
$key = $i == $curVer ? $docKey : file_get_contents($verDir . DIRECTORY_SEPARATOR . "key.txt");
$obj["key"] = $key;
$obj["version"] = $i;
if ($i == 1) { // check if the version number is equal to 1
// get meta data of this file
$createdInfo = file_get_contents($histDir . DIRECTORY_SEPARATOR . "createdInfo.json");
$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 = mb_strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$prevFileName = $verDir . DIRECTORY_SEPARATOR . "prev." . $filetype;
$prevFileName = mb_substr($prevFileName, mb_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];
// write information about changes to the object
$obj["changes"] = $changes ? $changes["changes"] : null;
$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
// write information about previous file version to the data object
$dataObj["previous"] = $isEnableDirectUrl ? [
"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);
}
$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);
// set the link to the document which contains a bookmark
docEditor.setActionLink(replaceActionLink(location.href, linkParam));
};
// 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,
mb_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) {
// insert recipient data for mail merge into the file
docEditor.setMailMergeRecipients(<?php echo json_encode($dataMailMergeRecipients) ?>);
};
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 () {
// show the document version history
docEditor.refreshHistory(<?php echo json_encode($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) ?>;
// send the link to the document for viewing the version history
docEditor.setHistoryData(histData[ver - 1]);
};
// the user is trying to go back to the document from viewing the document version history
config.events['onRequestHistoryClose'] = function () {
document.location.reload();
};
<?php } ?>
// 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 } ?>
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>

View File

@ -15,568 +15,8 @@
* limitations under the License.
*/
namespace OnlineEditorsExamplePhp;
use Exception;
use OnlineEditorsExamplePhp\Helpers\ConfigManager;
use OnlineEditorsExamplePhp\Helpers\ExampleUsers;
use OnlineEditorsExamplePhp\Helpers\JwtManager;
use OnlineEditorsExamplePhp\Helpers\Users;
/**
* Put log files into the log folder
*
* @param string $msg
* @param integer $logFileName
*
* @return void
*/
function sendlog($msg, $logFileName)
{
$logsFolder = "logs/";
if (!file_exists($logsFolder)) { // if log folder doesn't exist, make it
mkdir($logsFolder);
}
file_put_contents($logsFolder . $logFileName, $msg . PHP_EOL, FILE_APPEND);
}
/**
* Create new uuid
*
* @return string
*/
function guid()
{
if (function_exists('com_create_guid')) {
return com_create_guid();
}
mt_srand((float) microtime() * 10000); // optional for php 4.2.0 and up
$charid = mb_strtoupper(md5(uniqid(rand(), true)));
$hyphen = chr(45); // "-"
$uuid = chr(123) // "{"
.mb_substr($charid, 0, 8).$hyphen
.mb_substr($charid, 8, 4).$hyphen
.mb_substr($charid, 12, 4).$hyphen
.mb_substr($charid, 16, 4).$hyphen
.mb_substr($charid, 20, 12)
.chr(125); // "}"
return $uuid;
}
/**
* Get ip address
*
* @return string
*/
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
*
* @param string $forDocumentServer
*
* @return string
*/
function serverPath($forDocumentServer = null)
{
$configManager = new ConfigManager();
return $forDocumentServer && $configManager->getConfig("storagePath") != null
&& $configManager->getConfig("exampleUrl") != ""
? $configManager->getConfig("exampleUrl")
: (getScheme() . '://' . $_SERVER['HTTP_HOST']);
}
/**
* Get current user host address
*
* @param string $userAddress
*
* @return string
*/
function getCurUserHostAddress($userAddress = null)
{
$configManager = new ConfigManager();
if ($configManager->getConfig("alone")) {
if (empty($configManager->getConfig("storagePath"))) {
return "Storage";
}
return "";
}
if (is_null($userAddress)) {
$userAddress = getClientIp();
}
return preg_replace("[^0-9a-zA-Z.=]", '_', $userAddress);
}
/**
* Get an internal file extension
*
* @param string $filename
*
* @return string
*/
function getInternalExtension($filename)
{
$ext = mb_strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION));
$configManager = new ConfigManager();
if (in_array($ext, $configManager->getConfig("extsDocument"))) {
return ".docx";
} // .docx for text document extensions
if (in_array($ext, $configManager->getConfig("extsSpreadsheet"))) {
return ".xlsx";
} // .xlsx for spreadsheet extensions
if (in_array($ext, $configManager->getConfig("extsPresentation"))) {
return ".pptx";
} // .pptx for presentation extensions
return "";
}
/**
* Get image url for templates
*
* @param string $filename
*
* @return string
*/
function getTemplateImageUrl($filename)
{
$ext = mb_strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION));
$path = serverPath(true) . "/css/images/";
$configManager = new ConfigManager();
if (in_array($ext, $configManager->getConfig("extsDocument"))) {
return $path . "file_docx.svg";
} // for text document extensions
if (in_array($ext, $configManager->getConfig("extsSpreadsheet"))) {
return $path . "file_xlsx.svg";
} // for spreadsheet extensions
if (in_array($ext, $configManager->getConfig("extsPresentation"))) {
return $path . "file_pptx.svg";
} // for presentation extensions
return $path . "file_docx.svg";
}
/**
* Get the document type
*
* @param string $filename
*
* @return string
*/
function getDocumentType($filename)
{
$ext = mb_strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION));
$configManager = new ConfigManager();
if (in_array($ext, $configManager->getConfig("extsDocument"))) {
return "word";
} // word for text document extensions
if (in_array($ext, $configManager->getConfig("extsSpreadsheet"))) {
return "cell";
} // cell for spreadsheet extensions
if (in_array($ext, $configManager->getConfig("extsPresentation"))) {
return "slide";
} // slide for presentation extensions
return "word";
}
/**
* Get the protocol
*
* @return string
*/
function getScheme()
{
return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
}
/**
* Get the storage path of the given file
*
* @param string $fileName
* @param string $userAddress
*
* @return string
*/
function getStoragePath($fileName, $userAddress = null)
{
$configManager = new ConfigManager();
$storagePath = trim(
str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $configManager->getConfig("storagePath")),
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
*
* @param string $fileName
* @param string $userAddress
* @param bool $create
*
* @return string
*/
function getForcesavePath($fileName, $userAddress, $create)
{
$configManager = new ConfigManager();
$storagePath = trim(
str_replace(
['/', '\\'],
DIRECTORY_SEPARATOR,
$configManager->getConfig("storagePath")
),
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
*
* @param string $storagePath
*
* @return string
*/
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
*
* @param string $histDir
* @param string $version
*
* @return string
*/
function getVersionDir($histDir, $version)
{
return $histDir . DIRECTORY_SEPARATOR . $version;
}
/**
* Get a number of the last file version from the history directory
*
* @param string $histDir
*
* @return int
*/
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, [".", ".."])) {
if (is_dir($histDir . DIRECTORY_SEPARATOR . $fileName)) {
$ver++;
}
}
}
return $ver;
}
/**
* Get all the stored files from the folder
*
* @return array
*/
function getStoredFiles()
{
$configManager = new ConfigManager();
$storagePath = trim(str_replace(
['/', '\\'],
DIRECTORY_SEPARATOR,
$configManager->getConfig("storagePath")
), 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 = [];
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 = [];
foreach ($cdir as $key => $fileName) { // run through all the file and folder names
if (!in_array($fileName, [".", ".."])) {
if (!is_dir($directory . DIRECTORY_SEPARATOR . $fileName)) { // if an element isn't a directory
$ext = mb_strtolower('.' . pathinfo($fileName, PATHINFO_EXTENSION));
$dat = filemtime($directory . DIRECTORY_SEPARATOR . $fileName); // get the time of element modification
$result[$dat] = (object) [ // and write the file to the result
"name" => $fileName,
"documentType" => getDocumentType($fileName),
"canEdit" => in_array($ext, $configManager->getConfig("docServEdited")),
"isFillFormDoc" => in_array($ext, $configManager->getConfig("docServFillforms")),
];
}
}
}
ksort($result); // sort files by the modification date
return array_reverse($result);
}
/**
* Get the virtual path
*
* @param string $forDocumentServer
*
* @return string
*/
function getVirtualPath($forDocumentServer)
{
$configManager = new ConfigManager();
$storagePath = trim(str_replace(
['/', '\\'],
'/',
$configManager->getConfig("storagePath")
), '/');
$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
*
* @param string $fileName
* @param string $uid
* @param string $uname
* @param string $userAddress
*
* @return void
*/
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
*
* @param string $file_name
* @param string $forDocumentServer
*
* @return string
*/
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
*
* @param string $fileId
*
* @return array|string
*/
function getFileInfo($fileId)
{
$storedFiles = getStoredFiles();
$result = [];
$resultID = [];
// run through all the stored files
foreach ($storedFiles as $key => $value) {
$result[$key] = (object) [ // 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;
}
return "File not found";
}
return $result;
}
/**
* Get all the supported file extensions
*
* @return array
*/
function getFileExts()
{
$configManager = new ConfigManager();
return array_merge(
$configManager->getConfig("docServViewd"),
$configManager->getConfig("docServEdited"),
$configManager->getConfig("docServConvert"),
$configManager->getConfig("docServFillforms")
);
}
/**
* Get the correct file name if such a name already exists
*
* @param string $fileName
* @param string $userAddress
*
* @return string
*/
function GetCorrectName($fileName, $userAddress = null)
{
$path_parts = pathinfo($fileName);
$ext = mb_strtolower($path_parts['extension']);
$name = $path_parts['basename'];
// get file name from the basename without extension
$baseNameWithoutExt = mb_substr($name, 0, mb_strlen($name) - mb_strlen($ext) - 1);
$name = $baseNameWithoutExt . "." . $ext;
// if a file with such a name already exists in this directory
for ($i = 1; file_exists(getStoragePath($name, $userAddress)); $i++) {
$name = $baseNameWithoutExt . " (" . $i . ")." . $ext; // add an index after its base name
}
return $name;
}
/**
* Get document key
*
* @param string $fileName
*
* @return string
*/
function getDocEditorKey($fileName)
{
// get document key by adding local file url to the current user host address
$key = getCurUserHostAddress() . fileUri($fileName);
$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
}
require_once dirname(__FILE__) . '/config.php';
require_once dirname(__FILE__) . '/jwtmanager.php';
/**
* File uploading
@ -714,9 +154,7 @@ function sendRequestToConvertService(
// generate document token
$document_revision_id = generateRevisionId($document_revision_id);
$configManager = new ConfigManager();
$urlToConverter = $configManager->getConfig("docServSiteUrl").
$configManager->getConfig("docServConverterUrl");
$urlToConverter = $GLOBALS['DOC_SERV_SITE_URL'].$GLOBALS['DOC_SERV_CONVERTER_URL'];
$arr = [
"async" => $is_async,
@ -731,13 +169,11 @@ function sendRequestToConvertService(
// add header token
$headerToken = "";
$jwtHeader = $configManager->getConfig("docServJwtHeader") ==
"" ? "Authorization" : $configManager->getConfig("docServJwtHeader");
$jwtHeader = $GLOBALS['DOC_SERV_JWT_HEADER'] == "" ? "Authorization" : $GLOBALS['DOC_SERV_JWT_HEADER'];
$jwtManager = new JwtManager();
if ($jwtManager->isJwtEnabled() && $jwtManager->tokenUseForRequest()) {
$headerToken = $jwtManager->jwtEncode(["payload" => $arr]);
$arr["token"] = $jwtManager->jwtEncode($arr);
if (isJwtEnabled()) {
$headerToken = jwtEncode(["payload" => $arr]);
$arr["token"] = jwtEncode($arr);
}
$data = json_encode($arr);
@ -745,7 +181,7 @@ function sendRequestToConvertService(
// request parameters
$opts = ['http' => [
'method' => 'POST',
'timeout' => $configManager->getConfig("docServTimeout"),
'timeout' => $GLOBALS['DOC_SERV_TIMEOUT'],
'header' => "Content-type: application/json\r\n" .
"Accept: application/json\r\n" .
(empty($headerToken) ? "" : $jwtHeader.": Bearer $headerToken\r\n"),
@ -754,7 +190,7 @@ function sendRequestToConvertService(
];
if (mb_substr($urlToConverter, 0, mb_strlen("https")) === "https") {
if ($configManager->getConfig("docServVerifyPeerOff") === true) {
if ($GLOBALS['DOC_SERV_VERIFY_PEER_OFF'] === true) {
$opts['ssl'] = ['verify_peer' => false, 'verify_peer_name' => false];
}
}
@ -882,224 +318,3 @@ function getResponseUri($document_response, &$response_uri)
return $resultPercent;
}
/**
* Get demo file name by the extension
*
* @param string $createExt
* @param Users $user
*
* @return string
*/
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
*
* @param string $fileName
*
* @return string
*/
function getCallbackUrl($fileName)
{
return serverPath(true) . '/'
. "webeditor-ajax.php"
. "?type=track"
. "&fileName=" . urlencode($fileName)
. "&userAddress=" . getClientIp();
}
/**
* Get url to the created file
*
* @param string $fileName
* @param string $uid
* @param string $type
*
* @return string
*/
function getCreateUrl($fileName, $uid, $type)
{
$ext = trim(getInternalExtension($fileName), '.');
return serverPath(false) . '/'
. "doceditor.php"
. "?fileExt=" . $ext
. "&user=" . $uid
. "&type=" . $type;
}
/**
* Get url for history download
*
* @param string $fileName
* @param string $version
* @param string $file
* @param bool $isServer
*
* @return string
*/
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
*
* @param string $fileName
* @param bool $isServer
*
* @return string
*/
function getDownloadUrl($fileName, $isServer = true)
{
$userAddress = $isServer ? "&userAddress=" . getClientIp() : "";
return serverPath($isServer) . '/'
. "webeditor-ajax.php"
. "?type=download"
. "&fileName=" . urlencode($fileName)
. $userAddress;
}
/**
* Get document history
*
* @param string $filename
* @param string $filetype
* @param string $docKey
* @param string $fileuri
* @param bool $isEnableDirectUrl
*
* @return array
*/
function getHistory($filename, $filetype, $docKey, $fileuri, $isEnableDirectUrl)
{
$configManager = new ConfigManager();
$storagePath = $configManager->getConfig("storagePath");
$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
// get document key
$key = $i == $curVer ? $docKey : file_get_contents($verDir . DIRECTORY_SEPARATOR . "key.txt");
$obj["key"] = $key;
$obj["version"] = $i;
if ($i == 1) { // check if the version number is equal to 1
// get meta data of this file
$createdInfo = file_get_contents($histDir . DIRECTORY_SEPARATOR . "createdInfo.json");
$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 = mb_strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$prevFileName = $verDir . DIRECTORY_SEPARATOR . "prev." . $filetype;
$prevFileName = mb_substr($prevFileName, mb_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];
// write information about changes to the object
$obj["changes"] = $changes ? $changes["changes"] : null;
$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
// write information about previous file version to the data object
$dataObj["previous"] = $isEnableDirectUrl ? [
"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");
}
$jwtManager = new JwtManager();
if ($jwtManager->isJwtEnabled()) {
$dataObj["token"] = $jwtManager->jwtEncode($dataObj);
}
$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;
}
}

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,4 +1,7 @@
<?php
namespace PhpExample;
/**
* (c) Copyright Ascensio System SIA 2023
*
@ -15,12 +18,529 @@
* limitations under the License.
*/
namespace OnlineEditorsExamplePhp;
use OnlineEditorsExamplePhp\Views\IndexView;
require_once dirname(__FILE__) . '/config.php';
require_once dirname(__FILE__) . '/common.php';
require_once dirname(__FILE__) . '/functions.php';
require_once dirname(__FILE__) . '/vendor/autoload.php';
require_once dirname(__FILE__) . '/users.php';
$indexView = new IndexView($_REQUEST);
$indexView->render();
$user = $_GET["user"] ?? "";
$directUrlArg = isset($_GET["directUrl"]) ? "&directUrl=" . $_GET["directUrl"] : "";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<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 ?: "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 } ?>
<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 ?: "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>';
} elseif ($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> ';
}
} elseif ($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-1.9.0.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,62 @@
<?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.
*
* @return bool
*/
function isJwtEnabled()
{
return !empty($GLOBALS['DOC_SERV_JWT_SECRET']);
}
/**
* Encode a payload object into a token using a secret key
*
* @param array $payload
*
* @return string
*/
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
*
* @param string $token
*
* @return string
*/
function jwtDecode($token)
{
try {
$payload = \Firebase\JWT\JWT::decode($token, $GLOBALS["DOC_SERV_JWT_SECRET"], ["HS256"]);
} catch (\UnexpectedValueException $e) {
$payload = "";
}
return $payload;
}

View File

@ -2,6 +2,10 @@
<ruleset name="CustomRuleset">
<description>This standard changes the line length</description>
<rule ref="PSR1">
<exclude name="PSR1.Files.SideEffects" />
</rule>
<!-- Insert all sniff from PSR2 standard -->
<rule ref="PSR2"/>

View File

@ -1,243 +0,0 @@
<!DOCTYPE html>
<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/{docType}.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="{apiUrl}">
</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;
};
var onRequestReferenceData = function(event) { // user refresh external data source
innerAlert("onRequestReferenceData: " + JSON.stringify(event.data));
event.data.directUrl = !!config.document.directUrl;
let xhr = new XMLHttpRequest();
xhr.open("POST", "webeditor-ajax.php?type=reference");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(event.data));
xhr.onload = function () {
innerAlert(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
docEditor.setReferenceData(JSON.parse(xhr.responseText));
}
};
// 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);
// set the link to the document which contains a bookmark
docEditor.setActionLink(replaceActionLink(location.href, linkParam));
};
// 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,
{dataInsertImage}
})
};
// the user is trying to select document for comparing by clicking the Document from Storage button
var onRequestCompareFile = function() {
docEditor.setRevisedFile({dataCompareFile}); // select a document for comparing
};
// the user is trying to select recipients data by clicking the Mail merge button
var onRequestMailMergeRecipients = function (event) {
// insert recipient data for mail merge into the file
docEditor.setMailMergeRecipients({dataMailMergeRecipients});
};
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 () {
{fileNotFoundAlert}
config = {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,
'onRequestReferenceData': onRequestReferenceData,
};
{history}
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>

View File

@ -1,219 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<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={user}">Document</a>
</li>
<li>
<a class="try-editor cell reload-page" target="_blank"
href="doceditor.php?fileExt=xlsx&user={user}">Spreadsheet</a>
</li>
<li>
<a class="try-editor slide reload-page" target="_blank"
href="doceditor.php?fileExt=pptx&user={user}">Presentation</a>
</li>
<li>
<a class="try-editor form reload-page" target="_blank"
href="doceditor.php?fileExt=docxf&user={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={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">
{userOpts}
</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">
{langs}
</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">
<div id="portal-info" style="display: {portalInfoDisplay}">
<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>
{userDescr}
</div>
{storedList}
</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">
{editButton}
<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="{dataDocs}"></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 {date}. All rights reserved.
</td>
</tr>
</tbody>
</table>
</div>
</footer>
</form>
<script type="text/javascript" src="js/jquery-1.9.0.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 = '{docServFillforms}';
var ConverExtList = '{converExtList}';
var EditedExtList = '{editedExtList}';
</script>
</body>
</html>

View File

@ -1,32 +0,0 @@
<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>
{fileListTable}
</tbody>
</table>
</div>
</div>

View File

@ -15,11 +15,9 @@
* limitations under the License.
*/
namespace OnlineEditorsExamplePhp;
use Exception;
use OnlineEditorsExamplePhp\Helpers\ConfigManager;
use OnlineEditorsExamplePhp\Helpers\JwtManager;
require_once dirname(__FILE__) . '/jwtmanager.php';
require_once dirname(__FILE__) . '/common.php';
require_once dirname(__FILE__) . '/config.php';
/**
* Read request body
@ -29,8 +27,7 @@ use OnlineEditorsExamplePhp\Helpers\JwtManager;
function readBody()
{
$result["error"] = 0;
$configManager = new ConfigManager();
$jwtManager = new JwtManager();
// get the body of the post request and check if it is correct
if (($body_stream = file_get_contents('php://input')) === false) {
$result["error"] = "Bad Request";
@ -48,19 +45,18 @@ function readBody()
sendlog(" InputStream data: " . serialize($data), "webedior-ajax.log");
// check if the document token is enabled
if ($jwtManager->isJwtEnabled() && $jwtManager->tokenUseForRequest()) {
if (isJwtEnabled()) {
sendlog(" jwt enabled, checking tokens", "webedior-ajax.log");
$inHeader = false;
$data = "";
$jwtHeader = $configManager->getConfig("docServJwtHeader") ==
"" ? "Authorization" : $configManager->getConfig("docServJwtHeader");
$jwtHeader = $GLOBALS['DOC_SERV_JWT_HEADER'] == "" ? "Authorization" : $GLOBALS['DOC_SERV_JWT_HEADER'];
if (!empty($data["token"])) { // if the document token is in the data
$data = $jwtManager->jwtDecode($data["token"]); // decode it
$data = jwtDecode($data["token"]); // decode it
sendlog(" jwt in body", "webedior-ajax.log");
} elseif (!empty(apache_request_headers()[$jwtHeader])) { // if the Authorization header exists
$data = $jwtManager->jwtDecode(
$data = jwtDecode(
mb_substr(
apache_request_headers()[$jwtHeader],
mb_strlen("Bearer ")
@ -116,7 +112,7 @@ function processSave($data, $fileName, $userAddress)
try {
sendlog(" Convert " . $downloadUri . " from " . $downloadExt . " to " . $curExt, "webedior-ajax.log");
// convert file and give url to a new file
$convertedUri; // convert file and give url to a new file
$percent = getConvertedUri($downloadUri, $downloadExt, $curExt, $key, false, $convertedUri);
if (!empty($convertedUri)) {
$downloadUri = $convertedUri;
@ -219,7 +215,7 @@ function processForceSave($data, $fileName, $userAddress)
try {
sendlog(" Convert " . $downloadUri . " from " . $downloadExt . " to " . $curExt, "webedior-ajax.log");
// convert file and give url to a new file
$convertedUri; // convert file and give url to a new file
$percent = getConvertedUri($downloadUri, $downloadExt, $curExt, $key, false, $convertedUri);
if (!empty($convertedUri)) {
$downloadUri = $convertedUri;
@ -290,10 +286,7 @@ function processForceSave($data, $fileName, $userAddress)
*/
function commandRequest($method, $key, $meta = null)
{
$configManager = new ConfigManager();
$jwtManager = new JwtManager();
$documentCommandUrl = $configManager->getConfig("docServSiteUrl").
$configManager->getConfig("docServCommandUrl");
$documentCommandUrl = $GLOBALS['DOC_SERV_SITE_URL'].$GLOBALS['DOC_SERV_COMMAND_URL'];
$arr = [
"c" => $method,
@ -305,13 +298,11 @@ function commandRequest($method, $key, $meta = null)
}
$headerToken = "";
$jwtHeader = $configManager->getConfig("docServJwtHeader") == "" ? "Authorization" :
$configManager->getConfig("docServJwtHeader");
$jwtHeader = $GLOBALS['DOC_SERV_JWT_HEADER'] == "" ? "Authorization" : $GLOBALS['DOC_SERV_JWT_HEADER'];
// check if a secret key to generate token exists or not
if ($jwtManager->isJwtEnabled() && $jwtManager->tokenUseForRequest()) {
$headerToken = $jwtManager->jwtEncode(["payload" => $arr]); // encode a payload object into a header token
$arr["token"] = $jwtManager->jwtEncode($arr); // encode a payload object into a body token
if (isJwtEnabled()) { // check if a secret key to generate token exists or not
$headerToken = jwtEncode(["payload" => $arr]); // encode a payload object into a header token
$arr["token"] = jwtEncode($arr); // encode a payload object into a body token
}
$data = json_encode($arr);
@ -326,7 +317,7 @@ function commandRequest($method, $key, $meta = null)
]];
if (mb_substr($documentCommandUrl, 0, mb_strlen("https")) === "https") {
if ($configManager->getConfig("docServVerifyPeerOff") === true) {
if ($GLOBALS['DOC_SERV_VERIFY_PEER_OFF'] === true) {
$opts['ssl'] = ['verify_peer' => false, 'verify_peer_name' => false];
}
}

View File

@ -0,0 +1,226 @@
<?php
namespace PhpExample;
/**
* (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 User
{
/**
* Constructor
*
* @param string $id
* @param string $name
* @param string $email
* @param string $group
* @param array|null $reviewGroups
* @param array $commentGroups
* @param array|null $userInfoGroups
* @param bool|null $favorite
* @param array $deniedPermissions
* @param array $descriptions
* @param bool $templates
*
* @return void
*/
public function __construct(
$id,
$name,
$email,
$group,
$reviewGroups,
$commentGroups,
$userInfoGroups,
$favorite,
$deniedPermissions,
$descriptions,
$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;
}
}
$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",
];
$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",
];
$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",
];
$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",
];
$users = [
new User(
"uid-1",
"John Smith",
"smith@example.com",
"",
null,
[],
null,
null,
[],
$descr_user_1,
true
),
new User(
"uid-2",
"Mark Pottato",
"pottato@example.com",
"group-2",
["group-2", ""],
[
"view" => "",
"edit" => ["group-2", ""],
"remove" => ["group-2"],
],
["group-2", ""],
true,
[],
$descr_user_2,
false
),
new User(
"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"],
$descr_user_3,
false
),
new User(
"uid-0",
null,
null,
"",
null,
[],
[],
null,
[],
$descr_user_0,
false
),
];
/**
* Get a list of all the users
*
* @return array
*/
function getAllUsers()
{
global $users;
return $users;
}
/**
* Get a user by id specified
*
* @param string $id
*
* @return array
*/
function getUser($id)
{
global $users;
foreach ($users as $user) {
if ($user->id == $id) {
sendlog("User ". $user->id, "common.log");
return $user;
}
}
return $users[0];
}
/**
* Get a list of users with their names and emails for mentions
*
* @param string $id
*
* @return array
*/
function getUsersForMentions($id)
{
global $users;
$usersData = [];
foreach ($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,280 +0,0 @@
<?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.
*/
namespace OnlineEditorsExamplePhp\Views;
use OnlineEditorsExamplePhp\Helpers\ConfigManager;
use OnlineEditorsExamplePhp\Helpers\ExampleUsers;
use OnlineEditorsExamplePhp\Helpers\JwtManager;
use function OnlineEditorsExamplePhp\doUpload;
use function OnlineEditorsExamplePhp\fileUri;
use function OnlineEditorsExamplePhp\getCallbackUrl;
use function OnlineEditorsExamplePhp\getCreateUrl;
use function OnlineEditorsExamplePhp\getDocEditorKey;
use function OnlineEditorsExamplePhp\getDocumentType;
use function OnlineEditorsExamplePhp\getDownloadUrl;
use function OnlineEditorsExamplePhp\getHistory;
use function OnlineEditorsExamplePhp\getStoragePath;
use function OnlineEditorsExamplePhp\getTemplateImageUrl;
use function OnlineEditorsExamplePhp\serverPath;
use function OnlineEditorsExamplePhp\tryGetDefaultByType;
use function OnlineEditorsExamplePhp\getCurUserHostAddress;
final class DocEditorView extends View
{
public function __construct($request, $tempName = "docEditor")
{
parent::__construct($tempName);
$externalUrl = $request["fileUrl"] ?? "";
$confgManager = new ConfigManager();
$jwtManager = new JwtManager();
$userList = new ExampleUsers();
$user = $userList->getUser($request["user"]);
$isEnableDirectUrl = isset($request["directUrl"]) ? filter_var($request["directUrl"], FILTER_VALIDATE_BOOLEAN)
: false;
if (!empty($externalUrl)) {
$filename = doUpload($externalUrl);
} else { // if the file url doesn't exist, get file name and file extension
$filename = basename($request["fileID"]);
}
$createExt = $request["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=" . $request["user"];
header('Location: ' . $new_url, true);
exit;
}
$fileuri = fileUri($filename, true);
$fileuriUser = realpath($confgManager->getConfig("storagePath")) ===
$confgManager->getConfig("storagePath") ?
getDownloadUrl($filename) . "&dmode=emb" : fileUri($filename);
$directUrl = getDownloadUrl($filename, false);
$docKey = getDocEditorKey($filename);
$filetype = mb_strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$ext = mb_strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION));
$editorsMode = empty($request["action"]) ? "edit" : $request["action"]; // get the editors mode
$canEdit = in_array($ext, $confgManager->getConfig("docServEdited")); // check if the file can be edited
if ((!$canEdit && $editorsMode == "edit"
|| $editorsMode == "fillForms")
&& in_array($ext, $confgManager->getConfig("docServFillforms"))
) {
$editorsMode = "fillForms";
$canEdit = true;
}
// check if the Submit form button is displayed or not
$submitForm = $editorsMode == "fillForms" && $user->id == "uid-1" && !1;
$mode = $canEdit && $editorsMode != "view" ? "edit" : "view"; // define if the editing mode is edit or view
$type = empty($request["type"]) ? "desktop" : $request["type"];
$templatesImageUrl = getTemplateImageUrl($filename); // templates image url in the "From Template" section
$createUrl = getCreateUrl($filename, $user->id, $type);
$templates = [
[
"image" => "",
"title" => "Blank",
"url" => $createUrl,
],
[
"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,
"protect" => !in_array("protect", $user->deniedPermissions),
],
"referenceData" => [
"fileKey" => $user->id != "uid-0" ? json_encode([
"fileName" => $filename,
"userAddress" => getCurUserHostAddress()
]) : null,
"instanceId" => serverPath(),
],
],
"editorConfig" => [
"actionLink" => empty($request["actionLink"]) ? null : json_decode($request["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
// the absolute URL that will allow the document to be saved onto the user personal computer
"saveUrl" => $directUrl,
// the absolute URL to the document serving as a source file for the document embedded into
// the web page
"embedUrl" => $directUrl,
// the absolute URL that will allow other users to share this document
"shareUrl" => $directUrl,
"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
// adds the request for the forced file saving to the callback handler when saving the document
"forcesave" => false,
"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
// the absolute URL to the website address which will be opened
// when clicking the Open file location menu button
"url" => serverPath(),
],
],
],
];
// 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" ? $userList->getUsersForMentions($user->id) : null;
// check if the secret key to generate token exists
if ($jwtManager->isJwtEnabled()) {
$config["token"] = $jwtManager->jwtEncode($config); // encode config into the token
// encode the dataInsertImage object into the token
$dataInsertImage["token"] = $jwtManager->jwtEncode($dataInsertImage);
// encode the dataCompareFile object into the token
$dataCompareFile["token"] = $jwtManager->jwtEncode($dataCompareFile);
// encode the dataMailMergeRecipients object into the token
$dataMailMergeRecipients["token"] = $jwtManager->jwtEncode($dataMailMergeRecipients);
}
$out = getHistory($filename, $filetype, $docKey, $fileuri, $isEnableDirectUrl);
$history = $out[0];
$historyData = $out[1];
$historyLayout = "";
if ($user->id != "uid-0") {
if ($history != null && $historyData != null) {
$historyLayout .= " config.events['onRequestHistory'] = function () {
// show the document version history
docEditor.refreshHistory(".json_encode($history).");};";
$historyLayout .= " config.events['onRequestHistoryData'] = function (event) {
var ver = event.data;
var histData = ".json_encode($historyData).";".
"docEditor.setHistoryData(histData[ver - 1]);};
config.events['onRequestHistoryClose'] = function () {
document.location.reload();
};";
}
$historyLayout .= "// add mentions for not anonymous users
config.events['onRequestUsers'] = function () {
docEditor.setUsers({ // set a list of users to mention in the comments
\"users\": {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;";
}
$this->tagsValues = [
"docType" => getDocumentType($filename),
"apiUrl" => $confgManager->getConfig("docServSiteUrl").$confgManager->getConfig("docServApiUrl"),
"dataInsertImage" => mb_strimwidth(
json_encode($dataInsertImage),
1,
mb_strlen(json_encode($dataInsertImage)) - 2
),
"dataCompareFile" => json_encode($dataCompareFile),
"dataMailMergeRecipients" => json_encode($dataMailMergeRecipients),
"fileNotFoundAlert" => !file_exists(getStoragePath($filename)) ? "alert('File not found'); return;" : "",
"config" => json_encode($config),
"history" => $historyLayout,
"usersForMentions" => json_encode($usersForMentions),
];
}
}

View File

@ -1,152 +0,0 @@
<?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.
*/
namespace OnlineEditorsExamplePhp\Views;
use function OnlineEditorsExamplePhp\getStoredFiles;
use function OnlineEditorsExamplePhp\getFileVersion;
use function OnlineEditorsExamplePhp\getHistoryDir;
use function OnlineEditorsExamplePhp\getStoragePath;
class IndexStoredListView extends View
{
private $request;
public function __construct($request, $tempName = "storedList")
{
parent::__construct($tempName);
$this->request = $request;
$this->tagsValues = [
"user" => isset($this->request["user"]) ? htmlentities($this->request["user"]) : "",
"fileListTable" => $this->getStoredListLayout(),
];
}
public function getStoredListLayout()
{
$storedFiles = getStoredFiles();
$layout = "";
$user = isset($this->request["user"]) ? htmlentities($this->request["user"]) : "";
$directUrlArg = isset($this->request["directUrl"]) ? "&directUrl=" . $this->request["directUrl"] : "";
if (!empty($storedFiles)) {
foreach ($storedFiles as &$storeFile) {
$layout .= '<tr class="tableRow" title="'.$storeFile->name.' ['.getFileVersion(
getHistoryDir(
getStoragePath($storeFile->name)
)
).']">';
$layout .= ' <td class="contentCells"><a class="stored-edit '.
$storeFile->documentType.'" href="doceditor.php?fileID='.
urlencode($storeFile->name).
'&user='.$user.
$directUrlArg .'" target="_blank">'.'<span>'.$storeFile->name.'</span></a></td>';
if ($storeFile->canEdit) {
$layout .= ' <td class="contentCells contentCells-icon"> <a href="doceditor.php?fileID='.
urlencode($storeFile->name).'&user=' . htmlentities($user).$directUrlArg.
'&action=edit&type=desktop" target="_blank">'.
'<img src="css/images/desktop.svg" alt="Open in editor for full size screens"'.
' title="Open in editor for full size screens"/></a></td>'.
' <td class="contentCells contentCells-icon"> <a href="doceditor.php?fileID='.
urlencode($storeFile->name).'&user=' . htmlentities($user).$directUrlArg.
'&action=edit&type=mobile" target="_blank">'.
'<img src="css/images/mobile.svg" alt="Open in editor for mobile devices"'.
' title="Open in editor for mobile devices" /></a></td>'.
' <td class="contentCells contentCells-icon"> <a href="doceditor.php?fileID='.
urlencode($storeFile->name).'&user='.htmlentities($user).$directUrlArg.
'&action=comment&type=desktop" target="_blank">'.
' <img src="css/images/comment.svg" alt="Open in editor for comment"'.
' title="Open in editor for comment" /></a></td>';
if ($storeFile->documentType == "word") {
$layout .= '<td class="contentCells contentCells-icon"> <a href="doceditor.php?fileID='.
urlencode($storeFile->name).'&user='.htmlentities($user).$directUrlArg.
'&action=review&type=desktop" target="_blank">'.
' <img src="css/images/review.svg" alt="Open in editor for review"'.
' title="Open in editor for review" /></a></td>'.
' <td class="contentCells contentCells-icon "> <a href="doceditor.php?fileID='.
urlencode($storeFile->name).'&user='.htmlentities($user).$directUrlArg.
'&action=blockcontent&type=desktop" target="_blank">'.
' <img src="css/images/block-content.svg"'.
' alt="Open in editor without content control modification"'.
' title="Open in editor without content control modification"</a></td>';
} elseif ($storeFile->documentType == "cell") {
$layout .= '<td class="contentCells contentCells-icon"> <a href="doceditor.php?fileID='.
urlencode($storeFile->name).'&user='.htmlentities($user).$directUrlArg.
'&action=filter&type=desktop" target="_blank">'.
' <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></td>';
} else {
$layout .= '<td class="contentCells contentCells-icon"></td>';
$layout .= '<td class="contentCells contentCells-icon"></td>';
}
if ($storeFile->isFillFormDoc) {
$layout.= ' <td class="contentCells contentCells-shift contentCells-icon'.
' firstContentCellShift">'.
' <a href="doceditor.php?fileID='.urlencode($storeFile->name).
'&user='.htmlentities($user).$directUrlArg.
'&action=fillForms&type=desktop" target="_blank">'.
' <img src="css/images/fill-forms.svg" alt="Open in editor for filling in forms"'.
' title="Open in editor for filling in forms" /></a></td>';
} else {
$layout .= '<td class="contentCells contentCells-shift contentCells-icon'.
'firstContentCellShift"></td>';
}
} elseif ($storeFile->isFillFormDoc) {
$layout .= '<td class="contentCells contentCells-icon"> <a href="doceditor.php?fileID='.
urlencode($storeFile->name).'&user='.htmlentities($user).$directUrlArg.
'&action=fillForms&type=desktop" target="_blank">'.
' <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></td>'.
'<td class="contentCells contentCells-icon"></td>'.
'<td class="contentCells contentCells-icon"></td>'.
'<td class="contentCells contentCells-icon"></td>'.
'<td class="contentCells contentCells-shift contentCells-icon firstContentCellShift">'.
'<a href="doceditor.php?fileID='.urlencode($storeFile->name).'&user='.htmlentities($user).
$directUrlArg.'&action=fillForms&type=desktop" target="_blank">'.
'<img src="css/images/fill-forms.svg" alt="Open in editor for filling in forms"'.
' title="Open in editor for filling in forms"/></a></td>';
} else {
$layout .= '<td class="contentCells contentCells-shift contentCells-icon' .
'contentCellsEmpty" colspan="6"></td>';
}
$layout .= '<td class="contentCells contentCells-icon firstContentCellViewers">'.
' <a href="doceditor.php?fileID='.urlencode($storeFile->name).'&user='.htmlentities($user).
$directUrlArg.'&action=view&type=desktop" target="_blank">'.
' <img src="css/images/desktop.svg" alt="Open in viewer for full size screens"'.
' title="Open in viewer for full size screens" /></a></td>'.
' <td class="contentCells contentCells-icon"> <a href="doceditor.php?fileID='.
urlencode($storeFile->name).'&user='.htmlentities($user).$directUrlArg.
'&action=view&type=mobile" target="_blank">'.
' <img src="css/images/mobile.svg" alt="Open in viewer for mobile devices"'.
' title="Open in viewer for mobile devices" /></a></td>'.
' <td class="contentCells contentCells-icon contentCells-shift">'.
' <a href="doceditor.php?fileID='.urlencode($storeFile->name).'&user='.htmlentities($user).
$directUrlArg.'&action=embedded&type=embedded" target="_blank">'.
' <img src="css/images/embeded.svg" alt="Open in embedded mode"'.
' title="Open in embedded mode" /></a>'.
' <td class="contentCells contentCells-icon contentCells-shift downloadContentCellShift">'.
'<a href="webeditor-ajax.php?type=download&fileName='.urlencode($storeFile->name).'">'.
' <img class="icon-download" src="css/images/download.svg" alt="Download" title="Download"'.
' /></a></td>'.
'<td class="contentCells contentCells-icon contentCells-shift">'.
' <a class="delete-file" data="'.$storeFile->name.'">'.
' <img class="icon-delete" src="css/images/delete.svg" alt="Delete" title="Delete" /></a>'.
'</td></tr>';
}
}
return $layout;
}
}

View File

@ -1,115 +0,0 @@
<?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.
*/
namespace OnlineEditorsExamplePhp\Views;
use OnlineEditorsExamplePhp\Helpers\ConfigManager;
use OnlineEditorsExamplePhp\Helpers\ExampleUsers;
use function OnlineEditorsExamplePhp\getStoredFiles;
final class IndexView extends View
{
public function __construct($request, $tempName = "index")
{
parent::__construct($tempName);
$storedList = new IndexStoredListView($request);
$configManager = new ConfigManager();
$portalInfo = $this->getPortalInfoStyleDisplay();
$this->tagsValues = [
"user" => isset($request["user"]) ? htmlentities($request["user"]) : "",
"userOpts" => $this->getUserListOptionsLayout(),
"langs" => $this->getLanguageListOptionsLayout(),
"portalInfoDisplay" => $portalInfo,
"userDescr" => $this->getUserDescriptionLayout(),
"storedList" => $portalInfo == "none" ? $storedList->getParsedTemplate() : "",
"editButton" => $this->getEditButton(),
"dataDocs" => $this->getPreloaderUrl(),
"date" => date("Y"),
"fillFormsExtList" => implode(",", $configManager->getConfig("docServFillforms")),
"converExtList" => implode(",", $configManager->getConfig("docServConvert")),
"editedExtList" => implode(",", $configManager->getConfig("docServEdited")),
];
}
private function getUserListOptionsLayout()
{
$layout = "";
$userList = new ExampleUsers();
foreach ($userList->getAllUsers() as $userL) {
$name = $userL->name ?: "Anonymous";
$layout .= '<option value="'.$userL->id.'">'.$name.'</option>'.PHP_EOL;
}
return $layout;
}
private function getLanguageListOptionsLayout()
{
$layout = "";
$configManager = new ConfigManager();
foreach ($configManager->getConfig("languages") as $key => $language) {
$layout .= '<option value="'.$key.'">'.$language.'</option>'.PHP_EOL;
}
return $layout;
}
private function getPortalInfoStyleDisplay()
{
$storedFiles = getStoredFiles();
if (!empty($storedFiles)) {
return "none";
}
return "table-cell";
}
private function getUserDescriptionLayout()
{
$layout = "";
$userList = new ExampleUsers();
foreach ($userList->getAllUsers() as $userL) {
$name = $userL->name ?: "Anonymous";
$layout .= '<div class="user-descr"><br><b>'.$name.'</b><br><ul>';
foreach ($userL->descriptions as $description) {
$layout .= '<li>'.$description.'</li>';
}
$layout .= '</ul><br></div>';
}
return $layout;
}
private function getStoredListLayout()
{
$storedList = new IndexStoredListView();
return $storedList->getParsedTemplate();
}
private function getPreloaderUrl()
{
$configManager = new ConfigManager();
return $configManager->getConfig("docServSiteUrl").
$configManager->getConfig("docServPreloaderUrl");
}
private function getEditButton()
{
$configManager = new ConfigManager();
return $configManager->getConfig("mode") != "view" ?
'<div id="beginEdit" class="button orange disable">Edit</div>' : "";
}
}

View File

@ -1,58 +0,0 @@
<?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.
*/
namespace OnlineEditorsExamplePhp\Views;
class View
{
private $template;
protected $tagsValues;
public function __construct($tempName)
{
$pathToTemplate = "./templates/".$tempName.".tpl";
if (file_exists($pathToTemplate)) {
$this->template = file_get_contents($pathToTemplate);
} else {
$this->template = "";
}
}
private function parseTemplate($tagsValues = []): array|bool|string
{
$parsedTemplate = $this->template;
foreach ($tagsValues as $tag => $value) {
$parsedTemplate = str_replace("{".$tag."}", $value, $parsedTemplate);
}
return $parsedTemplate;
}
protected function getParsedTemplate()
{
return $this->parseTemplate($this->tagsValues);
}
private function renderTemplate($tagsValues)
{
echo ($this->parseTemplate($tagsValues));
}
public function render()
{
$this->renderTemplate($this->tagsValues);
}
}

View File

@ -1,4 +1,7 @@
<?php
namespace PhpExample;
/**
* (c) Copyright Ascensio System SIA 2023
*
@ -15,20 +18,17 @@
* limitations under the License.
*/
namespace OnlineEditorsExamplePhp;
use OnlineEditorsExamplePhp\Helpers\ConfigManager;
/**
* WebEditor AJAX Process Execution.
*/
require_once dirname(__FILE__) . '/config.php';
require_once dirname(__FILE__) . '/ajax.php';
require_once dirname(__FILE__) . '/common.php';
require_once dirname(__FILE__) . '/functions.php';
require_once dirname(__FILE__) . '/jwtmanager.php';
require_once dirname(__FILE__) . '/trackmanager.php';
require_once dirname(__FILE__) . '/vendor/autoload.php';
require_once dirname(__FILE__) . '/users.php';
$configManager = new ConfigManager();
// define tracker status
$_trackerStatus = [
0 => 'NotFound',
@ -41,7 +41,7 @@ $_trackerStatus = [
];
// ignore self-signed certificate
if ($configManager->getConfig("docServVerifyPeerOff") === true) {
if ($GLOBALS['DOC_SERV_VERIFY_PEER_OFF'] === true) {
stream_context_set_default([
'ssl' => [
'verify_peer' => false,
@ -52,6 +52,7 @@ if ($configManager->getConfig("docServVerifyPeerOff") === true) {
// check if type value exists
if (isset($_GET["type"]) && !empty($_GET["type"])) {
$response_array;
@header('Content-Type: application/json; charset==utf-8');
@header('X-Robots-Tag: noindex');
@header('X-Content-Type-Options: nosniff');
@ -98,10 +99,6 @@ if (isset($_GET["type"]) && !empty($_GET["type"])) {
$response_array = csv();
$response_array['status'] = 'success';
die(json_encode($response_array));
case "reference":
$response_array = reference();
$response_array['status'] = 'success';
die(json_encode($response_array));
case "files":
$response_array = files();
die(json_encode($response_array));
@ -118,3 +115,458 @@ if (isset($_GET["type"]) && !empty($_GET["type"])) {
die(json_encode($response_array));
}
}
/**
* Save copy as...
*
* @return array
*/
function saveas()
{
try {
$result;
$post = json_decode(file_get_contents('php://input'), true);
$fileurl = $post["url"];
$title = $post["title"];
$extension = mb_strtolower(pathinfo($title, PATHINFO_EXTENSION));
$allexts = array_merge(
$GLOBALS['DOC_SERV_CONVERT'],
$GLOBALS['DOC_SERV_EDITED'],
$GLOBALS['DOC_SERV_VIEWD'],
$GLOBALS['DOC_SERV_FILLFORMS']
);
$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 > $GLOBALS['FILE_SIZE_MAX']) {
$result["error"] = "File size is incorrect";
return $result;
}
file_put_contents(getStoragePath($filename), $data, LOCK_EX); // write data to the new file
$user = 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()
{
$result;
$filename;
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 > $GLOBALS['FILE_SIZE_MAX']) {
$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;
}
$user = 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 = trim(getInternalExtension($fileName), '.');
// check if the file with such an extension can be converted
if (in_array("." . $extension, $GLOBALS['DOC_SERV_CONVERT']) && $internalExtension != "") {
$fileUri = $post["fileUri"];
if ($fileUri == null || $fileUri == "") {
$fileUri = $fileUri = serverPath(true) . '/'
. "webeditor-ajax.php"
. "?type=download"
. "&fileName=" . urlencode($fileName)
. "&userAddress=" . getClientIp();
}
$key = getDocEditorKey($fileName);
$newFileUri;
$result;
$percent;
try {
// convert file and get the percentage of the conversion completion
$percent = getConvertedUri(
$fileUri,
$extension,
$internalExtension,
$key,
true,
$newFileUri,
$filePass,
$lang
);
} catch (Exception $e) {
$result["error"] = "error: " . $e->getMessage();
return $result;
}
if ($percent != 100) {
$result["step"] = $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 . "." . $internalExtension);
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
$user = 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"];
if (isJwtEnabled()) {
$jwtHeader = $GLOBALS['DOC_SERV_JWT_HEADER'] == "" ? "Authorization" : $GLOBALS['DOC_SERV_JWT_HEADER'];
if (!empty(apache_request_headers()[$jwtHeader])) {
$token = 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 {
$fileName = realpath($GLOBALS['STORAGE_PATH'])
=== $GLOBALS['STORAGE_PATH'] ? $_GET["fileName"] : basename($_GET["fileName"]); // get the file name
$userAddress = $_GET["userAddress"];
$isEmbedded = $_GET["&dmode"];
if (isJwtEnabled() && $isEmbedded == null && $userAddress) {
$jwtHeader = $GLOBALS['DOC_SERV_JWT_HEADER'] == "" ? "Authorization" : $GLOBALS['DOC_SERV_JWT_HEADER'];
if (!empty(apache_request_headers()[$jwtHeader])) {
$token = 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"];
$curExt = mb_strtolower(array_pop(explode('.', $newfilename)));
$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];
}

View File

@ -1,37 +0,0 @@
ONLYOFFICE Applications example uses code from the following 3rd party projects:
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.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

View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
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 "[]"
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
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
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.
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.

View File

@ -5,20 +5,15 @@ VERSION = '1.5.0'
FILE_SIZE_MAX = 5242880
STORAGE_PATH = 'app_data'
DOC_SERV_FILLFORMS = [".docx", ".oform"]
DOC_SERV_VIEWED = [".djvu", ".oxps", ".pdf", ".xps"] # file extensions that can be viewed
DOC_SERV_EDITED = [ # file extensions that can be edited
".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"
]
DOC_SERV_CONVERT = [ # file extensions that can be converted
".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"
DOC_SERV_FILLFORMS = [".oform", ".docx"]
DOC_SERV_VIEWED = [".pdf", ".djvu", ".xps", ".oxps"] # file extensions that can be viewed
DOC_SERV_EDITED = [".docx", ".xlsx", ".csv", ".pptx", ".txt", ".docxf"] # file extensions that can be edited
DOC_SERV_CONVERT = [ # file extensions that can be converted
".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"
]
DOC_SERV_TIMEOUT = 120000
@ -34,7 +29,6 @@ EXAMPLE_DOMAIN = None
DOC_SERV_JWT_SECRET = '' # the secret key for generating token
DOC_SERV_JWT_HEADER = 'Authorization'
DOC_SERV_JWT_USE_FOR_REQUEST = True
DOC_SERV_VERIFY_PEER = False

View File

@ -1,37 +0,0 @@
ONLYOFFICE Applications example uses code from the following 3rd party projects:
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.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

View File

@ -1,27 +0,0 @@
Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Django nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015-2022 José Padilla
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,9 +0,0 @@
Copyright <20> 2007-2013 M. Alsup.
The BlockUI plugin is dual licensed under the MIT and GPL licenses.
You may use either license. The MIT license is recommended for most projects because it is simple and easy to understand and it places almost no restrictions on what you can do with the plugin.
If the GPL suits your project better you are also free to use the plugin under that license.
You do not have to do anything special to choose one license or the other and you don't have to notify anyone which license you are using. You are free to use the BlockUI plugin in commercial projects as long as the copyright header is left intact.

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