OCA\Richdocuments\Db\Wopi::generateFileToken PHP Method

generateFileToken() public method

version is 0 if current version of fileId is requested, otherwise its the version number as stored by files_version app Returns the token.
public generateFileToken ( $fileId, $version )
    public function generateFileToken($fileId, $version)
    {
        // Get the FS view of the current user.
        $view = \OC\Files\Filesystem::getView();
        // Get the virtual path (if the file is shared).
        $path = $view->getPath($fileId);
        if (!$view->is_file($path) || !$view->isUpdatable($path)) {
            throw new \Exception('Invalid fileId.');
        }
        // Figure out the real owner, if not us.
        $owner = $view->getOwner($path);
        // Create a view into the owner's FS.
        $view = new \OC\Files\View('/' . $owner . '/files');
        // Find the real path.
        $path = $view->getPath($fileId);
        if (!$view->is_file($path)) {
            throw new \Exception('Invalid fileId.');
        }
        $editor = \OC::$server->getUserSession()->getUser()->getUID();
        $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(32, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
        \OC::$server->getLogger()->debug('Issuing token for {editor} file {fileId}, version {version} owned by {owner}, path {path}: {token}', ['owner' => $owner, 'editor' => $editor, 'fileId' => $fileId, 'version' => $version, 'path' => $path, 'token' => $token]);
        $wopi = new \OCA\Richdocuments\Db\Wopi([$owner, $editor, $fileId, $version, $path, $token, time() + self::TOKEN_LIFETIME_SECONDS]);
        if (!$wopi->insert()) {
            throw new \Exception('Failed to add wopi token into database');
        }
        return $token;
    }

Usage Example

 /**
  * @NoAdminRequired
  * Generates and returns an access token for a given fileId.
  * Only for authenticated users!
  */
 public function wopiGetToken($fileId)
 {
     $arr = explode('_', $fileId, 2);
     $version = '0';
     if (count($arr) == 2) {
         $fileId = $arr[0];
         $version = $arr[1];
     }
     \OC::$server->getLogger()->debug('Generating WOPI Token for file {fileId}, version {version}.', ['app' => $this->appName, 'fileId' => $fileId, 'version' => $version]);
     $row = new Db\Wopi();
     $token = $row->generateFileToken($fileId, $version);
     // Return the token.
     return array('status' => 'success', 'token' => $token);
 }