Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/nextcloud/richdocuments.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorLukas Reschke <lukas@statuscode.ch>2016-12-07 02:57:01 +0300
committerLukas Reschke <lukas@statuscode.ch>2016-12-07 02:57:01 +0300
commit7ef24654cf0963bc9e27e2846fabea706b1a1cc5 (patch)
tree5f8619bd75127b3d1ffc2368211acbf583afdd75 /lib
parent4464726d8076d71a09c8b67e28ae0aad0e168f6c (diff)
Public editing
Signed-off-by: Lukas Reschke <lukas@statuscode.ch>
Diffstat (limited to 'lib')
-rw-r--r--lib/Controller/DocumentController.php172
-rw-r--r--lib/Controller/WopiController.php72
-rw-r--r--lib/TokenManager.php105
-rw-r--r--lib/WOPI/DiscoveryManager.php20
-rw-r--r--lib/db/wopi.php45
-rw-r--r--lib/filter.php74
-rw-r--r--lib/helper.php12
-rw-r--r--lib/storage.php175
8 files changed, 242 insertions, 433 deletions
diff --git a/lib/Controller/DocumentController.php b/lib/Controller/DocumentController.php
index b961b126..4a93558c 100644
--- a/lib/Controller/DocumentController.php
+++ b/lib/Controller/DocumentController.php
@@ -11,8 +11,13 @@
namespace OCA\Richdocuments\Controller;
-use OCA\Richdocuments\WOPI\DiscoveryManager;
+use OCA\Richdocuments\TokenManager;
+use OCA\Richdocuments\WOPI\Parser;
use \OCP\AppFramework\Controller;
+use OCP\AppFramework\Http\JSONResponse;
+use OCP\Files\Folder;
+use OCP\Files\IRootFolder;
+use OCP\Files\Node;
use \OCP\IRequest;
use \OCP\IConfig;
use \OCP\IL10N;
@@ -21,57 +26,148 @@ use \OCP\AppFramework\Http\TemplateResponse;
use \OCA\Richdocuments\AppConfig;
use \OCA\Richdocuments\Helper;
use \OC\Files\View;
-use \OCP\ICacheFactory;
+use OCP\Share\IManager;
class DocumentController extends Controller {
-
+ /** @var string */
private $uid;
+ /** @var IL10N */
private $l10n;
+ /** @var IConfig */
private $settings;
+ /** @var AppConfig */
private $appConfig;
- private $cache;
- /** @var DiscoveryManager */
- private $discoveryManager;
+ /** @var Parser */
+ private $wopiParser;
+ /** @var IManager */
+ private $shareManager;
+ /** @var TokenManager */
+ private $tokenManager;
+ /** @var IRootFolder */
+ private $rootFolder;
+
const ODT_TEMPLATE_PATH = '/assets/odttemplate.odt';
+ /**
+ * @param string $appName
+ * @param IRequest $request
+ * @param IConfig $settings
+ * @param AppConfig $appConfig
+ * @param IL10N $l10n
+ * @param Parser $wopiParser
+ * @param IManager $shareManager
+ * @param TokenManager $tokenManager
+ * @param IRootFolder $rootFolder
+ * @param string $UserId
+ */
public function __construct($appName,
- $UserId,
IRequest $request,
IConfig $settings,
AppConfig $appConfig,
IL10N $l10n,
- ICacheFactory $cache,
- DiscoveryManager $discoveryManager) {
+ Parser $wopiParser,
+ IManager $shareManager,
+ TokenManager $tokenManager,
+ IRootFolder $rootFolder,
+ $UserId) {
parent::__construct($appName, $request);
$this->uid = $UserId;
$this->l10n = $l10n;
$this->settings = $settings;
$this->appConfig = $appConfig;
- $this->cache = $cache->create($appName);
- $this->discoveryManager = $discoveryManager;
+ $this->wopiParser = $wopiParser;
+ $this->shareManager = $shareManager;
+ $this->tokenManager = $tokenManager;
+ $this->rootFolder = $rootFolder;
}
/**
* @NoAdminRequired
- * @NoCSRFRequired
*
+ * @param string $fileId
* @return TemplateResponse
*/
- public function index(){
- $response = new TemplateResponse('richdocuments', 'documents');
- $policy = new ContentSecurityPolicy();
- $policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
- $response->setContentSecurityPolicy($policy);
- return $response;
+ public function index($fileId) {
+ try {
+ $folder = $this->rootFolder->getUserFolder($this->uid);
+ $item = $folder->getById($fileId)[0];
+ if(!($item instanceof Node)) {
+ throw new \Exception();
+ }
+ list($urlSrc, $token) = $this->tokenManager->getToken($item->getId());
+ $params = [
+ 'permissions' => $item->getPermissions(),
+ 'title' => $item->getName(),
+ 'fileId' => $item->getId(),
+ 'token' => $token,
+ 'urlsrc' => $urlSrc,
+ 'path' => '/',
+ ];
+
+ $response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
+ $policy = new ContentSecurityPolicy();
+ $policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
+ $policy->allowInlineScript(true);
+ $response->setContentSecurityPolicy($policy);
+ return $response;
+ } catch (\Exception $e) {
+ }
+
+ return new TemplateResponse('core', '403', [], 'guest');
+ }
+
+ /**
+ * @PublicPage
+ *
+ * @param string $shareToken
+ * @param string $fileName
+ * @return TemplateResponse
+ * @throws \Exception
+ */
+ public function publicPage($shareToken, $fileName) {
+ try {
+ $share = $this->shareManager->getShareByToken($shareToken);
+ $node = $share->getNode();
+ if($node instanceof Folder) {
+ $item = $node->get($fileName);
+ } else {
+ $item = $node;
+ }
+ if ($item instanceof Node) {
+ list($urlSrc, $token) = $this->tokenManager->getToken($item->getId(), $shareToken);
+ $params = [
+ 'permissions' => $share->getPermissions(),
+ 'title' => $item->getName(),
+ 'fileId' => $item->getId(),
+ 'token' => $token,
+ 'urlsrc' => $urlSrc,
+ 'path' => '/',
+ ];
+
+ $response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
+ $policy = new ContentSecurityPolicy();
+ $policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
+ $policy->allowInlineScript(true);
+ $response->setContentSecurityPolicy($policy);
+ return $response;
+ }
+ } catch (\Exception $e) {
+ }
+
+ return new TemplateResponse('core', '403', [], 'guest');
}
/**
* @NoAdminRequired
+ *
+ * @param string $mimetype
+ * @param string $filename
+ * @param string $dir
+ * @return JSONResponse
*/
- public function create(){
- $mimetype = $this->request->post['mimetype'];
- $filename = $this->request->post['filename'];
- $dir = $this->request->post['dir'];
+ public function create($mimetype,
+ $filename,
+ $dir){
$view = new View('/' . $this->uid . '/files');
if (!$dir){
@@ -117,36 +213,9 @@ class DocumentController extends Controller {
$content = file_get_contents(dirname(__DIR__) . self::ODT_TEMPLATE_PATH);
}
- $discovery_parsed = null;
- try {
- $discovery = $this->discoveryManager->get();
-
- $loadEntities = libxml_disable_entity_loader(true);
- $discovery_parsed = simplexml_load_string($discovery);
- libxml_disable_entity_loader($loadEntities);
-
- if ($discovery_parsed === false) {
- $this->cache->remove('discovery.xml');
- $wopiRemote = $this->getWopiUrl(false);
-
- return array(
- 'status' => 'error',
- 'message' => $this->l10n->t('Collabora Online: discovery.xml from "%s" is not a well-formed XML string.', array($wopiRemote)),
- 'hint' => $this->l10n->t('Please contact the "%s" administrator.', array($wopiRemote))
- );
- }
- }
- catch (ResponseException $e) {
- return array(
- 'status' => 'error',
- 'message' => $e->getMessage(),
- 'hint' => $e->getHint()
- );
- }
-
- if ($content && $view->file_put_contents($path, $content)){
+ if ($content && $view->file_put_contents($path, $content)) {
$info = $view->getFileInfo($path);
- $ret = $this->getWopiSrcUrl($discovery_parsed, $mimetype);
+ $ret = $this->wopiParser->getUrlSrc($mimetype);
$response = array(
'status' => 'success',
'fileid' => $info['fileid'],
@@ -161,6 +230,7 @@ class DocumentController extends Controller {
'message' => (string) $this->l10n->t('Can\'t create document')
);
}
+
return $response;
}
}
diff --git a/lib/Controller/WopiController.php b/lib/Controller/WopiController.php
index 676fb0e9..8f9050f2 100644
--- a/lib/Controller/WopiController.php
+++ b/lib/Controller/WopiController.php
@@ -64,60 +64,6 @@ class WopiController extends Controller {
}
/**
- * Generates and returns an access token for a given fileId
- *
- * @NoAdminRequired
- *
- * @param string $fileId
- * @return JSONResponse
- */
- public function getToken($fileId) {
- $arr = explode('_', $fileId, 2);
- $version = '0';
- if (count($arr) === 2) {
- list($fileId, $version) = $arr;
- }
-
- try {
- /** @var File $file */
- $file = $this->rootFolder->getUserFolder($this->userId)->getById($fileId)[0];
- $updatable = $file->isUpdateable();
- } catch (\Exception $e) {
- return new JSONResponse([], Http::STATUS_FORBIDDEN);
- }
-
- // If token is for some versioned file
- if ($version !== '0') {
- $updatable = false;
- }
-
- $row = new Wopi();
- $serverHost = $this->request->getServerProtocol() . '://' . $this->request->getServerHost();
- $token = $row->generateFileToken($fileId, $version, $updatable, $serverHost);
-
- try {
- $userFolder = $this->rootFolder->getUserFolder($this->userId);
- /** @var File $file */
- $file = $userFolder->getById($fileId)[0];
- $sessionData['title'] = basename($file->getPath());
- $sessionData['permissions'] = $file->getPermissions();
- $sessionData['file_id'] = $file->getId();
-
- $sessionData['documents'] = [
- 0 => [
- 'urlsrc' => $this->wopiParser->getUrlSrc($file->getMimeType())['urlsrc'],
- 'path' => $file->getPath(),
- 'token' => $token,
- ],
- ];
-
- return new JSONResponse($sessionData);
- } catch (\Exception $e){
- return new JSONResponse([], Http::STATUS_FORBIDDEN);
- }
- }
-
- /**
* Returns general info about a file.
*
* @NoAdminRequired
@@ -141,25 +87,29 @@ class WopiController extends Controller {
$res = $row->getPathForToken($fileId, $version, $token);
if ($res === false) {
- return new JSONResponse();
+ return new JSONResponse([], Http::STATUS_FORBIDDEN);
}
// Login the user to see his mount locations
try {
/** @var File $file */
- $userFolder = $this->rootFolder->getUserFolder($res['editor']);
+ $userFolder = $this->rootFolder->getUserFolder($res['owner']);
$file = $userFolder->getById($fileId)[0];
} catch (\Exception $e) {
return new JSONResponse([], Http::STATUS_FORBIDDEN);
}
+ if(!($file instanceof File)) {
+ return new JSONResponse([], Http::STATUS_FORBIDDEN);
+ }
+
return new JSONResponse(
[
'BaseFileName' => $file->getName(),
'Size' => $file->getSize(),
'Version' => $version,
- 'UserId' => $res['editor'],
- 'UserFriendlyName' => $this->userManager->get($res['editor'])->getDisplayName(),
+ 'UserId' => $res['editor'] !== '' ? $res['editor'] : 'Guest user',
+ 'UserFriendlyName' => $res['editor'] !== '' ? $res['editor'] : 'Guest user',
'UserCanWrite' => $res['canwrite'] ? true : false,
'PostMessageOrigin' => $res['server_host'],
]
@@ -192,7 +142,7 @@ class WopiController extends Controller {
try {
/** @var File $file */
- $userFolder = $this->rootFolder->getUserFolder($res['editor']);
+ $userFolder = $this->rootFolder->getUserFolder($res['owner']);
$file = $userFolder->getById($fileId)[0];
$response = new StreamResponse($file->fopen('rb'));
$response->addHeader('Content-Disposition', 'attachment');
@@ -203,8 +153,6 @@ class WopiController extends Controller {
}
}
-
-
/**
* Given an access token and a fileId, replaces the files with the request body.
* Expects a valid token in access_token parameter.
@@ -233,7 +181,7 @@ class WopiController extends Controller {
try {
/** @var File $file */
- $userFolder = $this->rootFolder->getUserFolder($res['editor']);
+ $userFolder = $this->rootFolder->getUserFolder($res['owner']);
$file = $userFolder->getById($fileId)[0];
$content = fopen('php://input', 'rb');
$file->putContent($content);
diff --git a/lib/TokenManager.php b/lib/TokenManager.php
new file mode 100644
index 00000000..357720ed
--- /dev/null
+++ b/lib/TokenManager.php
@@ -0,0 +1,105 @@
+<?php
+/**
+ * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch>
+ *
+ * @license GNU AGPL version 3 or any later version
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace OCA\Richdocuments;
+
+use OC\Share\Constants;
+use OCA\Richdocuments\Db\Wopi;
+use OCA\Richdocuments\WOPI\Parser;
+use OCP\Files\File;
+use OCP\Files\IRootFolder;
+use OCP\IURLGenerator;
+use OCP\Share\IManager;
+
+class TokenManager {
+ /** @var IRootFolder */
+ private $rootFolder;
+ /** @var IManager */
+ private $shareManager;
+ /** @var IURLGenerator */
+ private $urlGenerator;
+ /** @var Parser */
+ private $wopiParser;
+
+ /**
+ * @param IRootFolder $rootFolder
+ * @param IManager $shareManager
+ * @param IURLGenerator $urlGenerator
+ * @param string $UserId
+ */
+ public function __construct(IRootFolder $rootFolder,
+ IManager $shareManager,
+ IURLGenerator $urlGenerator,
+ Parser $wopiParser,
+ $UserId) {
+ $this->rootFolder = $rootFolder;
+ $this->shareManager = $shareManager;
+ $this->urlGenerator = $urlGenerator;
+ $this->wopiParser = $wopiParser;
+ $this->userId = $UserId;
+ }
+
+ /**
+ * @param string $fileId
+ * @param string $shareToken
+ * @return array
+ * @throws \Exception
+ */
+ public function getToken($fileId, $shareToken = null) {
+ $arr = explode('_', $fileId, 2);
+ $version = '0';
+ if (count($arr) === 2) {
+ list($fileId, $version) = $arr;
+ }
+
+ // if the user is not logged-in do use the sharers storage
+ if($shareToken !== null) {
+ /** @var File $file */
+ $rootFolder = $this->rootFolder;
+ $share = $this->shareManager->getShareByToken($shareToken);
+ $updatable = (bool)($share->getPermissions() & \OCP\Constants::PERMISSION_UPDATE);
+ } else {
+ try {
+ /** @var File $file */
+ $rootFolder = $this->rootFolder->getUserFolder($this->userId);
+ $updatable = $rootFolder->isUpdateable();
+ } catch (\Exception $e) {
+ throw $e;
+ }
+ }
+ /** @var File $file */
+ $file = $rootFolder->getById($fileId)[0];
+
+ $row = new Wopi();
+ $serverHost = $this->urlGenerator->getAbsoluteURL('/');//$this->request->getServerProtocol() . '://' . $this->request->getServerHost();
+ $token = $row->generateFileToken($fileId, $file->getOwner()->getUID(), $this->userId, $version, $updatable, $serverHost);
+
+ try {
+
+ return [
+ $this->wopiParser->getUrlSrc($file->getMimeType())['urlsrc'],
+ $token,
+ ];
+ } catch (\Exception $e){
+ throw $e;
+ }
+ }
+} \ No newline at end of file
diff --git a/lib/WOPI/DiscoveryManager.php b/lib/WOPI/DiscoveryManager.php
index 39326c17..b3d18fed 100644
--- a/lib/WOPI/DiscoveryManager.php
+++ b/lib/WOPI/DiscoveryManager.php
@@ -84,25 +84,7 @@ class DiscoveryManager {
try {
$response = $client->get($wopiDiscovery);
} catch (\Exception $e) {
- $error_message = $e->getMessage();
- if (preg_match('/^cURL error ([0-9]*):/', $error_message, $matches)) {
- $admin_check = $this->l10n->t('Please ask your administrator to check the Collabora Online server setting. The exact error message was: ') . $error_message;
-
- $curl_error = $matches[1];
- switch ($curl_error) {
- case '1':
- throw new ResponseException($this->l10n->t('Collabora Online: The protocol specified in "%s" is not allowed.', array($wopiRemote)), $admin_check);
- case '3':
- throw new ResponseException($this->l10n->t('Collabora Online: Malformed URL "%s".', array($wopiRemote)), $admin_check);
- case '6':
- throw new ResponseException($this->l10n->t('Collabora Online: Cannot resolve the host "%s".', array($wopiRemote)), $admin_check);
- case '7':
- throw new ResponseException($this->l10n->t('Collabora Online: Cannot connect to the host "%s".', array($wopiRemote)), $admin_check);
- case '60':
- throw new ResponseException($this->l10n->t('Collabora Online: SSL certificate is not installed.'), $this->l10n->t('Please ask your administrator to add ca-chain.cert.pem to the ca-bundle.crt, for example "cat /etc/loolwsd/ca-chain.cert.pem >> <server-installation>/resources/config/ca-bundle.crt" . The exact error message was: ') . $error_message);
- }
- }
- throw new ResponseException($this->l10n->t('Collabora Online unknown error: ') . $error_message, $contact_admin);
+ throw $e;
}
$responseBody = $response->getBody();
diff --git a/lib/db/wopi.php b/lib/db/wopi.php
index e30de4cf..232a533d 100644
--- a/lib/db/wopi.php
+++ b/lib/db/wopi.php
@@ -23,63 +23,28 @@ class Wopi extends \OCA\Richdocuments\Db{
protected $tableName = '`*PREFIX*richdocuments_wopi`';
- protected $insertStatement = 'INSERT INTO `*PREFIX*richdocuments_wopi` (`owner_uid`, `editor_uid`, `fileid`, `version`, `path`, `canwrite`, `server_host`, `token`, `expiry`)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)';
+ protected $insertStatement = 'INSERT INTO `*PREFIX*richdocuments_wopi` (`fileid`, `owner_uid`, `editor_uid`, `version`, `canwrite`, `server_host`, `token`, `expiry`)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
protected $loadStatement = 'SELECT * FROM `*PREFIX*richdocuments_wopi` WHERE `token`= ?';
- /*
- * Given a fileId and version, generates a token
- * and stores in the database.
- * 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 function generateFileToken($fileId, $version, $updatable, $serverHost){
-
- // 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)) {
- 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();
-
+ public function generateFileToken($fileId, $owner, $editor, $version, $updatable, $serverHost) {
$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([
+ $fileId,
$owner,
$editor,
- $fileId,
$version,
- $path,
$updatable,
$serverHost,
$token,
time() + self::TOKEN_LIFETIME_SECONDS
]);
- if (!$wopi->insert()){
+ if (!$wopi->insert()) {
throw new \Exception('Failed to add wopi token into database');
}
diff --git a/lib/filter.php b/lib/filter.php
deleted file mode 100644
index 9b5a93f1..00000000
--- a/lib/filter.php
+++ /dev/null
@@ -1,74 +0,0 @@
-<?php
-
-/**
- * ownCloud - Richdocuments App
- *
- * @author Victor Dubiniuk
- * @copyright 2013 Victor Dubiniuk victor.dubiniuk@gmail.com
- *
- * This file is licensed under the Affero General Public License version 3 or
- * later.
- */
-
-namespace OCA\Richdocuments;
-
- class Filter {
- protected static $filters = array();
-
- public static function add($mimetype, $class){
- self::$filters[$mimetype] = $class;
- }
-
- public static function read($content, $mimetype){
- $data = array(
- 'mimetype' => $mimetype,
- 'content' => $content
- );
-
- if (isset(self::$filters[$mimetype])){
- $data = call_user_func(
- array(
- self::$filters[$mimetype],
- 'read'
- ),
- $data
- );
- }
-
- return $data;
- }
-
- public static function write($content, $mimetype){
- $data = array(
- 'mimetype' => $mimetype,
- 'content' => $content
- );
-
- if (isset(self::$filters[$mimetype])){
- $data = call_user_func(
- array(
- self::$filters[$mimetype],
- 'write'
- ),
- $data
- );
- }
-
- return $data;
- }
-
- public static function getAll(){
- return array_keys(self::$filters);
- }
-
- /**
- * Checks if mimetype is supported by the app
- * @param string $mimetype - checked mimetype
- * @return bool
- */
- public static function isSupportedMimetype($mimetype){
- return in_array($mimetype, Storage::getSupportedMimetypes());
- }
-}
-
- \ No newline at end of file
diff --git a/lib/helper.php b/lib/helper.php
index 35866e8d..b5d6cda9 100644
--- a/lib/helper.php
+++ b/lib/helper.php
@@ -12,7 +12,6 @@
namespace OCA\Richdocuments;
class Helper {
-
const APP_ID = 'richdocuments';
public static function getNewFileName($view, $path, $prepend = ' '){
@@ -25,15 +24,4 @@ class Helper {
return $path;
}
-
- public static function getArrayValueByKey($array, $key, $default=''){
- if (array_key_exists($key, $array)){
- return $array[$key];
- }
- return $default;
- }
-
- public static function isVersionsEnabled(){
- return \OCP\App::isEnabled('files_versions');
- }
}
diff --git a/lib/storage.php b/lib/storage.php
deleted file mode 100644
index fc450fa1..00000000
--- a/lib/storage.php
+++ /dev/null
@@ -1,175 +0,0 @@
-<?php
-
-/**
- * ownCloud - Richdocuments App
- *
- * @author Frank Karlitschek
- * @copyright 2013-2014 Frank Karlitschek frank@owncloud.org
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
- *
- * You should have received a copy of the GNU Affero General Public
- * License along with this library. If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-
-namespace OCA\Richdocuments;
-
-class Storage {
- public static $MIMETYPE_LIBREOFFICE_WORDPROCESSOR = array(
- 'application/vnd.oasis.opendocument.text',
- 'application/vnd.oasis.opendocument.presentation',
- 'application/vnd.oasis.opendocument.spreadsheet',
- 'application/vnd.oasis.opendocument.graphics',
- 'application/vnd.lotus-wordpro',
- 'image/svg+xml',
- 'application/vnd.visio',
- 'application/vnd.wordperfect',
- 'application/msonenote',
- 'application/msword',
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
- 'application/vnd.ms-word.document.macroEnabled.12',
- 'application/vnd.ms-word.template.macroEnabled.12',
- 'application/vnd.ms-excel',
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
- 'application/vnd.ms-excel.sheet.macroEnabled.12',
- 'application/vnd.ms-excel.template.macroEnabled.12',
- 'application/vnd.ms-excel.addin.macroEnabled.12',
- 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
- 'application/vnd.ms-powerpoint',
- 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
- 'application/vnd.openxmlformats-officedocument.presentationml.template',
- 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
- 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
- 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
- 'application/vnd.ms-powerpoint.template.macroEnabled.12',
- 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12'
- );
-
- public static function getDocuments() {
- $list = array_filter(
- self::searchDocuments(),
- function($item){
- //filter Deleted
- if (strpos($item['path'], '_trashbin')===0){
- return false;
- }
- return true;
- }
- );
-
- return $list;
- }
-
- public static function getDocumentById($fileId){
- $root = \OC::$server->getUserFolder();
- $ret = array();
-
- // If type of fileId is a string, then it
- // doesn't work for shared documents, lets cast to int everytime
- $document = $root->getById((int)$fileId)[0];
- if ($document === null){
- error_log('File with file id, ' . $fileId . ', not found');
- return $ret;
- }
-
- $ret['mimetype'] = $document->getMimeType();
- $ret['path'] = $root->getRelativePath($document->getPath());
- $ret['name'] = $document->getName();
- $ret['fileid'] = $fileId;
-
- return $ret;
- }
-
- public static function resolvePath($fileId){
- $list = array_filter(
- self::searchDocuments(),
- function($item) use ($fileId){
- return intval($item['fileid'])==$fileId;
- }
- );
- if (count($list)>0){
- $item = current($list);
- return $item['path'];
- }
- return false;
- }
-
- /**
- * @brief Cleanup session data on removing the document
- * @param array
- *
- * This function is connected to the delete signal of OC_Filesystem
- * to delete the related info from database
- */
- public static function onDelete($params) {
- $info = \OC\Files\Filesystem::getFileInfo($params['path']);
-
- $fileId = @$info['fileid'];
- if (!$fileId){
- return;
- }
-
- $session = new Db\Session();
- $session->loadBy('file_id', $fileId);
-
- if (!$session->getEsId()){
- return;
- }
-
- $member = new Db\Member();
- $sessionMembers = $member->getCollectionBy('es_id', $session->getEsId());
- foreach ($sessionMembers as $memberData){
- if (intval($memberData['status'])===Db\Member::MEMBER_STATUS_ACTIVE){
- return;
- }
- }
-
- }
-
- private static function processDocuments($rawDocuments){
- $documents = array();
- $view = \OC\Files\Filesystem::getView();
- foreach($rawDocuments as $rawDocument){
- $document = array(
- 'fileid' => $rawDocument->getId(),
- 'path' => $view->getPath($rawDocument->getId()),
- 'name' => $rawDocument->getName(),
- 'mimetype' => $rawDocument->getMimetype(),
- 'mtime' => $rawDocument->getMTime()
- );
-
- array_push($documents, $document);
- }
-
- return $documents;
- }
-
- protected static function searchDocuments(){
- $documents = array();
- foreach (self::getSupportedMimetypes() as $mime){
- $rawDocuments = \OCP\Files::searchByMime($mime);
- $documents = array_merge($documents, self::processDocuments($rawDocuments));
- }
-
- return $documents;
- }
-
- public static function getSupportedMimetypes(){
- return array_merge(
- self::$MIMETYPE_LIBREOFFICE_WORDPROCESSOR,
- Filter::getAll()
- );
- }
-}