Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Integrating ONLYOFFICE With a Document Management System

DZone's Guide to

Integrating ONLYOFFICE With a Document Management System

In this article, we will explain how the integration is done, what permissions should be granted to ONLYOFFICE by the DMS, and how to put the permissions into practice.

· Integration Zone ·
Free Resource

Learn how to add document editing and viewing to your web app on .Net (C#), Node.JS, Java, PHP, Ruby, etc.

ONLYOFFICE is an open-source office suite that includes document, spreadsheet, and presentation editors. The suite can be integrated with third-party web apps to be used within their interface.

The most popular case here is integration with document management systems (DMS). Here’s what ONLYOFFICE can add to their functionality:

  • Text document, spreadsheet, and presentation viewing and editing
  • Document co-editing in real-time

To integrate ONLYOFFICE document editors, we’ll need to create an integration app (we also call it a connector) that will work as a bridge connecting the editors (we call it Document Server) and the file storage (DMS).

In this article, we will explain how the integration is done, what permissions should be granted to ONLYOFFICE by the DMS, and how to put the permissions into practice. As an example, we will use the ONLYOFFICE integration with Nextcloud, an open source, self-hosted file-sharing and communication platform.Image title

Integration Checklist

This is the list of permissions that should be granted to ONLYOFFICE by the DMS, otherwise, integration won’t be possible:

  1. Adding and executing custom code
  2. Anonymous access for downloading and saving files (which may sound as a vulnerability, but it’s not, and later we’ll tell you how files are protected). It means that our editors only communicate with document management system on the server side without involving any user authorization data from the client side (browser cookies)
  3. Adding new buttons to UI (for example, “Edit in ONLYOFFICE”)
  4. Оpening a new page where we can execute our script to add an editor
  5. Ability to specify settings: at least, the virtual address of the ONLYOFFICE Document Server

Let’s go over this checklist and see how we used those in the ONLYOFFICE integration app for Nextcloud.

1. Adding Code

ONLYOFFICE doesn’t go modifying any source code, so to make integration possible, the service should allow adding custom modules, plugins, packages, or apps.

Nextcloud enables third-party developers to add their own apps. All the apps are published in its app store for users to easily get the enhancements they need for their DMS. ONLYOFFICE integration app is available there too. You can also check out its source code on GitHub to use it as an example for integration app for your service. We'll guide you through the most important parts.

Note that Nextcloud and all of its add-ons are written on PHP, so this programming language is used in the code samples below.

2. Anonymous Access

For the integration app/connector, you’ll need to write a callback handler. This one will handle requests from ONLYOFFICE Document Server to the file storage.

Depending on the request parameters documented here, different actions can be performed on the file storage side (e.g. returning a file’s contents or saving a file). It’s important that it is a direct interaction between Document Server and the file storage, and it doesn’t require any user authentication data like browser cookies which, as we said above, is not a vulnerability in any way.

The security here is organized by means of JWT technology, with request signature validation. Document Server adds JWT to the request using the secret word from its configuration file, and file storage checks it using the secret word from its own config. The callback handler will only perform the requested action if the signature was validated successfully.

A callback handler for the Nextcloud connector is called when requests are sent to certain URLs:

"routes" => [
   ["name" => "callback#download", "url" => "/download", "verb" => "GET"],
   ["name" => "callback#track", "url" => "/track", "verb" => "POST"],
   ...
]

For incoming requests, the signature validation is performed:

try {
    $decodedHeader = \Firebase\JWT\JWT::decode($header,
        $this->config->GetDocumentServerSecret(), array("HS256"));
} catch (\UnexpectedValueException $e) {
    return new JSONResponse(["message" => $this->trans->t("Access denied")],
        Http::STATUS_FORBIDDEN);
}

Here’s how Document Server requests file contents from the file storage:

class CallbackController extends Controller {
    public function download($doc) {
        $file = $this->getFile($doc);
        return new DataDownloadResponse($file->getContent(), $file->getName(),
            $file->getMimeType());
    }
    ...
}

And here’s how the file is saved back to the storage:

class CallbackController extends Controller {
    public function track($doc, $status, $url) {
        $error = 1;
        switch ($status) {
            case "MustSave":
                $file = $this->getFile($doc);
                if (($newData = $this->Request($url))) {
                    $file->putContent($newData);
                    $error = 0;
                }
                break;

            case "Editing":
            case "Closed":
                $error = 0;
                break;
        }
        return new JSONResponse(["error" => $error], Http::STATUS_OK);
    }
    ...
}

The response should be:

{”error”: 0}

3. Adding Buttons

For end users, work with ONLYOFFICE starts with buttons like “Open,” “Edit,” “Create (New),” or “Convert.” These actions can be associated with certain file types; to be more exact:

  • View docx, xlsx, pptx, csv, txt, pdf.
  • Edit docx, xlsx, pptx, csv, txt.
  • Create new docx, xlsx, pptx, txt.
  • Convert into the Office Open XML formats (docx, xlsx, pptx): doc, docm, dot, dotx, epub, htm, html, odp, odt, pot, potm, potx, pps, ppsm, ppsx, ppt, pptm, rtf, xls, xlsm, xlsx, xlt, xltm, xltx.

(Also, we need to keep in mind the types of access rights that users have).

Nextcloud allows both executing scripts on the client side and adding buttons to the context menu. This is how the button is done for opening a docx file:

fileList.fileActions.registerAction({
    name: "onlyofficeOpen",
    displayName: t(OCA.Onlyoffice.AppName, "Open in ONLYOFFICE"),
    mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    permissions: OC.PERMISSION_READ,
    iconClass: "icon-onlyoffice-open",
    actionHandler: function(fileName, context) {
            window.open(OC.generateUrl("/apps/" + OCA.Onlyoffice.AppName +
                "/" + context.fileInfoModel.id);
        }
});

Image title

4. Opening the Page With Editors

When the user clicks an action button, the new page with editors initialization config. is generated. In this stage, we check whether the file can be opened and the user’s access rights.

Besides that, we send some additional parameters for the editor, such as interface options. For example, document.permissions.download = false will remove the file download button from the editor, and editorConfig.lang = "de-DE" will change the interface language to German.

In Nextcloud, this mechanism is implemented as a separate request handler:

class EditorController extends Controller {
    public function config($fileId) {
        $file = $this->getFile($fileId);

        $fileName = $file->getName();
        $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        $formats = [
            "docx" => [ "type" => "text" ],
            "xlsx" => [ "type" => "spreadsheet" ],
            "pptx" => [ "type" => "presentation" ]
        ];

        $params = [
            "document" => [
                "fileType" => $ext,
                "key" =>  $this->getKey($file),
                "title" => $fileName,
                "url" => $this->getUrl($fileId),
            ],
            "documentType" => $format[$ext]["type"]
        ];

        if ($file->isUpdateable()) {
            $params["editorConfig"]["callbackUrl"] = $this->urlGenerator->linkToRouteAbsolute(
                $this->appName . ".callback.track", ["doc" => $fileId]);
        } else {
            $params["editorConfig"]["mode"] = "view";
        }

        return $params;
    }
    ...
}

Several users can work in the same document at the same time. In this case, co-editing is implemented by using the same document.key for the same file opened by several users on a single Nextcloud instance.

private function getKey($file) {
    $instanceId = $this->config->getSystemValue("instanceid");
    $key = $instanceId . "_" . $file->getId() . "_" . $file->getMtime();
    return $key;
}

To protect the configuration from unwanted changes, we add a JWT signature:

if (!empty($this->config->GetDocumentServerSecret())) {
    $token = \Firebase\JWT\JWT::encode($params, $this->config->GetDocumentServerSecret());
    $params["token"] = $token;
}

5. The App Settings

The integration app must get its global (Document Server address) and per-user (e.g. user preferences) settings. You can configure the app using server-side configuration files or by creating the whole web settings page. In Nextcloud ONLYOFFICE, connection settings are available on the admin settings page.

Image title

Read more about how ONLYOFFICE-Nextcloud integration works in the API documentation.

We hope that you will create your own integration app using principles from this article. Apart from Nextcloud connector source code (PHP), you might as well check the source code of other integration apps:

If you are willing to integrate ONLYOFFICE with apps written in other languages, check out these test examples (simplest doc management systems) to see how the editors work with them, or read our article on how to integrate the editors into your Node.js app. And stay tuned; more articles on ONLYOFFICE integration are coming soon to DZone!

If you know document management systems that would benefit from adding docx, xlsx, and pptx editing, share in comments.

Extend your web service functionality with docx, xlsx and pptx editing. Check out ONLYOFFICE document editors for integration.

Topics:
integration ,open source ,api ,tutorial ,php ,document management software

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}