code splitting

This commit is contained in:
Robin Appelman 2017-02-22 17:42:04 +01:00
commit 1e7efdd48b
4 changed files with 294 additions and 127 deletions

110
src/DAV/DiscoverHandler.php Normal file
View file

@ -0,0 +1,110 @@
<?php
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @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 SearchDAV\DAV;
use Sabre\DAV\Exception\BadRequest;
use Sabre\DAV\Xml\Response\MultiStatus;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
use SearchDAV\Backend\ISearchBackend;
use SearchDAV\Backend\SearchPropertyDefinition;
use SearchDAV\XML\BasicSearch;
use SearchDAV\XML\BasicSearchSchema;
use SearchDAV\XML\PropDesc;
use SearchDAV\XML\QueryDiscoverResponse;
use SearchDAV\XML\Scope;
class DiscoverHandler {
/** @var ISearchBackend */
private $searchBackend;
/** @var PathHelper */
private $pathHelper;
/** @var QueryParser */
private $queryParser;
/**
* @param ISearchBackend $searchBackend
* @param PathHelper $pathHelper
* @param QueryParser $queryParser
*/
public function __construct(ISearchBackend $searchBackend, PathHelper $pathHelper, QueryParser $queryParser) {
$this->searchBackend = $searchBackend;
$this->pathHelper = $pathHelper;
$this->queryParser = $queryParser;
}
public function handelDiscoverRequest($xml, RequestInterface $request, ResponseInterface $response) {
if (!$xml['{DAV:}basicsearch']) {
throw new BadRequest('Unexpected xml content for query-schema-discovery, expected basicsearch');
}
/** @var BasicSearch $query */
$query = $xml['{DAV:}basicsearch'];
$scopes = $query->from;
$results = array_map(function (Scope $scope) {
$scope->path = $this->pathHelper->getPathFromUri($scope->href);
if ($this->searchBackend->isValidScope($scope->href, $scope->depth, $scope->path)) {
$searchProperties = $this->searchBackend->getPropertyDefinitionsForScope($scope->href, $scope->path);
$searchSchema = $this->getBasicSearchForProperties($searchProperties);
return new QueryDiscoverResponse($scope->href, $searchSchema, 200);
} else {
return new QueryDiscoverResponse($scope->href, null, 404); // TODO something other than 404? 403 maybe
}
}, $scopes);
$multiStatus = new MultiStatus($results);
$response->setStatus(207);
$response->setHeader('Content-Type', 'application/xml; charset="utf-8"');
$response->setBody($this->queryParser->write('{DAV:}multistatus', $multiStatus, $request->getUrl()));
return false;
}
private function hashDefinition(SearchPropertyDefinition $definition) {
return $definition->dataType
. (($definition->searchable) ? '1' : '0')
. (($definition->sortable) ? '1' : '0')
. (($definition->selectable) ? '1' : '0');
}
/**
* @param SearchPropertyDefinition[] $propertyDefinitions
* @return BasicSearchSchema
*/
private function getBasicSearchForProperties(array $propertyDefinitions) {
/** @var PropDesc[] $groups */
$groups = [];
foreach ($propertyDefinitions as $propertyDefinition) {
$key = $this->hashDefinition($propertyDefinition);
if (!isset($groups[$key])) {
$desc = new PropDesc();
$desc->dataType = $propertyDefinition->dataType;
$desc->sortable = $propertyDefinition->sortable;
$desc->selectable = $propertyDefinition->selectable;
$desc->searchable = $propertyDefinition->searchable;
$groups[$key] = $desc;
}
$groups[$key]->properties[] = $propertyDefinition->name;
}
return new BasicSearchSchema(array_values($groups));
}
}

50
src/DAV/PathHelper.php Normal file
View file

@ -0,0 +1,50 @@
<?php
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @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 SearchDAV\DAV;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Server;
class PathHelper {
/** @var Server */
private $server;
/**
* PathHelper constructor.
*
* @param Server $server
*/
public function __construct(Server $server) {
$this->server = $server;
}
public function getPathFromUri($uri) {
if (strpos($uri, '://') === false) {
return $uri;
}
try {
return ($uri === '' && $this->server->getBaseUri() === '/') ? '' : $this->server->calculateUri($uri);
} catch (Forbidden $e) {
return null;
}
}
}

117
src/DAV/SearchHandler.php Normal file
View file

