Compare commits

...

154 Commits

Author SHA1 Message Date
1e2ac3e23c Merge branch 'master' into develop 2023-03-17 12:02:40 +05:00
1683a08660 artifact on master only 2023-03-17 12:02:27 +05:00
459c7cd233 Merge pull request #359 from ONLYOFFICE/feature/prevent-anonymous-edit
Feature/prevent anonymous edit
2023-03-17 12:00:32 +05:00
c0241a84be onRequestEditRights to changelog 2023-03-17 11:56:54 +05:00
0df40f97ea Merge pull request #360 from ONLYOFFICE/dependabot/bundler/web/documentserver-example/ruby/rack-2.2.6.4
build(deps): bump rack from 2.2.4 to 2.2.6.4 in /web/documentserver-example/ruby
2023-03-17 11:54:03 +05:00
b7aa93e628 Merge branch 'develop' into dependabot/bundler/web/documentserver-example/ruby/rack-2.2.6.4 2023-03-17 11:53:47 +05:00
d47ec1820a build(deps): bump rack in /web/documentserver-example/ruby
Bumps [rack](https://github.com/rack/rack) from 2.2.4 to 2.2.6.4.
- [Release notes](https://github.com/rack/rack/releases)
- [Changelog](https://github.com/rack/rack/blob/main/CHANGELOG.md)
- [Commits](https://github.com/rack/rack/compare/2.2.4...v2.2.6.4)

---
updated-dependencies:
- dependency-name: rack
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-03-16 11:17:15 +00:00
3952663302 php: re-hide edit icon on view screen for anonymous 2023-03-15 11:18:32 +05:00
9e39adddcc php: hide edit icon on view screen for anonymous 2023-03-14 16:26:32 +05:00
f79fb213f1 ruby: hide edit icon on view screen for anonymous 2023-03-14 16:16:01 +05:00
c236f2902e python: hide edit icon on view screen for anonymous 2023-03-14 15:53:34 +05:00
96368f871c java-spring: hide edit icon on view screen for anonymous 2023-03-14 15:51:33 +05:00
5831c7f651 java: hide edit icon on view screen for anonymous 2023-03-14 15:50:03 +05:00
52706402a2 csharp-mvc: hide edit icon on view screen for anonymous 2023-03-14 15:42:12 +05:00
90be38c240 csharp: hide edit icon on view screen for anonymous 2023-03-14 13:30:49 +05:00
19f75a0646 nodejs: hide edit icon on view screen for anonymous 2023-03-14 13:02:14 +05:00
4fd38856fd Merge pull request #358 from ONLYOFFICE/feature/csharp-close-history
Feature/csharp close history
2023-03-13 14:17:58 +05:00
593ad9559f csharp-mvc: add close history button 2023-03-13 13:39:13 +05:00
8d06c0afcb csharp: add close history button 2023-03-13 13:36:46 +05:00
4b3b44d828 Merge pull request #356 from ONLYOFFICE/dependabot/bundler/web/documentserver-example/ruby/rack-2.2.6.3
build(deps): bump rack from 2.2.4 to 2.2.6.3 in /web/documentserver-example/ruby
2023-03-13 11:29:11 +05:00
bb9d73610e build(deps): bump rack in /web/documentserver-example/ruby
Bumps [rack](https://github.com/rack/rack) from 2.2.4 to 2.2.6.3.
- [Release notes](https://github.com/rack/rack/releases)
- [Changelog](https://github.com/rack/rack/blob/main/CHANGELOG.md)
- [Commits](https://github.com/rack/rack/compare/2.2.4...v2.2.6.3)

---
updated-dependencies:
- dependency-name: rack
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-03-13 11:28:41 +05:00
8468c87170 Merge remote-tracking branch 'remotes/origin/master' into develop 2023-03-08 13:14:15 +05:00
3427554bf0 Merge pull request #355 from ONLYOFFICE/fix/gitignore
chore: remove .gitignore from spring,ruby
2023-03-08 13:13:30 +05:00
ec2845af5e chore: remove .gitignore from spring,ruby 2023-03-06 12:27:58 +05:00
976dfc9276 Merge pull request #353 from ONLYOFFICE/feature/formats
Feature/formats
2023-03-06 10:45:39 +05:00
da7cc3e65d Merge pull request #344 from hunimuni/patch-1
Fixed links
2023-03-05 18:36:42 +05:00
3283e14c01 Merge pull request #354 from ONLYOFFICE/feature/artifact-actions
ci: artifact and release actions
2023-03-05 17:20:23 +05:00
17f336a156 ci: artifact and release actions 2023-03-03 18:11:58 +05:00
3d7ea8715a ruby: changed format list 2023-03-03 17:11:01 +05:00
487467cbed python: changed format list 2023-03-03 17:09:15 +05:00
cb71e3fb35 java-spring: changed format list 2023-03-03 16:57:35 +05:00
5749ad8db2 java: changed format list 2023-03-03 16:55:59 +05:00
f3d03c6011 csharp-mvc: changed format list 2023-03-03 16:53:56 +05:00
16b1a90cb1 csharp: changed format list 2023-03-03 16:51:47 +05:00
a29d98eb10 php: changed format list 2023-03-03 16:44:20 +05:00
82cb492bb7 python: unused import 2023-03-03 14:12:51 +05:00
6fde4de187 nodejs: changed format list 2023-03-03 01:12:05 +05:00
ad073bb2f8 Merge remote-tracking branch 'remotes/origin/master' into develop 2023-03-02 22:10:19 +05:00
827b315bff Merge pull request #345 from ONLYOFFICE/refactor/php-example-refactoring
Refactor/php example refactoring
2023-03-02 18:12:01 +05:00
33c093f7a6 Revert "fix: remove on develop pull request"
This reverts commit 2d9a7ed502.
2023-03-02 18:11:27 +05:00
855dfb4736 php: format 2023-03-02 18:09:10 +05:00
50eeaf0db4 php: formatting by linter 2023-03-02 15:16:25 +03:00
8d3afb7ad0 Merge branch 'develop' into refactor/php-example-refactoring 2023-03-02 14:10:32 +03:00
830fa87e27 fix reload page with cached checkbox status in FireFox 2023-03-02 14:35:54 +05:00
4d8a893326 Merge branch 'feature/wopi-mobile' into develop 2023-03-02 14:22:36 +05:00
7f371699b1 nodejs: remove empty media style 2023-03-02 14:22:20 +05:00
76a2bfd9f9 Margin of icons in WOPI-template. New actions included. (#351)
* nodejs: WOPI - margin of icons = 8px, media-queries changed.

* nodejs: WOPI - margin of icons for new actions.
2023-03-02 14:04:21 +05:00
9c88f86e80 Merge pull request #346 from ONLYOFFICE/feature/referenceData
Feature/reference data
2023-03-02 13:47:40 +05:00
4d4951f184 referenceData to changelog 2023-03-02 13:22:00 +05:00
251f48ee1e nodejs: do not check oform param in ie11 2023-02-28 17:40:37 +05:00
bdca343550 Copyright 2023 2023-02-28 12:26:45 +05:00
dcc7bdfcae nodejs: icons for mobile actions in wopi 2023-02-28 00:07:58 +05:00
469a8c087b Merge branch 'develop' into feature/referenceData 2023-02-27 10:17:41 +03:00
61a8490d4f csharp: check of empty filename-string (logical error fixed) 2023-02-27 10:10:37 +03:00
4fa2049adc csharp-mvc: names of helpers fixed + check of empty filename-string (logical error fixed) 2023-02-27 10:08:47 +03:00
060f28e404 csharp-mvc: unnecessary replace of symbols deleted 2023-02-27 09:30:44 +03:00
82bc0e6496 csharp: unnecessary replace of symbols deleted. 2023-02-27 09:25:32 +03:00
beaab91223 Merge pull request #350 from ONLYOFFICE/feature/permissions-protect-for-anonymous
Feature/permissions protect for anonymous
2023-02-23 17:44:30 +05:00
49953199d4 protect to changelog 2023-02-23 17:44:11 +05:00
9c7b39bd5a protect field to information 2023-02-23 17:43:09 +05:00
c2f653bbde nodejs: "protect" permission is added 2023-02-22 16:06:28 +03:00
d3d3121d51 java-spring: "protect" permission is added 2023-02-22 15:27:39 +03:00
ebd252f42c java: "protect" permission is added 2023-02-22 14:53:24 +03:00
586d7767b4 csharp-mvc: "protect" permission is added 2023-02-22 14:42:21 +03:00
ea8b0c0fa3 csharp: "protect" permission is added 2023-02-22 14:39:27 +03:00
055f548056 ruby: "protect" permission is added 2023-02-22 14:30:59 +03:00
78752275fd python: "protect" permission is added 2023-02-22 14:20:00 +03:00
c26a17f29e php: "protect" permission is added 2023-02-22 14:04:11 +03:00
61d64e909b java-spring: fix - search for filename by path 2023-02-22 12:22:41 +03:00
21d1fd962f java: fix - search for filename by path 2023-02-22 11:55:13 +03:00
4eff2e7d89 ruby: fix - search for filename by path 2023-02-21 11:49:42 +03:00
2b6b48720e python: apache 2 license 2023-02-21 11:56:15 +05:00
4f26ff64c6 csharp-mvc: fix - search for filename by path 2023-02-21 09:31:50 +03:00
d23e139272 csharp: fix - search for filename by path 2023-02-21 09:29:52 +03:00
e6ec9acc96 Merge pull request #349 from ONLYOFFICE/feature/python-licenses-list
python: licenses list added
2023-02-21 11:02:59 +05:00
9d54ec748a python: fix - search for filename by path 2023-02-20 17:06:56 +03:00
8d2cbca12f php: fix - search for filename by path 2023-02-20 16:49:44 +03:00
20c51ea577 python: licenses list added 2023-02-20 12:34:35 +03:00
23f2837c66 php: removed unused "use" statements 2023-02-17 16:05:45 +03:00
9faf540f8c php: docEditor template added 2023-02-17 15:44:48 +03:00
5bb8719e00 php: README.md updated 2023-02-17 15:44:21 +03:00
2bb01fbfff php: building an docEditorView from a templates + formatting by linter 2023-02-17 14:58:13 +03:00
de9f27465f Merge pull request #348 from ONLYOFFICE/feature/add-oform-parameter
nodejs: disable oform module
2023-02-17 16:10:02 +05:00
66ab02199b Merge pull request #347 from ONLYOFFICE/bugfix/wopi-language
nodejs: wopi: fix language
2023-02-17 16:02:16 +05:00
d77be1fcbd nodejs: wopi: refactor wopi params 2023-02-17 13:26:18 +03:00
e729afdd05 java-spring: search for fileName by path added + json-data fix 2023-02-17 12:59:09 +03:00
e88c2e9c68 java: search for fileName by path added + json-data fix 2023-02-17 12:20:25 +03:00
63b7641c47 csharp: fix - "Path not found" - error handled 2023-02-17 11:46:17 +03:00
54f501c82b csharp-mvc: search for fileName by path added 2023-02-17 11:43:15 +03:00
c291b1059c nodejs: wopi: fix language 2023-02-17 11:35:25 +03:00
ee0a167708 csharp: search for fileName by path added 2023-02-17 11:15:33 +03:00
f76c611033 ruby: search for fileName by path added 2023-02-17 10:40:03 +03:00
7d1c3a994d python: search for fileName by path added 2023-02-17 10:13:43 +03:00
42b7c8353e php: search for fileName by path added 2023-02-17 09:34:22 +03:00
584dd720de php: dictionary of templates names deleted 2023-02-16 16:21:37 +03:00
aa5d6fce47 php: common methods are collected in the parent class View, changed methods visibility 2023-02-16 16:17:35 +03:00
32c64daa4d php: building an IndexView from a templates 2023-02-16 15:55:20 +03:00
1b1d07ebc5 python: referenceData 2023-02-16 12:19:33 +03:00
55734a1458 ruby: referenceData 2023-02-16 10:10:23 +03:00
43875b06bf java-spring: ReferenceData 2023-02-15 15:33:07 +03:00
97ba0da3c2 java: referenceData 2023-02-15 14:54:12 +03:00
8147608d3b csharp-mvc: fix referenceData - path-parameter in ajax-handler added 2023-02-15 14:24:44 +03:00
9213143e14 chsarp: fix referenceData - path-parameter in ajax-handler added 2023-02-15 14:20:40 +03:00
f1a9a84777 php: new methods for views, IndexStoredListView added 2023-02-14 17:18:09 +03:00
75046b80c6 csharp-mvc: referenceData 2023-02-14 15:42:36 +03:00
69caf53646 csharp: referenceData 2023-02-14 15:20:27 +03:00
6f69350183 php: views-classes added 2023-02-13 16:30:00 +03:00
2e75037b4e php: referenceData 2023-02-13 14:56:09 +03:00
bba6473b95 Merge branch 'develop' into refactor/php-example-refactoring 2023-02-10 13:38:03 +03:00
2aaa32449a Merge pull request #341 from ONLYOFFICE/feature/config-request-jwt
Feature/config request jwt
2023-02-10 13:09:09 +03:00
1a44d6d415 token.useforrequest to changelog 2023-02-10 15:07:52 +05:00
7a3025c548 php: ajax-handlers transferred from functions.php to ajax.php 2023-02-10 11:33:02 +03:00
cdd816ef35 php: deleted declarations of variables without values 2023-02-10 09:33:04 +03:00
f69097b209 php: header comment fixed 2023-02-09 17:05:12 +03:00
9896be023e php: sendlog() returned into ExampleUsers 2023-02-09 16:01:43 +03:00
1d99c8f58e php: objects of helpers used instead of functions 2023-02-09 14:51:41 +03:00
835e10ed4b Fixed links
The paths were not formed correctly, the symbol '/' was missing
2023-02-09 13:41:48 +03:00
e4439bfc3e php: "\r\n" replaced with "\n" 2023-02-09 11:05:06 +03:00
5ad77a855b Merge remote-tracking branch 'remotes/origin/develop' into feature/config-request-jwt
# Conflicts:
#	web/documentserver-example/php/config.php
#	web/documentserver-example/php/functions.php
#	web/documentserver-example/php/jwtmanager.php
#	web/documentserver-example/php/trackmanager.php
2023-02-09 12:32:06 +05:00
37f49af588 Revert "php: PSR1.Files.SideEffects disabled in ruleset.xml"
This reverts commit b11a1be481.
2023-02-09 09:19:58 +03:00
f86c09b19d Merge branch 'refactor/linter-formatting' into refactor/php-example-refactoring 2023-02-09 09:18:16 +03:00
3112be387e php: helpers used in functions 2023-02-08 17:49:20 +03:00
383d7c27c0 php: helpers fixed 2023-02-08 16:50:47 +03:00
7190725726 php: TrackManager class added 2023-02-08 14:31:44 +03:00
065da92d65 php: FileUtility and Utils added 2023-02-08 12:33:43 +03:00
5c877cf902 php: classes JwtManager and ConfigManager used instead of included functions and GLOBALS array 2023-02-08 11:24:45 +03:00
726808813a php: config.json default values 2023-02-08 11:07:13 +03:00
7af4c16b35 php: JwtManager class added 2023-02-08 10:51:58 +03:00
e7fc9bb8c2 php: ConfigManager class added, config.json for ConfigManager added (instead of $GLOBALS array in future) 2023-02-08 10:36:43 +03:00
baf429a0d0 php: methods of ExampleUsers class used instead of functions 2023-02-07 16:44:46 +03:00
00b2d948dc php: class users converted to classes Users(user entity) and ExampleUsers(users-collection entity) 2023-02-07 16:37:21 +03:00
81258cc717 php: created parameters for composer autoloader 2023-02-07 16:34:37 +03:00
9db426ffe5 php: tokenUseForRequest() function used instead of $GLOBALS array value 2023-02-06 16:33:26 +03:00
a6ee7d28d0 php: added tokenUseForRequest() method into jwtmanager 2023-02-06 16:25:41 +03:00
7a50b8fda2 ruby: config request JWT used in functions 2023-02-06 16:14:53 +03:00
5f7f8d66d5 ruby: added use_for_request method into jwt_helper 2023-02-06 16:11:41 +03:00
d514acf32e python: config request JWT used in functions 2023-02-06 15:44:59 +03:00
d3df1499d2 python: added useForRequest() method into jwtManager 2023-02-06 15:37:29 +03:00
f7682b12ae java-spring: config request JWT used in functions 2023-02-06 15:22:06 +03:00
8c2d62d917 java-spring: added tokenUseForRequest method and field into DefaultJwtManager class and JwtManager interface 2023-02-06 15:10:47 +03:00
f0d9c54038 java: config request JWT used in functions 2023-02-06 14:52:33 +03:00
fbe5b1de37 java: added tokenUseForRequest methods into DocumentManager 2023-02-06 14:24:02 +03:00
dccfbb2edf csharp-mvc: config request JWT used in functions 2023-02-06 12:46:11 +03:00
0f2b5305e3 csharp-mvc: added SignatureUseForRequest field into JwtManager 2023-02-06 12:39:38 +03:00
c69a7c92a5 csharp: config request JWT used in functions 2023-02-06 12:30:43 +03:00
6fa3aab99c csharp: added SignatureUseForRequest field into JwtManager 2023-02-06 12:13:49 +03:00
02f4777058 php: config request JWT used in functions 2023-02-06 11:12:14 +03:00
66cbb64039 php: require user address on download
nodejs: require token on download
2023-02-01 15:00:10 +05:00
879ee1f750 java-spring: token and user address required on download 2023-02-01 15:00:10 +05:00
90449fff3a java: token and address required on download 2023-02-01 15:00:09 +05:00
893c6306f2 csharp-mvc: user address required on download 2023-02-01 15:00:09 +05:00
aa3806f1dd c-sharp: user address required on download 2023-02-01 15:00:09 +05:00
4000117811 ruby: user address required on download 2023-02-01 15:00:09 +05:00
3319e6428a python: user address required on download 2023-02-01 15:00:08 +05:00
133 changed files with 5064 additions and 2953 deletions

View File

@ -0,0 +1,33 @@
name: Artifact Csharp MVC
on:
workflow_dispatch:
push:
branches: [master, main]
paths: ['web/documentserver-example/csharp-mvc/**']
pull_request:
branches: [master, main]
paths: ['web/documentserver-example/csharp-mvc/**']
jobs:
artifact:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Build Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/csharp-mvc
mkdir -p ./deploy/'DotNet (Csharp MVN) Example'
rsync -av --exclude='deploy' ./ ./deploy/'DotNet (Csharp MVC) Example'
cd ./deploy/'DotNet (Csharp MVC) Example'/assets
rm -rf ./.git/
rm .git
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: DotNet.Csharp.MVC.Example
path: ${{ github.workspace }}/web/documentserver-example/csharp-mvc/deploy

33
.github/workflows/artifact-csharp.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: Artifact Csharp
on:
workflow_dispatch:
push:
branches: [master, main]
paths: ['web/documentserver-example/csharp/**']
pull_request:
branches: [master, main, develop]
paths: ['web/documentserver-example/csharp/**']
jobs:
artifact:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Build Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/csharp
mkdir -p ./deploy/'DotNet (Csharp) Example'
rsync -av --exclude='deploy' ./ ./deploy/'DotNet (Csharp) Example'
cd ./deploy/'DotNet (Csharp) Example'/assets
rm -rf ./.git/
rm .git
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: DotNet.Csharp.Example
path: ${{ github.workspace }}/web/documentserver-example/csharp/deploy

33
.github/workflows/artifact-java.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: Artifact Java
on:
workflow_dispatch:
push:
branches: [master, main]
paths: ['web/documentserver-example/java/**']
pull_request:
branches: [master, main]
paths: ['web/documentserver-example/java/**']
jobs:
artifact:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Build Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/java
mkdir -p ./deploy/'Java Example'
rsync -av --exclude='deploy' ./ ./deploy/'Java Example'
cd ./deploy/'Java Example'/src/main/resources/assets
rm -rf ./.git/
rm .git
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: Java.Example
path: ${{ github.workspace }}/web/documentserver-example/java/deploy

33
.github/workflows/artifact-node.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: Artifact Nodejs
on:
workflow_dispatch:
push:
branches: [master, main]
paths: ['web/documentserver-example/nodejs/**']
pull_request:
branches: [master, main]
paths: ['web/documentserver-example/nodejs/**']
jobs:
artifact:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Build Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/nodejs
mkdir -p ./deploy/'Node.js Example'
rsync -av --exclude='deploy' ./ ./deploy/'Node.js Example'
cd ./deploy/'Node.js Example'/public/assets
rm -rf ./.git/
rm .git
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: Node.js.Example
path: ${{ github.workspace }}/web/documentserver-example/nodejs/deploy

33
.github/workflows/artifact-php.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: Artifact PHP
on:
workflow_dispatch:
push:
branches: [master, main]
paths: ['web/documentserver-example/php/**']
pull_request:
branches: [master, main]
paths: ['web/documentserver-example/php/**']
jobs:
artifact:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Build Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/php
mkdir -p ./deploy/'PHP Example'
rsync -av --exclude='deploy' ./ ./deploy/'PHP Example'
cd ./deploy/'PHP Example'/assets
rm -rf ./.git/
rm .git
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: PHP.Example
path: ${{ github.workspace }}/web/documentserver-example/php/deploy

33
.github/workflows/artifact-python.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: Artifact Python
on:
workflow_dispatch:
push:
branches: [master, main]
paths: ['web/documentserver-example/python/**']
pull_request:
branches: [master, main]
paths: ['web/documentserver-example/python/**']
jobs:
artifact:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Build Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/python
mkdir -p ./deploy/'Python Example'
rsync -av --exclude='deploy' ./ ./deploy/'Python Example'
cd ./deploy/'Python Example'/assets
rm -rf ./.git/
rm .git
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: Python.Example
path: ${{ github.workspace }}/web/documentserver-example/python/deploy

33
.github/workflows/artifact-ruby.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: Artifact Ruby
on:
workflow_dispatch:
push:
branches: [master, main]
paths: ['web/documentserver-example/ruby/**']
pull_request:
branches: [master, main]
paths: ['web/documentserver-example/ruby/**']
jobs:
artifact:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Build Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/ruby
mkdir -p ./deploy/'Ruby Example'
rsync -av --exclude='deploy' ./ ./deploy/'Ruby Example'
cd ./deploy/'Ruby Example'/public/assets
rm -rf ./.git/
rm .git
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: Ruby.Example
path: ${{ github.workspace }}/web/documentserver-example/ruby/deploy

33
.github/workflows/artifact-spring.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: Artifact Java Spring
on:
workflow_dispatch:
push:
branches: [master, main]
paths: ['web/documentserver-example/java-spring/**']
pull_request:
branches: [master, main]
paths: ['web/documentserver-example/java-spring/**']
jobs:
artifact:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Build Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/java-spring
mkdir -p ./deploy/'Java Spring Example'
rsync -av --exclude='deploy' ./ ./deploy/'Java Spring Example'
cd ./deploy/'Java Spring Example'/src/main/resources/assets
rm -rf ./.git/
rm .git
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: Java.Spring.Example
path: ${{ github.workspace }}/web/documentserver-example/java-spring/deploy

View File

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

146
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,146 @@
name: Release
on:
push:
branches: [master,main]
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Install Zip
run: sudo apt-get install zip
- name: Get Info
run: |
echo "version=$(grep -Eo '[0-9]+(\.[0-9]+)+' CHANGELOG.md | head -n 1)" >> $GITHUB_OUTPUT
id: info
- name: Generate Changelog
run: |
awk '/## [0-9]/{p++} p; /## [0-9]/{if (p > 1) exit}' CHANGELOG.md | awk 'NR>2 {print last} {last=$0}' > RELEASE.md
- name: Build Csharp MVC Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/csharp-mvc
mkdir -p ./'DotNet (Csharp MVC) Example'
rsync -av --exclude='DotNet (Csharp MVC) Example' ./ ./'DotNet (Csharp MVC) Example'
cd ./'DotNet (Csharp MVC) Example'/assets
rm -rf ./.git/
rm .git
- name: Build Csharp Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/csharp
mkdir -p ./'DotNet (Csharp) Example'
rsync -av --exclude='DotNet (Csharp) Example' ./ ./'DotNet (Csharp) Example'
cd ./'DotNet (Csharp) Example'/assets
rm -rf ./.git/
rm .git
- name: Build Java Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/java
mkdir -p ./'Java Example'
rsync -av --exclude='Java Example' ./ ./'Java Example'
cd ./'Java Example'/src/main/resources/assets
rm -rf ./.git/
rm .git
- name: Build Nodejs Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/nodejs
mkdir -p ./'Node.js Example'
rsync -av --exclude='Node.js Example' ./ ./'Node.js Example'
cd ./'Node.js Example'/public/assets
rm -rf ./.git/
rm .git
- name: Build PHP Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/php
mkdir -p ./'PHP Example'
rsync -av --exclude='PHP Example' ./ ./'PHP Example'
cd ./'PHP Example'/assets
rm -rf ./.git/
rm .git
- name: Build Python Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/python
mkdir -p ./'Python Example'
rsync -av --exclude='Python Example' ./ ./'Python Example'
cd ./'Python Example'/assets
rm -rf ./.git/
rm .git
- name: Build Ruby Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/ruby
mkdir -p ./'Ruby Example'
rsync -av --exclude='Ruby Example' ./ ./'Ruby Example'
cd ./'Ruby Example'/public/assets
rm -rf ./.git/
rm .git
- name: Build Spring Artifact
run: |
cd ${{ github.workspace }}
cwd=$(pwd)
git submodule update --init --recursive
cd ./web/documentserver-example/java-spring
mkdir -p ./'Java Spring Example'
rsync -av --exclude='Java Spring Example' ./ ./'Java Spring Example'
cd ./'Java Spring Example'/src/main/resources/assets
rm -rf ./.git/
rm .git
- name: Pack Artifacts
run: |
cd ${{ github.workspace }}/web/documentserver-example/csharp-mvc
zip -r DotNet.Csharp.MVC.Example.zip ./'DotNet (Csharp MVC) Example'
cd ${{ github.workspace }}/web/documentserver-example/csharp
zip -r DotNet.Csharp.Example.zip ./'DotNet (Csharp) Example'
cd ${{ github.workspace }}/web/documentserver-example/java
zip -r Java.Example.zip ./'Java Example'
cd ${{ github.workspace }}/web/documentserver-example/nodejs
zip -r Node.js.Example.zip ./'Node.js Example'
cd ${{ github.workspace }}/web/documentserver-example/php
zip -r PHP.Example.zip ./'PHP Example'
cd ${{ github.workspace }}/web/documentserver-example/python
zip -r Python.Example.zip ./'Python Example'
cd ${{ github.workspace }}/web/documentserver-example/ruby
zip -r Ruby.Example.zip ./'Ruby Example'
cd ${{ github.workspace }}/web/documentserver-example/java-spring
zip -r Java.Spring.Example.zip ./'Java Spring Example'
- name: Create Release
uses: ncipollo/release-action@v1
id: create_release
with:
bodyFile: RELEASE.md
artifacts: "
${{ github.workspace }}/web/documentserver-example/csharp-mvc/DotNet.Csharp.MVC.Example.zip,
${{ github.workspace }}/web/documentserver-example/csharp/DotNet.Csharp.Example.zip,
${{ github.workspace }}/web/documentserver-example/java/Java.Example.zip,
${{ github.workspace }}/web/documentserver-example/nodejs/Node.js.Example.zip,
${{ github.workspace }}/web/documentserver-example/php/PHP.Example.zip,
${{ github.workspace }}/web/documentserver-example/python/Python.Example.zip,
${{ github.workspace }}/web/documentserver-example/ruby/Ruby.Example.zip,
${{ github.workspace }}/web/documentserver-example/java-spring/Java.Spring.Example.zip
"
tag: v${{ steps.info.outputs.version }}

13
.gitignore vendored
View File

@ -11,6 +11,19 @@
**/.vscode/
**/.vs/
**/.idea
.classpath
.project
.settings/
*.iml
*.iws
.DS_Store
/web/documentserver-example/java/target/
/web/documentserver-example/java-spring/target/
/web/documentserver-example/csharp/packages
/web/documentserver-example/csharp-mvc/packages
/web/documentserver-example/java-spring/documents/
/web/documentserver-example/ruby/.bundle
/web/documentserver-example/ruby/db/*.sqlite3
/web/documentserver-example/ruby/db/*.sqlite3-journal
/web/documentserver-example/ruby/log/*
/web/documentserver-example/ruby/tmp

View File

@ -259,6 +259,45 @@ 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,5 +1,9 @@
# Change Log
- anonymous can't change viewer to edit
- 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)
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
{
// create payload object
var payload = new Dictionary<string, object>

View File

@ -29,11 +29,13 @@ 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)
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
{
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)
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
{
var payload = new Dictionary<string, object>
{

View File

@ -69,6 +69,7 @@ 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",
};
@ -131,7 +132,7 @@ namespace OnlineEditorsExampleMVC.Helpers
new Dictionary<string,object>(),
new List<string>(),
null,
new List<string>(),
new List<string>() { "protect" },
descr_user_0,
false
)

View File

@ -138,6 +138,17 @@ 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>
@ -154,7 +165,8 @@ namespace OnlineEditorsExampleMVC.Models
{ "chat", !user.id.Equals("uid-0") },
{ "reviewGroups", user.reviewGroups },
{ "commentGroups", user.commentGroups },
{ "userInfoGroups", user.userInfoGroups }
{ "userInfoGroups", user.userInfoGroups },
{ "protect", !user.deniedPermissions.Contains("protect") }
}
}
}

View File

@ -31,7 +31,7 @@
-->
<link rel="icon" href="<%= "content/images/" + Model.DocumentType + ".ico" %>" type="image/x-icon" />
<title><%= Model.FileName + " - ONLYOFFICE" %></title>
<%: Styles.Render("~/Content/editor") %>
</head>
@ -40,7 +40,7 @@
<div id="iframeEditor">
</div>
</div>
<%: Scripts.Render(new []{ WebConfigurationManager.AppSettings["files.docservice.url.site"] + WebConfigurationManager.AppSettings["files.docservice.url.api"] }) %>
<script type="text/javascript" language="javascript">
@ -141,7 +141,7 @@
<% Model.GetMailMergeConfig(out dataMailMergeRecipients); %>
docEditor.setMailMergeRecipients(<%= dataMailMergeRecipients%>); // insert recipient data for mail merge into the file
};
var onRequestSaveAs = function (event) { // the user is trying to save file by clicking Save Copy as... button
var title = event.data.title;
var url = event.data.url;
@ -178,6 +178,18 @@
}
};
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%";
@ -186,7 +198,6 @@
config.events = {
'onAppReady': onAppReady,
'onDocumentStateChange': onDocumentStateChange,
'onRequestEditRights': onRequestEditRights,
'onError': onError,
'onOutdatedVersion': onOutdatedVersion,
"onMakeActionLink": onMakeActionLink,
@ -216,7 +227,7 @@
docEditor.setHistoryData(histData[ver - 1]); // send the link to the document for viewing the version history
};
// the user is trying to go back to the document from viewing the document version history
config.events['onRequestHistoryClose '] = function () {
config.events['onRequestHistoryClose'] = function () {
document.location.reload();
};
<% } %>
@ -239,6 +250,9 @@
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
config.events['onRequestReferenceData'] = onRequestReferenceData;
// prevent switch the document from the viewing into the editing mode for anonymous users
config.events['onRequestEditRights'] = onRequestEditRights;
}
if (config.editorConfig.createUrl) {

View File

@ -74,6 +74,9 @@ namespace OnlineEditorsExampleMVC
case "rename":
Rename(context);
break;
case "reference":
Reference(context);
break;
}
}
@ -461,7 +464,7 @@ namespace OnlineEditorsExampleMVC
var userAddress = context.Request["userAddress"];
var isEmbedded = context.Request["dmode"];
if (JwtManager.Enabled && isEmbedded == null && userAddress != null)
if (JwtManager.Enabled && isEmbedded == null && userAddress != null && JwtManager.SignatureUseForRequest)
{
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
@ -519,7 +522,7 @@ namespace OnlineEditorsExampleMVC
var version = System.Convert.ToInt32(context.Request["ver"]);
var file = Path.GetFileName(context.Request["file"]);
if (JwtManager.Enabled)
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
{
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
@ -591,5 +594,96 @@ 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,14 +6,16 @@
<add key="filesize-max" value="52428800"/>
<add key="storage-path" value=""/>
<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.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.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

@ -153,7 +153,7 @@
var onRequestMailMergeRecipients = function (event) {
docEditor.setMailMergeRecipients(<%= DataMailMergeRecipients %>); // insert recipient data for mail merge into the file
};
var onRequestSaveAs = function (event) { // the user is trying to save file by clicking Save Copy as... button
var title = event.data.title;
var url = event.data.url;
@ -190,6 +190,19 @@
}
};
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%";
@ -198,7 +211,6 @@
config.events = {
'onAppReady': onAppReady,
'onDocumentStateChange': onDocumentStateChange,
'onRequestEditRights': onRequestEditRights,
'onError': onError,
'onOutdatedVersion': onOutdatedVersion,
'onMakeActionLink': onMakeActionLink,
@ -219,7 +231,7 @@
var histData = <%= HistoryData %>;
docEditor.setHistoryData(histData[ver - 1]); // send the link to the document for viewing the version history
};
config.events['onRequestHistoryClose '] = function () { // the user is trying to go back to the document from viewing the document version history
config.events['onRequestHistoryClose'] = function () { // the user is trying to go back to the document from viewing the document version history
document.location.reload();
};
<% } %>
@ -242,6 +254,9 @@
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
config.events['onRequestReferenceData'] = onRequestReferenceData;
// prevent switch the document from the viewing into the editing mode for anonymous users
config.events['onRequestEditRights'] = onRequestEditRights;
}
if (config.editorConfig.createUrl) {

View File

@ -206,6 +206,17 @@ 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>
@ -222,7 +233,8 @@ namespace OnlineEditorsExample
{ "chat", !user.id.Equals("uid-0") },
{ "reviewGroups", user.reviewGroups },
{ "commentGroups", user.commentGroups },
{ "userInfoGroups", user.userInfoGroups }
{ "userInfoGroups", user.userInfoGroups },
{ "protect", !user.deniedPermissions.Contains("protect") }
}
}
}

View File

@ -121,7 +121,7 @@ namespace ASC.Api.DocumentConverter
{ "region", lang }
};
if (JwtManager.Enabled)
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
{
// create payload object
var payload = new Dictionary<string, object>

View File

@ -29,11 +29,13 @@ 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)
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
{
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)
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
{
var payload = new Dictionary<string, object>
{

View File

@ -68,6 +68,7 @@ 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",
};
@ -130,7 +131,7 @@ namespace OnlineEditorsExample
new Dictionary<string, object>(),
new List<string>(),
null,
new List<string>(),
new List<string>() { "protect" },
descr_user_0,
false
)

View File

@ -26,6 +26,7 @@ using System.Diagnostics;
using System.Web.Configuration;
using System.Linq;
using System.Net;
using System.Net.Sockets;
namespace OnlineEditorsExample
{
@ -71,6 +72,9 @@ namespace OnlineEditorsExample
case "rename":
Rename(context);
break;
case "reference":
Reference(context);
break;
}
}
@ -281,7 +285,7 @@ namespace OnlineEditorsExample
var userAddress = Path.GetFileName(context.Request["userAddress"]);
var isEmbedded = context.Request["dmode"];
if (JwtManager.Enabled && isEmbedded == null && userAddress != null)
if (JwtManager.Enabled && isEmbedded == null && userAddress != null && JwtManager.SignatureUseForRequest)
{
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
@ -338,7 +342,7 @@ namespace OnlineEditorsExample
var version = Path.GetFileName(context.Request["ver"]);
var file = Path.GetFileName(context.Request["file"]);
if (JwtManager.Enabled)
if (JwtManager.Enabled && JwtManager.SignatureUseForRequest)
{
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
@ -409,5 +413,94 @@ 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,15 +6,17 @@
<add key="filesize-max" value="52428800"/>
<add key="storage-path" value=""/>
<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.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.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

@ -1,19 +0,0 @@
# Eclipse
.classpath
.project
.settings/
# Intellij
.idea/
*.iml
*.iws
# Mac
.DS_Store
# Maven
log/
target/
#project
documents

View File

@ -45,6 +45,7 @@ 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"
);
@ -92,22 +93,23 @@ 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);
List.of(FilterState.NULL.toString()), null, true, 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);
List.of("group-2", ""), List.of("group-2"), List.of("group-2", ""), true, 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);
new ArrayList<>(), List.of("group-2"), false, true, 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);
new ArrayList<>(), null, false, false);
}
}

View File

@ -19,6 +19,8 @@
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;
@ -51,8 +53,10 @@ 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;
@ -266,7 +270,7 @@ public class FileController {
@RequestParam("file") final String file) { // history file
try {
// check if a token is enabled or not
if (jwtManager.tokenEnabled()) {
if (jwtManager.tokenEnabled() && jwtManager.tokenUseForRequest()) {
String header = request.getHeader(documentJwtHeader == null // get the document JWT header
|| documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader);
if (header != null && !header.isEmpty()) {
@ -289,7 +293,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) {
if (jwtManager.tokenEnabled() && userAddress != null && jwtManager.tokenUseForRequest()) {
String header = request.getHeader(documentJwtHeader == null // get the document JWT header
|| documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader);
if (header != null && !header.isEmpty()) {
@ -445,4 +449,71 @@ 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,7 +211,8 @@ public class DefaultCallbackManager implements CallbackManager {
}
String headerToken;
if (jwtManager.tokenEnabled()) { // check if a secret key to generate token exists or not
// check if a secret key to generate token exists or not
if (jwtManager.tokenEnabled() && jwtManager.tokenUseForRequest()) {
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,6 +37,8 @@ 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
@ -62,6 +64,10 @@ 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 {
@ -84,7 +90,7 @@ public class DefaultJwtManager implements JwtManager {
} catch (Exception ex) {
throw new RuntimeException("{\"error\":1,\"message\":\"JSON Parsing error\"}");
}
if (tokenEnabled()) { // check if the token is enabled
if (tokenEnabled() && tokenUseForRequest()) { // 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,6 +26,7 @@ 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,5 +27,6 @@ public enum Action {
comment,
chat,
fillForms,
blockcontent
blockcontent,
protect
}

View File

@ -18,6 +18,7 @@
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;
@ -25,6 +26,8 @@ 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
@ -43,4 +46,5 @@ 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,4 +51,5 @@ 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

@ -0,0 +1,24 @@
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()) {
if (jwtManager.tokenEnabled() && jwtManager.tokenUseForRequest()) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("region", lang);
map.put("url", body.getUrl());

View File

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

View File

@ -38,7 +38,8 @@ public class PermissionServices {
final List<Group> commentEditGroups,
final List<Group> commentRemoveGroups,
final List<Group> userInfoGroups,
final Boolean chat) {
final Boolean chat,
final Boolean protect) {
Permission permission = new Permission();
permission.setReviewGroups(reviewGroups); // define the groups whose changes the user can accept/reject
@ -48,6 +49,7 @@ 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,7 +57,8 @@ public class UserServices {
final List<String> editGroups,
final List<String> removeGroups,
final List<String> userInfoGroups, final Boolean favoriteDoc,
final Boolean chat) {
final Boolean chat,
final Boolean protect) {
User newUser = new User();
newUser.setName(name); // set the user name
newUser.setEmail(email); // set the user email
@ -81,7 +82,8 @@ public class UserServices {
commentGroupsEdit,
commentGroupsRemove,
usInfoGroups,
chat); // specify permissions for the current user
chat,
protect); // specify permissions for the current user
newUser.setPermissions(permission);
userRepository.save(newUser); // save a new user

View File

@ -18,8 +18,10 @@
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;
@ -31,6 +33,8 @@ 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
@ -52,6 +56,7 @@ 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
@ -71,7 +76,21 @@ 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,6 +19,7 @@
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;
@ -29,4 +30,5 @@ public class DefaultDocumentWrapper {
private String fileName;
private Boolean favorite;
private Boolean isEnableDirectUrl;
private ReferenceData referenceData;
}

View File

@ -8,10 +8,10 @@ filesize-max=5242880
files.storage=
files.storage.folder=documents
files.docservice.fillforms-docs=.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.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.timeout=120000
files.docservice.history.postfix=-hist
@ -24,6 +24,7 @@ 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,12 +160,23 @@
}
};
var onRequestReferenceData = function(event) { // user refresh external data source
event.data.directUrl = !!config.document.directUrl;
let xhr = new XMLHttpRequest();
xhr.open("POST", "reference");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(event.data));
xhr.onload = function () {
innerAlert(xhr.responseText);
docEditor.setReferenceData(JSON.parse(xhr.responseText));
}
};
config.width = "100%";
config.height = "100%";
config.events = {
"onAppReady": onAppReady,
"onDocumentStateChange": onDocumentStateChange,
'onRequestEditRights': onRequestEditRights,
"onError": onError,
"onOutdatedVersion": onOutdatedVersion,
"onMakeActionLink": onMakeActionLink,
@ -211,6 +222,9 @@
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
config.events['onRequestReferenceData'] = onRequestReferenceData;
// prevent switch the document from the viewing into the editing mode for anonymous users
config.events['onRequestEditRights'] = onRequestEditRights;
}
if (config.editorConfig.createUrl) {

View File

@ -19,6 +19,7 @@
package controllers;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import entities.FileType;
import entities.User;
import helpers.ConfigManager;
@ -63,7 +64,6 @@ import java.util.Scanner;
import static utils.Constants.KILOBYTE_SIZE;
@WebServlet(name = "IndexServlet", urlPatterns = {"/IndexServlet"})
@MultipartConfig
public class IndexServlet extends HttpServlet {
@ -118,6 +118,9 @@ public class IndexServlet extends HttpServlet {
case "rename":
rename(request, response, writer);
break;
case "reference":
reference(request, response, writer);
break;
default:
break;
}
@ -472,7 +475,7 @@ public class IndexServlet extends HttpServlet {
final HttpServletResponse response,
final PrintWriter writer) {
try {
if (DocumentManager.tokenEnabled()) {
if (DocumentManager.tokenEnabled() && DocumentManager.tokenUseForRequest()) {
String documentJwtHeader = ConfigManager.getProperty("files.docservice.header");
@ -517,7 +520,8 @@ public class IndexServlet extends HttpServlet {
String userAddress = request.getParameter("userAddress");
String isEmbedded = request.getParameter("dmode");
if (DocumentManager.tokenEnabled() && isEmbedded == null && userAddress != null) {
if (DocumentManager.tokenEnabled() && isEmbedded == null && userAddress != null
&& DocumentManager.tokenUseForRequest()) {
String documentJwtHeader = ConfigManager.getProperty("files.docservice.header");
@ -633,6 +637,87 @@ 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,6 +77,7 @@ 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<>();
@ -302,6 +303,7 @@ public class FileModel {
private String key;
private Info info;
private Permissions permissions;
private ReferenceData referenceData;
public String getTitle() {
return title;
@ -354,6 +356,13 @@ 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
@ -371,6 +380,7 @@ 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
@ -391,9 +401,25 @@ 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,11 +565,22 @@ 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()) {
if (DocumentManager.tokenEnabled() && DocumentManager.tokenUseForRequest()) {
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()) {
if (DocumentManager.tokenEnabled() && DocumentManager.tokenUseForRequest()) {
String token = (String) body.get("token"); // get the document token
if (token == null) { // if JSON web token is not received
@ -388,7 +388,8 @@ public final class TrackManager {
}
String headerToken = "";
if (DocumentManager.tokenEnabled()) { // check if a secret key to generate token exists or not
// check if a secret key to generate token exists or not
if (DocumentManager.tokenEnabled() && DocumentManager.tokenUseForRequest()) {
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,6 +72,7 @@ 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");
}};
@ -90,7 +91,7 @@ public final class Users {
descriptionUserThird, false));
add(new User("uid-0", null, null,
"", null, new CommentGroups(), new ArrayList<String>(),
null, new ArrayList<String>(), descriptionUserZero, false));
null, Arrays.asList("protect"), 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=.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.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.timeout=120000
files.docservice.url.site=http://documentserver/
@ -20,5 +20,6 @@ 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,13 +161,24 @@
}
};
var onRequestReferenceData = function(event) { // user refresh external data source
event.data.directUrl = !!config.document.directUrl;
let xhr = new XMLHttpRequest();
xhr.open("POST", "IndexServlet?type=reference");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(event.data));
xhr.onload = function () {
innerAlert(xhr.responseText);
docEditor.setReferenceData(JSON.parse(xhr.responseText));
}
};
config = JSON.parse('<%= FileModel.serialize(Model) %>');
config.width = "100%";
config.height = "100%";
config.events = {
"onAppReady": onAppReady,
"onDocumentStateChange": onDocumentStateChange,
'onRequestEditRights': onRequestEditRights,
"onError": onError,
"onOutdatedVersion": onOutdatedVersion,
"onMakeActionLink": onMakeActionLink,
@ -215,6 +226,9 @@
};
// prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename;
config.events['onRequestReferenceData'] = onRequestReferenceData;
// prevent switch the document from the viewing into the editing mode for anonymous users
config.events['onRequestEditRights'] = onRequestEditRights;
}
if (config.editorConfig.createUrl) {

View File

@ -997,7 +997,8 @@ 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
instanceId: userid != "uid-0" ? req.docManager.getInstanceId() : null,
protect: !user.deniedPermissions.includes("protect")
},
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": [".pdf", ".djvu", ".xps", ".oxps"],
"editedDocs": [".docx", ".xlsx", ".csv", ".pptx", ".txt", ".docxf"],
"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"],
"fillDocs": [".docx", ".oform"],
"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"],
"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"],
"storageFolder": "./files",
"storagePath": "/files",
"maxFileSize": 1073741824,

View File

@ -61,6 +61,7 @@ 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"
];
@ -85,7 +86,7 @@ var users = [
false, ["copy", "download", "print"], descr_user_3, false), // other group only
new User("uid-0", null, null,
null, null, {}, [],
null, [], descr_user_0, false),
null, ["protect"], descr_user_0, false),
];
function User(id, name, email, group, reviewGroups, commentGroups, userInfoGroups, favorite, deniedPermissions, descriptions, templates) {

View File

@ -26,6 +26,19 @@ 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
@ -115,7 +128,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: req.docManager.getCustomParams(),
params: getCustomWopiParams(req.query),
});
} catch (ex) {

View File

@ -0,0 +1,4 @@
<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>

After

Width:  |  Height:  |  Size: 638 B

View File

@ -0,0 +1,4 @@
<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>

After

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();
document.location.reload(true);
});
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();
document.location.reload(true);
});
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(); }, 1000);
setTimeout(function () { document.location.reload(true); }, 1000);
return true;
});
jq(document).on("mouseup", ".reload-page", function (event) {
if (event.which == 2) {
setTimeout(function () { document.location.reload(); }, 1000);
setTimeout(function () { document.location.reload(true); }, 1000);
}
return true;
});
@ -288,7 +288,7 @@ if (typeof jQuery != "undefined") {
jq("#embeddedView").remove();
jq.unblockUI();
if (mustReload) {
document.location.reload();
document.location.reload(true);
}
});
@ -303,7 +303,7 @@ if (typeof jQuery != "undefined") {
type: "delete",
url: requestAddress,
complete: function (data) {
document.location.reload();
document.location.reload(true);
}
});
});

View File

@ -18,7 +18,7 @@
.tableRow td:first-child{
flex-grow: 1;
max-width: 100%;
max-width: 50%;
}
.downloadContentCells{
@ -55,6 +55,9 @@
.tableHeaderCellRemove{
padding-left: 7px;
}
.tableRow td:first-child {
max-width: 45%;
}
}
@media (max-width: 986px) and (min-width: 890px){
.tableHeaderCellRemove{
@ -68,18 +71,19 @@
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: 50%;
max-width: 30%;
}
.contentCells-shift{
padding-right: 26px;
}
}
@media (max-width: 769px) and (min-width: 593px){
.tableRow td:first-child{
max-width: 40%;
.contentCells-wopi{
width: unset;
}
}
@media (max-width: 769px) {
@ -88,7 +92,12 @@
border: none;
}
.tableRow td:last-child:after{
width: 95%;
top: 65px;
width: 100%;
height: 1%;
}
.tableRow td:first-child{
max-width: 100%;
}
}
@media (max-width: 593px){
@ -101,3 +110,28 @@
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,6 +605,7 @@ footer table tr td:first-child {
.contentCells-wopi a {
text-decoration: none;
margin-right: 8px;
}
.select-user {

View File

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

View File

@ -208,7 +208,6 @@
config.events = {
"onAppReady": onAppReady,
"onDocumentStateChange": onDocumentStateChange,
"onRequestEditRights": onRequestEditRights,
"onError": onError,
"onOutdatedVersion": onOutdatedVersion,
"onMakeActionLink": onMakeActionLink,
@ -219,6 +218,7 @@
};
if (<%- JSON.stringify(editor.userid) %> != null) {
config.events.onRequestEditRights = onRequestEditRights;
config.events.onRequestHistory = onRequestHistory;
config.events.onRequestHistoryData = onRequestHistoryData;
config.events.onRequestHistoryClose = onRequestHistoryClose;
@ -232,7 +232,10 @@
config.events.onRequestSaveAs = onRequestSaveAs;
}
if (new URL(window.location).searchParams.get("oform") == "false") {
try {
var oformParam = new URL(window.location).searchParams.get("oform");
} catch (e) {}
if (oformParam == "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 2021. All rights reserved.
&copy; Ascensio Systems SIA 2023. 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 %>" method="post">
<input name="access_token" value="<%= token %><%= params %>" type="hidden" />
<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" />
<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 2021. All rights reserved.
&copy; Ascensio Systems SIA 2023. 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.php* 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.json* file:
```
$GLOBALS['STORAGE_PATH'] = "";
$GLOBALS['DOC_SERV_SITE_URL'] = "https://documentserver/";
"storagePath" = "";
"docServSiteUrl" = "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. 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 **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.
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:
![handlerclick](screenshots/handlerclick.png)
Double-click the **Handler Mappings** feature:
In the **Action** panel, click **Add Module Mapping**. In the **Add Module Mapping** dialog box, specify the configuration settings as follows:
![handlerclick](screenshots/handlerclick.png)
* **Request path**: *.php,
* **Module**: FastCgiModule,
* **Executable**: "C:\[Path to your PHP installation]\php-cgi.exe",
* **Name**: PHP via FastCGI.
In the **Action** panel, click **Add Module Mapping**. In the **Add Module Mapping** dialog box, specify the configuration settings as follows:
Click **OK**.
![handler-add](screenshots/handler-add.png)
* **Request path**: *.php,
* **Module**: FastCgiModule,
* **Executable**: "C:\[Path to your PHP installation]\php-cgi.exe",
* **Name**: PHP via FastCGI.
After IIS manager configuration is complete, everything is ready for running the PHP example.
Click **OK**.
![handler-add](screenshots/handler-add.png)
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,7 +122,13 @@ 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. Download the archive with the PHP example and unpack the archive:
2. Install **Composer**:
```
instructions should be here
```
3. Download the archive with the PHP example and unpack the archive:
```
cd /var/www/html
@ -136,40 +142,45 @@ See the detailed guide to learn how to [install Document Server for Linux](https
unzip PHP\ Example.zip
```
3. Change the current directory for the project directory:
4. Change the current directory for the project directory:
```
cd PHP\ Example/
```
4. Edit the *config.php* configuration file. Specify the name of your local server with the ONLYOFFICE Document Server installed.
5. Edit the *config.json* configuration file. Specify the name of your local server with the ONLYOFFICE Document Server installed.
```
nano config.php
nano config.json
```
Edit the following lines:
Edit the following lines:
```
$GLOBALS['STORAGE_PATH'] = "";
$GLOBALS['DOC_SERV_SITE_URL'] = "https://documentserver/";
"storagePath" = "";
"docServSiteUrl" = "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.
5. Set permission for site:
6. Run *composer install*:
```
php composer.phar install
```
7. Set permission for site:
```
chown -R www-data:www-data /var/www/html
```
6. Restart apache:
8. Restart apache:
```
service apache2 restart
```
7. See the result in your browser using the address:
9. See the result in your browser using the address:
```
http://localhost/PHP%20Example/

View File

@ -15,7 +15,12 @@
* limitations under the License.
*/
require dirname(__FILE__) . '/config.php';
namespace OnlineEditorsExamplePhp;
use Exception;
use OnlineEditorsExamplePhp\Helpers\ConfigManager;
use OnlineEditorsExamplePhp\Helpers\ExampleUsers;
use OnlineEditorsExamplePhp\Helpers\JwtManager;
/**
* Check if the request is an AJAX request
@ -76,3 +81,529 @@ 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

@ -1,626 +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.
*/
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,6 +1,7 @@
{
"require-dev": {
"squizlabs/php_codesniffer": "*"
"squizlabs/php_codesniffer": "*",
"ext-mbstring": "*"
},
"scripts": {
"code-sniffer": [
@ -13,5 +14,13 @@
"post-update-cmd": [
"@code-sniffer"
]
},
"autoload-dev": {
"psr-4": {
"OnlineEditorsExamplePhp\\" : "",
"OnlineEditorsExamplePhp\\Helpers\\" : "helpers/",
"OnlineEditorsExamplePhp\\Views\\" : "views/",
"Firebase\\JWT\\" : "lib/jwt/"
}
}
}

View File

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

@ -1,108 +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.
*/
$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,6 +467,8 @@ footer table tr td:first-child {
.stored-edit span {
font-size: 12px;
line-height: 12px;
bottom: 35%;
position: relative;
}
.stored-edit:hover span {
@ -572,7 +574,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,7 +1,4 @@
<?php
namespace PhpExample;
/**
* (c) Copyright Ascensio System SIA 2023
*
@ -18,684 +15,12 @@ namespace PhpExample;
* limitations under the License.
*/
require_once dirname(__FILE__) . '/config.php';
require_once dirname(__FILE__) . '/common.php';
namespace OnlineEditorsExamplePhp;
use OnlineEditorsExamplePhp\Views\DocEditorView;
require_once dirname(__FILE__) . '/functions.php';
require_once dirname(__FILE__) . '/jwtmanager.php';
require_once dirname(__FILE__) . '/users.php';
require_once dirname(__FILE__) . '/vendor/autoload.php';
$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>
$docEditorView = new DocEditorView($_REQUEST);
$docEditorView->render();

View File

@ -15,8 +15,568 @@
* limitations under the License.
*/
require_once dirname(__FILE__) . '/config.php';
require_once dirname(__FILE__) . '/jwtmanager.php';
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
}
/**
* File uploading
@ -154,7 +714,9 @@ function sendRequestToConvertService(
// generate document token
$document_revision_id = generateRevisionId($document_revision_id);
$urlToConverter = $GLOBALS['DOC_SERV_SITE_URL'].$GLOBALS['DOC_SERV_CONVERTER_URL'];
$configManager = new ConfigManager();
$urlToConverter = $configManager->getConfig("docServSiteUrl").
$configManager->getConfig("docServConverterUrl");
$arr = [
"async" => $is_async,
@ -169,11 +731,13 @@ function sendRequestToConvertService(
// add header token
$headerToken = "";
$jwtHeader = $GLOBALS['DOC_SERV_JWT_HEADER'] == "" ? "Authorization" : $GLOBALS['DOC_SERV_JWT_HEADER'];
$jwtHeader = $configManager->getConfig("docServJwtHeader") ==
"" ? "Authorization" : $configManager->getConfig("docServJwtHeader");
if (isJwtEnabled()) {
$headerToken = jwtEncode(["payload" => $arr]);
$arr["token"] = jwtEncode($arr);
$jwtManager = new JwtManager();
if ($jwtManager->isJwtEnabled() && $jwtManager->tokenUseForRequest()) {
$headerToken = $jwtManager->jwtEncode(["payload" => $arr]);
$arr["token"] = $jwtManager->jwtEncode($arr);
}
$data = json_encode($arr);
@ -181,7 +745,7 @@ function sendRequestToConvertService(
// request parameters
$opts = ['http' => [
'method' => 'POST',
'timeout' => $GLOBALS['DOC_SERV_TIMEOUT'],
'timeout' => $configManager->getConfig("docServTimeout"),
'header' => "Content-type: application/json\r\n" .
"Accept: application/json\r\n" .
(empty($headerToken) ? "" : $jwtHeader.": Bearer $headerToken\r\n"),
@ -190,7 +754,7 @@ function sendRequestToConvertService(
];
if (mb_substr($urlToConverter, 0, mb_strlen("https")) === "https") {
if ($GLOBALS['DOC_SERV_VERIFY_PEER_OFF'] === true) {
if ($configManager->getConfig("docServVerifyPeerOff") === true) {
$opts['ssl'] = ['verify_peer' => false, 'verify_peer_name' => false];
}
}
@ -318,3 +882,224 @@ 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

@ -0,0 +1,46 @@
<?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

@ -0,0 +1,187 @@
<?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

@ -0,0 +1,80 @@
<?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

@ -0,0 +1,77 @@
<?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,7 +1,4 @@
<?php
namespace PhpExample;
/**
* (c) Copyright Ascensio System SIA 2023
*
@ -18,529 +15,12 @@ namespace PhpExample;
* limitations under the License.
*/
require_once dirname(__FILE__) . '/config.php';
require_once dirname(__FILE__) . '/common.php';
namespace OnlineEditorsExamplePhp;
use OnlineEditorsExamplePhp\Views\IndexView;
require_once dirname(__FILE__) . '/functions.php';
require_once dirname(__FILE__) . '/users.php';
require_once dirname(__FILE__) . '/vendor/autoload.php';
$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>
$indexView = new IndexView($_REQUEST);
$indexView->render();

View File

@ -251,7 +251,7 @@ if (typeof jQuery != "undefined") {
window.open(url, "_blank");
jq('#hiddenFileName').val("");
jq.unblockUI();
document.location.reload();
document.location.reload(true);
});
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();
document.location.reload(true);
});
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(); }, 1000);
setTimeout(function () { document.location.reload(true); }, 1000);
return true;
});
jq(document).on("mouseup", ".reload-page", function (event) {
if (event.which == 2) {
setTimeout(function () { document.location.reload(); }, 1000);
setTimeout(function () { document.location.reload(true); }, 1000);
}
return true;
});
@ -290,7 +290,7 @@ if (typeof jQuery != "undefined") {
jq("#embeddedView").attr("src", "");
jq.unblockUI();
if (mustReload) {
document.location.reload();
document.location.reload(true);
}
});
@ -305,7 +305,7 @@ if (typeof jQuery != "undefined") {
type: "get",
url: requestAddress,
complete: function (data) {
document.location.reload();
document.location.reload(true);
}
});
});

View File

@ -1,62 +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.
*/
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,10 +2,6 @@
<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

@ -0,0 +1,242 @@
<!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,
'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

@ -0,0 +1,219 @@
<!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

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

View File

@ -1,226 +0,0 @@
<?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

@ -0,0 +1,282 @@
<?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;
// prevent switch the document from the viewing into the editing mode for anonymous users
config.events['onRequestEditRights'] = onRequestEditRights;";
}
$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

@ -0,0 +1,152 @@
<?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

@ -0,0 +1,115 @@
<?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

@ -0,0 +1,58 @@
<?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);
}
}

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