ILIAS  Release_3_10_x_branch Revision 61812
 All Data Structures Namespaces Files Functions Variables Groups Pages
class.ilDAVServer.php
Go to the documentation of this file.
1 <?php
2 // BEGIN WebDAV
3 /*
4  +-----------------------------------------------------------------------------+
5  | ILIAS open source |
6  +-----------------------------------------------------------------------------+
7  | Copyright (c) 1998-2005 ILIAS open source, University of Cologne |
8  | |
9  | This program is free software; you can redistribute it and/or |
10  | modify it under the terms of the GNU General Public License |
11  | as published by the Free Software Foundation; either version 2 |
12  | of the License, or (at your option) any later version. |
13  | |
14  | This program is distributed in the hope that it will be useful, |
15  | but WITHOUT ANY WARRANTY; without even the implied warranty of |
16  | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
17  | GNU General Public License for more details. |
18  | |
19  | You should have received a copy of the GNU General Public License |
20  | along with this program; if not, write to the Free Software |
21  | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
22  +-----------------------------------------------------------------------------+
23 */
24 
25 require_once "Services/WebDAV/classes/Server.php";
26 require_once "Services/WebDAV/classes/class.ilDAVLocks.php";
27 require_once "Services/WebDAV/classes/class.ilDAVProperties.php";
28 require_once 'Services/WebDAV/classes/class.ilObjectDAV.php';
29 
30 require_once "Services/User/classes/class.ilObjUser.php";
31 require_once('include/Unicode/UtfNormal.php');
32 require_once('Services/Tracking/classes/class.ilChangeEvent.php');
33 
51 {
57 
61  private $locks;
65  private $properties;
66 
72  private $clientOS = 'unknown';
77  private $clientOSFlavor = 'unknown';
82  private $clientBrowser = 'unknown';
83 
94  private $putObjDAV = null;
95 
102  private $isHTTPS = null;
103 
108  private $isDebug = false;
109 
115  public function ilDAVServer()
116  {
117  $this->writelog("<constructor>");
118 
119  // Initialize the WebDAV server and create
120  // locking and property support objects
121  $this->HTTP_WebDAV_Server();
122  $this->locks =& new ilDAVLocks();
123  $this->properties =& new ilDAVProperties();
124  //$this->locks->createTable();
125  //$this->properties->createTable();
126 
127 
128  // Guess operating system, operating system flavor and browser of the webdav client
129  //
130  // - We need to know the operating system in order to properly
131  // hide hidden resources in directory listings.
132  //
133  // - We need the operating system flavor and the browser to
134  // properly support mounting of a webdav folder.
135  //
136  $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
137  $this->writelog('userAgent='.$userAgent);
138  if (strpos($userAgent,'windows') !== false
139  || strpos($userAgent,'microsoft') !== false)
140  {
141  $this->clientOS = 'windows';
142  $this->clientOSFlavor = 'xp';
143 
144  } else if (strpos($userAgent,'darwin') !== false
145  || strpos($userAgent,'macintosh') !== false
146  || strpos($userAgent,'linux') !== false
147  || strpos($userAgent,'solaris') !== false
148  || strpos($userAgent,'aix') !== false
149  || strpos($userAgent,'unix') !== false
150  || strpos($userAgent,'gvfs') !== false // nautilus browser uses this ID
151  )
152  {
153  $this->clientOS = 'unix';
154  if (strpos($userAgent,'linux') !== false)
155  {
156  $this->clientOSFlavor = 'linux';
157  }
158  else if (strpos($userAgent,'macintosh') !== false)
159  {
160  $this->clientOSFlavor = 'osx';
161  }
162  }
163  if (strpos($userAgent,'konqueror') !== false)
164  {
165  $this->clientBrowser = 'konqueror';
166  }
167  }
168 
172  public function serveRequest()
173  {
174  // die quickly if plugin is deactivated
175  if (!self::_isActive())
176  {
177  $this->http_status('403 Forbidden');
178  echo '<html><body><h1>Sorry</h1>'.
179  '<p><b>Please enable the WebDAV plugin in the ILIAS Administration panel.</b></p>'.
180  '<p>You can only access this page, if WebDAV is enabled on this server.</p>'.
181  '</body></html>';
182  return;
183  }
184 
185  try {
186  $start = time();
187  $this->writelog('serveRequest():'.$_SERVER['REQUEST_METHOD'].' '.$_SERVER['PATH_INFO'].' ...');
189  $end = time();
190  $this->writelog('serveRequest():'.$_SERVER['REQUEST_METHOD'].' done status='.$this->_http_status.' elapsed='.($end - $start));
191  $this->writelog('---');
192  } catch (Exception $e) {
193  $this->writelog('serveRequest():'.$_SERVER['REQUEST_METHOD'].' caught exception: '.$e->getMessage().'\n'.$e->getTraceAsString());
194  }
195  }
196 
231  private function davUrlEncode($path)
232  {
233  // We compose the path to Unicode Normal Form NFC
234  // This ensures that diaeresis and other special characters
235  // are treated uniformly on Windows and on Mac OS X
237 
238  $c = explode('/',$path);
239  for ($i = 0; $i < count($c); $i++)
240  {
241  $c[$i] = str_replace('+','%20',urlencode($c[$i]));
242  }
243  return implode('/',$c);
244  }
245 
253  public function PROPFIND(&$options, &$files)
254  {
255  // Activate tree cache
256  global $tree;
257  //$tree->useCache(true);
258 
259  $this->writelog('PROPFIND(options:'.var_export($options, true).' files:'.var_export($files, true).'.)');
260  $this->writelog('PROPFIND '.$options['path']);
261 
262  // get dav object for path
263  $path =& $this->davDeslashify($options['path']);
264  $objDAV =& $this->getObject($path);
265 
266  // prepare property array
267  $files['files'] = array();
268 
269  // sanity check
270  if (is_null($objDAV)) {
271  return false;
272  }
273  if (! $objDAV->isPermitted('visible,read')) {
274  return '403 Forbidden';
275  }
276 
277  // store information for the requested path itself
278  // FIXME : create display name for object.
279  $encodedPath = $this->davUrlEncode($path);
280  $files['files'][] =& $this->fileinfo($encodedPath, $encodedPath, $objDAV);
281 
282  // information for contained resources requested?
283  if (!empty($options['depth'])) {
284  // The breadthFirst list holds the collections which we have not
285  // processed yet. If depth is infinity we append unprocessed collections
286  // to the end of this list, and remove processed collections from
287  // the beginning of this list.
288  $breadthFirst = array($objDAV);
289  $objDAV->encodedPath = $encodedPath;
290 
291  while (count($breadthFirst) > 0) {
292  // remove a collection from the beginning of the breadthFirst list
293  $collectionDAV = array_shift($breadthFirst);
294  $childrenDAV =& $collectionDAV->childrenWithPermission('visible');
295  foreach ($childrenDAV as $childDAV)
296  {
297  // On duplicate names, work with the older object (the one with the
298  // smaller object id).
299  foreach ($childrenDAV as $duplChildDAV)
300  {
301  if ($duplChildDAV->getObjectId() < $childDAV->getObjectId() &&
302  $duplChildDAV->getResourceName() == $childDAV->getResourceName())
303  {
304  continue 2;
305  }
306  }
307 
308  // only add visible objects to the file list
309  if (!$this->isFileHidden($childDAV))
310  {
311  $this->writelog('PROPFIND() child ref_id='.$childDAV->getRefId());
312  $files['files'][] =& $this->fileinfo(
313  $collectionDAV->encodedPath.'/'.$this->davUrlEncode($childDAV->getResourceName()),
314  $collectionDAV->encodedPath.'/'.$this->davUrlEncode($childDAV->getDisplayName()),
315  $childDAV
316  );
317 
318  if ($options['depth']=='infinity' && $childDAV->isCollection()) {
319  // add a collection to the end of the breadthFirst list
320  $breadthFirst[] = $childDAV;
321  $childDAV->encodedPath = $collectionDAV->encodedPath.'/'.$this->davUrlEncode($childDAV->getResourceName());
322  }
323  }
324  }
325  }
326  }
327 
328  // Record read event but don't catch up with write events, because
329  // with WebDAV, a user can not see all objects contained in a folder.
331  {
332  global $ilUser;
333  ilChangeEvent::_recordReadEvent($objDAV->getObjectId(), $ilUser->getId(), false);
334  }
335 
336  // ok, all done
337  $this->writelog('PROPFIND():true options='.var_export($options, true).' files='.var_export($files,true));
338  return true;
339  }
340 
351  private function isFileHidden(&$objDAV)
352  {
353  // Hide null resources which haven't got an active lock
354  if ($objDAV->isNullResource()) {
355  if (count($this->locks->getLocksOnObjectDAV($objDAV)) == 0) {
356  return;
357  }
358  }
359 
360  $name = $objDAV->getResourceName();
361  $isFileHidden = false;
362  switch ($this->clientOS)
363  {
364  case 'unix' :
365  // Hide Windows thumbnail files, and files which start with '~$'.
366  $isFileHidden =
367  $name == 'Thumbs.db'
368  || substr($name, 0, 2) == '~$';
369  // Hide files which contain /
370  $isFileHidden |= preg_match('/\\//', $name);
371  break;
372  case 'windows' :
373  // Hide files that start with '.'.
374  $isFileHidden = substr($name, 0, 1) == '.';
375  // Hide files which contain \ / : * ? " < > |
376  $isFileHidden |= preg_match('/\\\\|\\/|:|\\*|\\?|"|<|>|\\|/', $name);
377  break;
378  default :
379  // Hide files which contain /
380  $isFileHidden |= preg_match('/\\//', $name);
381  break;
382  }
383  $this->writelog($this->clientOS.' '.$name.' isHidden:'.$isFileHidden.' clientOS:'.$this->clientOS);
384  return $isFileHidden;
385  }
386 
394  private function fileinfo($resourcePath, $displayPath, &$objDAV)
395  {
396  global $ilias;
397 
398  $this->writelog('fileinfo('.$resourcePath.')');
399  // create result array
400  $info = array();
401  /* Some clients, for example WebDAV-Sync, need a trailing slash at the
402  * end of a resource path to a collection.
403  * However Mac OS X does not like this!
404  */
405  if ($objDAV->isCollection() && $this->clientOSFlavor != 'osx') {
406  $info['path'] = $resourcePath.'/';
407  } else {
408  $info['path'] = $resourcePath;
409  }
410 
411  $info['props'] = array();
412 
413  // no special beautified displayname here ...
414  $info["props"][] =& $this->mkprop("displayname", $displayPath);
415 
416  // creation and modification time
417  $info["props"][] =& $this->mkprop("creationdate", $objDAV->getCreationTimestamp());
418  $info["props"][] =& $this->mkprop("getlastmodified", $objDAV->getModificationTimestamp());
419 
420  // directory (WebDAV collection)
421  $info["props"][] =& $this->mkprop("resourcetype", $objDAV->getResourceType());
422  $info["props"][] =& $this->mkprop("getcontenttype", $objDAV->getContentType());
423  $info["props"][] =& $this->mkprop("getcontentlength", $objDAV->getContentLength());
424 
425  // Only show supported locks for users who have write permission
426  if ($objDAV->isPermitted('write'))
427  {
428  $info["props"][] =& $this->mkprop("supportedlock",
429  '<D:lockentry>'
430  .'<D:lockscope><D:exclusive/></D:lockscope>'
431  .'<D:locktype><D:write/></D:locktype>'
432  .'</D:lockentry>'
433  .'<D:lockentry>'
434  .'<D:lockscope><D:shared/></D:lockscope>'
435  .'<D:locktype><D:write/></D:locktype>'
436  .'</D:lockentry>'
437  );
438  }
439 
440  // Maybe we should only show locks on objects for users who have write permission.
441  // But if we don't show these locks, users who have write permission in an object
442  // further down in a hierarchy can't see who is locking their object.
443  $locks = $this->locks->getLocksOnObjectDAV($objDAV);
444  $lockdiscovery = '';
445  foreach ($locks as $lock)
446  {
447  // DAV Clients expects to see their own owner name in
448  // the locks. Since these names are not unique (they may
449  // just be the name of the local user running the DAV client)
450  // we return the ILIAS user name in all other cases.
451  if ($lock['ilias_owner'] == $ilias->account->getId())
452  {
453  $owner = $lock['dav_owner'];
454  } else {
455  $owner = '<D:href>'.$this->getLogin($lock['ilias_owner']).'</D:href>';
456  }
457  $this->writelog('lockowner='.$owner.' ibi:'.$lock['ilias_owner'].' davi:'.$lock['dav_owner']);
458 
459  $lockdiscovery .=
460  '<D:activelock>'
461  .'<D:lockscope><D:'.$lock['scope'].'/></D:lockscope>'
462  //.'<D:locktype><D:'.$lock['type'].'/></D:locktype>'
463  .'<D:locktype><D:write/></D:locktype>'
464  .'<D:depth>'.$lock['depth'].'</D:depth>'
465  .'<D:owner>'.$owner.'</D:owner>'
466 
467  // more than a million is considered an absolute timestamp
468  // less is more likely a relative value
469  .'<D:timeout>Second-'.(($lock['expires'] > 1000000) ? $lock['expires']-time():$lock['expires']).'</D:timeout>'
470  .'<D:locktoken><D:href>'.$lock['token'].'</D:href></D:locktoken>'
471  .'</D:activelock>'
472  ;
473  }
474  if (strlen($lockdiscovery) > 0)
475  {
476  $info["props"][] =& $this->mkprop("lockdiscovery", $lockdiscovery);
477  }
478 
479  // get additional properties from database
480  $properties = $this->properties->getAll($objDAV);
481  foreach ($properties as $prop)
482  {
483  $info["props"][] = $this->mkprop($prop['namespace'], $prop['name'], $prop['value']);
484  }
485 
486  //$this->writelog('fileinfo():'.var_export($info, true));
487 
488  return $info;
489  }
490 
502  public function GET(&$options)
503  {
504  global $ilUser;
505 
506  $this->writelog('GET('.var_export($options, true).')');
507  $this->writelog('GET('.$options['path'].')');
508 
509  // get dav object for path
510  $path = $this->davDeslashify($options['path']);
511  $objDAV =& $this->getObject($path);
512 
513  // sanity check
514  if (is_null($objDAV) || $objDAV->isNullResource())
515  {
516  return false;
517  }
518 
519  if (! $objDAV->isPermitted('visible,read'))
520  {
521  return '403 Forbidden';
522  }
523 
524  // is this a collection?
525  if ($objDAV->isCollection())
526  {
527  if (isset($_GET['mount']))
528  {
529  return $this->mountDir($objDAV, $options);
530  } else if (isset($_GET['mount-instructions']))
531  {
532  return $this->showMountInstructions($objDAV, $options);
533  } else {
534  return $this->getDir($objDAV, $options);
535  }
536  }
537  // detect content type
538  $options['mimetype'] =& $objDAV->getContentType();
539  // detect modification time
540  // see rfc2518, section 13.7
541  // some clients seem to treat this as a reverse rule
542  // requiring a Last-Modified header if the getlastmodified header was set
543  $options['mtime'] =& $objDAV->getModificationTimestamp();
544 
545  // detect content length
546  $options['size'] =& $objDAV->getContentLength();
547 
548  // get content as stream or as data array
549  $options['stream'] =& $objDAV->getContentStream();
550  if (is_null($options['stream']))
551  {
552  $options['data'] =& $objDAV->getContentData();
553  }
554 
555  // Record read event and catch up write events
557  {
558  ilChangeEvent::_recordReadEvent($objDAV->getObjectId(), $ilUser->getId());
559  }
560  $this->writelog('GET:'.var_export($options, true));
561 
562  return true;
563  }
575  private function mountDir(&$objDAV, &$options)
576  {
577  $path = $this->davDeslashify($options['path']);
578 
579  header('Content-Type: application/davmount+xml');
580 
581  echo "<dm:mount xmlns:dm=\"http://purl.org/NET/webdav/mount\">\n";
582  echo " </dm:url>".$this->base_uri."</dm:url>\n";
583 
584  $xmlPath = str_replace('&','&amp;',$path);
585  $xmlPath = str_replace('<','&lt;',$xmlPath);
586  $xmlPath = str_replace('>','&gt;',$xmlPath);
587 
588  echo " </dm:open>$xmlPath</dm:open>\n";
589  echo "</dm:mount>\n";
590 
591  exit;
592 
593  }
600  private function showMountInstructions(&$objDAV, &$options)
601  {
602  global $lng;
603 
604  $path = $this->davDeslashify($options['path']);
605 
606  // The $path variable may contain a full or a shortened DAV path.
607  // We convert it into an object path, which we can then use to
608  // construct a new full DAV path.
609  $objectPath = $this->toObjectPath($path);
610 
611  // Construct a (possibly) full DAV path from the object path.
612  $fullPath = '';
613  foreach ($objectPath as $object)
614  {
615  if ($object->getRefId() == 1 && $this->isFileHidden($object))
616  {
617  // If the repository root object is hidden, we can not
618  // create a full path, because nothing would appear in the
619  // webfolder. We resort to a shortened path instead.
620  $fullPath .= '/ref_1';
621  }
622  else
623  {
624  $fullPath .= '/'.$this->davUrlEncode($object->getResourceName());
625  }
626  }
627 
628  // Construct a shortened DAV path from the object path.
629  $shortenedPath = '/ref_'.
630  $objectPath[count($objectPath) - 1]->getRefId();
631 
632 
633  if ($objDAV->isCollection())
634  {
635  $shortenedPath .= '/';
636  $fullPath .= '/';
637  }
638 
639  // Prepend client id to path
640  $shortenedPath = '/'.CLIENT_ID.$shortenedPath;
641  $fullPath = '/'.CLIENT_ID.$fullPath;
642 
643  // Construct webfolder URI's. The URI's are used for mounting the
644  // webfolder. Since mounting using URI's is not standardized, we have
645  // to create different URI's for different browsers.
646  $webfolderURI = $this->base_uri.$shortenedPath;
647  $webfolderURI_Konqueror = ($this->isWebDAVoverHTTPS() ? "webdavs" : "webdav").
648  substr($this->base_uri, strrpos($this->base_uri,':')).
649  $shortenedPath;
650  ;
651  $webfolderURI_Nautilus = ($this->isWebDAVoverHTTPS() ? "davs" : "dav").
652  substr($this->base_uri, strrpos($this->base_uri,':')).
653  $shortenedPath
654  ;
655  $webfolderURI_IE = $this->base_uri.$shortenedPath;
656 
657  $webfolderTitle = $objectPath[count($objectPath) - 1]->getResourceName();
658 
659  header('Content-Type: text/html; charset=UTF-8');
660  echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
661  echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN\"\n";
662  echo " \"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd\">\n";
663  echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
664  echo " <head>\n";
665  echo " <title>".sprintf($lng->txt('webfolder_instructions_titletext'), $webfolderTitle)."</title>\n";
666  echo " </head>\n";
667  echo " <body>\n";
668 
669  echo ilDAVServer::_getWebfolderInstructionsFor($webfolderTitle,
670  $webfolderURI, $webfolderURI_IE, $webfolderURI_Konqueror, $webfolderURI_Nautilus,
671  $this->clientOS,$this->clientOSFlavor);
672 
673  echo " </body>\n";
674  echo "</html>\n";
675  exit;
676  }
686  private function getDir(&$objDAV, &$options)
687  {
688  global $ilias, $lng;
689 
690  // Activate tree cache
691  global $tree;
692  //$tree->useCache(true);
693 
694  $path = $this->davDeslashify($options['path']);
695 
696  // The URL of a directory must end with a slash.
697  // If it does not we are redirecting the browser.
698  // The slash is required, because we are using relative links in the
699  // HTML code we are generating below.
700  if ($path.'/' != $options['path'])
701  {
702  header('Location: '.$this->base_uri.$path.'/');
703  exit;
704  }
705 
706  header('Content-Type: text/html; charset=UTF-8');
707 
708  // fixed width directory column format
709  $format = "%15s %-19s %-s\n";
710 
711  echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
712  echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN\"\n";
713  echo " \"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd\">\n";
714  echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
715  echo "<head>\n";
716  echo "<title>".sprintf($lng->txt('webfolder_index_of'), $path)."</title>\n";
717 
718  // Create "anchorClick" behavior for for Internet Explorer
719  // This allows to create a link to a webfolder
720  echo "<style type=\"text/css\">\n";
721  echo "<!--\n";
722  echo "a {\n";
723  echo " behavior:url(#default#AnchorClick);\n";
724  echo "}\n";
725  echo "-->\n";
726  echo "</style>\n";
727 
728  echo "</head><body>\n";
729 
730  $hrefPath = '';
731  $pathComponents = explode('/',$path);
732  $uriComponents = array();
733  foreach ($pathComponents as $component)
734  {
735  $uriComponents[] = $this->davUrlEncode($component);
736  }
737  for ($i = 0; $i < count($pathComponents); $i++)
738  {
739  $displayName = htmlspecialchars($pathComponents[$i]);
740  if ($i != 0) {
741  $hrefPath .= '/';
742  }
743  $uriPath = implode('/', array_slice($uriComponents,0,$i + 1));
744  if ($i < 2)
745  {
746  // The first two path elements consist of the webdav.php script
747  // and the client id. These elements are not part of the
748  // directory structure and thus are not represented as links.
749  $hrefPath .= $displayName;
750  }
751  else
752  {
753  $hrefPath .= '<a href="'.$this->base_uri.$uriPath.'/">'.$displayName.'</a>';
754  }
755  }
756  echo "<h3>".sprintf($lng->txt('webfolder_index_of'), $hrefPath)."</h3>\n";
757 
758  // Display user id
759  if ($ilias->account->getLogin() == 'anonymous')
760  {
761  echo "<p><font size=\"-1\">".$lng->txt('not_logged_in')."</font><br>\n";
762  } else {
763  echo "<p><font size=\"-1\">".$lng->txt('login_as')." <i>"
764  .$ilias->account->getFirstname().' '
765  .$ilias->account->getLastname().' '
766  .' '.$ilias->account->getLogin().'</i> '
767  .', '.$lng->txt('client').' <i>'.$ilias->getClientId().'</i>.'
768  ."</font><p>\n";
769  }
770 
771  // Create "open as webfolder" link
772  $href = $this->base_uri.$uriPath;
773  // IE can not mount long paths. If the path has more than one element, we
774  // create a relative path with a ref-id.
775  if (count($pathComponents) > 2)
776  {
777  $hrefIE = $this->base_uri.'/'.CLIENT_ID.'/ref_'.$objDAV->getRefId();
778  } else {
779  $hrefIE = $href;
780  }
781  echo "<p><font size=\"-1\">".
782  sprintf($lng->txt('webfolder_dir_info'), "$href?mount-instructions").
783  "</font></p>\n";
784  echo "<p><font size=\"-1\">".
785  sprintf($lng->txt('webfolder_mount_dir_with'),
786  "$hrefIE\" folder=\"$hrefIE", // Internet Explorer
787  'webdav'.substr($href,4), // Konqueror
788  'dav'.substr($href,4), // Nautilus
789  $href.'?mount' // RFC 4709
790  )
791  ."</font></p>\n";
792 
793  echo "<pre>";
794  printf($format, $lng->txt('size'), $lng->txt('last_change'), $lng->txt('filename'));
795  echo "<hr>";
796 
797  $collectionCount = 0;
798  $fileCount = 0;
799  $children =& $objDAV->childrenWithPermission('visible');
800  foreach ($children as $childDAV) {
801  if ($childDAV->isCollection() && !$this->isFileHidden($childDAV))
802  {
803  $collectionCount++;
804  $name = $this->davUrlEncode($childDAV->getResourceName());
805  printf($format,
806  '-',
807  strftime("%Y-%m-%d %H:%M:%S", $childDAV->getModificationTimestamp()),
808  '<a href="'.$name.'/'.'">'.$childDAV->getDisplayName()."</a>");
809  }
810  }
811  foreach ($children as $childDAV) {
812  if ($childDAV->isFile() && !$this->isFileHidden($childDAV))
813  {
814  $fileCount++;
815  $name = $this->davUrlEncode($childDAV->getResourceName());
816  printf($format,
817  number_format($childDAV->getContentLength()),
818  strftime("%Y-%m-%d %H:%M:%S", $childDAV->getModificationTimestamp()),
819  '<a href="'.$name.'">'.$childDAV->getDisplayName()."</a>");
820  }
821  }
822  foreach ($children as $childDAV) {
823  if ($childDAV->isNullResource() && !$this->isFileHidden($childDAV))
824  {
825  $name = $this->davUrlEncode($childDAV->getResourceName());
826  printf($format,
827  'Lock',
828  strftime("%Y-%m-%d %H:%M:%S", $childDAV->getModificationTimestamp()),
829  '<a href="'.$name.'">'.$childDAV->getDisplayName()."</a>");
830  }
831  }
832  echo "<hr>";
833  echo $collectionCount.' '.$lng->txt(($collectionCount == 1) ? 'folder' : 'folders').', ';
834  echo $fileCount.' '.$lng->txt(($fileCount == 1) ? 'file' : 'files').'.';
835  echo "</pre>";
836  echo "</body></html>\n";
837 
838  exit;
839  }
840 
841 
848  public function PUT(&$options)
849  {
850  global $ilUser;
851 
852  $this->writelog('PUT('.var_export($options, true).')');
853 
854  $path = $this->davDeslashify($options['path']);
855  $parent = dirname($path);
856  $name = $this->davBasename($path);
857 
858  // get dav object for path
859  $parentDAV =& $this->getObject($parent);
860 
861  // sanity check
862  if (is_null($parentDAV) || ! $parentDAV->isCollection()) {
863  return '409 Conflict';
864  }
865 
866  // Prevent putting of files which exceed upload limit
867  // FIXME: since this is an optional parameter, we should to do the
868  // same check again in function PUTfinished.
869  if ($options['content_length'] != null &&
870  $options['content_length'] > $this->getUploadMaxFilesize()) {
871 
872  $this->writelog('PUT is forbidden, because content length='.
873  $options['content_length'].' is larger than upload_max_filesize='.
874  $this->getUploadMaxFilesize().'in php.ini');
875 
876  return '403 Forbidden';
877  }
878 
879  // determine mime type
880  include_once("./Services/Utilities/classes/class.ilMimeTypeUtil.php");
881  $mime = ilMimeTypeUtil::getMimeType("", $name, $options['content_type']);
882 
883  $objDAV =& $this->getObject($path);
884  if (is_null($objDAV))
885  {
886  if (! $parentDAV->isPermitted('create', $parentDAV->getILIASFileType()))
887  {
888  $this->writelog('PUT is forbidden, because user has no create permission');
889  return '403 Forbidden';
890  }
891  $options["new"] = true;
892  $objDAV =& $parentDAV->createFile($name);
893  $this->writelog('PUT obj='.$objDAV.' name='.$name.' content_type='.$options['content_type']);
894  //$objDAV->setContentType($options['content_type']);
895  $objDAV->setContentType($mime);
896  if ($options['content_length'] != null)
897  {
898  $objDAV->setContentLength($options['content_length']);
899  }
900  $objDAV->write();
901 
902  // Record write event
904  {
905  ilChangeEvent::_recordWriteEvent($objDAV->getObjectId(), $ilUser->getId(), 'create', $parentDAV->getObjectId());
906  }
907  }
908  else if ($objDAV->isNullResource())
909  {
910  if (! $parentDAV->isPermitted('create', $parentDAV->getILIASFileType()))
911  {
912  $this->writelog('PUT is forbidden, because user has no create permission');
913  return '403 Forbidden';
914  }
915  $options["new"] = false;
916  $objDAV =& $parentDAV->createFileFromNull($name, $objDAV);
917  $this->writelog('PUT obj='.$objDAV.' name='.$name.' content_type='.$options['content_type']);
918  //$objDAV->setContentType($options['content_type']);
919  $objDAV->setContentType($mime);
920  if ($options['content_length'] != null)
921  {
922  $objDAV->setContentLength($options['content_length']);
923  }
924  $objDAV->write();
925 
926  // Record write event
928  {
929  ilChangeEvent::_recordWriteEvent($objDAV->getObjectId(), $ilUser->getId(), 'create', $parentDAV->getObjectId());
930  }
931  }
932  else
933  {
934  if (! $objDAV->isPermitted('write'))
935  {
936  $this->writelog('PUT is forbidden, because user has no write permission');
937  return '403 Forbidden';
938  }
939  $options["new"] = false;
940  $this->writelog('PUT obj='.$objDAV.' name='.$name.' content_type='.$options['content_type'].' content_length='.$options['content_length']);
941 
942  // Create a new version if the previous version is not empty
943  if ($objDAV->getContentLength() != 0) {
944  $objDAV->createNewVersion();
945  }
946 
947  //$objDAV->setContentType($options['content_type']);
948  $objDAV->setContentType($mime);
949  if ($options['content_length'] != null)
950  {
951  $objDAV->setContentLength($options['content_length']);
952  }
953  $objDAV->write();
954 
955  // Record write event
957  {
958  ilChangeEvent::_recordWriteEvent($objDAV->getObjectId(), $ilUser->getId(), 'update');
959  ilChangeEvent::_catchupWriteEvents($objDAV->getObjectId(), $ilUser->getId(), 'update');
960  }
961  }
962  // store this object, we reuse it in method PUTfinished
963  $this->putObjDAV = $objDAV;
964 
965  $out =& $objDAV->getContentOutputStream();
966  $this->writelog('PUT outputstream='.$out);
967  return $out;
968  }
969 
976  public function PUTfinished(&$options)
977  {
978  $this->writelog('PUTfinished('.var_export($options, true).')');
979 
980  // Update the content length in the file object, if the
981  // the client did not specify a content_length
982  if ($options['content_length'] == null)
983  {
984  $objDAV = $this->putObjDAV;
985  $objDAV->setContentLength($objDAV->getContentOutputStreamLength());
986  $objDAV->write();
987  $this->putObjDAV = null;
988  }
989  return true;
990  }
991 
992 
999  public function MKCOL($options)
1000  {
1001  global $ilUser;
1002 
1003  $this->writelog('MKCOL('.var_export($options, true).')');
1004  $this->writelog('MKCOL '.$options['path']);
1005 
1006  $path =& $this->davDeslashify($options['path']);
1007  $parent =& dirname($path);
1008  $name =& $this->davBasename($path);
1009 
1010  // No body parsing yet
1011  if(!empty($_SERVER["CONTENT_LENGTH"])) {
1012  return "415 Unsupported media type";
1013  }
1014 
1015  // Check if an object with the path already exists.
1016  $objDAV =& $this->getObject($path);
1017  if (! is_null($objDAV))
1018  {
1019  return '405 Method not allowed';
1020  }
1021 
1022  // get parent dav object for path
1023  $parentDAV =& $this->getObject($parent);
1024 
1025  // sanity check
1026  if (is_null($parentDAV) || ! $parentDAV->isCollection())
1027  {
1028  return '409 Conflict';
1029  }
1030 
1031  if (! $parentDAV->isPermitted('create',$parentDAV->getILIASCollectionType()))
1032  {
1033  return '403 Forbidden';
1034  }
1035 
1036  // XXX Implement code that Handles null resource here
1037 
1038  $objDAV = $parentDAV->createCollection($name);
1039 
1040  if ($objDAV != null)
1041  {
1042  // Record write event
1044  {
1045  ilChangeEvent::_recordWriteEvent($objDAV->getObjectId(), $ilUser->getId(), 'create', $parentDAV->getObjectId());
1046  }
1047  }
1048 
1049  $result = ($objDAV != null) ? "201 Created" : "409 Conflict";
1050  return $result;
1051  }
1052 
1053 
1060  public function DELETE($options)
1061  {
1062  global $ilUser;
1063 
1064  $this->writelog('DELETE('.var_export($options, true).')');
1065  $this->writelog('DELETE '.$options['path']);
1066 
1067  // get dav object for path
1068  $path =& $this->davDeslashify($options['path']);
1069  $parentDAV =& $this->getObject(dirname($path));
1070  $objDAV =& $this->getObject($path);
1071 
1072  // sanity check
1073  if (is_null($objDAV) || $objDAV->isNullResource())
1074  {
1075  return '404 Not Found';
1076  }
1077  if (! $objDAV->isPermitted('delete'))
1078  {
1079  return '403 Forbidden';
1080  }
1081 
1082  $parentDAV->remove($objDAV);
1083 
1084  // Record write event
1086  {
1087  ilChangeEvent::_recordWriteEvent($objDAV->getObjectId(), $ilUser->getId(), 'delete', $parentDAV->getObjectId());
1088  }
1089 
1090  return '204 No Content';
1091  }
1092 
1099  public function MOVE($options)
1100  {
1101  global $ilUser;
1102 
1103  $this->writelog('MOVE('.var_export($options, true).')');
1104  $this->writelog('MOVE '.$options['path'].' '.$options['dest']);
1105 
1106  // Get path names
1107  $src = $this->davDeslashify($options['path']);
1108  $srcParent = dirname($src);
1109  $srcName = $this->davBasename($src);
1110  $dst = $this->davDeslashify($options['dest']);
1111 
1112  $dstParent = dirname($dst);
1113  $dstName = $this->davBasename($dst);
1114  $this->writelog('move '.$dst.' dstname='.$dstName);
1115  // Source and destination must not be the same
1116  if ($src == $dst)
1117  {
1118  return '409 Conflict (source and destination are the same)';
1119  }
1120 
1121  // Destination must not be in a subtree of source
1122  if (substr($dst,strlen($src)+1) == $src.'/')
1123  {
1124  return '409 Conflict (destination is in subtree of source)';
1125  }
1126 
1127  // Get dav objects for path
1128  $srcDAV =& $this->getObject($src);
1129  $dstDAV =& $this->getObject($dst);
1130  $srcParentDAV =& $this->getObject($srcParent);
1131  $dstParentDAV =& $this->getObject($dstParent);
1132 
1133  // Source must exist
1134  if ($srcDAV == null)
1135  {
1136  return '409 Conflict (source does not exist)';
1137  }
1138 
1139  // Overwriting is only allowed, if overwrite option is set to 'T'
1140  $isOverwritten = false;
1141  if ($dstDAV != null)
1142  {
1143  if ($options['overwrite'] == 'T')
1144  {
1145  // Delete the overwritten destination
1146  if ($dstDAV->isPermitted('delete'))
1147  {
1148  $dstParentDAV->remove($dstDAV);
1149  $dstDAV = null;
1150  $isOverwritten = true;
1151  } else {
1152  return '403 Not Permitted';
1153  }
1154  } else {
1155  return '412 Precondition Failed';
1156  }
1157  }
1158 
1159  // Parents of destination must exist
1160  if ($dstParentDAV == null)
1161  {
1162  return '409 Conflict (parent of destination does not exist)';
1163  }
1164 
1165  if ($srcParent == $dstParent)
1166  {
1167  // Rename source, if source and dest are in same parent
1168 
1169  // Check permission
1170  if (! $srcDAV->isPermitted('write'))
1171  {
1172  return '403 Forbidden';
1173  }
1174  $this->writelog('rename dstName='.$dstName);
1175  $srcDAV->setResourceName($dstName);
1176  $srcDAV->write();
1177  } else {
1178  // Move source, if source and dest are in same parent
1179 
1180 
1181  if (! $srcDAV->isPermitted('delete'))
1182  {
1183  return '403 Forbidden';
1184  }
1185 
1186  if (! $dstParentDAV->isPermitted('create', $srcDAV->getILIASType()))
1187  {
1188  return '403 Forbidden';
1189  }
1190  $dstParentDAV->addMove($srcDAV, $dstName);
1191  }
1192 
1193  // Record write event
1195  {
1196  if ($isOverwritten)
1197  {
1198  ilChangeEvent::_recordWriteEvent($srcDAV->getObjectId(), $ilUser->getId(), 'rename');
1199  }
1200  else
1201  {
1202  ilChangeEvent::_recordWriteEvent($srcDAV->getObjectId(), $ilUser->getId(), 'remove', $srcParentDAV->getObjectId());
1203  ilChangeEvent::_recordWriteEvent($srcDAV->getObjectId(), $ilUser->getId(), 'add', $dstParentDAV->getObjectId());
1204  }
1205  }
1206 
1207  return ($isOverwritten) ? '204 No Content' : '201 Created';
1208  }
1209 
1216  public function COPY($options, $del=false)
1217  {
1218  global $ilUser;
1219  $this->writelog('COPY('.var_export($options, true).' ,del='.$del.')');
1220  $this->writelog('COPY '.$options['path'].' '.$options['dest']);
1221 
1222  // no copying to different WebDAV Servers
1223  if (isset($options["dest_url"])) {
1224  return "502 bad gateway";
1225  }
1226 
1227  $src = $this->davDeslashify($options['path']);
1228  $srcParent = dirname($src);
1229  $srcName = $this->davBasename($src);
1230  $dst = $this->davDeslashify($options['dest']);
1231  $dstParent = dirname($dst);
1232  $dstName = $this->davBasename($dst);
1233 
1234  // sanity check
1235  if ($src == $dst)
1236  {
1237  return '409 Conflict'; // src and dst are the same
1238  }
1239 
1240  if (substr($dst,strlen($src)+1) == $src.'/')
1241  {
1242  return '409 Conflict'; // dst is in subtree of src
1243  }
1244 
1245  $this->writelog('COPY src='.$src.' dst='.$dst);
1246  // get dav object for path
1247  $srcDAV =& $this->getObject($src);
1248  $dstDAV =& $this->getObject($dst);
1249  $dstParentDAV =& $this->getObject($dstParent);
1250 
1251  if (is_null($srcDAV) || $srcDAV->isNullResource())
1252  {
1253  return '409 Conflict'; // src does not exist
1254  }
1255  if (is_null($dstParentDAV) || $dstParentDAV->isNullResource())
1256  {
1257  return '409 Conflict'; // parent of dst does not exist
1258  }
1259  $isOverwritten = false;
1260 
1261  // XXX Handle nulltype for dstDAV
1262  if (! is_null($dstDAV))
1263  {
1264  if ($options['overwrite'] == 'T')
1265  {
1266  if ($dstDAV->isPermitted('delete'))
1267  {
1268  $dstParentDAV->remove($dstDAV);
1270  {
1271  ilChangeEvent::_recordWriteEvent($dstDAV->getObjectId(), $ilUser->getId(), 'delete', $dstParentDAV->getObjectId());
1272  }
1273 
1274  $dstDAV = null;
1275  $isOverwritten = true;
1276  } else {
1277  return '403 Forbidden';
1278  }
1279  } else {
1280  return '412 Precondition Failed';
1281  }
1282  }
1283 
1284  if (! $dstParentDAV->isPermitted('create', $srcDAV->getILIASType()))
1285  {
1286  return '403 Forbidden';
1287  }
1288  $dstDAV = $dstParentDAV->addCopy($srcDAV, $dstName);
1289 
1290  // Record write event
1292  {
1293  ilChangeEvent::_recordReadEvent($srcDAV->getObjectId(), $ilUser->getId());
1294  ilChangeEvent::_recordWriteEvent($dstDAV->getObjectId(), $ilUser->getId(), 'create', $dstParentDAV->getObjectId());
1295  }
1296 
1297  return ($isOverwritten) ? '204 No Content' : '201 Created';
1298  }
1299 
1306  public function PROPPATCH(&$options)
1307  {
1308  $this->writelog('PROPPATCH(options='.var_export($options, true).')');
1309  $this->writelog('PROPPATCH '.$options['path']);
1310 
1311  // get dav object for path
1312  $path =& $this->davDeslashify($options['path']);
1313  $objDAV =& $this->getObject($path);
1314 
1315  // sanity check
1316  if (is_null($objDAV) || $objDAV->isNullResource()) return false;
1317 
1318  $isPermitted = $objDAV->isPermitted('write');
1319  foreach($options['props'] as $key => $prop) {
1320  if (!$isPermitted || $prop['ns'] == 'DAV:')
1321  {
1322  $options['props'][$key]['status'] = '403 Forbidden';
1323  } else {
1324  $this->properties->put($objDAV, $prop['ns'],$prop['name'],$prop['val']);
1325  }
1326  }
1327 
1328  return "";
1329  }
1330 
1331 
1338  public function LOCK(&$options)
1339  {
1340  global $ilias;
1341  $this->writelog('LOCK('.var_export($options, true).')');
1342  $this->writelog('LOCK '.$options['path']);
1343 
1344  // Check if an object with the path exists.
1345  $path =& $this->davDeslashify($options['path']);
1346  $objDAV =& $this->getObject($path);
1347  // Handle null-object locking
1348  // --------------------------
1349  if (is_null($objDAV))
1350  {
1351  $this->writelog('LOCK handling null-object locking...');
1352 
1353  // If the name does not exist, we create a null-object for it
1354  if (isset($options["update"]))
1355  {
1356  $this->writelog('LOCK lock-update failed on non-existing null-object.');
1357  return '412 Precondition Failed';
1358  }
1359 
1360  $parent = dirname($path);
1361  $parentDAV =& $this->getObject($parent);
1362  if (is_null($parentDAV))
1363  {
1364  $this->writelog('LOCK lock failed on non-existing path to null-object.');
1365  return '404 Not Found';
1366  }
1367  if (! $parentDAV->isPermitted('create', $parentDAV->getILIASFileType()) &&
1368  ! $parentDAV->isPermitted('create', $parentDAV->getILIASCollectionType()))
1369  {
1370  $this->writelog('LOCK lock failed - creation of null object not permitted.');
1371  return '403 Forbidden';
1372  }
1373 
1374  $objDAV =& $parentDAV->createNull($this->davBasename($path));
1375  $this->writelog('created null resource for '.$path);
1376  }
1377 
1378  // ---------------------
1379  if (! $objDAV->isNullResource() && ! $objDAV->isPermitted('write'))
1380  {
1381  $this->writelog('LOCK lock failed - user has no write permission.');
1382  return '403 Forbidden';
1383  }
1384 
1385  // XXX - Check if there are other locks on the resource
1386  if (!isset($options['timeout']) || is_array($options['timeout']))
1387  {
1388  $options["timeout"] = time()+360; // 6min.
1389  }
1390 
1391  if(isset($options["update"])) { // Lock Update
1392  $this->writelog('LOCK update token='.var_export($options,true));
1393  $success = $this->locks->updateLockWithoutCheckingDAV(
1394  $objDAV,
1395  $options['update'],
1396  $options['timeout']
1397  );
1398  if ($success)
1399  {
1400  $data = $this->locks->getLockDAV($objDAV, $options['update']);
1401  if ($data['ilias_owner'] == $ilias->account->getId())
1402  {
1403  $owner = $data['dav_owner'];
1404  } else {
1405  $owner = '<D:href>'.$this->getLogin($data['ilias_owner']).'</D:href>';
1406  }
1407  $options['owner'] = $owner;
1408  $options['locktoken'] = $data['token'];
1409  $options['timeout'] = $data['expires'];
1410  $options['depth'] = $data['depth'];
1411  $options['scope'] = $data['scope'];
1412  $options['type'] = $data['scope'];
1413  }
1414 
1415  } else {
1416  $this->writelog('LOCK create new lock');
1417 
1418  // XXX - Attempting to create a recursive exclusive lock
1419  // on a collection must fail, if any of nodes in the subtree
1420  // of the collection already has a lock.
1421  // XXX - Attempting to create a recursive shared lock
1422  // on a collection must fail, if any of nodes in the subtree
1423  // of the collection already has an exclusive lock.
1424  //$owner = (strlen(trim($options['owner'])) == 0) ? $ilias->account->getLogin() : $options['owner'];
1425  $this->writelog('lock owner='.$owner);
1426  $success = $this->locks->lockWithoutCheckingDAV(
1427  $objDAV,
1428  $ilias->account->getId(),
1429  trim($options['owner']),
1430  $options['locktoken'],
1431  $options['timeout'],
1432  $options['depth'],
1433  $options['scope']
1434  );
1435  }
1436 
1437  // Note: As a workaround for the Microsoft WebDAV Client, we return
1438  // true/false here (resulting in the status '200 OK') instead of
1439  // '204 No Content').
1440  //return ($success) ? '204 No Content' : false;
1441  return $success;
1442  }
1443 
1450  public function UNLOCK(&$options)
1451  {
1452  global $log, $ilias;
1453  $this->writelog('UNLOCK(options='.var_export($options, true).')');
1454  $this->writelog('UNLOCK '.$options['path']);
1455 
1456  // Check if an object with the path exists.
1457  $path =& $this->davDeslashify($options['path']);
1458  $objDAV =& $this->getObject($path);
1459  if (is_null($objDAV)) {
1460  return '404 Not Found';
1461  }
1462  if (! $objDAV->isPermitted('write')) {
1463  return '403 Forbidden';
1464  }
1465 
1466  $success = $this->locks->unlockWithoutCheckingDAV(
1467  $objDAV,
1468  $options['token']
1469  );
1470 
1471  // Delete null resource object if there are no locks associated to
1472  // it anymore
1473  if ($objDAV->isNullResource()
1474  && count($this->locks->getLocksOnObjectDAV($objDAV)) == 0)
1475  {
1476  $parent = dirname($this->davDeslashify($options['path']));
1477  $parentDAV =& $this->getObject($parent);
1478  $parentDAV->remove($objDAV);
1479  }
1480 
1481  // Workaround for Mac OS X: We must return 200 here instead of
1482  // 204.
1483  //return ($success) ? '204 No Content' : '412 Precondition Failed';
1484  return ($success) ? '200 OK' : '412 Precondition Failed';
1485  }
1486 
1499  protected function checkLock($path)
1500  {
1501  global $ilias;
1502 
1503  $this->writelog('checkLock('.$path.')');
1504  $result = null;
1505 
1506  // get dav object for path
1507  //$objDAV = $this->getObject($path);
1508 
1509  // convert DAV path into ilObjectDAV path
1510  $objPath = $this->toObjectPath($path);
1511  if (! is_null($objPath))
1512  {
1513  $objDAV = $objPath[count($objPath) - 1];
1514  $locks = $this->locks->getLocksOnPathDAV($objPath);
1515  foreach ($locks as $lock)
1516  {
1517  $isLastPathComponent = $lock['obj_id'] == $objDAV->getObjectId()
1518  && $lock['node_id'] == $objDAV->getNodeId();
1519 
1520  // Check all locks on last object in path,
1521  // but only locks with depth infinity on parent objects.
1522  if ($isLastPathComponent || $lock['depth'] == 'infinity')
1523  {
1524  // DAV Clients expects to see their own owner name in
1525  // the locks. Since these names are not unique (they may
1526  // just be the name of the local user running the DAV client)
1527  // we return the ILIAS user name in all other cases.
1528  if ($lock['ilias_owner'] == $ilias->account->getId())
1529  {
1530  $owner = $lock['dav_owner'];
1531  } else {
1532  $owner = $this->getLogin($lock['ilias_owner']);
1533  }
1534 
1535  // FIXME - Shouldn't we collect all locks instead of
1536  // using an arbitrary one?
1537  $result = array(
1538  "type" => "write",
1539  "obj_id" => $lock['obj_id'],
1540  "node_id" => $lock['node_id'],
1541  "scope" => $lock['scope'],
1542  "depth" => $lock['depth'],
1543  "owner" => $owner,
1544  "token" => $lock['token'],
1545  "expires" => $lock['expires']
1546  );
1547  if ($lock['scope'] == 'exclusive')
1548  {
1549  // If there is an exclusive lock in the path, it
1550  // takes precedence over all non-exclusive locks in
1551  // parent nodes. Therefore we can can finish collecting
1552  // locks.
1553  break;
1554  }
1555  }
1556  }
1557  }
1558  $this->writelog('checkLock('.$path.'):'.var_export($result,true));
1559 
1560  return $result;
1561  }
1562 
1567  protected function getLogin($userId)
1568  {
1569  $login = ilObjUser::_lookupLogin($userId);
1570  $this->writelog('getLogin('.$userId.'):'.var_export($login,true));
1571  return $login;
1572  }
1573 
1574 
1581  private function getObject($davPath)
1582  {
1583  global $tree;
1584 
1585 
1586  // If the second path elements starts with 'file_', the following
1587  // characters of the path element directly identify the ref_id of
1588  // a file object.
1589  $davPathComponents = split('/',substr($davPath,1));
1590  if (count($davPathComponents) > 1 &&
1591  substr($davPathComponents[1],0,5) == 'file_')
1592  {
1593  $ref_id = substr($davPathComponents[1],5);
1594  $nodePath = $tree->getNodePath($ref_id, $tree->root_id);
1595 
1596  // Poor IE needs this, in order to successfully display
1597  // PDF documents
1598  header('Pragma: private');
1599  }
1600  else
1601  {
1602  $nodePath = $this->toNodePath($davPath);
1603  if ($nodePath == null && count($davPathComponents) == 1)
1604  {
1605  return ilObjectDAV::createObject(-1,'mountPoint');
1606  }
1607  }
1608  if (is_null($nodePath))
1609  {
1610  return null;
1611  } else {
1612  $top = $nodePath[count($nodePath) - 1];
1613  return ilObjectDAV::createObject($top['child'],$top['type']);
1614  }
1615  }
1622  private function toObjectPath($davPath)
1623  {
1624  $this->writelog('toObjectPath('.$davPath);
1625  global $tree;
1626 
1627  $nodePath = $this->toNodePath($davPath);
1628  if (is_null($nodePath))
1629  {
1630  return null;
1631  } else {
1632  $objectPath = array();
1633  foreach ($nodePath as $node)
1634  {
1635  $pathElement = ilObjectDAV::createObject($node['child'],$node['type']);
1636  if (is_null($pathElement))
1637  {
1638  break;
1639  }
1640  $objectPath[] = $pathElement;
1641  }
1642  return $objectPath;
1643  }
1644  }
1645 
1657  public function toNodePath($davPath)
1658  {
1659  global $tree;
1660  $this->writelog('toNodePath('.$davPath.')...');
1661 
1662  // Split the davPath into path titles
1663  $titlePath = split('/',substr($davPath,1));
1664 
1665  // Remove the client id from the beginning of the title path
1666  if (count($titlePath) > 0)
1667  {
1668  array_shift($titlePath);
1669  }
1670 
1671  // If the last path title is empty, remove it
1672  if (count($titlePath) > 0 && $titlePath[count($titlePath) - 1] == '')
1673  {
1674  array_pop($titlePath);
1675  }
1676 
1677  // If the path is empty, return null
1678  if (count($titlePath) == 0)
1679  {
1680  $this->writelog('toNodePath('.$davPath.'):null, because path is empty.');
1681  return null;
1682  }
1683 
1684  // If the path is an absolute path, ref_id is null.
1685  $ref_id = null;
1686 
1687  // If the path is a relative folder path, convert it into an absolute path
1688  if (count($titlePath) > 0 && substr($titlePath[0],0,4) == 'ref_')
1689  {
1690  $ref_id = substr($titlePath[0],4);
1691  array_shift($titlePath);
1692  }
1693 
1694  $nodePath = $tree->getNodePathForTitlePath($titlePath, $ref_id);
1695 
1696  $this->writelog('toNodePath():'.var_export($nodePath,true));
1697  return $nodePath;
1698  }
1699 
1706  private function davDeslashify($path)
1707  {
1709 
1710  if ($path[strlen($path)-1] == '/') {
1711  $path = substr($path,0, strlen($path) - 1);
1712  }
1713  $this->writelog('davDeslashify:'.$path);
1714  return $path;
1715  }
1716 
1723  private function davBasename($path)
1724  {
1725  $components = split('/',$path);
1726  return count($components) == 0 ? '' : $components[count($components) - 1];
1727  }
1728 
1735  protected function writelog($message)
1736  {
1737  // Only write log message, if we are in debug mode
1738  if ($this->isDebug)
1739  {
1740  global $ilLog, $ilias;
1741  if ($ilLog)
1742  {
1743  if ($message == '---')
1744  {
1745  $ilLog->write('');
1746  } else {
1747  $ilLog->write(
1748  $ilias->account->getLogin()
1749  .' '.$_SERVER['REMOTE_ADDR'].':'.$_SERVER['REMOTE_PORT']
1750  .' ilDAVServer.'.str_replace("\n",";",$message)
1751  );
1752  }
1753  }
1754  else
1755  {
1756  $fh = fopen('/opt/ilias/log/ilias.log', 'a');
1757  fwrite($fh, date('Y-m-d H:i:s '));
1758  fwrite($fh, str_replace("\n",";",$message));
1759  fwrite($fh, "\n\n");
1760  fclose($fh);
1761  }
1762  }
1763  }
1764 
1777  function getMountURI($refId, $nodeId = 0, $ressourceName = null, $parentRefId = null, $genericURI = false)
1778  {
1779  if ($genericURI) {
1780  $baseUri = ($this->isWebDAVoverHTTPS() ? "https:" : "http:");
1781  $query = null;
1782  } else if ($this->clientOS == 'windows') {
1783  $baseUri = ($this->isWebDAVoverHTTPS() ? "https:" : "http:");
1784  $query = 'mount-instructions';
1785  } else if ($this->clientBrowser == 'konqueror') {
1786  $baseUri = ($this->isWebDAVoverHTTPS() ? "webdavs:" : "webdav:");
1787  $query = null;
1788  } else if ($this->clientBrowser == 'nautilus') {
1789  $baseUri = ($this->isWebDAVoverHTTPS() ? "davs:" : "dav:");
1790  $query = null;
1791  } else {
1792  $baseUri = ($this->isWebDAVoverHTTPS() ? "https:" : "http:");
1793  $query = 'mount-instructions';
1794  }
1795  $baseUri.= "//$_SERVER[HTTP_HOST]$_SERVER[SCRIPT_NAME]";
1796  $baseUri = substr($baseUri,0,strrpos($baseUri,'/')).'/webdav.php/'.CLIENT_ID;
1797 
1798  $uri = $baseUri.'/ref_'.$refId.'/';
1799  if ($query != null)
1800  {
1801  $uri .= '?'.$query;
1802  }
1803 
1804  return $uri;
1805  }
1820  function getFolderURI($refId, $nodeId = 0, $ressourceName = null, $parentRefId = null)
1821  {
1822  if ($this->clientOS == 'windows') {
1823  $baseUri = ($this->isWebDAVoverHTTPS() ? "https:" : "http:");
1824  $query = null;
1825  } else if ($this->clientBrowser == 'konqueror') {
1826  $baseUri = ($this->isWebDAVoverHTTPS() ? "webdavs:" : "webdav:");
1827  $query = null;
1828  } else if ($this->clientBrowser == 'nautilus') {
1829  $baseUri = ($this->isWebDAVoverHTTPS() ? "davs:" : "dav:");
1830  $query = null;
1831  } else {
1832  $baseUri = ($this->isWebDAVoverHTTPS() ? "https:" : "http:");
1833  $query = null;
1834  }
1835  $baseUri.= "//$_SERVER[HTTP_HOST]$_SERVER[SCRIPT_NAME]";
1836  $baseUri = substr($baseUri,0,strrpos($baseUri,'/')).'/webdav.php/'.CLIENT_ID;
1837 
1838  $uri = $baseUri.'/ref_'.$refId.'/';
1839  if ($query != null)
1840  {
1841  $uri .= '?'.$query;
1842  }
1843 
1844  return $uri;
1845  }
1857  public function getObjectURI($refId, $ressourceName = null, $parentRefId = null)
1858  {
1859  $nodeId = 0;
1860  $baseUri = ($this->isWebDAVoverHTTPS() ? "https:" : "http:").
1861  "//$_SERVER[HTTP_HOST]$_SERVER[SCRIPT_NAME]";
1862  $baseUri = substr($baseUri,0,strrpos($baseUri,'/')).'/webdav.php/'.CLIENT_ID;
1863 
1864  if (! is_null($ressourceName) && ! is_null($parentRefId))
1865  {
1866  // Quickly create URI from the known data without needing SQL queries
1867  $uri = $baseUri.'/ref_'.$parentRefId.'/'.$this->davUrlEncode($ressourceName);
1868  } else {
1869  // Create URI and use some SQL queries to get the missing data
1870  global $tree;
1871  $nodePath = $tree->getNodePath($refId);
1872 
1873  if (is_null($nodePath) || count($nodePath) < 2)
1874  {
1875  // No object path? Return null - file is not in repository.
1876  $uri = null;
1877  } else {
1878  $uri = $baseUri.'/ref_'.$nodePath[count($nodePath) - 2]['child'].'/'.
1879  $this->davUrlEncode($nodePath[count($nodePath) - 1]['title']);
1880  }
1881  }
1882  return $uri;
1883  }
1884 
1902  public function getFileURI($refId, $ressourceName = null, $parentRefId = null)
1903  {
1904  $nodeId = 0;
1905  $baseUri = ($this->isWebDAVoverHTTPS() ? "https:" : "http:").
1906  "//$_SERVER[HTTP_HOST]$_SERVER[SCRIPT_NAME]";
1907  $baseUri = substr($baseUri,0,strrpos($baseUri,'/')).'/webdav.php/'.CLIENT_ID;
1908 
1909  if (! is_null($ressourceName) && ! is_null($parentRefId))
1910  {
1911  // Quickly create URI from the known data without needing SQL queries
1912  $uri = $baseUri.'/file_'.$refId.'/'.$this->davUrlEncode($ressourceName);
1913  } else {
1914  // Create URI and use some SQL queries to get the missing data
1915  global $tree;
1916  $nodePath = $tree->getNodePath($refId);
1917 
1918  if (is_null($nodePath) || count($nodePath) < 2)
1919  {
1920  // No object path? Return null - file is not in repository.
1921  $uri = null;
1922  } else {
1923  $uri = $baseUri.'/file_'.$nodePath[count($nodePath) - 1]['child'].'/'.
1924  $this->davUrlEncode($nodePath[count($nodePath) - 1]['title']);
1925  }
1926  }
1927  return $uri;
1928  }
1929 
1935  public function isWebDAVoverHTTPS() {
1936  if ($this->isHTTPS == null) {
1937  global $ilSetting;
1938  require_once 'classes/class.ilHTTPS.php';
1939  $https = new ilHTTPS();
1940  $this->isHTTPS = $https->isDetected() || $ilSetting->get('https');
1941  }
1942  return $this->isHTTPS;
1943  }
1944 
1953  public static function _isActive()
1954  {
1955  global $ilClientIniFile;
1956  return $ilClientIniFile->readVariable('file_access','webdav_enabled') == '1' &&
1957  @include_once("Auth/HTTP.php");
1958  }
1964  public static function _isActionsVisible()
1965  {
1966  global $ilClientIniFile;
1967  return $ilClientIniFile->readVariable('file_access','webdav_actions_visible') == '1';
1968  }
1969 
1979  public static function _getDefaultWebfolderInstructions()
1980  {
1981  global $lng;
1982  return $lng->txt('webfolder_instructions_text');
1983  }
1984 
2011  public static function _getWebfolderInstructionsFor($webfolderTitle,
2012  $webfolderURI, $webfolderURI_IE, $webfolderURI_Konqueror, $webfolderURI_Nautilus,
2013  $os = 'unknown', $osFlavor = 'unknown')
2014  {
2015  global $ilSetting;
2016 
2017  $settings = new ilSetting('file_access');
2018  $str = $settings->get('custom_webfolder_instructions', '');
2019  if (strlen($str) == 0 || ! $settings->get('custom_webfolder_instructions_enabled'))
2020  {
2022  }
2023 
2024  $str = str_replace("[WEBFOLDER_TITLE]", $webfolderTitle, $str);
2025  $str = str_replace("[WEBFOLDER_URI]", $webfolderURI, $str);
2026  $str = str_replace("[WEBFOLDER_URI_IE]", $webfolderURI_IE, $str);
2027  $str = str_replace("[WEBFOLDER_URI_KONQUEROR]", $webfolderURI_Konqueror, $str);
2028  $str = str_replace("[WEBFOLDER_URI_NAUTILUS]", $webfolderURI_Nautilus, $str);
2029  $str = str_replace("[ADMIN_MAIL]", $ilSetting->get("admin_email"), $str);
2030 
2031  switch ($os)
2032  {
2033  case 'windows' :
2034  $operatingSystem = 'WINDOWS';
2035  break;
2036  case 'unix' :
2037  switch ($osFlavor)
2038  {
2039  case 'osx' :
2040  $operatingSystem = 'MAC';
2041  break;
2042  case 'linux' :
2043  $operatingSystem = 'LINUX';
2044  break;
2045  default :
2046  $operatingSystem = 'LINUX';
2047  break;
2048  }
2049  break;
2050  default :
2051  $operatingSystem = 'UNKNOWN';
2052  break;
2053  }
2054 
2055  if ($operatingSystem != 'UNKNOWN')
2056  {
2057  $str = preg_replace('/\[IF_'.$operatingSystem.'\]((?:.|\n)*)\[\/IF_'.$operatingSystem.'\]/','\1', $str);
2058  $str = preg_replace('/\[IF_([A-Z_]+)\](?:(?:.|\n)*)\[\/IF_\1\]/','', $str);
2059  }
2060  else
2061  {
2062  $str = preg_replace('/\[IF_([A-Z_]+)\]((?:.|\n)*)\[\/IF_\1\]/','\2', $str);
2063  }
2064  return $str;
2065  }
2066 
2072  private function getUploadMaxFilesize() {
2073  $val = ini_get('upload_max_filesize');
2074 
2075  $val = trim($val);
2076  $last = strtolower($val[strlen($val)-1]);
2077  switch($last) {
2078  // The 'G' modifier is available since PHP 5.1.0
2079  case 'g':
2080  $val *= 1024;
2081  case 'm':
2082  $val *= 1024;
2083  case 'k':
2084  $val *= 1024;
2085  }
2086 
2087  return $val;
2088  }
2089 }
2090 // END WebDAV
2091 ?>