@ -0,0 +1,117 @@
<?php
/**
* @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
*
* @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 SearchDAV\DAV;
use Sabre\DAV\Exception\BadRequest;
use Sabre\DAV\PropFind;
use Sabre\DAV\Server;
use Sabre\HTTP\ResponseInterface;
use SearchDAV\Backend\ISearchBackend;
use SearchDAV\Backend\SearchResult;
use SearchDAV\XML\BasicSearch;
class SearchHandler {
/** @var ISearchBackend */
private $searchBackend;
/** @var PathHelper */
private $pathHelper;
/** @var Server */
private $server;
/**
* @param ISearchBackend $searchBackend
* @param PathHelper $pathHelper
* @param Server $server
*/
public function __construct(ISearchBackend $searchBackend, PathHelper $pathHelper, Server $server) {
$this->searchBackend = $searchBackend;
$this->pathHelper = $pathHelper;
$this->server = $server;
}
public function handleSearchRequest($xml, ResponseInterface $response) {
if (!$xml['{DAV:}basicsearch']) {
throw new BadRequest('Unexpected xml content for searchrequest, expected basicsearch');
}
/** @var BasicSearch $query */
$query = $xml['{DAV:}basicsearch'];
if (!$query->where) {
$response->setStatus(400);
$response->setBody('Parse error: Missing {DAV:}where from {DAV:}basicsearch');
return false;
}
if (!$query->select) {
$response->setStatus(400);
$response->setBody('Parse error: Missing {DAV:}select from {DAV:}basicsearch');
return false;
}
$response->setStatus(207);
$response->setHeader('Content-Type', 'application/xml; charset="utf-8"');
foreach ($query->from as $scope) {
$scope->path = $this->pathHelper->getPathFromUri($scope->href);
}
$results = $this->searchBackend->search($query);
$data = $this->server->generateMultiStatus(iterator_to_array($this->getPropertiesIteratorResults($results, $query->select)), false);
$response->setBody($data);
return false;
}
/**
* Returns a list of properties for a given path
*
* The path that should be supplied should have the baseUrl stripped out
* The list of properties should be supplied in Clark notation. If the list is empty
* 'allprops' is assumed.
*
* If a depth of 1 is requested child elements will also be returned.
*
* @param SearchResult[] $results
* @param array $propertyNames
* @param int $depth
* @return \Iterator
*/
private function getPropertiesIteratorResults($results, $propertyNames = [], $depth = 0) {
$propFindType = $propertyNames ? PropFind::NORMAL : PropFind::ALLPROPS;
foreach ($results as $result) {
$node = $result->node;
$propFind = new PropFind($result->href, (array)$propertyNames, $depth, $propFindType);
$r = $this->server->getPropertiesByNode($propFind, $node);
if ($r) {
$result = $propFind->getResultForMultiStatus();
$result['href'] = $propFind->getPath();
// WebDAV recommends adding a slash to the path, if the path is
// a collection.
// Furthermore, iCal also demands this to be the case for
// principals. This is non-standard, but we support it.
$resourceType = $this->server->getResourceTypeForNode($node);
if (in_array('{DAV:}collection', $resourceType) || in_array('{DAV:}principal', $resourceType)) {
$result['href'] .= '/';
}
yield $result;
}
}
}
}

View file

