Blame view

sources/3rdparty/sabre/dav/lib/Sabre/DAV/Browser/Plugin.php 15.4 KB
03e52840d   Kload   Init
1
  <?php
6d9380f96   Cédric Dupont   Update sources OC...
2
3
4
  namespace Sabre\DAV\Browser;
  
  use Sabre\DAV;
03e52840d   Kload   Init
5
6
7
8
9
10
11
12
13
  /**
   * Browser Plugin
   *
   * This plugin provides a html representation, so that a WebDAV server may be accessed
   * using a browser.
   *
   * The class intercepts GET requests to collection resources and generates a simple
   * html index.
   *
6d9380f96   Cédric Dupont   Update sources OC...
14
15
16
   * @copyright Copyright (C) 2007-2014 fruux GmbH (https://fruux.com/).
   * @author Evert Pot (http://evertpot.com/)
   * @license http://sabre.io/license/ Modified BSD License
03e52840d   Kload   Init
17
   */
6d9380f96   Cédric Dupont   Update sources OC...
18
  class Plugin extends DAV\ServerPlugin {
03e52840d   Kload   Init
19
20
21
22
23
24
25
26
27
28
29
30
31
  
      /**
       * List of default icons for nodes.
       *
       * This is an array with class / interface names as keys, and asset names
       * as values.
       *
       * The evaluation order is reversed. The last item in the list gets
       * precendence.
       *
       * @var array
       */
      public $iconMap = array(
6d9380f96   Cédric Dupont   Update sources OC...
32
33
34
35
36
37
          'Sabre\\DAV\\IFile' => 'icons/file',
          'Sabre\\DAV\\ICollection' => 'icons/collection',
          'Sabre\\DAVACL\\IPrincipal' => 'icons/principal',
          'Sabre\\CalDAV\\ICalendar' => 'icons/calendar',
          'Sabre\\CardDAV\\IAddressBook' => 'icons/addressbook',
          'Sabre\\CardDAV\\ICard' => 'icons/card',
03e52840d   Kload   Init
38
39
40
41
42
43
44
45
46
47
48
49
      );
  
      /**
       * The file extension used for all icons
       *
       * @var string
       */
      public $iconExtension = '.png';
  
      /**
       * reference to server class
       *
6d9380f96   Cédric Dupont   Update sources OC...
50
       * @var Sabre\DAV\Server
03e52840d   Kload   Init
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
       */
      protected $server;
  
      /**
       * enablePost turns on the 'actions' panel, which allows people to create
       * folders and upload files straight from a browser.
       *
       * @var bool
       */
      protected $enablePost = true;
  
      /**
       * By default the browser plugin will generate a favicon and other images.
       * To turn this off, set this property to false.
       *
       * @var bool
       */
      protected $enableAssets = true;
  
      /**
       * Creates the object.
       *
       * By default it will allow file creation and uploads.
       * Specify the first argument as false to disable this
       *
       * @param bool $enablePost
       * @param bool $enableAssets
       */
      public function __construct($enablePost=true, $enableAssets = true) {
  
          $this->enablePost = $enablePost;
          $this->enableAssets = $enableAssets;
  
      }
  
      /**
       * Initializes the plugin and subscribes to events
       *
6d9380f96   Cédric Dupont   Update sources OC...
89
       * @param DAV\Server $server
03e52840d   Kload   Init
90
91
       * @return void
       */
6d9380f96   Cédric Dupont   Update sources OC...
92
      public function initialize(DAV\Server $server) {
03e52840d   Kload   Init
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
  
          $this->server = $server;
          $this->server->subscribeEvent('beforeMethod',array($this,'httpGetInterceptor'));
          $this->server->subscribeEvent('onHTMLActionsPanel', array($this, 'htmlActionsPanel'),200);
          if ($this->enablePost) $this->server->subscribeEvent('unknownMethod',array($this,'httpPOSTHandler'));
      }
  
      /**
       * This method intercepts GET requests to collections and returns the html
       *
       * @param string $method
       * @param string $uri
       * @return bool
       */
      public function httpGetInterceptor($method, $uri) {
  
          if ($method !== 'GET') return true;
  
          // We're not using straight-up $_GET, because we want everything to be
          // unit testable.
          $getVars = array();
          parse_str($this->server->httpRequest->getQueryString(), $getVars);
  
          if (isset($getVars['sabreAction']) && $getVars['sabreAction'] === 'asset' && isset($getVars['assetName'])) {
              $this->serveAsset($getVars['assetName']);
              return false;
          }
  
          try {
              $node = $this->server->tree->getNodeForPath($uri);
6d9380f96   Cédric Dupont   Update sources OC...
123
          } catch (DAV\Exception\NotFound $e) {
03e52840d   Kload   Init
124
125
126
127
              // We're simply stopping when the file isn't found to not interfere
              // with other plugins.
              return;
          }
6d9380f96   Cédric Dupont   Update sources OC...
128
          if ($node instanceof DAV\IFile)
03e52840d   Kload   Init
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
              return;
  
          $this->server->httpResponse->sendStatus(200);
          $this->server->httpResponse->setHeader('Content-Type','text/html; charset=utf-8');
  
          $this->server->httpResponse->sendBody(
              $this->generateDirectoryIndex($uri)
          );
  
          return false;
  
      }
  
      /**
       * Handles POST requests for tree operations.
       *
       * @param string $method
       * @param string $uri
       * @return bool
       */
      public function httpPOSTHandler($method, $uri) {
  
          if ($method!='POST') return;
          $contentType = $this->server->httpRequest->getHeader('Content-Type');
          list($contentType) = explode(';', $contentType);
          if ($contentType !== 'application/x-www-form-urlencoded' &&
              $contentType !== 'multipart/form-data') {
                  return;
          }
          $postVars = $this->server->httpRequest->getPostVars();
  
          if (!isset($postVars['sabreAction']))
              return;
  
          if ($this->server->broadcastEvent('onBrowserPostAction', array($uri, $postVars['sabreAction'], $postVars))) {
  
              switch($postVars['sabreAction']) {
  
                  case 'mkcol' :
                      if (isset($postVars['name']) && trim($postVars['name'])) {
                          // Using basename() because we won't allow slashes
6d9380f96   Cédric Dupont   Update sources OC...
170
                          list(, $folderName) = DAV\URLUtil::splitPath(trim($postVars['name']));
03e52840d   Kload   Init
171
172
173
174
175
176
                          $this->server->createDirectory($uri . '/' . $folderName);
                      }
                      break;
                  case 'put' :
                      if ($_FILES) $file = current($_FILES);
                      else break;
6d9380f96   Cédric Dupont   Update sources OC...
177
                      list(, $newName) = DAV\URLUtil::splitPath(trim($file['name']));
03e52840d   Kload   Init
178
179
180
181
                      if (isset($postVars['name']) && trim($postVars['name']))
                          $newName = trim($postVars['name']);
  
                      // Making sure we only have a 'basename' component
6d9380f96   Cédric Dupont   Update sources OC...
182
                      list(, $newName) = DAV\URLUtil::splitPath($newName);
03e52840d   Kload   Init
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
  
                      if (is_uploaded_file($file['tmp_name'])) {
                          $this->server->createFile($uri . '/' . $newName, fopen($file['tmp_name'],'r'));
                      }
                      break;
  
              }
  
          }
          $this->server->httpResponse->setHeader('Location',$this->server->httpRequest->getUri());
          $this->server->httpResponse->sendStatus(302);
          return false;
  
      }
  
      /**
       * Escapes a string for html.
       *
       * @param string $value
       * @return string
       */
      public function escapeHTML($value) {
  
          return htmlspecialchars($value,ENT_QUOTES,'UTF-8');
  
      }
  
      /**
       * Generates the html directory index for a given url
       *
       * @param string $path
       * @return string
       */
      public function generateDirectoryIndex($path) {
  
          $version = '';
6d9380f96   Cédric Dupont   Update sources OC...
219
220
          if (DAV\Server::$exposeVersion) {
              $version = DAV\Version::VERSION ."-". DAV\Version::STABILITY;
03e52840d   Kload   Init
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
          }
  
          $html = "<html>
  <head>
    <title>Index for " . $this->escapeHTML($path) . "/ - SabreDAV " . $version . "</title>
    <style type=\"text/css\">
    body { Font-family: arial}
    h1 { font-size: 150% }
    </style>
          ";
  
          if ($this->enableAssets) {
              $html.='<link rel="shortcut icon" href="'.$this->getAssetUrl('favicon.ico').'" type="image/vnd.microsoft.icon" />';
          }
  
          $html .= "</head>
  <body>
    <h1>Index for " . $this->escapeHTML($path) . "/</h1>
    <table>
      <tr><th width=\"24\"></th><th>Name</th><th>Type</th><th>Size</th><th>Last modified</th></tr>
      <tr><td colspan=\"5\"><hr /></td></tr>";
  
          $files = $this->server->getPropertiesForPath($path,array(
              '{DAV:}displayname',
              '{DAV:}resourcetype',
              '{DAV:}getcontenttype',
              '{DAV:}getcontentlength',
              '{DAV:}getlastmodified',
          ),1);
  
          $parent = $this->server->tree->getNodeForPath($path);
  
  
          if ($path) {
6d9380f96   Cédric Dupont   Update sources OC...
255
256
              list($parentUri) = DAV\URLUtil::splitPath($path);
              $fullPath = DAV\URLUtil::encodePath($this->server->getBaseUri() . $parentUri);
03e52840d   Kload   Init
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
  
              $icon = $this->enableAssets?'<a href="' . $fullPath . '"><img src="' . $this->getAssetUrl('icons/parent' . $this->iconExtension) . '" width="24" alt="Parent" /></a>':'';
              $html.= "<tr>
      <td>$icon</td>
      <td><a href=\"{$fullPath}\">..</a></td>
      <td>[parent]</td>
      <td></td>
      <td></td>
      </tr>";
  
          }
  
          foreach($files as $file) {
  
              // This is the current directory, we can skip it
              if (rtrim($file['href'],'/')==$path) continue;
6d9380f96   Cédric Dupont   Update sources OC...
273
              list(, $name) = DAV\URLUtil::splitPath($file['href']);
03e52840d   Kload   Init
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
  
              $type = null;
  
  
              if (isset($file[200]['{DAV:}resourcetype'])) {
                  $type = $file[200]['{DAV:}resourcetype']->getValue();
  
                  // resourcetype can have multiple values
                  if (!is_array($type)) $type = array($type);
  
                  foreach($type as $k=>$v) {
  
                      // Some name mapping is preferred
                      switch($v) {
                          case '{DAV:}collection' :
                              $type[$k] = 'Collection';
                              break;
                          case '{DAV:}principal' :
                              $type[$k] = 'Principal';
                              break;
                          case '{urn:ietf:params:xml:ns:carddav}addressbook' :
                              $type[$k] = 'Addressbook';
                              break;
                          case '{urn:ietf:params:xml:ns:caldav}calendar' :
                              $type[$k] = 'Calendar';
                              break;
                          case '{urn:ietf:params:xml:ns:caldav}schedule-inbox' :
                              $type[$k] = 'Schedule Inbox';
                              break;
                          case '{urn:ietf:params:xml:ns:caldav}schedule-outbox' :
                              $type[$k] = 'Schedule Outbox';
                              break;
                          case '{http://calendarserver.org/ns/}calendar-proxy-read' :
                              $type[$k] = 'Proxy-Read';
                              break;
                          case '{http://calendarserver.org/ns/}calendar-proxy-write' :
                              $type[$k] = 'Proxy-Write';
                              break;
                      }
  
                  }
                  $type = implode(', ', $type);
              }
  
              // If no resourcetype was found, we attempt to use
              // the contenttype property
              if (!$type && isset($file[200]['{DAV:}getcontenttype'])) {
                  $type = $file[200]['{DAV:}getcontenttype'];
              }
              if (!$type) $type = 'Unknown';
  
              $size = isset($file[200]['{DAV:}getcontentlength'])?(int)$file[200]['{DAV:}getcontentlength']:'';
6d9380f96   Cédric Dupont   Update sources OC...
326
              $lastmodified = isset($file[200]['{DAV:}getlastmodified'])?$file[200]['{DAV:}getlastmodified']->getTime()->format(\DateTime::ATOM):'';
03e52840d   Kload   Init
327

6d9380f96   Cédric Dupont   Update sources OC...
328
              $fullPath = DAV\URLUtil::encodePath('/' . trim($this->server->getBaseUri() . ($path?$path . '/':'') . $name,'/'));
03e52840d   Kload   Init
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
  
              $displayName = isset($file[200]['{DAV:}displayname'])?$file[200]['{DAV:}displayname']:$name;
  
              $displayName = $this->escapeHTML($displayName);
              $type = $this->escapeHTML($type);
  
              $icon = '';
  
              if ($this->enableAssets) {
                  $node = $this->server->tree->getNodeForPath(($path?$path.'/':'') . $name);
                  foreach(array_reverse($this->iconMap) as $class=>$iconName) {
  
                      if ($node instanceof $class) {
                          $icon = '<a href="' . $fullPath . '"><img src="' . $this->getAssetUrl($iconName . $this->iconExtension) . '" alt="" width="24" /></a>';
                          break;
                      }
  
  
                  }
  
              }
  
              $html.= "<tr>
      <td>$icon</td>
      <td><a href=\"{$fullPath}\">{$displayName}</a></td>
      <td>{$type}</td>
      <td>{$size}</td>
      <td>{$lastmodified}</td>
      </tr>";
  
          }
  
          $html.= "<tr><td colspan=\"5\"><hr /></td></tr>";
  
          $output = '';
  
          if ($this->enablePost) {
              $this->server->broadcastEvent('onHTMLActionsPanel',array($parent, &$output));
          }
  
          $html.=$output;
  
          $html.= "</table>
6d9380f96   Cédric Dupont   Update sources OC...
372
          <address>Generated by SabreDAV " . $version . " (c)2007-2014 <a href=\"http://sabre.io/\">http://sabre.io/</a></address>
03e52840d   Kload   Init
373
374
375
376
377
378
379
380
381
382
383
384
385
386
          </body>
          </html>";
  
          return $html;
  
      }
  
      /**
       * This method is used to generate the 'actions panel' output for
       * collections.
       *
       * This specifically generates the interfaces for creating new files, and
       * creating new directories.
       *
6d9380f96   Cédric Dupont   Update sources OC...
387
       * @param DAV\INode $node
03e52840d   Kload   Init
388
389
390
       * @param mixed $output
       * @return void
       */
6d9380f96   Cédric Dupont   Update sources OC...
391
      public function htmlActionsPanel(DAV\INode $node, &$output) {
03e52840d   Kload   Init
392

6d9380f96   Cédric Dupont   Update sources OC...
393
          if (!$node instanceof DAV\ICollection)
03e52840d   Kload   Init
394
395
396
397
              return;
  
          // We also know fairly certain that if an object is a non-extended
          // SimpleCollection, we won't need to show the panel either.
6d9380f96   Cédric Dupont   Update sources OC...
398
          if (get_class($node)==='Sabre\\DAV\\SimpleCollection')
03e52840d   Kload   Init
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
              return;
  
          $output.= '<tr><td colspan="2"><form method="post" action="">
              <h3>Create new folder</h3>
              <input type="hidden" name="sabreAction" value="mkcol" />
              Name: <input type="text" name="name" /><br />
              <input type="submit" value="create" />
              </form>
              <form method="post" action="" enctype="multipart/form-data">
              <h3>Upload file</h3>
              <input type="hidden" name="sabreAction" value="put" />
              Name (optional): <input type="text" name="name" /><br />
              File: <input type="file" name="file" /><br />
              <input type="submit" value="upload" />
              </form>
              </td></tr>';
  
      }
  
      /**
       * This method takes a path/name of an asset and turns it into url
       * suiteable for http access.
       *
       * @param string $assetName
       * @return string
       */
      protected function getAssetUrl($assetName) {
  
          return $this->server->getBaseUri() . '?sabreAction=asset&assetName=' . urlencode($assetName);
  
      }
  
      /**
       * This method returns a local pathname to an asset.
       *
       * @param string $assetName
       * @return string
       */
      protected function getLocalAssetPath($assetName) {
6d9380f96   Cédric Dupont   Update sources OC...
438
          $assetDir = __DIR__ . '/assets/';
03e52840d   Kload   Init
439
440
441
          $path = $assetDir . $assetName;
  
          // Making sure people aren't trying to escape from the base path.
6d9380f96   Cédric Dupont   Update sources OC...
442
443
          if (strpos(realpath($path), realpath($assetDir)) === 0) {
              return $path;
03e52840d   Kload   Init
444
          }
6d9380f96   Cédric Dupont   Update sources OC...
445
          throw new DAV\Exception\Forbidden('Path does not exist, or escaping from the base path was detected');
03e52840d   Kload   Init
446
447
448
449
450
451
452
453
454
455
456
457
      }
  
      /**
       * This method reads an asset from disk and generates a full http response.
       *
       * @param string $assetName
       * @return void
       */
      protected function serveAsset($assetName) {
  
          $assetPath = $this->getLocalAssetPath($assetName);
          if (!file_exists($assetPath)) {
6d9380f96   Cédric Dupont   Update sources OC...
458
              throw new DAV\Exception\NotFound('Could not find an asset with this name');
03e52840d   Kload   Init
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
          }
          // Rudimentary mime type detection
          switch(strtolower(substr($assetPath,strpos($assetPath,'.')+1))) {
  
          case 'ico' :
              $mime = 'image/vnd.microsoft.icon';
              break;
  
          case 'png' :
              $mime = 'image/png';
              break;
  
          default:
              $mime = 'application/octet-stream';
              break;
  
          }
  
          $this->server->httpResponse->setHeader('Content-Type', $mime);
          $this->server->httpResponse->setHeader('Content-Length', filesize($assetPath));
          $this->server->httpResponse->setHeader('Cache-Control', 'public, max-age=1209600');
          $this->server->httpResponse->sendStatus(200);
          $this->server->httpResponse->sendBody(fopen($assetPath,'r'));
  
      }
  
  }