aboutsummaryrefslogtreecommitdiffstats
path: root/apps/files_external/lib/smb.php
blob: 91c0f16c1f692069976fdfff2d3652eed2892c6b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
89
90
91
92
93
94
95
96
<?php
/**
 * Copyright (c) 2012 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

require_once 'smb4php/smb.php';

class OC_FileStorage_SMB extends OC_FileStorage_StreamWrapper{
	private $password;
	private $user;
	private $host;
	private $root;
	private $share;

	public function __construct($params){
		$this->host=$params['host'];
		$this->user=$params['user'];
		$this->password=$params['password'];
		$this->share=$params['share'];
		$this->root=isset($params['root'])?$params['root']:'/';
		if(!$this->root || $this->root[0]!='/'){
			$this->root='/'.$this->root;
		}
		if(substr($this->root,-1,1)!='/'){
			$this->root.='/';
		}
		if(!$this->share || $this->share[0]!='/'){
			$this->share='/'.$this->share;
		}
		if(substr($this->share,-1,1)=='/'){
			$this->share=substr($this->share,0,-1);
		}

		//create the root folder if necesary
		if(!$this->is_dir('')){
			$this->mkdir('');
		}
	}

	public function constructUrl($path){
		if(substr($path,-1)=='/'){
			$path=substr($path,0,-1);
		}
		return 'smb://'.$this->user.':'.$this->password.'@'.$this->host.$this->share.$this->root.$path;
	}

	public function stat($path){
		if(!$path and $this->root=='/'){//mtime doesn't work for shares
			$mtime=$this->shareMTime();
			$stat=stat($this->constructUrl($path));
			$stat['mtime']=$mtime;
			return $stat;
		}else{
			return stat($this->constructUrl($path));
		}
	}

	public function filetype($path){
		return (bool)@$this->opendir($path);//using opendir causes the same amount of requests and caches the content of the folder in one go
	}

	/**
	 * check if a file or folder has been updated since $time
	 * @param int $time
	 * @return bool
	 */
	public function hasUpdated($path,$time){
		if(!$path and $this->root=='/'){
			//mtime doesn't work for shares, but giving the nature of the backend, doing a full update is still just fast enough
			return true;
		}else{
			$actualTime=$this->filemtime($path);
			return $actualTime>$time;
		}
	}

	/**
	 * get the best guess for the modification time of the share
	 */
	private function shareMTime(){
		$dh=$this->opendir('');
		$lastCtime=0;
		while($file=readdir($dh)){
			if($file!='.' and $file!='..'){
				$ctime=$this->filemtime($file);
				if($ctime>$lastCtime){
					$lastCtime=$ctime;
				}
			}
		}
		return $lastCtime;
	}
}