php: objects of helpers used instead of functions

This commit is contained in:
rivexe
2023-02-09 14:51:41 +03:00
parent 37f49af588
commit 1d99c8f58e
15 changed files with 1393 additions and 2933 deletions

View File

@ -18,14 +18,6 @@ namespace OnlineEditorsExamplePhp;
* limitations under the License. * limitations under the License.
*/ */
use Exception;
use OnlineEditorsExamplePhp\Helpers\ConfigManager;
use OnlineEditorsExamplePhp\Helpers\ExampleUsers;
use OnlineEditorsExamplePhp\Helpers\FileUtility;
use OnlineEditorsExamplePhp\Helpers\JwtManager;
use OnlineEditorsExamplePhp\Helpers\TrackManager;
use OnlineEditorsExamplePhp\Helpers\Utils;
/** /**
* Check if the request is an AJAX request * Check if the request is an AJAX request
* *
@ -85,480 +77,3 @@ function nocacheHeaders()
@header("{$name}: {$field_value}"); @header("{$name}: {$field_value}");
} }
} }
/**
* Save copy as...
*
* @return array
*/
function saveas()
{
$fileUtility = new FileUtility();
try {
$result;
$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 = $fileUtility->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($fileUtility->getStoragePath($filename), $data, LOCK_EX); // write data to the new file
$users = new ExampleUsers();
$user = $users->getUser($_GET["user"]);
$fileUtility->createMeta($filename, $user->id, $user->name); // and create meta data for this file
$result["file"] = $filename;
return $result;
} catch (Exception $e) {
$fileUtility->sendlog("SaveAs: ".$e->getMessage(), "webedior-ajax.log");
$result["error"] = "error: " . 1 . "message:" . $e->getMessage();
return $result;
}
}
/**
* Uploading a file
*
* @return array
*/
function upload()
{
$result;
$filename;
if ($_FILES['files']['error'] > 0) {
$result["error"] = 'Error ' . json_encode($_FILES['files']['error']);
return $result;
}
// get the temporary name with which the received file was saved on the server
$tmp = $_FILES['files']['tmp_name'];
// if the temporary name doesn't exist, then an error occurs
if (empty($tmp)) {
$result["error"] = 'No file sent';
return $result;
}
// check if the file was uploaded using HTTP POST
if (is_uploaded_file($tmp)) {
$filesize = $_FILES['files']['size']; // get the file size
$ext = mb_strtolower('.' . pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION)); // get file extension
// check if the file size is correct (it should be less than the max file size, but greater than 0)
$configManager = new ConfigManager();
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;
}
$users = new ExampleUsers();
$user = $users->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 mixed
*/
function track()
{
$fileUtility = new FileUtility();
$trackManager = new TrackManager();
$fileUtility->sendlog("Track START", "webedior-ajax.log");
$fileUtility->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 = $trackManager->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"]);
$fileUtility->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 = $trackManager->commandRequest("forcesave", $data->key);
$fileUtility->sendlog(
" CommandRequest forcesave: " . serialize($commandRequest),
"webedior-ajax.log"
);
}
}
break;
case "MustSave": // status == 2
case "Corrupted": // status == 3
$result = $trackManager->processSave($data, $fileName, $userAddress);
break;
case "MustForceSave": // status == 6
case "CorruptedForceSave": // status == 7
$result = $trackManager->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), '.');
$fileUtility = new FileUtility();
// check if the file with such an extension can be converted
$configManager = new ConfigManager();
if (in_array("." . $extension, $configManager->getConfig("docServConvert")) && $internalExtension != "") {
$fileUri = $post["fileUri"];
$fileUtility = new FileUtility();
if ($fileUri == null || $fileUri == "") {
$fileUri = $fileUtility->serverPath(true) . '/'
. "webeditor-ajax.php"
. "?type=download"
. "&fileName=" . urlencode($fileName)
. "&userAddress=" . $fileUtility->getClientIp();
}
$key = $fileUtility->getDocEditorKey($fileName);
$newFileUri;
$result;
$percent;
try {
// convert file and get the percentage of the conversion completion
$utils = new Utils();
$percent = $utils->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 = $fileUtility->getCorrectName($baseNameWithoutExt . "." . $internalExtension);
if (($data = file_get_contents(str_replace(" ", "%20", $newFileUri))) === false) {
$result["error"] = 'Bad Request';
return $result;
}
file_put_contents($fileUtility->getStoragePath($newFileName), $data, LOCK_EX); // write data to the new file
$users = new ExampleUsers();
$user = $users->getUser($_GET["user"]);
$fileUtility->createMeta($newFileName, $user->id, $user->name); // and create meta data for this file
// delete the original file and its history
$stPath = $fileUtility->getStoragePath($fileName);
unlink($stPath);
\PhpExample\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;
\PhpExample\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"];
$jwtManager = new JwtManager();
$ver = $_GET["ver"];
$file = $_GET["file"];
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"];
$curExt = mb_strtolower(array_pop(explode('.', $newfilename)));
$origExt = $post["ext"];
if ($origExt !== $curExt) {
$newfilename .= '.' . $origExt;
}
$dockey = $post["dockey"];
$meta = ["title" => $newfilename];
$commandRequest = commandRequest("meta", $dockey, $meta); // create a command request with the forcasave method
sendlog(" CommandRequest rename: " . serialize($commandRequest), "webedior-ajax.log");
return ["result" => $commandRequest];
}

View File

@ -1,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": { "require-dev": {
"squizlabs/php_codesniffer": "*" "squizlabs/php_codesniffer": "*",
"ext-mbstring": "*"
}, },
"scripts": { "scripts": {
"code-sniffer": [ "code-sniffer": [
@ -18,8 +19,6 @@
"psr-4": { "psr-4": {
"OnlineEditorsExamplePhp\\" : "", "OnlineEditorsExamplePhp\\" : "",
"OnlineEditorsExamplePhp\\Helpers\\" : "helpers/", "OnlineEditorsExamplePhp\\Helpers\\" : "helpers/",
"OnlineEditorsExamplePhp\\Controllers\\" : "controllers/",
"OnlineEditorsExamplePhp\\Views\\" : "views/",
"Firebase\\JWT\\" : "lib/jwt/" "Firebase\\JWT\\" : "lib/jwt/"
} }
} }

View File

@ -14,14 +14,14 @@
".potx", ".potm", ".pot", ".odp", ".fodp", ".otp", ".rtf", ".mht", ".html", ".htm", ".xml", ".epub", ".fb2"], ".potx", ".potm", ".pot", ".odp", ".fodp", ".otp", ".rtf", ".mht", ".html", ".htm", ".xml", ".epub", ".fb2"],
"docServTimeout": "120000", "docServTimeout": "120000",
"docServSiteUrl": "https://documentserver/", "docServSiteUrl": "http://127.0.0.1/",
"docServConverterUrl": "ConvertService.ashx", "docServConverterUrl": "ConvertService.ashx",
"docServApiUrl": "web-apps/apps/api/documents/api.js", "docServApiUrl": "web-apps/apps/api/documents/api.js",
"docServPreloaderUrl": "web-apps/apps/api/documents/cache-scripts.html", "docServPreloaderUrl": "web-apps/apps/api/documents/cache-scripts.html",
"docServCommandUrl": "coauthoring/CommandService.ashx", "docServCommandUrl": "coauthoring/CommandService.ashx",
"docServJwtSecret": "", "docServJwtSecret": "9GKkwG4oUrswxS0sp1RJ",
"docServJwtHeader": "Authorization", "docServJwtHeader": "Authorization",
"docServJwtUseForRequest": true, "docServJwtUseForRequest": true,

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