@ -54,6 +54,15 @@ class SearchPlugin extends ServerPlugin {
/** @var QueryParser */
private $queryParser;
/** @var PathHelper */
private $pathHelper;
/** @var SearchHandler */
private $search;
/** @var DiscoverHandler */
private $discover;
public function __construct(ISearchBackend $searchBackend) {
$this->searchBackend = $searchBackend;
$this->queryParser = new QueryParser();
@ -61,6 +70,9 @@ class SearchPlugin extends ServerPlugin {
public function initialize(Server $server) {
$this->server = $server;
$this->pathHelper = new PathHelper($server);
$this->search = new SearchHandler($this->searchBackend, $this->pathHelper, $server);
$this->discover = new DiscoverHandler($this->searchBackend, $this->pathHelper, $this->queryParser);
$server->on('method:SEARCH', [$this, 'searchHandler']);
$server->on('afterMethod:OPTIONS', [$this, 'optionHandler']);
$server->on('propFind', [$this, 'propFindHandler']);
@ -72,17 +84,6 @@ class SearchPlugin extends ServerPlugin {
}
}
private function getPathFromUri($uri) {
if (strpos($uri, '://') === false) {
return $uri;
}
try {
return ($uri === '' && $this->server->getBaseUri() === '/') ? '' : $this->server->calculateUri($uri);
} catch (Forbidden $e) {
return null;
}
}
/**
* SEARCH is allowed for users files
*
@ -90,7 +91,7 @@ class SearchPlugin extends ServerPlugin {
* @return array
*/
public function getHTTPMethods($uri) {
$path = $this->getPathFromUri($uri);
$path = $this->pathHelper->getPathFromUri($uri);
if ($this->searchBackend->getArbiterPath() === $path) {
return ['SEARCH'];
} else {
@ -109,11 +110,11 @@ class SearchPlugin extends ServerPlugin {
// Currently we only support xml search queries
if ((strpos($contentType, 'text/xml') === false) && (strpos($contentType, 'application/xml') === false)) {
return;
return true;
}
if ($request->getPath() !== $this->searchBackend->getArbiterPath()) {
return;
return true;
}
try {
@ -130,122 +131,11 @@ class SearchPlugin extends ServerPlugin {
switch ($documentType) {
case '{DAV:}searchrequest':
if (!$xml['{DAV:}basicsearch']) {
throw new BadRequest('Unexpected xml content for searchrequest, expected basicsearch');
}
/** @var BasicSearch $query */
$query = $xml['{DAV:}basicsearch'];
if (!$query->where) {
$response->setStatus(400);
$response->setBody('Parse error: Missing {DAV:}where from {DAV:}basicsearch');
return false;
}
if (!$query->select) {
$response->setStatus(400);
$response->setBody('Parse error: Missing {DAV:}select from {DAV:}basicsearch');
return false;
}
$response->setStatus(207);
$response->setHeader('Content-Type', 'application/xml; charset="utf-8"');
foreach ($query->from as $scope) {
$scope->path = $this->getPathFromUri($scope->href);
}
$results = $this->searchBackend->search($query);
$data = $this->server->generateMultiStatus(iterator_to_array($this->getPropertiesIteratorResults($results, $query->select)), false);
$response->setBody($data);
return false;
return $this->search->handleSearchRequest($xml, $response);
case '{DAV:}query-schema-discovery':
if (!$xml['{DAV:}basicsearch']) {
throw new BadRequest('Unexpected xml content for query-schema-discovery, expected basicsearch');
}
/** @var BasicSearch $query */
$query = $xml['{DAV:}basicsearch'];
$scopes = $query->from;
$results = array_map(function (Scope $scope) {
$scope->path = $this->getPathFromUri($scope->href);
if ($this->searchBackend->isValidScope($scope->href, $scope->depth, $scope->path)) {
$searchProperties = $this->searchBackend->getPropertyDefinitionsForScope($scope->href, $scope->path);
$searchSchema = $this->getBasicSearchForProperties($searchProperties);
return new QueryDiscoverResponse($scope->href, $searchSchema, 200);
} else {
return new QueryDiscoverResponse($scope->href, null, 404); // TODO something other than 404? 403 maybe
}
}, $scopes);
$multiStatus = new MultiStatus($results);
$response->setStatus(207);
$response->setHeader('Content-Type', 'application/xml; charset="utf-8"');
$response->setBody($this->queryParser->write('{DAV:}multistatus', $multiStatus, $request->getUrl()));
return false;
return $this->discover->handelDiscoverRequest($xml, $request, $response);
default:
throw new BadRequest('Unexpected document type: ' . $documentType . ' for this Content-Type');
}
}
/**
* Returns a list of properties for a given path
*
* The path that should be supplied should have the baseUrl stripped out
* The list of properties should be supplied in Clark notation. If the list is empty
* 'allprops' is assumed.
*
* If a depth of 1 is requested child elements will also be returned.
*
* @param SearchResult[] $results
* @param array $propertyNames
* @param int $depth
* @return \Iterator
*/
function getPropertiesIteratorResults($results, $propertyNames = [], $depth = 0) {
$propFindType = $propertyNames ? PropFind::NORMAL : PropFind::ALLPROPS;
foreach ($results as $result) {
$node = $result->node;
$propFind = new PropFind($result->href, (array)$propertyNames, $depth, $propFindType);
$r = $this->server->getPropertiesByNode($propFind, $node);
if ($r) {
$result = $propFind->getResultForMultiStatus();
$result['href'] = $propFind->getPath();
// WebDAV recommends adding a slash to the path, if the path is
// a collection.
// Furthermore, iCal also demands this to be the case for
// principals. This is non-standard, but we support it.
$resourceType = $this->server->getResourceTypeForNode($node);
if (in_array('{DAV:}collection', $resourceType) || in_array('{DAV:}principal', $resourceType)) {
$result['href'] .= '/';
}
yield $result;
}
}
}
private function hashDefinition(SearchPropertyDefinition $definition) {
return $definition->dataType
. (($definition->searchable) ? '1' : '0')
. (($definition->sortable) ? '1' : '0')
. (($definition->selectable) ? '1' : '0');
}
/**
* @param SearchPropertyDefinition[] $propertyDefinitions
* @return BasicSearchSchema
*/
private function getBasicSearchForProperties(array $propertyDefinitions) {
/** @var PropDesc[] $groups */
$groups = [];
foreach ($propertyDefinitions as $propertyDefinition) {
$key = $this->hashDefinition($propertyDefinition);
if (!isset($groups[$key])) {
$desc = new PropDesc();
$desc->dataType = $propertyDefinition->dataType;
$desc->sortable = $propertyDefinition->sortable;
$desc->selectable = $propertyDefinition->selectable;
$desc->searchable = $propertyDefinition->searchable;
$groups[$key] = $desc;
}
$groups[$key]->properties[] = $propertyDefinition->name;
}
return new BasicSearchSchema(array_values($groups));
}
}