Plugin.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sabre\DAV\Sync;
  4. use Sabre\DAV;
  5. use Sabre\DAV\Xml\Request\SyncCollectionReport;
  6. use Sabre\HTTP\RequestInterface;
  7. /**
  8. * This plugin all WebDAV-sync capabilities to the Server.
  9. *
  10. * WebDAV-sync is defined by rfc6578
  11. *
  12. * The sync capabilities only work with collections that implement
  13. * Sabre\DAV\Sync\ISyncCollection.
  14. *
  15. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  16. * @author Evert Pot (http://evertpot.com/)
  17. * @license http://sabre.io/license/ Modified BSD License
  18. */
  19. class Plugin extends DAV\ServerPlugin
  20. {
  21. /**
  22. * Reference to server object.
  23. *
  24. * @var DAV\Server
  25. */
  26. protected $server;
  27. const SYNCTOKEN_PREFIX = 'http://sabre.io/ns/sync/';
  28. /**
  29. * Returns a plugin name.
  30. *
  31. * Using this name other plugins will be able to access other plugins
  32. * using \Sabre\DAV\Server::getPlugin
  33. *
  34. * @return string
  35. */
  36. public function getPluginName()
  37. {
  38. return 'sync';
  39. }
  40. /**
  41. * Initializes the plugin.
  42. *
  43. * This is when the plugin registers it's hooks.
  44. */
  45. public function initialize(DAV\Server $server)
  46. {
  47. $this->server = $server;
  48. $server->xml->elementMap['{DAV:}sync-collection'] = 'Sabre\\DAV\\Xml\\Request\\SyncCollectionReport';
  49. $self = $this;
  50. $server->on('report', function ($reportName, $dom, $uri) use ($self) {
  51. if ('{DAV:}sync-collection' === $reportName) {
  52. $this->server->transactionType = 'report-sync-collection';
  53. $self->syncCollection($uri, $dom);
  54. return false;
  55. }
  56. });
  57. $server->on('propFind', [$this, 'propFind']);
  58. $server->on('validateTokens', [$this, 'validateTokens']);
  59. }
  60. /**
  61. * Returns a list of reports this plugin supports.
  62. *
  63. * This will be used in the {DAV:}supported-report-set property.
  64. * Note that you still need to subscribe to the 'report' event to actually
  65. * implement them
  66. *
  67. * @param string $uri
  68. *
  69. * @return array
  70. */
  71. public function getSupportedReportSet($uri)
  72. {
  73. $node = $this->server->tree->getNodeForPath($uri);
  74. if ($node instanceof ISyncCollection && $node->getSyncToken()) {
  75. return [
  76. '{DAV:}sync-collection',
  77. ];
  78. }
  79. return [];
  80. }
  81. /**
  82. * This method handles the {DAV:}sync-collection HTTP REPORT.
  83. *
  84. * @param string $uri
  85. */
  86. public function syncCollection($uri, SyncCollectionReport $report)
  87. {
  88. // Getting the data
  89. $node = $this->server->tree->getNodeForPath($uri);
  90. if (!$node instanceof ISyncCollection) {
  91. throw new DAV\Exception\ReportNotSupported('The {DAV:}sync-collection REPORT is not supported on this url.');
  92. }
  93. $token = $node->getSyncToken();
  94. if (!$token) {
  95. throw new DAV\Exception\ReportNotSupported('No sync information is available at this node');
  96. }
  97. $syncToken = $report->syncToken;
  98. if (!is_null($syncToken)) {
  99. // Sync-token must start with our prefix
  100. if (self::SYNCTOKEN_PREFIX !== substr($syncToken, 0, strlen(self::SYNCTOKEN_PREFIX))) {
  101. throw new DAV\Exception\InvalidSyncToken('Invalid or unknown sync token');
  102. }
  103. $syncToken = substr($syncToken, strlen(self::SYNCTOKEN_PREFIX));
  104. }
  105. $changeInfo = $node->getChanges($syncToken, $report->syncLevel, $report->limit);
  106. if (is_null($changeInfo)) {
  107. throw new DAV\Exception\InvalidSyncToken('Invalid or unknown sync token');
  108. }
  109. if (!array_key_exists('result_truncated', $changeInfo)) {
  110. $changeInfo['result_truncated'] = false;
  111. }
  112. // Encoding the response
  113. $this->sendSyncCollectionResponse(
  114. $changeInfo['syncToken'],
  115. $uri,
  116. $changeInfo['added'],
  117. $changeInfo['modified'],
  118. $changeInfo['deleted'],
  119. $report->properties,
  120. $changeInfo['result_truncated']
  121. );
  122. }
  123. /**
  124. * Sends the response to a sync-collection request.
  125. *
  126. * @param string $syncToken
  127. * @param string $collectionUrl
  128. */
  129. protected function sendSyncCollectionResponse($syncToken, $collectionUrl, array $added, array $modified, array $deleted, array $properties, bool $resultTruncated = false)
  130. {
  131. $fullPaths = [];
  132. // Pre-fetching children, if this is possible.
  133. foreach (array_merge($added, $modified) as $item) {
  134. $fullPath = $collectionUrl.'/'.$item;
  135. $fullPaths[] = $fullPath;
  136. }
  137. $responses = [];
  138. foreach ($this->server->getPropertiesForMultiplePaths($fullPaths, $properties) as $fullPath => $props) {
  139. // The 'Property_Response' class is responsible for generating a
  140. // single {DAV:}response xml element.
  141. $responses[] = new DAV\Xml\Element\Response($fullPath, $props);
  142. }
  143. // Deleted items also show up as 'responses'. They have no properties,
  144. // and a single {DAV:}status element set as 'HTTP/1.1 404 Not Found'.
  145. foreach ($deleted as $item) {
  146. $fullPath = $collectionUrl.'/'.$item;
  147. $responses[] = new DAV\Xml\Element\Response($fullPath, [], 404);
  148. }
  149. if ($resultTruncated) {
  150. $responses[] = new DAV\Xml\Element\Response($collectionUrl.'/', [], 507);
  151. }
  152. $multiStatus = new DAV\Xml\Response\MultiStatus($responses, self::SYNCTOKEN_PREFIX.$syncToken);
  153. $this->server->httpResponse->setStatus(207);
  154. $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8');
  155. $this->server->httpResponse->setBody(
  156. $this->server->xml->write('{DAV:}multistatus', $multiStatus, $this->server->getBaseUri())
  157. );
  158. }
  159. /**
  160. * This method is triggered whenever properties are requested for a node.
  161. * We intercept this to see if we must return a {DAV:}sync-token.
  162. */
  163. public function propFind(DAV\PropFind $propFind, DAV\INode $node)
  164. {
  165. $propFind->handle('{DAV:}sync-token', function () use ($node) {
  166. if (!$node instanceof ISyncCollection || !$token = $node->getSyncToken()) {
  167. return;
  168. }
  169. return self::SYNCTOKEN_PREFIX.$token;
  170. });
  171. }
  172. /**
  173. * The validateTokens event is triggered before every request.
  174. *
  175. * It's a moment where this plugin can check all the supplied lock tokens
  176. * in the If: header, and check if they are valid.
  177. *
  178. * @param array $conditions
  179. */
  180. public function validateTokens(RequestInterface $request, &$conditions)
  181. {
  182. foreach ($conditions as $kk => $condition) {
  183. foreach ($condition['tokens'] as $ii => $token) {
  184. // Sync-tokens must always start with our designated prefix.
  185. if (self::SYNCTOKEN_PREFIX !== substr($token['token'], 0, strlen(self::SYNCTOKEN_PREFIX))) {
  186. continue;
  187. }
  188. // Checking if the token is a match.
  189. $node = $this->server->tree->getNodeForPath($condition['uri']);
  190. if (
  191. $node instanceof ISyncCollection &&
  192. $node->getSyncToken() == substr($token['token'], strlen(self::SYNCTOKEN_PREFIX))
  193. ) {
  194. $conditions[$kk]['tokens'][$ii]['validToken'] = true;
  195. }
  196. }
  197. }
  198. }
  199. /**
  200. * Returns a bunch of meta-data about the plugin.
  201. *
  202. * Providing this information is optional, and is mainly displayed by the
  203. * Browser plugin.
  204. *
  205. * The description key in the returned array may contain html and will not
  206. * be sanitized.
  207. *
  208. * @return array
  209. */
  210. public function getPluginInfo()
  211. {
  212. return [
  213. 'name' => $this->getPluginName(),
  214. 'description' => 'Adds support for WebDAV Collection Sync (rfc6578)',
  215. 'link' => 'http://sabre.io/dav/sync/',
  216. ];
  217. }
  218. }