@ -4,10 +4,7 @@ namespace OnlineEditorsExamplePhp;
use OnlineEditorsExamplePhp\Helpers\ConfigManager; use OnlineEditorsExamplePhp\Helpers\ConfigManager;
use OnlineEditorsExamplePhp\Helpers\ExampleUsers; use OnlineEditorsExamplePhp\Helpers\ExampleUsers;
use OnlineEditorsExamplePhp\Helpers\FileUtility;
use OnlineEditorsExamplePhp\Helpers\JwtManager; use OnlineEditorsExamplePhp\Helpers\JwtManager;
use OnlineEditorsExamplePhp\Helpers\Users;
use OnlineEditorsExamplePhp\Helpers\Utils;
/** /**
* (c) Copyright Ascensio System SIA 2023 * (c) Copyright Ascensio System SIA 2023
@ -25,22 +22,19 @@ use OnlineEditorsExamplePhp\Helpers\Utils;
* limitations under the License. * limitations under the License.
*/ */
require_once dirname(__FILE__) . '/functions.php';
require_once dirname(__FILE__) . '/vendor/autoload.php'; require_once dirname(__FILE__) . '/vendor/autoload.php';
$users = new ExampleUsers(); $userList = new ExampleUsers();
$configManager = new ConfigManager(); $confgManager = new ConfigManager();
$fileUtility = new FileUtility(); $jwtManager = new JwtManager();
$utils = new Utils(); $user = $userList->getUser($_GET["user"]);
$user = $users->getUser($_GET["user"]);
$isEnableDirectUrl = isset($_GET["directUrl"]) ? filter_var($_GET["directUrl"], FILTER_VALIDATE_BOOLEAN) : false; $isEnableDirectUrl = isset($_GET["directUrl"]) ? filter_var($_GET["directUrl"], FILTER_VALIDATE_BOOLEAN) : false;
// get the file url and upload it // get the file url and upload it
$externalUrl = $_GET["fileUrl"] ?? ""; $externalUrl = $_GET["fileUrl"] ?? "";
if (!empty($externalUrl)) { if (!empty($externalUrl)) {
try { $filename = doUpload($externalUrl);
$filename = $utils->doUpload($externalUrl);
} catch (\Exception $e) {
}
} else { // if the file url doesn't exist, get file name and file extension } else { // if the file url doesn't exist, get file name and file extension
$filename = basename($_GET["fileID"]); $filename = basename($_GET["fileID"]);
} }
@ -48,7 +42,7 @@ $createExt = $_GET["fileExt"] ?? "";
if (!empty($createExt)) { if (!empty($createExt)) {
// and get demo file name by the extension // and get demo file name by the extension
$filename = $fileUtility->tryGetDefaultByType($createExt, $user); $filename = tryGetDefaultByType($createExt, $user);
// create the demo file url // create the demo file url
$new_url = "doceditor.php?fileID=" . $filename . "&user=" . $_GET["user"]; $new_url = "doceditor.php?fileID=" . $filename . "&user=" . $_GET["user"];
@ -56,19 +50,20 @@ if (!empty($createExt)) {
exit; exit;
} }
$fileuri = $fileUtility->fileUri($filename, true); $fileuri = fileUri($filename, true);
$fileuriUser = realpath($configManager->getConfig("storagePath")) === $configManager->getConfig("storagePath") ? $fileuriUser = realpath($confgManager->getConfig("storagePath")) ===
$fileUtility->getDownloadUrl($filename) . "&dmode=emb" : $fileUtility->fileUri($filename); $confgManager->getConfig("storagePath") ?
$directUrl = $fileUtility->getDownloadUrl($filename, false); getDownloadUrl($filename) . "&dmode=emb" : fileUri($filename);
$docKey = $fileUtility->getDocEditorKey($filename); $directUrl = getDownloadUrl($filename, false);
$docKey = getDocEditorKey($filename);
$filetype = mb_strtolower(pathinfo($filename, PATHINFO_EXTENSION)); $filetype = mb_strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$ext = mb_strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION)); $ext = mb_strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION));
$editorsMode = empty($_GET["action"]) ? "edit" : $_GET["action"]; // get the editors mode $editorsMode = empty($_GET["action"]) ? "edit" : $_GET["action"]; // get the editors mode
$canEdit = in_array($ext, $configManager->getConfig("docServEdited")); // check if the file can be edited $canEdit = in_array($ext, $confgManager->getConfig("docServEdited")); // check if the file can be edited
if ((!$canEdit && $editorsMode == "edit" if ((!$canEdit && $editorsMode == "edit"
|| $editorsMode == "fillForms") || $editorsMode == "fillForms")
&& in_array($ext, $configManager->getConfig("docServFillforms")) && in_array($ext, $confgManager->getConfig("docServFillforms"))
) { ) {
$editorsMode = "fillForms"; $editorsMode = "fillForms";
$canEdit = true; $canEdit = true;
@ -79,8 +74,8 @@ $submitForm = $editorsMode == "fillForms" && $user->id == "uid-1" && !1;
$mode = $canEdit && $editorsMode != "view" ? "edit" : "view"; // define if the editing mode is edit or view $mode = $canEdit && $editorsMode != "view" ? "edit" : "view"; // define if the editing mode is edit or view
$type = empty($_GET["type"]) ? "desktop" : $_GET["type"]; $type = empty($_GET["type"]) ? "desktop" : $_GET["type"];
$templatesImageUrl = $fileUtility->getTemplateImageUrl($filename); // templates image url in the "From Template" section $templatesImageUrl = getTemplateImageUrl($filename); // templates image url in the "From Template" section
$createUrl = $fileUtility->getCreateUrl($filename, $user->id, $type); $createUrl = getCreateUrl($filename, $user->id, $type);
$templates = [ $templates = [
[ [
"image" => "", "image" => "",
@ -97,10 +92,10 @@ $templates = [
// specify the document config // specify the document config
$config = [ $config = [
"type" => $type, "type" => $type,
"documentType" => $fileUtility->getDocumentType($filename), "documentType" => getDocumentType($filename),
"document" => [ "document" => [
"title" => $filename, "title" => $filename,
"url" => $fileUtility->getDownloadUrl($filename), "url" => getDownloadUrl($filename),
"directUrl" => $isEnableDirectUrl ? $directUrl : "", "directUrl" => $isEnableDirectUrl ? $directUrl : "",
"fileType" => $filetype, "fileType" => $filetype,
"key" => $docKey, "key" => $docKey,
@ -132,7 +127,7 @@ $config = [
"actionLink" => empty($_GET["actionLink"]) ? null : json_decode($_GET["actionLink"]), "actionLink" => empty($_GET["actionLink"]) ? null : json_decode($_GET["actionLink"]),
"mode" => $mode, "mode" => $mode,
"lang" => empty($_COOKIE["ulang"]) ? "en" : $_COOKIE["ulang"], "lang" => empty($_COOKIE["ulang"]) ? "en" : $_COOKIE["ulang"],
"callbackUrl" => $fileUtility->getCallbackUrl($filename), // absolute URL to the document storage service "callbackUrl" => getCallbackUrl($filename), // absolute URL to the document storage service
"coEditing" => $editorsMode == "view" && $user->id == "uid-0" ? [ "coEditing" => $editorsMode == "view" && $user->id == "uid-0" ? [
"mode" => "strict", "mode" => "strict",
"change" => false, "change" => false,
@ -163,7 +158,7 @@ $config = [
"goback" => [ // settings for the Open file location menu button and upper right corner button "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 // the absolute URL to the website address which will be opened
// when clicking the Open file location menu button // when clicking the Open file location menu button
"url" => $fileUtility->serverPath(), "url" => serverPath(),
], ],
], ],
], ],
@ -172,38 +167,37 @@ $config = [
// an image for inserting // an image for inserting
$dataInsertImage = $isEnableDirectUrl ? [ $dataInsertImage = $isEnableDirectUrl ? [
"fileType" => "png", "fileType" => "png",
"url" => $fileUtility->serverPath(true) . "/css/images/logo.png", "url" => serverPath(true) . "/css/images/logo.png",
"directUrl" => $fileUtility->serverPath(false) . "/css/images/logo.png", "directUrl" => serverPath(false) . "/css/images/logo.png",
] : [ ] : [
"fileType" => "png", "fileType" => "png",
"url" => $fileUtility->serverPath(true) . "/css/images/logo.png", "url" => serverPath(true) . "/css/images/logo.png",
]; ];
// a document for comparing // a document for comparing
$dataCompareFile = $isEnableDirectUrl ? [ $dataCompareFile = $isEnableDirectUrl ? [
"fileType" => "docx", "fileType" => "docx",
"url" => $fileUtility->serverPath(true) . "/webeditor-ajax.php?type=assets&name=sample.docx", "url" => serverPath(true) . "/webeditor-ajax.php?type=assets&name=sample.docx",
"directUrl" => $fileUtility->serverPath(false) . "/webeditor-ajax.php?type=assets&name=sample.docx", "directUrl" => serverPath(false) . "/webeditor-ajax.php?type=assets&name=sample.docx",
] : [ ] : [
"fileType" => "docx", "fileType" => "docx",
"url" => $fileUtility->serverPath(true) . "/webeditor-ajax.php?type=assets&name=sample.docx", "url" => serverPath(true) . "/webeditor-ajax.php?type=assets&name=sample.docx",
]; ];
// recipients data for mail merging // recipients data for mail merging
$dataMailMergeRecipients = $isEnableDirectUrl ? [ $dataMailMergeRecipients = $isEnableDirectUrl ? [
"fileType" => "csv", "fileType" => "csv",
"url" => $fileUtility->serverPath(true) . "/webeditor-ajax.php?type=csv", "url" => serverPath(true) . "/webeditor-ajax.php?type=csv",
"directUrl" => $fileUtility->serverPath(false) . "/webeditor-ajax.php?type=csv", "directUrl" => serverPath(false) . "/webeditor-ajax.php?type=csv",
] : [ ] : [
"fileType" => "csv", "fileType" => "csv",
"url" => $fileUtility->serverPath(true) . "/webeditor-ajax.php?type=csv", "url" => serverPath(true) . "/webeditor-ajax.php?type=csv",
]; ];
// users data for mentions // users data for mentions
$usersForMentions = $user->id != "uid-0" ? $users->getUsersForMentions($user->id) : null; $usersForMentions = $user->id != "uid-0" ? $userList->getUsersForMentions($user->id) : null;
// check if the secret key to generate token exists // check if the secret key to generate token exists
$jwtManager = new JwtManager();
if ($jwtManager->isJwtEnabled()) { if ($jwtManager->isJwtEnabled()) {
$config["token"] = $jwtManager->jwtEncode($config); // encode config into the token $config["token"] = $jwtManager->jwtEncode($config); // encode config into the token
// encode the dataInsertImage object into the token // encode the dataInsertImage object into the token
@ -225,7 +219,7 @@ if ($jwtManager->isJwtEnabled()) {
maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui" /> maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui" />
<meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-capable" content="yes" /> <meta name="mobile-web-app-capable" content="yes" />
<link rel="icon" href="css/images/<?php echo $fileUtility->getDocumentType($filename) ?>.ico" type="image/x-icon" /> <link rel="icon" href="css/images/<?php echo getDocumentType($filename) ?>.ico" type="image/x-icon" />
<title>ONLYOFFICE</title> <title>ONLYOFFICE</title>
<style> <style>
@ -258,8 +252,8 @@ if ($jwtManager->isJwtEnabled()) {
</style> </style>
<script type="text/javascript" src=" <script type="text/javascript" src="
<?php echo $configManager->getConfig("docServSiteUrl"). <?php echo $confgManager->getConfig("docServSiteUrl").
$configManager->getConfig("docServApiUrl") ?>"> $confgManager->getConfig("docServApiUrl") ?>">
</script> </script>
<script type="text/javascript"> <script type="text/javascript">
@ -401,11 +395,11 @@ if ($jwtManager->isJwtEnabled()) {
var сonnectEditor = function () { var сonnectEditor = function () {
<?php <?php
if (!file_exists($fileUtility->getStoragePath($filename))) { if (!file_exists(getStoragePath($filename))) {
echo "alert('File not found'); return;"; echo "alert('File not found'); return;";
} }
?> ?>
config = <?php echo json_encode($config) ?>; config = <?php echo json_encode($config) ?>;
@ -426,44 +420,44 @@ if ($jwtManager->isJwtEnabled()) {
}; };
<?php <?php
$out = $fileUtility->getHistory($filename, $filetype, $docKey, $fileuri, $isEnableDirectUrl); $out = getHistory($filename, $filetype, $docKey, $fileuri, $isEnableDirectUrl);
$history = $out[0]; $history = $out[0];
$historyData = $out[1]; $historyData = $out[1];
?> ?>
<?php if ($user->id != "uid-0") { ?> <?php if ($user->id != "uid-0") { ?>
<?php if ($history != null && $historyData != null) { ?> <?php if ($history != null && $historyData != null) { ?>
// the user is trying to show the document version history // the user is trying to show the document version history
config.events['onRequestHistory'] = function () { config.events['onRequestHistory'] = function () {
// show the document version history // show the document version history
docEditor.refreshHistory(<?php echo json_encode($history) ?>); docEditor.refreshHistory(<?php echo json_encode($history) ?>);
}; };
// the user is trying to click the specific document version in the document version history // the user is trying to click the specific document version in the document version history
config.events['onRequestHistoryData'] = function (event) { config.events['onRequestHistoryData'] = function (event) {
var ver = event.data; var ver = event.data;
var histData = <?php echo json_encode($historyData) ?>; var histData = <?php echo json_encode($historyData) ?>;
// send the link to the document for viewing the version history // send the link to the document for viewing the version history
docEditor.setHistoryData(histData[ver - 1]); docEditor.setHistoryData(histData[ver - 1]);
}; };
// the user is trying to go back to the document from viewing the document 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(); document.location.reload();
}; };
<?php } ?> <?php } ?>
// add mentions for not anonymous users // add mentions for not anonymous users
config.events['onRequestUsers'] = function () { config.events['onRequestUsers'] = function () {
docEditor.setUsers({ // set a list of users to mention in the comments docEditor.setUsers({ // set a list of users to mention in the comments
"users": <?php echo json_encode($usersForMentions) ?> "users": <?php echo json_encode($usersForMentions) ?>
}); });
}; };
// the user is mentioned in a comment // the user is mentioned in a comment
config.events['onRequestSendNotify'] = function (event) { config.events['onRequestSendNotify'] = function (event) {
event.data.actionLink = replaceActionLink(location.href, JSON.stringify(event.data.actionLink)); event.data.actionLink = replaceActionLink(location.href, JSON.stringify(event.data.actionLink));
var data = JSON.stringify(event.data); var data = JSON.stringify(event.data);
innerAlert("onRequestSendNotify: " + data); innerAlert("onRequestSendNotify: " + data);
}; };
// prevent file renaming for anonymous users // prevent file renaming for anonymous users
config.events['onRequestRename'] = onRequestRename; config.events['onRequestRename'] = onRequestRename;
<?php } ?> <?php } ?>
if (config.editorConfig.createUrl) { if (config.editorConfig.createUrl) {
@ -488,9 +482,9 @@ if ($jwtManager->isJwtEnabled()) {
</script> </script>
</head> </head>
<body> <body>
<form id="form1"> <form id="form1">
<div id="iframeEditor"> <div id="iframeEditor">
</div> </div>
</form> </form>
</body> </body>
</html> </html>

File diff suppressed because it is too large Load Diff

View File

@ -155,7 +155,6 @@ final class ExampleUsers
{ {
foreach ($this->users as $user) { foreach ($this->users as $user) {
if ($user->id == $id) { if ($user->id == $id) {
sendlog("User ". $user->id, "common.log");
return $user; return $user;
} }
} }

View File

@ -1,814 +0,0 @@
<?php
namespace OnlineEditorsExamplePhp\Helpers;
/**
* (c) Copyright Ascensio System SIA 2023
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
final class FileUtility
{
/**
* Put log files into the log folder
*
* @param string $msg
* @param integer $logFileName
*
* @return void
*/
public 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
*/
public 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
*/
public 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
*/
public function serverPath($forDocumentServer = null)
{
$configManager = new ConfigManager();
return $forDocumentServer && $configManager->getConfig("exampleUrl") !== null
&& $configManager->getConfig("exampleUrl") != ""
? $configManager->getConfig("exampleUrl")
: ($this->getScheme() . '://' . $_SERVER['HTTP_HOST']);
}
/**
* Get current user host address
*
* @param string $userAddress
*
* @return string
*/
public function getCurUserHostAddress($userAddress = null)
{
$configManager = new ConfigManager();
if ($configManager->getConfig("alone")) {
if (empty($configManager->getConfig("storagePath"))) {
return "Storage";
}
return "";
}
if (is_null($userAddress)) {
$userAddress = $this->getClientIp();
}
return preg_replace("[^0-9a-zA-Z.=]", '_', $userAddress);
}
/**
* Get an internal file extension
*
* @param string $filename
*
* @return string
*/
public function getInternalExtension($filename)
{
$configManager = new ConfigManager();
$ext = mb_strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION));
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
*/
public function getTemplateImageUrl($filename)
{
$configManager = new ConfigManager();
$ext = mb_strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION));
$path = $this->serverPath(true) . "/css/images/";
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
*/
public function getDocumentType($filename)
{
$configManager = new ConfigManager();
$ext = mb_strtolower('.' . pathinfo($filename, PATHINFO_EXTENSION));
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
*/
public 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
*/
public 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 = dirname(__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 . $this->getCurUserHostAddress($userAddress) . DIRECTORY_SEPARATOR;
}
if (!file_exists($directory) && !is_dir($directory)) {
mkdir($directory);
}
$this->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
*/
public 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 = dirname(__DIR__) . DIRECTORY_SEPARATOR . $storagePath .
$this->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
*/
public 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
*/
public 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
*/
public 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
*/
public 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 = dirname(__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 . $this->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));
// get the time of element modification
$dat = filemtime($directory . DIRECTORY_SEPARATOR . $fileName);
$result[$dat] = (object) [ // and write the file to the result
"name" => $fileName,
"documentType" => $this->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
*/
public function getVirtualPath($forDocumentServer)
{
$configManager = new ConfigManager();
$storagePath = trim(str_replace(['/', '\\'], '/', $configManager->getConfig("storagePath")), '/');
$storagePath = $storagePath != "" ? $storagePath . '/' : "";
if (realpath($storagePath) === $storagePath) {
$virtPath = $this->serverPath($forDocumentServer) . '/' . $storagePath . '/';
} else {
$virtPath = $this->serverPath($forDocumentServer) . '/' .
$storagePath . $this->getCurUserHostAddress() . '/';
}
$this->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
*/
public function createMeta($fileName, $uid, $uname, $userAddress = null)
{
$histDir = $this->getHistoryDir($this->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
*/
public function fileUri($file_name, $forDocumentServer = null)
{
// add encoded file name to the virtual path
$uri = $this->getVirtualPath($forDocumentServer) . rawurlencode($file_name);
return $uri;
}
/**
* Get file information
*
* @param string $fileId
*
* @return array|string
*/
public function getFileInfo($fileId)
{
$storedFiles = $this->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" => $this->getFileVersion($this->getHistoryDir($this->getStoragePath($value->name))),
"id" => $this->getDocEditorKey($value->name),
"contentLength" => number_format(filesize($this->getStoragePath($value->name)) / 1024, 2)." KB",
"pureContentLength" => filesize($this->getStoragePath($value->name)),
"title" => $value->name,
"updated" => date(DATE_ATOM, filemtime($this->getStoragePath($value->name))),
];
// get file information by its id
if ($fileId != null) {
if ($fileId == $this->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
*/
public 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
*/
public 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($this->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
*/
public function getDocEditorKey($fileName)
{
$utils = new Utils();
// get document key by adding local file url to the current user host address
$key = $this->getCurUserHostAddress() . $this->fileUri($fileName);
$stat = filemtime($this->getStoragePath($fileName)); // get creation time
$key = $key . $stat; // and add it to the document key
return $utils->generateRevisionId($key); // generate the document key value
}
/**
* Get demo file name by the extension
*
* @param string $createExt
* @param Users $user
*
* @return string
*/
public function tryGetDefaultByType($createExt, $user)
{
$demoName = ($_GET["sample"] ? "sample." : "new.") . $createExt;
$demoPath = "assets" . DIRECTORY_SEPARATOR . ($_GET["sample"] ? "sample" : "new") . DIRECTORY_SEPARATOR;
$demoFilename = $this->getCorrectName($demoName);
if (!@copy(
dirname(__FILE__) .
DIRECTORY_SEPARATOR .
$demoPath .
$demoName,
$this->getStoragePath($demoFilename)
)) {
$this->sendlog("Copy file error to ". $this->getStoragePath($demoFilename), "common.log");
// Copy error!!!
}
// create demo file meta information
$this->createMeta($demoFilename, $user->id, $user->name);
return $demoFilename;
}
/**
* Get the callback url
*
* @param string $fileName
*
* @return string
*/
public function getCallbackUrl($fileName)
{
return $this->serverPath(true) . '/'
. "webeditor-ajax.php"
. "?type=track"
. "&fileName=" . urlencode($fileName)
. "&userAddress=" . $this->getClientIp();
}
/**
* Get url to the created file
*
* @param string $fileName
* @param string $uid
* @param string $type
*
* @return string
*/
public function getCreateUrl($fileName, $uid, $type)
{
$ext = trim($this->getInternalExtension($fileName), '.');
return $this->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
*/
public function getHistoryDownloadUrl($fileName, $version, $file, $isServer = true)
{
$userAddress = $isServer ? "&userAddress=" . $this->getClientIp() : "";
return $this->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
*/
public function getDownloadUrl($fileName, $isServer = true)
{
$userAddress = $isServer ? "&userAddress=" . $this->getClientIp() : "";
return $this->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
*/
public function getHistory($filename, $filetype, $docKey, $fileuri, $isEnableDirectUrl)
{
$configManager = new ConfigManager();
$storagePath = $configManager->getConfig("storagePath");
$histDir = $this->getHistoryDir($this->getStoragePath($filename)); // get the path to the file history
// check if the file was modified (the file version is greater than 0)
if ($this->getFileVersion($histDir) > 0) {
$curVer = $this->getFileVersion($histDir);
$hist = [];
$histData = [];
for ($i = 1; $i <= $curVer; $i++) { // run through all the file versions
$obj = [];
$dataObj = [];
$verDir = $this->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($this->getStoragePath("")));
$dataObj["fileType"] = $fileExe;
$dataObj["key"] = $key;
$directUrl = $i == $curVer ? $this->fileUri($filename, false) :
$this->getHistoryDownloadUrl($filename, $i, "prev.".$fileExe, false);
$prevFileUrl = $i == $curVer ? $fileuri : $this->getHistoryDownloadUrl($filename, $i, "prev.".$fileExe);
if (realpath($storagePath) === $storagePath) {
$prevFileUrl = $i == $curVer ? $this->getDownloadUrl($filename) :
$this->getHistoryDownloadUrl($filename, $i, "prev.".$fileExe);
if ($isEnableDirectUrl) {
$directUrl = $i == $curVer ? $this->getDownloadUrl($filename, false) :
$this->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($this->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"] = $this->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;
}
return [];
}
}

View File

@ -1,365 +0,0 @@
<?php
namespace OnlineEditorsExamplePhp\Helpers;
use Exception;
/**
* (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 TrackManager
{
/**
* Read request body
*
* @return int|array
*/
public function readBody()
{
$result["error"] = 0;
// 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";
return $result;
}
$data = json_decode($body_stream, false);
// check if the response is correct
if ($data === null) {
$result["error"] = "Bad Response";
return $result;
}
$fileUtility = new FileUtility();
$fileUtility->sendlog(" InputStream data: " . serialize($data), "webedior-ajax.log");
// check if the document token is enabled
$jwtManager = new JwtManager();
if ($jwtManager->isJwtEnabled()) {
$fileUtility->sendlog(" jwt enabled, checking tokens", "webedior-ajax.log");
$inHeader = false;
$data = "";
$configManager = new ConfigManager();
$jwtHeader = $configManager->getConfig("docServJwtHeader") ==
"" ? "Authorization" : $configManager->getConfig("docServJwtHeader");
if (!empty($data["token"])) { // if the document token is in the data
$data = $jwtManager->jwtDecode($data["token"]); // decode it
$fileUtility->sendlog(" jwt in body", "webedior-ajax.log");
} elseif (!empty(apache_request_headers()[$jwtHeader])) { // if the Authorization header exists
$data = $jwtManager->jwtDecode(
mb_substr(
apache_request_headers()[$jwtHeader],
mb_strlen("Bearer ")
)
); // decode its part after Authorization prefix
$inHeader = true;
$fileUtility->sendlog(" jwt in header", "webedior-ajax.log");
} else { // otherwise, an error occurs
$fileUtility->sendlog(" jwt token wasn't found in body or headers", "webedior-ajax.log");
$result["error"] = "Expected JWT";
return $result;
}
if ($data === "") { // invalid signature error
$fileUtility->sendlog(" token was found but signature is invalid", "webedior-ajax.log");
$result["error"] = "Invalid JWT signature";
return $result;
}
if ($inHeader) {
$data = $data->payload;
}
}
return $data;
}
/**
* File saving process
*
* @param mixed $data
* @param string $fileName
* @param string $userAddress
*
* @return array
*/
public function processSave($data, $fileName, $userAddress)
{
$downloadUri = $data->url;
if ($downloadUri === null) {
$result["error"] = 1;
return $result;
}
$curExt = mb_strtolower('.' . pathinfo($fileName, PATHINFO_EXTENSION)); // get current file extension
$downloadExt = mb_strtolower('.' . $data->filetype); // get the extension of the downloaded file
$newFileName = $fileName;
// convert downloaded file to the file with the current extension if these extensions aren't equal
if ($downloadExt != $curExt) {
$utils = new Utils();
$key = $utils->generateRevisionId($downloadUri);
try {
$fileUtility = new FileUtility();
$fileUtility->sendlog(" Convert " . $downloadUri . " from " .
$downloadExt . " to " . $curExt, "webedior-ajax.log");
$convertedUri; // convert file and give url to a new file
$percent = $utils->getConvertedUri(
$downloadUri,
$downloadExt,
$curExt,
$key,
false,
$convertedUri
);
if (!empty($convertedUri)) {
$downloadUri = $convertedUri;
} else {
$fileUtility->sendlog(" Convert after save convertedUri is empty", "webedior-ajax.log");
$baseNameWithoutExt = mb_substr($fileName, 0, mb_strlen($fileName) - mb_strlen($curExt));
// get the correct file name if it already exists
$newFileName = $fileUtility->getCorrectName($baseNameWithoutExt . $downloadExt, $userAddress);
}
} catch (Exception $e) {
$fileUtility->sendlog(" Convert after save ".$e->getMessage(), "webedior-ajax.log");
$baseNameWithoutExt = mb_substr($fileName, 0, mb_strlen($fileName) - mb_strlen($curExt));
$newFileName = $fileUtility->getCorrectName($baseNameWithoutExt . $downloadExt, $userAddress);
}
}
$saved = 1;
if (!(($new_data = file_get_contents(
$downloadUri,
false,
stream_context_create(["http" => ["timeout" => 5]])
)) === false)
) {
$storagePath = $fileUtility->getStoragePath($newFileName, $userAddress); // get the file path
$histDir = $fileUtility->getHistoryDir($storagePath); // get the path to the history direction
// get the path to the file version
$verDir = $fileUtility->getVersionDir($histDir, $fileUtility->getFileVersion($histDir));
mkdir($verDir); // if the path doesn't exist, create it
// get the path to the previous file version and rename the storage path with it
rename($fileUtility->getStoragePath($fileName, $userAddress), $verDir .
DIRECTORY_SEPARATOR . "prev" . $curExt);
file_put_contents($storagePath, $new_data, LOCK_EX); // save file to the storage directory
if ($changesData = file_get_contents(
$data->changesurl,
false,
stream_context_create(["http" => ["timeout" => 5]])
)
) {
// save file changes to the diff.zip archive
file_put_contents($verDir . DIRECTORY_SEPARATOR .
"diff.zip", $changesData, LOCK_EX);
}
$histData = empty($data->changeshistory) ? null : $data->changeshistory;
if (empty($histData)) {
$histData = json_encode($data->history, JSON_PRETTY_PRINT);
}
if (!empty($histData)) {
// write the history changes to the changes.json file
file_put_contents($verDir .
DIRECTORY_SEPARATOR . "changes.json", $histData, LOCK_EX);
}
// write the key value to the key.txt file
file_put_contents($verDir .
DIRECTORY_SEPARATOR . "key.txt", $data->key, LOCK_EX);
// get the path to the forcesaved file version
$forcesavePath = $fileUtility->getForcesavePath($newFileName, $userAddress, false);
if ($forcesavePath != "") { // if the forcesaved file version exists
unlink($forcesavePath); // remove it
}
$saved = 0;
}
$result["error"] = $saved;
return $result;
}
/**
* File force saving process
*
* @param mixed $data
* @param mixed $fileName
* @param mixed $userAddress
*
* @return array
*/
public function processForceSave($data, $fileName, $userAddress)
{
$downloadUri = $data->url;
$fileUtility = new FileUtility();
if ($downloadUri === null) {
$result["error"] = 1;
return $result;
}
$curExt = mb_strtolower('.' . pathinfo($fileName, PATHINFO_EXTENSION)); // get current file extension
$downloadExt = mb_strtolower('.' . $data->filetype); // get the extension of the downloaded file
$newFileName = false;
// convert downloaded file to the file with the current extension if these extensions aren't equal
if ($downloadExt != $curExt) {
$utils = new Utils();
$key = $utils->generateRevisionId($downloadUri);
try {
$fileUtility->sendlog(" Convert " . $downloadUri . " from " .
$downloadExt . " to " . $curExt, "webedior-ajax.log");
$convertedUri; // convert file and give url to a new file
$percent = $utils->getConvertedUri(
$downloadUri,
$downloadExt,
$curExt,
$key,
false,
$convertedUri
);
if (!empty($convertedUri)) {
$downloadUri = $convertedUri;
} else {
$fileUtility->sendlog(" Convert after save convertedUri is empty", "webedior-ajax.log");
$baseNameWithoutExt = mb_substr($fileName, 0, mb_strlen($fileName) - mb_strlen($curExt));
$newFileName = true;
}
} catch (Exception $e) {
$fileUtility->sendlog(" Convert after save ".$e->getMessage(), "webedior-ajax.log");
$newFileName = true;
}
}
$saved = 1;
if (!(($new_data = file_get_contents(
$downloadUri,
false,
stream_context_create(["http" => ["timeout" => 5]])
)) === false)
) {
$baseNameWithoutExt = mb_substr($fileName, 0, mb_strlen($fileName) - mb_strlen($curExt));
$isSubmitForm = $data->forcesavetype == 3; // SubmitForm
if ($isSubmitForm) {
if ($newFileName) {
$fileName = $fileUtility->getCorrectName($baseNameWithoutExt .
"-form" . $downloadExt, $userAddress); // get the correct file name if it already exists
} else {
$fileName =
$fileUtility->getCorrectName($baseNameWithoutExt . "-form" . $curExt, $userAddress);
}
$forcesavePath = $fileUtility->getStoragePath($fileName, $userAddress);
} else {
if ($newFileName) {
$fileName = $fileUtility->getCorrectName($baseNameWithoutExt . $downloadExt, $userAddress);
}
// create forcesave path if it doesn't exist
$forcesavePath = $fileUtility->getForcesavePath($fileName, $userAddress, false);
if ($forcesavePath == "") {
$forcesavePath = $fileUtility->getForcesavePath($fileName, $userAddress, true);
}
}
file_put_contents($forcesavePath, $new_data, LOCK_EX);
if ($isSubmitForm) {
$uid = $data->actions[0]->userid; // get the user id
// create meta data for the forcesaved file
$fileUtility->createMeta($fileName, $uid, "Filling Form", $userAddress);
}
$saved = 0;
}
$result["error"] = $saved;
return $result;
}
/**
* Create a command request
*
* @param string $method
* @param string $key
* @param string $meta
*
* @return false|string
*/
public function commandRequest($method, $key, $meta = null)
{
$configManager = new ConfigManager();
$documentCommandUrl = $configManager->getConfig("docServSiteUrl").
$configManager->getConfig("docServCommandUrl");
$arr = [
"c" => $method,
"key" => $key,
];
if ($meta) {
$arr["meta"] = $meta;
}
$headerToken = "";
$jwtHeader = $configManager->getConfig("docServJwtHeader") ==
"" ? "Authorization" : $configManager->getConfig("docServJwtHeader");
$jwtManager = new JwtManager();
if ($jwtManager->isJwtEnabled()) { // check if a secret key to generate token exists or not
// encode a payload object into a header token
$headerToken = $jwtManager->jwtEncode(["payload" => $arr]);
$arr["token"] = $jwtManager->jwtEncode($arr); // encode a payload object into a body token
}
$data = json_encode($arr);
$opts = ['http' => [
'method' => 'POST',
'header' => "Content-type: application/json\r\n" .
// add a header Authorization with a header token and Authorization prefix in it
(empty($headerToken) ? "" : $jwtHeader.
": Bearer $headerToken\r\n"),
'content' => $data,
]];
if (mb_substr($documentCommandUrl, 0, mb_strlen("https")) === "https") {
if ($configManager->getConfig("docServVerifyPeerOff") === true) {
$opts['ssl'] = ['verify_peer' => false, 'verify_peer_name' => false];
}
}
$context = stream_context_create($opts);
$response_data = file_get_contents($documentCommandUrl, false, $context);
return $response_data;
}
}

View File

@ -1,331 +0,0 @@
<?php
namespace OnlineEditorsExamplePhp\Helpers;
use Exception;
/**
* (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 Utils
{
/**
* File uploading
*
* @param string $fileUri
*
* @throws Exception If file type is not supported or copy operation is unsuccessful
*
* @return null
*/
public function doUpload($fileUri)
{
$fileUtility = new FileUtility();
$_fileName = $fileUtility->getCorrectName($fileUri);
// check if file extension is supported by the editor
$ext = mb_strtolower('.' . pathinfo($_fileName, PATHINFO_EXTENSION));
if (!in_array($ext, $fileUtility->getFileExts())) {
throw new Exception("File type is not supported");
}
// check if the file copy operation is successful
if (!@copy($fileUri, $fileUtility->getStoragePath($_fileName))) {
$errors = error_get_last();
$err = "Copy file error: " . $errors['type'] . "<br />\n" . $errors['message'];
throw new Exception($err);
}
return $_fileName;
}
/**
* Generate an error code table
*
* @param string $errorCode Error code
*
* @throws Exception If error code is unknown
*
* @return null
*/
public function processConvServResponceError($errorCode)
{
$errorMessageTemplate = "Error occurred in the document service: ";
$errorMessage = '';
// add the error message to the error message template depending on the error code
switch ($errorCode) {
case -8:
$errorMessage = $errorMessageTemplate . "Error document VKey";
break;
case -7:
$errorMessage = $errorMessageTemplate . "Error document request";
break;
case -6:
$errorMessage = $errorMessageTemplate . "Error database";
break;
case -5:
$errorMessage = $errorMessageTemplate . "Incorrect password";
break;
case -4:
$errorMessage = $errorMessageTemplate . "Error download error";
break;
case -3:
$errorMessage = $errorMessageTemplate . "Error convertation error";
break;
case -2:
$errorMessage = $errorMessageTemplate . "Error convertation timeout";
break;
case -1:
$errorMessage = $errorMessageTemplate . "Error convertation unknown";
break;
case 0: // if the error code is equal to 0, the error message is empty
break;
default: // default value for the error message
$errorMessage = $errorMessageTemplate . "ErrorCode = " . $errorCode;
break;
}
throw new Exception($errorMessage);
}
/**
* Translation key to a supported form.
*
* @param string $expected_key Expected key
*
* @return string key
*/
public function generateRevisionId($expected_key)
{
if (mb_strlen($expected_key) > 20) {
$expected_key = crc32($expected_key);
} // if the expected key length is greater than 20, calculate the crc32 for it
$key = preg_replace("[^0-9-.a-zA-Z_=]", "_", $expected_key);
$key = mb_substr($key, 0, min([mb_strlen($key), 20])); // the resulting key length is 20 or less
return $key;
}
/**
* Request for conversion to a service.
*
* @param string $document_uri Uri for the document to convert
* @param string $from_extension Document extension
* @param string $to_extension Extension to which to convert
* @param string $document_revision_id Key for caching on service
* @param bool $is_async Perform conversions asynchronously
* @param string $filePass
* @param string $lang
*
* @return string request result of conversion
*/
public function sendRequestToConvertService(
$document_uri,
$from_extension,
$to_extension,
$document_revision_id,
$is_async,
$filePass,
$lang
) {
if (empty($from_extension)) {
$path_parts = pathinfo($document_uri);
$from_extension = mb_strtolower($path_parts['extension']);
}
// if title is undefined, then replace it with a random guid
$title = basename($document_uri);
if (empty($title)) {
$fileUtility = new FileUtility();
$title = $fileUtility->guid();
}
if (empty($document_revision_id)) {
$document_revision_id = $document_uri;
}
// generate document token
$document_revision_id = $this->generateRevisionId($document_revision_id);
$configManager = new ConfigManager();
$urlToConverter = $configManager->getConfig("docServSiteUrl").
$configManager->getConfig("docServConverterUrl");
$arr = [
"async" => $is_async,
"url" => $document_uri,
"outputtype" => trim($to_extension, '.'),
"filetype" => trim($from_extension, '.'),
"title" => $title,
"key" => $document_revision_id,
"password" => $filePass,
"region" => $lang,
];
// add header token
$headerToken = "";
$jwtHeader = $configManager->getConfig("docServJwtHeader") == "" ?
"Authorization" : $configManager->getConfig("docServJwtHeader");
$jwtManager = new JwtManager();
if ($jwtManager->isJwtEnabled()) {
$headerToken = $jwtManager->jwtEncode(["payload" => $arr]);
$arr["token"] = $jwtManager->jwtEncode($arr);
}
$data = json_encode($arr);
// request parameters
$opts = ['http' => [
'method' => 'POST',
'timeout' => $configManager->getConfig("docServTimeout"),
'header' => "Content-type: application/json\r\n" .
"Accept: application/json\r\n" .
(empty($headerToken) ? "" : $jwtHeader.": Bearer $headerToken\r\n"),
'content' => $data,
],
];
if (mb_substr($urlToConverter, 0, mb_strlen("https")) === "https") {
if ($configManager->getConfig("docServVerifyPeerOff") === true) {
$opts['ssl'] = ['verify_peer' => false, 'verify_peer_name' => false];
}
}
$context = stream_context_create($opts);
$response_data = file_get_contents($urlToConverter, false, $context);
return $response_data;
}
/**
* The method is to convert the file to the required format.
*
* Example:
* string convertedDocumentUri;
* getConvertedUri("http://helpcenter.onlyoffice.com/content/GettingStarted.pdf",
* ".pdf", ".docx", "http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", false, out convertedDocumentUri);
*
* @param string $document_uri Uri for the document to convert
* @param string $from_extension Document extension
* @param string $to_extension Extension to which to convert
* @param string $document_revision_id Key for caching on service
* @param bool $is_async Perform conversions asynchronously
* @param string $converted_document_uri Uri to the converted document
* @param string $filePass File pass
* @param string $lang Language
*
* @throws Exception if an error occurs
*
* @return int percentage of completion of conversion
*/
public function getConvertedUri(
$document_uri,
$from_extension,
$to_extension,
$document_revision_id,
$is_async,
&$converted_document_uri,
$filePass,
$lang
) {
$converted_document_uri = "";
$responceFromConvertService = sendRequestToConvertService(
$document_uri,
$from_extension,
$to_extension,
$document_revision_id,
$is_async,
$filePass,
$lang
);
$json = json_decode($responceFromConvertService, true);
// if an error occurs, then display an error message
$errorElement = $json["error"];
if ($errorElement != null && $errorElement != "") {
processConvServResponceError($errorElement);
}
$isEndConvert = $json["endConvert"];
$percent = $json["percent"];
// if the conversion is completed successfully
if ($isEndConvert != null && $isEndConvert == true) {
// then get the file url
$converted_document_uri = $json["fileUrl"];
$percent = 100;
} elseif ($percent >= 100) { // otherwise, get the percentage of conversion completion
$percent = 99;
}
return $percent;
}
/**
* Processing document received from the editing service.
*
* @param Response $document_response The result from editing service
* @param string $response_uri Uri to the converted document
*
* @throws Exception if an error occurs
*
* @return int percentage of completion of conversion
*/
public function getResponseUri($document_response, &$response_uri)
{
$response_uri = "";
$resultPercent = 0;
if (!$document_response) {
$errs = "Invalid answer format";
}
// if an error occurs, then display an error message
$errorElement = $document_response->Error;
if ($errorElement != null && $errorElement != "") {
processConvServResponceError($document_response->Error);
}
$endConvert = $document_response->EndConvert;
if ($endConvert != null && $endConvert == "") {
throw new Exception("Invalid answer format");
}
// if the conversion is completed successfully
if ($endConvert != null && mb_strtolower($endConvert) == true) {
$fileUrl = $document_response->FileUrl;
if ($fileUrl == null || $fileUrl == "") {
throw new Exception("Invalid answer format");
}
// get the response file url
$response_uri = $fileUrl;
$resultPercent = 100;
} else { // otherwise, get the percentage of conversion completion
$percent = $document_response->Percent;
if ($percent != null && $percent != "") {
$resultPercent = $percent;
}
if ($resultPercent >= 100) {
$resultPercent = 99;
}
}
return $resultPercent;
}
}

View File

@ -4,10 +4,6 @@ namespace OnlineEditorsExamplePhp;
use OnlineEditorsExamplePhp\Helpers\ConfigManager; use OnlineEditorsExamplePhp\Helpers\ConfigManager;
use OnlineEditorsExamplePhp\Helpers\ExampleUsers; use OnlineEditorsExamplePhp\Helpers\ExampleUsers;
use OnlineEditorsExamplePhp\Helpers\FileUtility;
use OnlineEditorsExamplePhp\Helpers\JwtManager;
use OnlineEditorsExamplePhp\Helpers\TrackManager;
use OnlineEditorsExamplePhp\Helpers\Utils;
/** /**
* (c) Copyright Ascensio System SIA 2023 * (c) Copyright Ascensio System SIA 2023
@ -25,14 +21,13 @@ use OnlineEditorsExamplePhp\Helpers\Utils;
* limitations under the License. * limitations under the License.
*/ */
require_once dirname(__FILE__) . '/functions.php';
require_once dirname(__FILE__) . '/vendor/autoload.php'; require_once dirname(__FILE__) . '/vendor/autoload.php';
$user = $_GET["user"] ?? ""; $user = $_GET["user"] ?? "";
$directUrlArg = isset($_GET["directUrl"]) ? "&directUrl=" . $_GET["directUrl"] : ""; $directUrlArg = isset($_GET["directUrl"]) ? "&directUrl=" . $_GET["directUrl"] : "";
$users = new ExampleUsers(); $userList = new ExampleUsers();
$configManager = new ConfigManager(); $configManager = new ConfigManager();
$fileUtility = new FileUtility();
$utils = new Utils();
?> ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
@ -112,7 +107,7 @@ $utils = new Utils();
<span class="select-user">Username</span> <span class="select-user">Username</span>
<img id="info" class="info" src="css/images/info.svg" /> <img id="info" class="info" src="css/images/info.svg" />
<select class="select-user" id="user"> <select class="select-user" id="user">
<?php foreach ($users->getAllUsers() as $user_l) { <?php foreach ($userList->getAllUsers() as $user_l) {
$name = $user_l->name ?: "Anonymous"; $name = $user_l->name ?: "Anonymous";
echo '<option value="'.$user_l->id.'">'.$name.'</option>'; echo '<option value="'.$user_l->id.'">'.$name.'</option>';
} ?> } ?>
@ -126,11 +121,9 @@ $utils = new Utils();
data-tooltip="Choose the language for ONLYOFFICE editors interface" data-tooltip="Choose the language for ONLYOFFICE editors interface"
src="css/images/info.svg" /> src="css/images/info.svg" />
<select class="select-user" id="language"> <select class="select-user" id="language">
<?php <?php foreach ($configManager->getConfig("languages") as $key => $language) { ?>
foreach ($configManager->getConfig("languages") as $key => $language) {
?>
<option value="<?=$key?>"><?=$language?></option> <option value="<?=$key?>"><?=$language?></option>
<?php } ?> <?php } ?>
</select> </select>
</td> </td>
</tr> </tr>
@ -154,7 +147,7 @@ $utils = new Utils();
<td class="section"> <td class="section">
<div class="main-panel"> <div class="main-panel">
<?php <?php
$storedFiles = $fileUtility->getStoredFiles(); $storedFiles = getStoredFiles();
if (!empty($storedFiles)) { ?> if (!empty($storedFiles)) { ?>
<div id="portal-info" style="display: none"> <div id="portal-info" style="display: none">
<?php } else { ?> <?php } else { ?>
@ -179,7 +172,7 @@ $utils = new Utils();
users in different Web browser sessions, so you can check out multi-user users in different Web browser sessions, so you can check out multi-user
editing functions. editing functions.
</span> </span>
<?php foreach ($users->getAllUsers() as $user_l) { <?php foreach ($userList->getAllUsers() as $user_l) {
$name = $user_l->name ?: "Anonymous"; $name = $user_l->name ?: "Anonymous";
echo '<div class="user-descr">'; echo '<div class="user-descr">';
echo '<b>'.$name.'</b>'; echo '<b>'.$name.'</b>';
@ -223,11 +216,9 @@ $utils = new Utils();
<?php foreach ($storedFiles as &$storeFile) { <?php foreach ($storedFiles as &$storeFile) {
echo '<tr class="tableRow" title="'. echo '<tr class="tableRow" title="'.
$storeFile->name.' ['. $storeFile->name.' ['.
$fileUtility->getFileVersion( getFileVersion(
$fileUtility->getHistoryDir( getHistoryDir(
$fileUtility->getStoragePath( getStoragePath($storeFile->name)
$storeFile->name
)
) )
). ).
']">'; ']">';
@ -506,7 +497,7 @@ $utils = new Utils();
frameborder="0" scrolling="no" allowtransparency></iframe> frameborder="0" scrolling="no" allowtransparency></iframe>
<br /> <br />
<div class="buttonsMobile"> <div class="buttonsMobile">
<?php if ($configManager->getConfig("mode") != "view") { ?> <?php if (($configManager->getConfig("mode")) != "view") { ?>
<div id="beginEdit" class="button orange disable">Edit</div> <div id="beginEdit" class="button orange disable">Edit</div>
<?php } ?> <?php } ?>
<div id="beginView" class="button gray disable">View</div> <div id="beginView" class="button gray disable">View</div>
@ -516,9 +507,8 @@ $utils = new Utils();
</div> </div>
<span id="loadScripts" data-docs=" <span id="loadScripts" data-docs="
<?php <?php echo $configManager->getConfig("docServSiteUrl").
echo $configManager->getConfig("docServSiteUrl").$configManager->getConfig("docServPreloaderUrl"); $configManager->getConfig("docServPreloaderUrl") ?>
?>
"></span> "></span>
<footer> <footer>

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

@ -1,4 +1,10 @@
<?php <?php
namespace OnlineEditorsExamplePhp;
use OnlineEditorsExamplePhp\Helpers\ConfigManager;
use OnlineEditorsExamplePhp\Helpers\JwtManager;
/** /**
* (c) Copyright Ascensio System SIA 2023 * (c) Copyright Ascensio System SIA 2023
* *
@ -15,10 +21,6 @@
* limitations under the License. * limitations under the License.
*/ */
require_once dirname(__FILE__) . '/jwtmanager.php';
require_once dirname(__FILE__) . '/common.php';
require_once dirname(__FILE__) . '/config.php';
/** /**
* Read request body * Read request body
* *
@ -27,7 +29,8 @@ require_once dirname(__FILE__) . '/config.php';
function readBody() function readBody()
{ {
$result["error"] = 0; $result["error"] = 0;
$configManager = new ConfigManager();
$jwtManager = new JwtManager();
// get the body of the post request and check if it is correct // get the body of the post request and check if it is correct
if (($body_stream = file_get_contents('php://input')) === false) { if (($body_stream = file_get_contents('php://input')) === false) {
$result["error"] = "Bad Request"; $result["error"] = "Bad Request";
@ -45,18 +48,19 @@ function readBody()
sendlog(" InputStream data: " . serialize($data), "webedior-ajax.log"); sendlog(" InputStream data: " . serialize($data), "webedior-ajax.log");
// check if the document token is enabled // check if the document token is enabled
if (isJwtEnabled()) { if ($jwtManager->isJwtEnabled()) {
sendlog(" jwt enabled, checking tokens", "webedior-ajax.log"); sendlog(" jwt enabled, checking tokens", "webedior-ajax.log");
$inHeader = false; $inHeader = false;
$data = ""; $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 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"); sendlog(" jwt in body", "webedior-ajax.log");
} elseif (!empty(apache_request_headers()[$jwtHeader])) { // if the Authorization header exists } elseif (!empty(apache_request_headers()[$jwtHeader])) { // if the Authorization header exists
$data = jwtDecode( $data = $jwtManager->jwtDecode(
mb_substr( mb_substr(
apache_request_headers()[$jwtHeader], apache_request_headers()[$jwtHeader],
mb_strlen("Bearer ") mb_strlen("Bearer ")
@ -286,7 +290,10 @@ function processForceSave($data, $fileName, $userAddress)
*/ */
function commandRequest($method, $key, $meta = null) 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 = [ $arr = [
"c" => $method, "c" => $method,
@ -298,11 +305,12 @@ function commandRequest($method, $key, $meta = null)
} }
$headerToken = ""; $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 if ($jwtManager->isJwtEnabled()) { // check if a secret key to generate token exists or not
$headerToken = jwtEncode(["payload" => $arr]); // encode a payload object into a header token $headerToken = $jwtManager->jwtEncode(["payload" => $arr]); // encode a payload object into a header token
$arr["token"] = jwtEncode($arr); // encode a payload object into a body token $arr["token"] = $jwtManager->jwtEncode($arr); // encode a payload object into a body token
} }
$data = json_encode($arr); $data = json_encode($arr);
@ -317,7 +325,7 @@ function commandRequest($method, $key, $meta = null)
]]; ]];
if (mb_substr($documentCommandUrl, 0, mb_strlen("https")) === "https") { 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]; $opts['ssl'] = ['verify_peer' => false, 'verify_peer_name' => false];
} }
} }

View File

@ -3,8 +3,6 @@
namespace OnlineEditorsExamplePhp; namespace OnlineEditorsExamplePhp;
use OnlineEditorsExamplePhp\Helpers\ConfigManager; use OnlineEditorsExamplePhp\Helpers\ConfigManager;
use OnlineEditorsExamplePhp\Helpers\FileUtility;
use OnlineEditorsExamplePhp\Helpers\Utils;
/** /**
* (c) Copyright Ascensio System SIA 2023 * (c) Copyright Ascensio System SIA 2023
@ -25,9 +23,13 @@ use OnlineEditorsExamplePhp\Helpers\Utils;
/** /**
* WebEditor AJAX Process Execution. * WebEditor AJAX Process Execution.
*/ */
require_once dirname(__FILE__) . '/ajax.php'; require_once dirname(__FILE__) . '/ajax.php';
require_once dirname(__FILE__) . '/functions.php';
require_once dirname(__FILE__) . '/trackmanager.php';
require_once dirname(__FILE__) . '/vendor/autoload.php'; require_once dirname(__FILE__) . '/vendor/autoload.php';
$configManager = new ConfigManager();
// define tracker status // define tracker status
$_trackerStatus = [ $_trackerStatus = [
0 => 'NotFound', 0 => 'NotFound',
@ -39,9 +41,6 @@ $_trackerStatus = [
7 => 'CorruptedForceSave', 7 => 'CorruptedForceSave',
]; ];
$fileUtility = new FileUtility();
$utils = new Utils();
$configManager = new ConfigManager();
// ignore self-signed certificate // ignore self-signed certificate
if ($configManager->getConfig("docServVerifyPeerOff") === true) { if ($configManager->getConfig("docServVerifyPeerOff") === true) {
stream_context_set_default([ stream_context_set_default([
@ -63,7 +62,7 @@ if (isset($_GET["type"]) && !empty($_GET["type"])) {
nocacheHeaders(); nocacheHeaders();
// write the request result to the log file // write the request result to the log file
$fileUtility->sendlog(serialize($_GET), "webedior-ajax.log"); sendlog(serialize($_GET), "webedior-ajax.log");
$type = $_GET["type"]; $type = $_GET["type"];