Completed
Pull Request — master (#3218)
by Vars
46:46 queued 34:29
created
lib/private/Memcache/APCu.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -30,140 +30,140 @@
 block discarded – undo
30 30
 use OCP\IMemcache;
31 31
 
32 32
 class APCu extends Cache implements IMemcache {
33
-	use CASTrait {
34
-		cas as casEmulated;
35
-	}
33
+    use CASTrait {
34
+        cas as casEmulated;
35
+    }
36 36
 
37
-	use CADTrait;
37
+    use CADTrait;
38 38
 
39
-	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
41
-		if (!$success) {
42
-			return null;
43
-		}
44
-		return $result;
45
-	}
39
+    public function get($key) {
40
+        $result = apcu_fetch($this->getPrefix() . $key, $success);
41
+        if (!$success) {
42
+            return null;
43
+        }
44
+        return $result;
45
+    }
46 46
 
47
-	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
-	}
47
+    public function set($key, $value, $ttl = 0) {
48
+        return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
+    }
50 50
 
51
-	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
53
-	}
51
+    public function hasKey($key) {
52
+        return apcu_exists($this->getPrefix() . $key);
53
+    }
54 54
 
55
-	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
57
-	}
55
+    public function remove($key) {
56
+        return apcu_delete($this->getPrefix() . $key);
57
+    }
58 58
 
59
-	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
61
-		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
-		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
-		}
67
-		return apcu_delete($iter);
68
-	}
59
+    public function clear($prefix = '') {
60
+        $ns = $this->getPrefix() . $prefix;
61
+        $ns = preg_quote($ns, '/');
62
+        if(class_exists('\APCIterator')) {
63
+            $iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
+        } else {
65
+            $iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
+        }
67
+        return apcu_delete($iter);
68
+    }
69 69
 
70
-	/**
71
-	 * Set a value in the cache if it's not already stored
72
-	 *
73
-	 * @param string $key
74
-	 * @param mixed $value
75
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
-	 * @return bool
77
-	 */
78
-	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
-	}
70
+    /**
71
+     * Set a value in the cache if it's not already stored
72
+     *
73
+     * @param string $key
74
+     * @param mixed $value
75
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
+     * @return bool
77
+     */
78
+    public function add($key, $value, $ttl = 0) {
79
+        return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
+    }
81 81
 
82
-	/**
83
-	 * Increase a stored number
84
-	 *
85
-	 * @param string $key
86
-	 * @param int $step
87
-	 * @return int | bool
88
-	 */
89
-	public function inc($key, $step = 1) {
90
-		$this->add($key, 0);
91
-		/**
92
-		 * TODO - hack around a PHP 7 specific issue in APCu
93
-		 *
94
-		 * on PHP 7 the apcu_inc method on a non-existing object will increment
95
-		 * "0" and result in "1" as value - therefore we check for existence
96
-		 * first
97
-		 *
98
-		 * on PHP 5.6 this is not the case
99
-		 *
100
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
-		 * for details
102
-		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
105
-			: false;
106
-	}
82
+    /**
83
+     * Increase a stored number
84
+     *
85
+     * @param string $key
86
+     * @param int $step
87
+     * @return int | bool
88
+     */
89
+    public function inc($key, $step = 1) {
90
+        $this->add($key, 0);
91
+        /**
92
+         * TODO - hack around a PHP 7 specific issue in APCu
93
+         *
94
+         * on PHP 7 the apcu_inc method on a non-existing object will increment
95
+         * "0" and result in "1" as value - therefore we check for existence
96
+         * first
97
+         *
98
+         * on PHP 5.6 this is not the case
99
+         *
100
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
+         * for details
102
+         */
103
+        return apcu_exists($this->getPrefix() . $key)
104
+            ? apcu_inc($this->getPrefix() . $key, $step)
105
+            : false;
106
+    }
107 107
 
108
-	/**
109
-	 * Decrease a stored number
110
-	 *
111
-	 * @param string $key
112
-	 * @param int $step
113
-	 * @return int | bool
114
-	 */
115
-	public function dec($key, $step = 1) {
116
-		/**
117
-		 * TODO - hack around a PHP 7 specific issue in APCu
118
-		 *
119
-		 * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
-		 * "0" and result in "-1" as value - therefore we check for existence
121
-		 * first
122
-		 *
123
-		 * on PHP 5.6 this is not the case
124
-		 *
125
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
-		 * for details
127
-		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
130
-			: false;
131
-	}
108
+    /**
109
+     * Decrease a stored number
110
+     *
111
+     * @param string $key
112
+     * @param int $step
113
+     * @return int | bool
114
+     */
115
+    public function dec($key, $step = 1) {
116
+        /**
117
+         * TODO - hack around a PHP 7 specific issue in APCu
118
+         *
119
+         * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
+         * "0" and result in "-1" as value - therefore we check for existence
121
+         * first
122
+         *
123
+         * on PHP 5.6 this is not the case
124
+         *
125
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
+         * for details
127
+         */
128
+        return apcu_exists($this->getPrefix() . $key)
129
+            ? apcu_dec($this->getPrefix() . $key, $step)
130
+            : false;
131
+    }
132 132
 
133
-	/**
134
-	 * Compare and set
135
-	 *
136
-	 * @param string $key
137
-	 * @param mixed $old
138
-	 * @param mixed $new
139
-	 * @return bool
140
-	 */
141
-	public function cas($key, $old, $new) {
142
-		// apc only does cas for ints
143
-		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
145
-		} else {
146
-			return $this->casEmulated($key, $old, $new);
147
-		}
148
-	}
133
+    /**
134
+     * Compare and set
135
+     *
136
+     * @param string $key
137
+     * @param mixed $old
138
+     * @param mixed $new
139
+     * @return bool
140
+     */
141
+    public function cas($key, $old, $new) {
142
+        // apc only does cas for ints
143
+        if (is_int($old) and is_int($new)) {
144
+            return apcu_cas($this->getPrefix() . $key, $old, $new);
145
+        } else {
146
+            return $this->casEmulated($key, $old, $new);
147
+        }
148
+    }
149 149
 
150
-	/**
151
-	 * @return bool
152
-	 */
153
-	static public function isAvailable() {
154
-		if (!extension_loaded('apcu')) {
155
-			return false;
156
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
-			return false;
158
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
-			return false;
160
-		} elseif (
161
-				version_compare(phpversion('apc'), '4.0.6') === -1 &&
162
-				version_compare(phpversion('apcu'), '5.1.0') === -1
163
-		) {
164
-			return false;
165
-		} else {
166
-			return true;
167
-		}
168
-	}
150
+    /**
151
+     * @return bool
152
+     */
153
+    static public function isAvailable() {
154
+        if (!extension_loaded('apcu')) {
155
+            return false;
156
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
+            return false;
158
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
+            return false;
160
+        } elseif (
161
+                version_compare(phpversion('apc'), '4.0.6') === -1 &&
162
+                version_compare(phpversion('apcu'), '5.1.0') === -1
163
+        ) {
164
+            return false;
165
+        } else {
166
+            return true;
167
+        }
168
+    }
169 169
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 	use CADTrait;
38 38
 
39 39
 	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
40
+		$result = apcu_fetch($this->getPrefix().$key, $success);
41 41
 		if (!$success) {
42 42
 			return null;
43 43
 		}
@@ -45,24 +45,24 @@  discard block
 block discarded – undo
45 45
 	}
46 46
 
47 47
 	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
48
+		return apcu_store($this->getPrefix().$key, $value, $ttl);
49 49
 	}
50 50
 
51 51
 	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
52
+		return apcu_exists($this->getPrefix().$key);
53 53
 	}
54 54
 
55 55
 	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
56
+		return apcu_delete($this->getPrefix().$key);
57 57
 	}
58 58
 
59 59
 	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
60
+		$ns = $this->getPrefix().$prefix;
61 61
 		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
62
+		if (class_exists('\APCIterator')) {
63
+			$iter = new \APCIterator('user', '/^'.$ns.'/', APC_ITER_KEY);
64 64
 		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
65
+			$iter = new \APCUIterator('/^'.$ns.'/', APC_ITER_KEY);
66 66
 		}
67 67
 		return apcu_delete($iter);
68 68
 	}
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	 * @return bool
77 77
 	 */
78 78
 	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
79
+		return apcu_add($this->getPrefix().$key, $value, $ttl);
80 80
 	}
81 81
 
82 82
 	/**
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101 101
 		 * for details
102 102
 		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
103
+		return apcu_exists($this->getPrefix().$key)
104
+			? apcu_inc($this->getPrefix().$key, $step)
105 105
 			: false;
106 106
 	}
107 107
 
@@ -125,8 +125,8 @@  discard block
 block discarded – undo
125 125
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126 126
 		 * for details
127 127
 		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
128
+		return apcu_exists($this->getPrefix().$key)
129
+			? apcu_dec($this->getPrefix().$key, $step)
130 130
 			: false;
131 131
 	}
132 132
 
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 	public function cas($key, $old, $new) {
142 142
 		// apc only does cas for ints
143 143
 		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
144
+			return apcu_cas($this->getPrefix().$key, $old, $new);
145 145
 		} else {
146 146
 			return $this->casEmulated($key, $old, $new);
147 147
 		}
Please login to merge, or discard this patch.
lib/private/Memcache/ArrayCache.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Indentation   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -27,133 +27,133 @@
 block discarded – undo
27 27
 use OCP\IMemcache;
28 28
 
29 29
 class ArrayCache extends Cache implements IMemcache {
30
-	/** @var array Array with the cached data */
31
-	protected $cachedData = array();
30
+    /** @var array Array with the cached data */
31
+    protected $cachedData = array();
32 32
 
33
-	use CADTrait;
33
+    use CADTrait;
34 34
 
35
-	/**
36
-	 * {@inheritDoc}
37
-	 */
38
-	public function get($key) {
39
-		if ($this->hasKey($key)) {
40
-			return $this->cachedData[$key];
41
-		}
42
-		return null;
43
-	}
35
+    /**
36
+     * {@inheritDoc}
37
+     */
38
+    public function get($key) {
39
+        if ($this->hasKey($key)) {
40
+            return $this->cachedData[$key];
41
+        }
42
+        return null;
43
+    }
44 44
 
45
-	/**
46
-	 * {@inheritDoc}
47
-	 */
48
-	public function set($key, $value, $ttl = 0) {
49
-		$this->cachedData[$key] = $value;
50
-		return true;
51
-	}
45
+    /**
46
+     * {@inheritDoc}
47
+     */
48
+    public function set($key, $value, $ttl = 0) {
49
+        $this->cachedData[$key] = $value;
50
+        return true;
51
+    }
52 52
 
53
-	/**
54
-	 * {@inheritDoc}
55
-	 */
56
-	public function hasKey($key) {
57
-		return isset($this->cachedData[$key]);
58
-	}
53
+    /**
54
+     * {@inheritDoc}
55
+     */
56
+    public function hasKey($key) {
57
+        return isset($this->cachedData[$key]);
58
+    }
59 59
 
60
-	/**
61
-	 * {@inheritDoc}
62
-	 */
63
-	public function remove($key) {
64
-		unset($this->cachedData[$key]);
65
-		return true;
66
-	}
60
+    /**
61
+     * {@inheritDoc}
62
+     */
63
+    public function remove($key) {
64
+        unset($this->cachedData[$key]);
65
+        return true;
66
+    }
67 67
 
68
-	/**
69
-	 * {@inheritDoc}
70
-	 */
71
-	public function clear($prefix = '') {
72
-		if ($prefix === '') {
73
-			$this->cachedData = [];
74
-			return true;
75
-		}
68
+    /**
69
+     * {@inheritDoc}
70
+     */
71
+    public function clear($prefix = '') {
72
+        if ($prefix === '') {
73
+            $this->cachedData = [];
74
+            return true;
75
+        }
76 76
 
77
-		foreach ($this->cachedData as $key => $value) {
78
-			if (strpos($key, $prefix) === 0) {
79
-				$this->remove($key);
80
-			}
81
-		}
82
-		return true;
83
-	}
77
+        foreach ($this->cachedData as $key => $value) {
78
+            if (strpos($key, $prefix) === 0) {
79
+                $this->remove($key);
80
+            }
81
+        }
82
+        return true;
83
+    }
84 84
 
85
-	/**
86
-	 * Set a value in the cache if it's not already stored
87
-	 *
88
-	 * @param string $key
89
-	 * @param mixed $value
90
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
91
-	 * @return bool
92
-	 */
93
-	public function add($key, $value, $ttl = 0) {
94
-		// since this cache is not shared race conditions aren't an issue
95
-		if ($this->hasKey($key)) {
96
-			return false;
97
-		} else {
98
-			return $this->set($key, $value, $ttl);
99
-		}
100
-	}
85
+    /**
86
+     * Set a value in the cache if it's not already stored
87
+     *
88
+     * @param string $key
89
+     * @param mixed $value
90
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
91
+     * @return bool
92
+     */
93
+    public function add($key, $value, $ttl = 0) {
94
+        // since this cache is not shared race conditions aren't an issue
95
+        if ($this->hasKey($key)) {
96
+            return false;
97
+        } else {
98
+            return $this->set($key, $value, $ttl);
99
+        }
100
+    }
101 101
 
102
-	/**
103
-	 * Increase a stored number
104
-	 *
105
-	 * @param string $key
106
-	 * @param int $step
107
-	 * @return int | bool
108
-	 */
109
-	public function inc($key, $step = 1) {
110
-		$oldValue = $this->get($key);
111
-		if (is_int($oldValue)) {
112
-			$this->set($key, $oldValue + $step);
113
-			return $oldValue + $step;
114
-		} else {
115
-			$success = $this->add($key, $step);
116
-			return ($success) ? $step : false;
117
-		}
118
-	}
102
+    /**
103
+     * Increase a stored number
104
+     *
105
+     * @param string $key
106
+     * @param int $step
107
+     * @return int | bool
108
+     */
109
+    public function inc($key, $step = 1) {
110
+        $oldValue = $this->get($key);
111
+        if (is_int($oldValue)) {
112
+            $this->set($key, $oldValue + $step);
113
+            return $oldValue + $step;
114
+        } else {
115
+            $success = $this->add($key, $step);
116
+            return ($success) ? $step : false;
117
+        }
118
+    }
119 119
 
120
-	/**
121
-	 * Decrease a stored number
122
-	 *
123
-	 * @param string $key
124
-	 * @param int $step
125
-	 * @return int | bool
126
-	 */
127
-	public function dec($key, $step = 1) {
128
-		$oldValue = $this->get($key);
129
-		if (is_int($oldValue)) {
130
-			$this->set($key, $oldValue - $step);
131
-			return $oldValue - $step;
132
-		} else {
133
-			return false;
134
-		}
135
-	}
120
+    /**
121
+     * Decrease a stored number
122
+     *
123
+     * @param string $key
124
+     * @param int $step
125
+     * @return int | bool
126
+     */
127
+    public function dec($key, $step = 1) {
128
+        $oldValue = $this->get($key);
129
+        if (is_int($oldValue)) {
130
+            $this->set($key, $oldValue - $step);
131
+            return $oldValue - $step;
132
+        } else {
133
+            return false;
134
+        }
135
+    }
136 136
 
137
-	/**
138
-	 * Compare and set
139
-	 *
140
-	 * @param string $key
141
-	 * @param mixed $old
142
-	 * @param mixed $new
143
-	 * @return bool
144
-	 */
145
-	public function cas($key, $old, $new) {
146
-		if ($this->get($key) === $old) {
147
-			return $this->set($key, $new);
148
-		} else {
149
-			return false;
150
-		}
151
-	}
137
+    /**
138
+     * Compare and set
139
+     *
140
+     * @param string $key
141
+     * @param mixed $old
142
+     * @param mixed $new
143
+     * @return bool
144
+     */
145
+    public function cas($key, $old, $new) {
146
+        if ($this->get($key) === $old) {
147
+            return $this->set($key, $new);
148
+        } else {
149
+            return false;
150
+        }
151
+    }
152 152
 
153
-	/**
154
-	 * {@inheritDoc}
155
-	 */
156
-	static public function isAvailable() {
157
-		return true;
158
-	}
153
+    /**
154
+     * {@inheritDoc}
155
+     */
156
+    static public function isAvailable() {
157
+        return true;
158
+    }
159 159
 }
Please login to merge, or discard this patch.
lib/private/User/Session.php 3 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
 	 * @param OC\Security\Bruteforce\Throttler $throttler
312 312
 	 * @throws LoginException
313 313
 	 * @throws PasswordLoginForbiddenException
314
-	 * @return boolean
314
+	 * @return boolean|null
315 315
 	 */
316 316
 	public function logClientIn($user,
317 317
 								$password,
@@ -361,6 +361,9 @@  discard block
 block discarded – undo
361 361
 		return $this->config->getSystemValue('token_auth_enforced', false);
362 362
 	}
363 363
 
364
+	/**
365
+	 * @param string $username
366
+	 */
364 367
 	protected function isTwoFactorEnforced($username) {
365 368
 		Util::emitHook(
366 369
 			'\OCA\Files_Sharing\API\Server2Server',
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -345,14 +345,14 @@  discard block
 block discarded – undo
345 345
 		if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
346 346
 			throw new PasswordLoginForbiddenException();
347 347
 		}
348
-		if (!$this->login($user, $password) ) {
348
+		if (!$this->login($user, $password)) {
349 349
 			$users = $this->manager->getByEmail($user);
350 350
 			if (count($users) === 1) {
351 351
 				return $this->login($users[0]->getUID(), $password);
352 352
 			}
353 353
 
354 354
 			$throttler->registerAttempt('login', $request->getRemoteAddress(), ['uid' => $user]);
355
-			if($currentDelay === 0) {
355
+			if ($currentDelay === 0) {
356 356
 				$throttler->sleepDelay($request->getRemoteAddress(), 'login');
357 357
 			}
358 358
 			return false;
@@ -360,7 +360,7 @@  discard block
 block discarded – undo
360 360
 
361 361
 		if ($isTokenPassword) {
362 362
 			$this->session->set('app_password', $password);
363
-		} else if($this->supportsCookies($request)) {
363
+		} else if ($this->supportsCookies($request)) {
364 364
 			// Password login, but cookies supported -> create (browser) session token
365 365
 			$this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
366 366
 		}
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 			\OC_Util::copySkeleton($user, $userFolder);
434 434
 
435 435
 			// trigger any other initialization
436
-			\OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
436
+			\OC::$server->getEventDispatcher()->dispatch(IUser::class.'::firstLogin', new GenericEvent($this->getUser()));
437 437
 		}
438 438
 	}
439 439
 
@@ -623,7 +623,7 @@  discard block
 block discarded – undo
623 623
 	private function checkTokenCredentials(IToken $dbToken, $token) {
624 624
 		// Check whether login credentials are still valid and the user was not disabled
625 625
 		// This check is performed each 5 minutes
626
-		$lastCheck = $dbToken->getLastCheck() ? : 0;
626
+		$lastCheck = $dbToken->getLastCheck() ?: 0;
627 627
 		$now = $this->timeFacory->getTime();
628 628
 		if ($lastCheck > ($now - 60 * 5)) {
629 629
 			// Checked performed recently, nothing to do now
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
 		if (!$this->loginWithToken($token)) {
714 714
 			return false;
715 715
 		}
716
-		if(!$this->validateToken($token)) {
716
+		if (!$this->validateToken($token)) {
717 717
 			return false;
718 718
 		}
719 719
 		return true;
@@ -836,9 +836,9 @@  discard block
 block discarded – undo
836 836
 		setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
837 837
 		// old cookies might be stored under /webroot/ instead of /webroot
838 838
 		// and Firefox doesn't like it!
839
-		setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
840
-		setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
841
-		setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
839
+		setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT.'/', '', $secureCookie, true);
840
+		setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT.'/', '', $secureCookie, true);
841
+		setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT.'/', '', $secureCookie, true);
842 842
 	}
843 843
 
844 844
 	/**
Please login to merge, or discard this patch.
Indentation   +783 added lines, -783 removed lines patch added patch discarded remove patch
@@ -77,789 +77,789 @@
 block discarded – undo
77 77
  */
78 78
 class Session implements IUserSession, Emitter {
79 79
 
80
-	/** @var IUserManager $manager */
81
-	private $manager;
82
-
83
-	/** @var ISession $session */
84
-	private $session;
85
-
86
-	/** @var ITimeFactory */
87
-	private $timeFacory;
88
-
89
-	/** @var IProvider */
90
-	private $tokenProvider;
91
-
92
-	/** @var IConfig */
93
-	private $config;
94
-
95
-	/** @var User $activeUser */
96
-	protected $activeUser;
97
-
98
-	/** @var ISecureRandom */
99
-	private $random;
100
-
101
-	/**
102
-	 * @param IUserManager $manager
103
-	 * @param ISession $session
104
-	 * @param ITimeFactory $timeFacory
105
-	 * @param IProvider $tokenProvider
106
-	 * @param IConfig $config
107
-	 * @param ISecureRandom $random
108
-	 */
109
-	public function __construct(IUserManager $manager,
110
-								ISession $session,
111
-								ITimeFactory $timeFacory,
112
-								$tokenProvider,
113
-								IConfig $config,
114
-								ISecureRandom $random) {
115
-		$this->manager = $manager;
116
-		$this->session = $session;
117
-		$this->timeFacory = $timeFacory;
118
-		$this->tokenProvider = $tokenProvider;
119
-		$this->config = $config;
120
-		$this->random = $random;
121
-	}
122
-
123
-	/**
124
-	 * @param IProvider $provider
125
-	 */
126
-	public function setTokenProvider(IProvider $provider) {
127
-		$this->tokenProvider = $provider;
128
-	}
129
-
130
-	/**
131
-	 * @param string $scope
132
-	 * @param string $method
133
-	 * @param callable $callback
134
-	 */
135
-	public function listen($scope, $method, callable $callback) {
136
-		$this->manager->listen($scope, $method, $callback);
137
-	}
138
-
139
-	/**
140
-	 * @param string $scope optional
141
-	 * @param string $method optional
142
-	 * @param callable $callback optional
143
-	 */
144
-	public function removeListener($scope = null, $method = null, callable $callback = null) {
145
-		$this->manager->removeListener($scope, $method, $callback);
146
-	}
147
-
148
-	/**
149
-	 * get the manager object
150
-	 *
151
-	 * @return Manager
152
-	 */
153
-	public function getManager() {
154
-		return $this->manager;
155
-	}
156
-
157
-	/**
158
-	 * get the session object
159
-	 *
160
-	 * @return ISession
161
-	 */
162
-	public function getSession() {
163
-		return $this->session;
164
-	}
165
-
166
-	/**
167
-	 * set the session object
168
-	 *
169
-	 * @param ISession $session
170
-	 */
171
-	public function setSession(ISession $session) {
172
-		if ($this->session instanceof ISession) {
173
-			$this->session->close();
174
-		}
175
-		$this->session = $session;
176
-		$this->activeUser = null;
177
-	}
178
-
179
-	/**
180
-	 * set the currently active user
181
-	 *
182
-	 * @param IUser|null $user
183
-	 */
184
-	public function setUser($user) {
185
-		if (is_null($user)) {
186
-			$this->session->remove('user_id');
187
-		} else {
188
-			$this->session->set('user_id', $user->getUID());
189
-		}
190
-		$this->activeUser = $user;
191
-	}
192
-
193
-	/**
194
-	 * get the current active user
195
-	 *
196
-	 * @return IUser|null Current user, otherwise null
197
-	 */
198
-	public function getUser() {
199
-		// FIXME: This is a quick'n dirty work-around for the incognito mode as
200
-		// described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155
201
-		if (OC_User::isIncognitoMode()) {
202
-			return null;
203
-		}
204
-		if (is_null($this->activeUser)) {
205
-			$uid = $this->session->get('user_id');
206
-			if (is_null($uid)) {
207
-				return null;
208
-			}
209
-			$this->activeUser = $this->manager->get($uid);
210
-			if (is_null($this->activeUser)) {
211
-				return null;
212
-			}
213
-			$this->validateSession();
214
-		}
215
-		return $this->activeUser;
216
-	}
217
-
218
-	/**
219
-	 * Validate whether the current session is valid
220
-	 *
221
-	 * - For token-authenticated clients, the token validity is checked
222
-	 * - For browsers, the session token validity is checked
223
-	 */
224
-	protected function validateSession() {
225
-		$token = null;
226
-		$appPassword = $this->session->get('app_password');
227
-
228
-		if (is_null($appPassword)) {
229
-			try {
230
-				$token = $this->session->getId();
231
-			} catch (SessionNotAvailableException $ex) {
232
-				return;
233
-			}
234
-		} else {
235
-			$token = $appPassword;
236
-		}
237
-
238
-		if (!$this->validateToken($token)) {
239
-			// Session was invalidated
240
-			$this->logout();
241
-		}
242
-	}
243
-
244
-	/**
245
-	 * Checks whether the user is logged in
246
-	 *
247
-	 * @return bool if logged in
248
-	 */
249
-	public function isLoggedIn() {
250
-		$user = $this->getUser();
251
-		if (is_null($user)) {
252
-			return false;
253
-		}
254
-
255
-		return $user->isEnabled();
256
-	}
257
-
258
-	/**
259
-	 * set the login name
260
-	 *
261
-	 * @param string|null $loginName for the logged in user
262
-	 */
263
-	public function setLoginName($loginName) {
264
-		if (is_null($loginName)) {
265
-			$this->session->remove('loginname');
266
-		} else {
267
-			$this->session->set('loginname', $loginName);
268
-		}
269
-	}
270
-
271
-	/**
272
-	 * get the login name of the current user
273
-	 *
274
-	 * @return string
275
-	 */
276
-	public function getLoginName() {
277
-		if ($this->activeUser) {
278
-			return $this->session->get('loginname');
279
-		} else {
280
-			$uid = $this->session->get('user_id');
281
-			if ($uid) {
282
-				$this->activeUser = $this->manager->get($uid);
283
-				return $this->session->get('loginname');
284
-			} else {
285
-				return null;
286
-			}
287
-		}
288
-	}
289
-
290
-	/**
291
-	 * set the token id
292
-	 *
293
-	 * @param int|null $token that was used to log in
294
-	 */
295
-	protected function setToken($token) {
296
-		if ($token === null) {
297
-			$this->session->remove('token-id');
298
-		} else {
299
-			$this->session->set('token-id', $token);
300
-		}
301
-	}
302
-
303
-	/**
304
-	 * try to log in with the provided credentials
305
-	 *
306
-	 * @param string $uid
307
-	 * @param string $password
308
-	 * @return boolean|null
309
-	 * @throws LoginException
310
-	 */
311
-	public function login($uid, $password) {
312
-		$this->session->regenerateId();
313
-		if ($this->validateToken($password, $uid)) {
314
-			return $this->loginWithToken($password);
315
-		}
316
-		return $this->loginWithPassword($uid, $password);
317
-	}
318
-
319
-	/**
320
-	 * Tries to log in a client
321
-	 *
322
-	 * Checks token auth enforced
323
-	 * Checks 2FA enabled
324
-	 *
325
-	 * @param string $user
326
-	 * @param string $password
327
-	 * @param IRequest $request
328
-	 * @param OC\Security\Bruteforce\Throttler $throttler
329
-	 * @throws LoginException
330
-	 * @throws PasswordLoginForbiddenException
331
-	 * @return boolean
332
-	 */
333
-	public function logClientIn($user,
334
-								$password,
335
-								IRequest $request,
336
-								OC\Security\Bruteforce\Throttler $throttler) {
337
-		$currentDelay = $throttler->sleepDelay($request->getRemoteAddress(), 'login');
338
-
339
-		if ($this->manager instanceof PublicEmitter) {
340
-			$this->manager->emit('\OC\User', 'preLogin', array($user, $password));
341
-		}
342
-
343
-		$isTokenPassword = $this->isTokenPassword($password);
344
-		if (!$isTokenPassword && $this->isTokenAuthEnforced()) {
345
-			throw new PasswordLoginForbiddenException();
346
-		}
347
-		if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
348
-			throw new PasswordLoginForbiddenException();
349
-		}
350
-		if (!$this->login($user, $password) ) {
351
-			$users = $this->manager->getByEmail($user);
352
-			if (count($users) === 1) {
353
-				return $this->login($users[0]->getUID(), $password);
354
-			}
355
-
356
-			$throttler->registerAttempt('login', $request->getRemoteAddress(), ['uid' => $user]);
357
-			if($currentDelay === 0) {
358
-				$throttler->sleepDelay($request->getRemoteAddress(), 'login');
359
-			}
360
-			return false;
361
-		}
362
-
363
-		if ($isTokenPassword) {
364
-			$this->session->set('app_password', $password);
365
-		} else if($this->supportsCookies($request)) {
366
-			// Password login, but cookies supported -> create (browser) session token
367
-			$this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
368
-		}
369
-
370
-		return true;
371
-	}
372
-
373
-	protected function supportsCookies(IRequest $request) {
374
-		if (!is_null($request->getCookie('cookie_test'))) {
375
-			return true;
376
-		}
377
-		setcookie('cookie_test', 'test', $this->timeFacory->getTime() + 3600);
378
-		return false;
379
-	}
380
-
381
-	private function isTokenAuthEnforced() {
382
-		return $this->config->getSystemValue('token_auth_enforced', false);
383
-	}
384
-
385
-	protected function isTwoFactorEnforced($username) {
386
-		Util::emitHook(
387
-			'\OCA\Files_Sharing\API\Server2Server',
388
-			'preLoginNameUsedAsUserName',
389
-			array('uid' => &$username)
390
-		);
391
-		$user = $this->manager->get($username);
392
-		if (is_null($user)) {
393
-			$users = $this->manager->getByEmail($username);
394
-			if (empty($users)) {
395
-				return false;
396
-			}
397
-			if (count($users) !== 1) {
398
-				return true;
399
-			}
400
-			$user = $users[0];
401
-		}
402
-		// DI not possible due to cyclic dependencies :'-/
403
-		return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user);
404
-	}
405
-
406
-	/**
407
-	 * Check if the given 'password' is actually a device token
408
-	 *
409
-	 * @param string $password
410
-	 * @return boolean
411
-	 */
412
-	public function isTokenPassword($password) {
413
-		try {
414
-			$this->tokenProvider->getToken($password);
415
-			return true;
416
-		} catch (InvalidTokenException $ex) {
417
-			return false;
418
-		}
419
-	}
420
-
421
-	protected function prepareUserLogin($firstTimeLogin) {
422
-		// TODO: mock/inject/use non-static
423
-		// Refresh the token
424
-		\OC::$server->getCsrfTokenManager()->refreshToken();
425
-		//we need to pass the user name, which may differ from login name
426
-		$user = $this->getUser()->getUID();
427
-		OC_Util::setupFS($user);
428
-
429
-		if ($firstTimeLogin) {
430
-			// TODO: lock necessary?
431
-			//trigger creation of user home and /files folder
432
-			$userFolder = \OC::$server->getUserFolder($user);
433
-
434
-			// copy skeleton
435
-			\OC_Util::copySkeleton($user, $userFolder);
436
-
437
-			// trigger any other initialization
438
-			\OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
439
-		}
440
-	}
441
-
442
-	/**
443
-	 * Tries to login the user with HTTP Basic Authentication
444
-	 *
445
-	 * @todo do not allow basic auth if the user is 2FA enforced
446
-	 * @param IRequest $request
447
-	 * @param OC\Security\Bruteforce\Throttler $throttler
448
-	 * @return boolean if the login was successful
449
-	 */
450
-	public function tryBasicAuthLogin(IRequest $request,
451
-									  OC\Security\Bruteforce\Throttler $throttler) {
452
-		if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) {
453
-			try {
454
-				if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) {
455
-					/**
456
-					 * Add DAV authenticated. This should in an ideal world not be
457
-					 * necessary but the iOS App reads cookies from anywhere instead
458
-					 * only the DAV endpoint.
459
-					 * This makes sure that the cookies will be valid for the whole scope
460
-					 * @see https://github.com/owncloud/core/issues/22893
461
-					 */
462
-					$this->session->set(
463
-						Auth::DAV_AUTHENTICATED, $this->getUser()->getUID()
464
-					);
465
-
466
-					// Set the last-password-confirm session to make the sudo mode work
467
-					 $this->session->set('last-password-confirm', $this->timeFacory->getTime());
468
-
469
-					return true;
470
-				}
471
-			} catch (PasswordLoginForbiddenException $ex) {
472
-				// Nothing to do
473
-			}
474
-		}
475
-		return false;
476
-	}
477
-
478
-	/**
479
-	 * Log an user in via login name and password
480
-	 *
481
-	 * @param string $uid
482
-	 * @param string $password
483
-	 * @return boolean
484
-	 * @throws LoginException if an app canceld the login process or the user is not enabled
485
-	 */
486
-	private function loginWithPassword($uid, $password) {
487
-		$user = $this->manager->checkPassword($uid, $password);
488
-		if ($user === false) {
489
-			// Password check failed
490
-			return false;
491
-		}
492
-
493
-		if ($user->isEnabled()) {
494
-			$this->setUser($user);
495
-			$this->setLoginName($uid);
496
-			$this->setToken(null);
497
-			$firstTimeLogin = $user->updateLastLoginTimestamp();
498
-			$this->manager->emit('\OC\User', 'postLogin', [$user, $password]);
499
-			if ($this->isLoggedIn()) {
500
-				$this->prepareUserLogin($firstTimeLogin);
501
-				return true;
502
-			} else {
503
-				// injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
504
-				$message = \OC::$server->getL10N('lib')->t('Login canceled by app');
505
-				throw new LoginException($message);
506
-			}
507
-		} else {
508
-			// injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
509
-			$message = \OC::$server->getL10N('lib')->t('User disabled');
510
-			throw new LoginException($message);
511
-		}
512
-	}
513
-
514
-	/**
515
-	 * Log an user in with a given token (id)
516
-	 *
517
-	 * @param string $token
518
-	 * @return boolean
519
-	 * @throws LoginException if an app canceled the login process or the user is not enabled
520
-	 */
521
-	private function loginWithToken($token) {
522
-		try {
523
-			$dbToken = $this->tokenProvider->getToken($token);
524
-		} catch (InvalidTokenException $ex) {
525
-			return false;
526
-		}
527
-		$uid = $dbToken->getUID();
528
-
529
-		// When logging in with token, the password must be decrypted first before passing to login hook
530
-		$password = '';
531
-		try {
532
-			$password = $this->tokenProvider->getPassword($dbToken, $token);
533
-		} catch (PasswordlessTokenException $ex) {
534
-			// Ignore and use empty string instead
535
-		}
536
-
537
-		$user = $this->manager->get($uid);
538
-		if (is_null($user)) {
539
-			// user does not exist
540
-			return false;
541
-		}
542
-		if (!$user->isEnabled()) {
543
-			// disabled users can not log in
544
-			// injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
545
-			$message = \OC::$server->getL10N('lib')->t('User disabled');
546
-			throw new LoginException($message);
547
-		}
548
-
549
-		//login
550
-		$this->setUser($user);
551
-		$this->setLoginName($dbToken->getLoginName());
552
-		$this->setToken($dbToken->getId());
553
-		\OC::$server->getLockdownManager()->setToken($dbToken);
554
-		$this->manager->emit('\OC\User', 'postLogin', array($user, $password));
555
-
556
-		if ($this->isLoggedIn()) {
557
-			$this->prepareUserLogin(false); // token login cant be the first
558
-		} else {
559
-			// injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
560
-			$message = \OC::$server->getL10N('lib')->t('Login canceled by app');
561
-			throw new LoginException($message);
562
-		}
563
-
564
-		return true;
565
-	}
566
-
567
-	/**
568
-	 * Create a new session token for the given user credentials
569
-	 *
570
-	 * @param IRequest $request
571
-	 * @param string $uid user UID
572
-	 * @param string $loginName login name
573
-	 * @param string $password
574
-	 * @param int $remember
575
-	 * @return boolean
576
-	 */
577
-	public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
578
-		if (is_null($this->manager->get($uid))) {
579
-			// User does not exist
580
-			return false;
581
-		}
582
-		$name = isset($request->server['HTTP_USER_AGENT']) ? $request->server['HTTP_USER_AGENT'] : 'unknown browser';
583
-		try {
584
-			$sessionId = $this->session->getId();
585
-			$pwd = $this->getPassword($password);
586
-			$this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
587
-			return true;
588
-		} catch (SessionNotAvailableException $ex) {
589
-			// This can happen with OCC, where a memory session is used
590
-			// if a memory session is used, we shouldn't create a session token anyway
591
-			return false;
592
-		}
593
-	}
594
-
595
-	/**
596
-	 * Checks if the given password is a token.
597
-	 * If yes, the password is extracted from the token.
598
-	 * If no, the same password is returned.
599
-	 *
600
-	 * @param string $password either the login password or a device token
601
-	 * @return string|null the password or null if none was set in the token
602
-	 */
603
-	private function getPassword($password) {
604
-		if (is_null($password)) {
605
-			// This is surely no token ;-)
606
-			return null;
607
-		}
608
-		try {
609
-			$token = $this->tokenProvider->getToken($password);
610
-			try {
611
-				return $this->tokenProvider->getPassword($token, $password);
612
-			} catch (PasswordlessTokenException $ex) {
613
-				return null;
614
-			}
615
-		} catch (InvalidTokenException $ex) {
616
-			return $password;
617
-		}
618
-	}
619
-
620
-	/**
621
-	 * @param IToken $dbToken
622
-	 * @param string $token
623
-	 * @return boolean
624
-	 */
625
-	private function checkTokenCredentials(IToken $dbToken, $token) {
626
-		// Check whether login credentials are still valid and the user was not disabled
627
-		// This check is performed each 5 minutes
628
-		$lastCheck = $dbToken->getLastCheck() ? : 0;
629
-		$now = $this->timeFacory->getTime();
630
-		if ($lastCheck > ($now - 60 * 5)) {
631
-			// Checked performed recently, nothing to do now
632
-			return true;
633
-		}
634
-
635
-		try {
636
-			$pwd = $this->tokenProvider->getPassword($dbToken, $token);
637
-		} catch (InvalidTokenException $ex) {
638
-			// An invalid token password was used -> log user out
639
-			return false;
640
-		} catch (PasswordlessTokenException $ex) {
641
-			// Token has no password
642
-
643
-			if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
644
-				$this->tokenProvider->invalidateToken($token);
645
-				return false;
646
-			}
647
-
648
-			$dbToken->setLastCheck($now);
649
-			return true;
650
-		}
651
-
652
-		if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false
653
-			|| (!is_null($this->activeUser) && !$this->activeUser->isEnabled())) {
654
-			$this->tokenProvider->invalidateToken($token);
655
-			// Password has changed or user was disabled -> log user out
656
-			return false;
657
-		}
658
-		$dbToken->setLastCheck($now);
659
-		return true;
660
-	}
661
-
662
-	/**
663
-	 * Check if the given token exists and performs password/user-enabled checks
664
-	 *
665
-	 * Invalidates the token if checks fail
666
-	 *
667
-	 * @param string $token
668
-	 * @param string $user login name
669
-	 * @return boolean
670
-	 */
671
-	private function validateToken($token, $user = null) {
672
-		try {
673
-			$dbToken = $this->tokenProvider->getToken($token);
674
-		} catch (InvalidTokenException $ex) {
675
-			return false;
676
-		}
677
-
678
-		// Check if login names match
679
-		if (!is_null($user) && $dbToken->getLoginName() !== $user) {
680
-			// TODO: this makes it imposssible to use different login names on browser and client
681
-			// e.g. login by e-mail '[email protected]' on browser for generating the token will not
682
-			//      allow to use the client token with the login name 'user'.
683
-			return false;
684
-		}
685
-
686
-		if (!$this->checkTokenCredentials($dbToken, $token)) {
687
-			return false;
688
-		}
689
-
690
-		$this->tokenProvider->updateTokenActivity($dbToken);
691
-
692
-		return true;
693
-	}
694
-
695
-	/**
696
-	 * Tries to login the user with auth token header
697
-	 *
698
-	 * @param IRequest $request
699
-	 * @todo check remember me cookie
700
-	 * @return boolean
701
-	 */
702
-	public function tryTokenLogin(IRequest $request) {
703
-		$authHeader = $request->getHeader('Authorization');
704
-		if (strpos($authHeader, 'token ') === false) {
705
-			// No auth header, let's try session id
706
-			try {
707
-				$token = $this->session->getId();
708
-			} catch (SessionNotAvailableException $ex) {
709
-				return false;
710
-			}
711
-		} else {
712
-			$token = substr($authHeader, 6);
713
-		}
714
-
715
-		if (!$this->loginWithToken($token)) {
716
-			return false;
717
-		}
718
-		if(!$this->validateToken($token)) {
719
-			return false;
720
-		}
721
-		return true;
722
-	}
723
-
724
-	/**
725
-	 * perform login using the magic cookie (remember login)
726
-	 *
727
-	 * @param string $uid the username
728
-	 * @param string $currentToken
729
-	 * @param string $oldSessionId
730
-	 * @return bool
731
-	 */
732
-	public function loginWithCookie($uid, $currentToken, $oldSessionId) {
733
-		$this->session->regenerateId();
734
-		$this->manager->emit('\OC\User', 'preRememberedLogin', array($uid));
735
-		$user = $this->manager->get($uid);
736
-		if (is_null($user)) {
737
-			// user does not exist
738
-			return false;
739
-		}
740
-
741
-		// get stored tokens
742
-		$tokens = $this->config->getUserKeys($uid, 'login_token');
743
-		// test cookies token against stored tokens
744
-		if (!in_array($currentToken, $tokens, true)) {
745
-			return false;
746
-		}
747
-		// replace successfully used token with a new one
748
-		$this->config->deleteUserValue($uid, 'login_token', $currentToken);
749
-		$newToken = $this->random->generate(32);
750
-		$this->config->setUserValue($uid, 'login_token', $newToken, $this->timeFacory->getTime());
751
-
752
-		try {
753
-			$sessionId = $this->session->getId();
754
-			$this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
755
-		} catch (SessionNotAvailableException $ex) {
756
-			return false;
757
-		} catch (InvalidTokenException $ex) {
758
-			\OC::$server->getLogger()->warning('Renewing session token failed', ['app' => 'core']);
759
-			return false;
760
-		}
761
-
762
-		$this->setMagicInCookie($user->getUID(), $newToken);
763
-		$token = $this->tokenProvider->getToken($sessionId);
764
-
765
-		//login
766
-		$this->setUser($user);
767
-		$this->setLoginName($token->getLoginName());
768
-		$this->setToken($token->getId());
769
-		$user->updateLastLoginTimestamp();
770
-		$this->manager->emit('\OC\User', 'postRememberedLogin', [$user]);
771
-		return true;
772
-	}
773
-
774
-	/**
775
-	 * @param IUser $user
776
-	 */
777
-	public function createRememberMeToken(IUser $user) {
778
-		$token = $this->random->generate(32);
779
-		$this->config->setUserValue($user->getUID(), 'login_token', $token, $this->timeFacory->getTime());
780
-		$this->setMagicInCookie($user->getUID(), $token);
781
-	}
782
-
783
-	/**
784
-	 * logout the user from the session
785
-	 */
786
-	public function logout() {
787
-		$this->manager->emit('\OC\User', 'logout');
788
-		$user = $this->getUser();
789
-		if (!is_null($user)) {
790
-			try {
791
-				$this->tokenProvider->invalidateToken($this->session->getId());
792
-			} catch (SessionNotAvailableException $ex) {
793
-
794
-			}
795
-		}
796
-		$this->setUser(null);
797
-		$this->setLoginName(null);
798
-		$this->setToken(null);
799
-		$this->unsetMagicInCookie();
800
-		$this->session->clear();
801
-		$this->manager->emit('\OC\User', 'postLogout');
802
-	}
803
-
804
-	/**
805
-	 * Set cookie value to use in next page load
806
-	 *
807
-	 * @param string $username username to be set
808
-	 * @param string $token
809
-	 */
810
-	public function setMagicInCookie($username, $token) {
811
-		$secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
812
-		$webRoot = \OC::$WEBROOT;
813
-		if ($webRoot === '') {
814
-			$webRoot = '/';
815
-		}
816
-
817
-		$expires = $this->timeFacory->getTime() + $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
818
-		setcookie('nc_username', $username, $expires, $webRoot, '', $secureCookie, true);
819
-		setcookie('nc_token', $token, $expires, $webRoot, '', $secureCookie, true);
820
-		try {
821
-			setcookie('nc_session_id', $this->session->getId(), $expires, $webRoot, '', $secureCookie, true);
822
-		} catch (SessionNotAvailableException $ex) {
823
-			// ignore
824
-		}
825
-	}
826
-
827
-	/**
828
-	 * Remove cookie for "remember username"
829
-	 */
830
-	public function unsetMagicInCookie() {
831
-		//TODO: DI for cookies and IRequest
832
-		$secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
833
-
834
-		unset($_COOKIE['nc_username']); //TODO: DI
835
-		unset($_COOKIE['nc_token']);
836
-		unset($_COOKIE['nc_session_id']);
837
-		setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
838
-		setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
839
-		setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
840
-		// old cookies might be stored under /webroot/ instead of /webroot
841
-		// and Firefox doesn't like it!
842
-		setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
843
-		setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
844
-		setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
845
-	}
846
-
847
-	/**
848
-	 * Update password of the browser session token if there is one
849
-	 *
850
-	 * @param string $password
851
-	 */
852
-	public function updateSessionTokenPassword($password) {
853
-		try {
854
-			$sessionId = $this->session->getId();
855
-			$token = $this->tokenProvider->getToken($sessionId);
856
-			$this->tokenProvider->setPassword($token, $sessionId, $password);
857
-		} catch (SessionNotAvailableException $ex) {
858
-			// Nothing to do
859
-		} catch (InvalidTokenException $ex) {
860
-			// Nothing to do
861
-		}
862
-	}
80
+    /** @var IUserManager $manager */
81
+    private $manager;
82
+
83
+    /** @var ISession $session */
84
+    private $session;
85
+
86
+    /** @var ITimeFactory */
87
+    private $timeFacory;
88
+
89
+    /** @var IProvider */
90
+    private $tokenProvider;
91
+
92
+    /** @var IConfig */
93
+    private $config;
94
+
95
+    /** @var User $activeUser */
96
+    protected $activeUser;
97
+
98
+    /** @var ISecureRandom */
99
+    private $random;
100
+
101
+    /**
102
+     * @param IUserManager $manager
103
+     * @param ISession $session
104
+     * @param ITimeFactory $timeFacory
105
+     * @param IProvider $tokenProvider
106
+     * @param IConfig $config
107
+     * @param ISecureRandom $random
108
+     */
109
+    public function __construct(IUserManager $manager,
110
+                                ISession $session,
111
+                                ITimeFactory $timeFacory,
112
+                                $tokenProvider,
113
+                                IConfig $config,
114
+                                ISecureRandom $random) {
115
+        $this->manager = $manager;
116
+        $this->session = $session;
117
+        $this->timeFacory = $timeFacory;
118
+        $this->tokenProvider = $tokenProvider;
119
+        $this->config = $config;
120
+        $this->random = $random;
121
+    }
122
+
123
+    /**
124
+     * @param IProvider $provider
125
+     */
126
+    public function setTokenProvider(IProvider $provider) {
127
+        $this->tokenProvider = $provider;
128
+    }
129
+
130
+    /**
131
+     * @param string $scope
132
+     * @param string $method
133
+     * @param callable $callback
134
+     */
135
+    public function listen($scope, $method, callable $callback) {
136
+        $this->manager->listen($scope, $method, $callback);
137
+    }
138
+
139
+    /**
140
+     * @param string $scope optional
141
+     * @param string $method optional
142
+     * @param callable $callback optional
143
+     */
144
+    public function removeListener($scope = null, $method = null, callable $callback = null) {
145
+        $this->manager->removeListener($scope, $method, $callback);
146
+    }
147
+
148
+    /**
149
+     * get the manager object
150
+     *
151
+     * @return Manager
152
+     */
153
+    public function getManager() {
154
+        return $this->manager;
155
+    }
156
+
157
+    /**
158
+     * get the session object
159
+     *
160
+     * @return ISession
161
+     */
162
+    public function getSession() {
163
+        return $this->session;
164
+    }
165
+
166
+    /**
167
+     * set the session object
168
+     *
169
+     * @param ISession $session
170
+     */
171
+    public function setSession(ISession $session) {
172
+        if ($this->session instanceof ISession) {
173
+            $this->session->close();
174
+        }
175
+        $this->session = $session;
176
+        $this->activeUser = null;
177
+    }
178
+
179
+    /**
180
+     * set the currently active user
181
+     *
182
+     * @param IUser|null $user
183
+     */
184
+    public function setUser($user) {
185
+        if (is_null($user)) {
186
+            $this->session->remove('user_id');
187
+        } else {
188
+            $this->session->set('user_id', $user->getUID());
189
+        }
190
+        $this->activeUser = $user;
191
+    }
192
+
193
+    /**
194
+     * get the current active user
195
+     *
196
+     * @return IUser|null Current user, otherwise null
197
+     */
198
+    public function getUser() {
199
+        // FIXME: This is a quick'n dirty work-around for the incognito mode as
200
+        // described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155
201
+        if (OC_User::isIncognitoMode()) {
202
+            return null;
203
+        }
204
+        if (is_null($this->activeUser)) {
205
+            $uid = $this->session->get('user_id');
206
+            if (is_null($uid)) {
207
+                return null;
208
+            }
209
+            $this->activeUser = $this->manager->get($uid);
210
+            if (is_null($this->activeUser)) {
211
+                return null;
212
+            }
213
+            $this->validateSession();
214
+        }
215
+        return $this->activeUser;
216
+    }
217
+
218
+    /**
219
+     * Validate whether the current session is valid
220
+     *
221
+     * - For token-authenticated clients, the token validity is checked
222
+     * - For browsers, the session token validity is checked
223
+     */
224
+    protected function validateSession() {
225
+        $token = null;
226
+        $appPassword = $this->session->get('app_password');
227
+
228
+        if (is_null($appPassword)) {
229
+            try {
230
+                $token = $this->session->getId();
231
+            } catch (SessionNotAvailableException $ex) {
232
+                return;
233
+            }
234
+        } else {
235
+            $token = $appPassword;
236
+        }
237
+
238
+        if (!$this->validateToken($token)) {
239
+            // Session was invalidated
240
+            $this->logout();
241
+        }
242
+    }
243
+
244
+    /**
245
+     * Checks whether the user is logged in
246
+     *
247
+     * @return bool if logged in
248
+     */
249
+    public function isLoggedIn() {
250
+        $user = $this->getUser();
251
+        if (is_null($user)) {
252
+            return false;
253
+        }
254
+
255
+        return $user->isEnabled();
256
+    }
257
+
258
+    /**
259
+     * set the login name
260
+     *
261
+     * @param string|null $loginName for the logged in user
262
+     */
263
+    public function setLoginName($loginName) {
264
+        if (is_null($loginName)) {
265
+            $this->session->remove('loginname');
266
+        } else {
267
+            $this->session->set('loginname', $loginName);
268
+        }
269
+    }
270
+
271
+    /**
272
+     * get the login name of the current user
273
+     *
274
+     * @return string
275
+     */
276
+    public function getLoginName() {
277
+        if ($this->activeUser) {
278
+            return $this->session->get('loginname');
279
+        } else {
280
+            $uid = $this->session->get('user_id');
281
+            if ($uid) {
282
+                $this->activeUser = $this->manager->get($uid);
283
+                return $this->session->get('loginname');
284
+            } else {
285
+                return null;
286
+            }
287
+        }
288
+    }
289
+
290
+    /**
291
+     * set the token id
292
+     *
293
+     * @param int|null $token that was used to log in
294
+     */
295
+    protected function setToken($token) {
296
+        if ($token === null) {
297
+            $this->session->remove('token-id');
298
+        } else {
299
+            $this->session->set('token-id', $token);
300
+        }
301
+    }
302
+
303
+    /**
304
+     * try to log in with the provided credentials
305
+     *
306
+     * @param string $uid
307
+     * @param string $password
308
+     * @return boolean|null
309
+     * @throws LoginException
310
+     */
311
+    public function login($uid, $password) {
312
+        $this->session->regenerateId();
313
+        if ($this->validateToken($password, $uid)) {
314
+            return $this->loginWithToken($password);
315
+        }
316
+        return $this->loginWithPassword($uid, $password);
317
+    }
318
+
319
+    /**
320
+     * Tries to log in a client
321
+     *
322
+     * Checks token auth enforced
323
+     * Checks 2FA enabled
324
+     *
325
+     * @param string $user
326
+     * @param string $password
327
+     * @param IRequest $request
328
+     * @param OC\Security\Bruteforce\Throttler $throttler
329
+     * @throws LoginException
330
+     * @throws PasswordLoginForbiddenException
331
+     * @return boolean
332
+     */
333
+    public function logClientIn($user,
334
+                                $password,
335
+                                IRequest $request,
336
+                                OC\Security\Bruteforce\Throttler $throttler) {
337
+        $currentDelay = $throttler->sleepDelay($request->getRemoteAddress(), 'login');
338
+
339
+        if ($this->manager instanceof PublicEmitter) {
340
+            $this->manager->emit('\OC\User', 'preLogin', array($user, $password));
341
+        }
342
+
343
+        $isTokenPassword = $this->isTokenPassword($password);
344
+        if (!$isTokenPassword && $this->isTokenAuthEnforced()) {
345
+            throw new PasswordLoginForbiddenException();
346
+        }
347
+        if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
348
+            throw new PasswordLoginForbiddenException();
349
+        }
350
+        if (!$this->login($user, $password) ) {
351
+            $users = $this->manager->getByEmail($user);
352
+            if (count($users) === 1) {
353
+                return $this->login($users[0]->getUID(), $password);
354
+            }
355
+
356
+            $throttler->registerAttempt('login', $request->getRemoteAddress(), ['uid' => $user]);
357
+            if($currentDelay === 0) {
358
+                $throttler->sleepDelay($request->getRemoteAddress(), 'login');
359
+            }
360
+            return false;
361
+        }
362
+
363
+        if ($isTokenPassword) {
364
+            $this->session->set('app_password', $password);
365
+        } else if($this->supportsCookies($request)) {
366
+            // Password login, but cookies supported -> create (browser) session token
367
+            $this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
368
+        }
369
+
370
+        return true;
371
+    }
372
+
373
+    protected function supportsCookies(IRequest $request) {
374
+        if (!is_null($request->getCookie('cookie_test'))) {
375
+            return true;
376
+        }
377
+        setcookie('cookie_test', 'test', $this->timeFacory->getTime() + 3600);
378
+        return false;
379
+    }
380
+
381
+    private function isTokenAuthEnforced() {
382
+        return $this->config->getSystemValue('token_auth_enforced', false);
383
+    }
384
+
385
+    protected function isTwoFactorEnforced($username) {
386
+        Util::emitHook(
387
+            '\OCA\Files_Sharing\API\Server2Server',
388
+            'preLoginNameUsedAsUserName',
389
+            array('uid' => &$username)
390
+        );
391
+        $user = $this->manager->get($username);
392
+        if (is_null($user)) {
393
+            $users = $this->manager->getByEmail($username);
394
+            if (empty($users)) {
395
+                return false;
396
+            }
397
+            if (count($users) !== 1) {
398
+                return true;
399
+            }
400
+            $user = $users[0];
401
+        }
402
+        // DI not possible due to cyclic dependencies :'-/
403
+        return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user);
404
+    }
405
+
406
+    /**
407
+     * Check if the given 'password' is actually a device token
408
+     *
409
+     * @param string $password
410
+     * @return boolean
411
+     */
412
+    public function isTokenPassword($password) {
413
+        try {
414
+            $this->tokenProvider->getToken($password);
415
+            return true;
416
+        } catch (InvalidTokenException $ex) {
417
+            return false;
418
+        }
419
+    }
420
+
421
+    protected function prepareUserLogin($firstTimeLogin) {
422
+        // TODO: mock/inject/use non-static
423
+        // Refresh the token
424
+        \OC::$server->getCsrfTokenManager()->refreshToken();
425
+        //we need to pass the user name, which may differ from login name
426
+        $user = $this->getUser()->getUID();
427
+        OC_Util::setupFS($user);
428
+
429
+        if ($firstTimeLogin) {
430
+            // TODO: lock necessary?
431
+            //trigger creation of user home and /files folder
432
+            $userFolder = \OC::$server->getUserFolder($user);
433
+
434
+            // copy skeleton
435
+            \OC_Util::copySkeleton($user, $userFolder);
436
+
437
+            // trigger any other initialization
438
+            \OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
439
+        }
440
+    }
441
+
442
+    /**
443
+     * Tries to login the user with HTTP Basic Authentication
444
+     *
445
+     * @todo do not allow basic auth if the user is 2FA enforced
446
+     * @param IRequest $request
447
+     * @param OC\Security\Bruteforce\Throttler $throttler
448
+     * @return boolean if the login was successful
449
+     */
450
+    public function tryBasicAuthLogin(IRequest $request,
451
+                                        OC\Security\Bruteforce\Throttler $throttler) {
452
+        if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) {
453
+            try {
454
+                if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) {
455
+                    /**
456
+                     * Add DAV authenticated. This should in an ideal world not be
457
+                     * necessary but the iOS App reads cookies from anywhere instead
458
+                     * only the DAV endpoint.
459
+                     * This makes sure that the cookies will be valid for the whole scope
460
+                     * @see https://github.com/owncloud/core/issues/22893
461
+                     */
462
+                    $this->session->set(
463
+                        Auth::DAV_AUTHENTICATED, $this->getUser()->getUID()
464
+                    );
465
+
466
+                    // Set the last-password-confirm session to make the sudo mode work
467
+                        $this->session->set('last-password-confirm', $this->timeFacory->getTime());
468
+
469
+                    return true;
470
+                }
471
+            } catch (PasswordLoginForbiddenException $ex) {
472
+                // Nothing to do
473
+            }
474
+        }
475
+        return false;
476
+    }
477
+
478
+    /**
479
+     * Log an user in via login name and password
480
+     *
481
+     * @param string $uid
482
+     * @param string $password
483
+     * @return boolean
484
+     * @throws LoginException if an app canceld the login process or the user is not enabled
485
+     */
486
+    private function loginWithPassword($uid, $password) {
487
+        $user = $this->manager->checkPassword($uid, $password);
488
+        if ($user === false) {
489
+            // Password check failed
490
+            return false;
491
+        }
492
+
493
+        if ($user->isEnabled()) {
494
+            $this->setUser($user);
495
+            $this->setLoginName($uid);
496
+            $this->setToken(null);
497
+            $firstTimeLogin = $user->updateLastLoginTimestamp();
498
+            $this->manager->emit('\OC\User', 'postLogin', [$user, $password]);
499
+            if ($this->isLoggedIn()) {
500
+                $this->prepareUserLogin($firstTimeLogin);
501
+                return true;
502
+            } else {
503
+                // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
504
+                $message = \OC::$server->getL10N('lib')->t('Login canceled by app');
505
+                throw new LoginException($message);
506
+            }
507
+        } else {
508
+            // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
509
+            $message = \OC::$server->getL10N('lib')->t('User disabled');
510
+            throw new LoginException($message);
511
+        }
512
+    }
513
+
514
+    /**
515
+     * Log an user in with a given token (id)
516
+     *
517
+     * @param string $token
518
+     * @return boolean
519
+     * @throws LoginException if an app canceled the login process or the user is not enabled
520
+     */
521
+    private function loginWithToken($token) {
522
+        try {
523
+            $dbToken = $this->tokenProvider->getToken($token);
524
+        } catch (InvalidTokenException $ex) {
525
+            return false;
526
+        }
527
+        $uid = $dbToken->getUID();
528
+
529
+        // When logging in with token, the password must be decrypted first before passing to login hook
530
+        $password = '';
531
+        try {
532
+            $password = $this->tokenProvider->getPassword($dbToken, $token);
533
+        } catch (PasswordlessTokenException $ex) {
534
+            // Ignore and use empty string instead
535
+        }
536
+
537
+        $user = $this->manager->get($uid);
538
+        if (is_null($user)) {
539
+            // user does not exist
540
+            return false;
541
+        }
542
+        if (!$user->isEnabled()) {
543
+            // disabled users can not log in
544
+            // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
545
+            $message = \OC::$server->getL10N('lib')->t('User disabled');
546
+            throw new LoginException($message);
547
+        }
548
+
549
+        //login
550
+        $this->setUser($user);
551
+        $this->setLoginName($dbToken->getLoginName());
552
+        $this->setToken($dbToken->getId());
553
+        \OC::$server->getLockdownManager()->setToken($dbToken);
554
+        $this->manager->emit('\OC\User', 'postLogin', array($user, $password));
555
+
556
+        if ($this->isLoggedIn()) {
557
+            $this->prepareUserLogin(false); // token login cant be the first
558
+        } else {
559
+            // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
560
+            $message = \OC::$server->getL10N('lib')->t('Login canceled by app');
561
+            throw new LoginException($message);
562
+        }
563
+
564
+        return true;
565
+    }
566
+
567
+    /**
568
+     * Create a new session token for the given user credentials
569
+     *
570
+     * @param IRequest $request
571
+     * @param string $uid user UID
572
+     * @param string $loginName login name
573
+     * @param string $password
574
+     * @param int $remember
575
+     * @return boolean
576
+     */
577
+    public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
578
+        if (is_null($this->manager->get($uid))) {
579
+            // User does not exist
580
+            return false;
581
+        }
582
+        $name = isset($request->server['HTTP_USER_AGENT']) ? $request->server['HTTP_USER_AGENT'] : 'unknown browser';
583
+        try {
584
+            $sessionId = $this->session->getId();
585
+            $pwd = $this->getPassword($password);
586
+            $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
587
+            return true;
588
+        } catch (SessionNotAvailableException $ex) {
589
+            // This can happen with OCC, where a memory session is used
590
+            // if a memory session is used, we shouldn't create a session token anyway
591
+            return false;
592
+        }
593
+    }
594
+
595
+    /**
596
+     * Checks if the given password is a token.
597
+     * If yes, the password is extracted from the token.
598
+     * If no, the same password is returned.
599
+     *
600
+     * @param string $password either the login password or a device token
601
+     * @return string|null the password or null if none was set in the token
602
+     */
603
+    private function getPassword($password) {
604
+        if (is_null($password)) {
605
+            // This is surely no token ;-)
606
+            return null;
607
+        }
608
+        try {
609
+            $token = $this->tokenProvider->getToken($password);
610
+            try {
611
+                return $this->tokenProvider->getPassword($token, $password);
612
+            } catch (PasswordlessTokenException $ex) {
613
+                return null;
614
+            }
615
+        } catch (InvalidTokenException $ex) {
616
+            return $password;
617
+        }
618
+    }
619
+
620
+    /**
621
+     * @param IToken $dbToken
622
+     * @param string $token
623
+     * @return boolean
624
+     */
625
+    private function checkTokenCredentials(IToken $dbToken, $token) {
626
+        // Check whether login credentials are still valid and the user was not disabled
627
+        // This check is performed each 5 minutes
628
+        $lastCheck = $dbToken->getLastCheck() ? : 0;
629
+        $now = $this->timeFacory->getTime();
630
+        if ($lastCheck > ($now - 60 * 5)) {
631
+            // Checked performed recently, nothing to do now
632
+            return true;
633
+        }
634
+
635
+        try {
636
+            $pwd = $this->tokenProvider->getPassword($dbToken, $token);
637
+        } catch (InvalidTokenException $ex) {
638
+            // An invalid token password was used -> log user out
639
+            return false;
640
+        } catch (PasswordlessTokenException $ex) {
641
+            // Token has no password
642
+
643
+            if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
644
+                $this->tokenProvider->invalidateToken($token);
645
+                return false;
646
+            }
647
+
648
+            $dbToken->setLastCheck($now);
649
+            return true;
650
+        }
651
+
652
+        if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false
653
+            || (!is_null($this->activeUser) && !$this->activeUser->isEnabled())) {
654
+            $this->tokenProvider->invalidateToken($token);
655
+            // Password has changed or user was disabled -> log user out
656
+            return false;
657
+        }
658
+        $dbToken->setLastCheck($now);
659
+        return true;
660
+    }
661
+
662
+    /**
663
+     * Check if the given token exists and performs password/user-enabled checks
664
+     *
665
+     * Invalidates the token if checks fail
666
+     *
667
+     * @param string $token
668
+     * @param string $user login name
669
+     * @return boolean
670
+     */
671
+    private function validateToken($token, $user = null) {
672
+        try {
673
+            $dbToken = $this->tokenProvider->getToken($token);
674
+        } catch (InvalidTokenException $ex) {
675
+            return false;
676
+        }
677
+
678
+        // Check if login names match
679
+        if (!is_null($user) && $dbToken->getLoginName() !== $user) {
680
+            // TODO: this makes it imposssible to use different login names on browser and client
681
+            // e.g. login by e-mail '[email protected]' on browser for generating the token will not
682
+            //      allow to use the client token with the login name 'user'.
683
+            return false;
684
+        }
685
+
686
+        if (!$this->checkTokenCredentials($dbToken, $token)) {
687
+            return false;
688
+        }
689
+
690
+        $this->tokenProvider->updateTokenActivity($dbToken);
691
+
692
+        return true;
693
+    }
694
+
695
+    /**
696
+     * Tries to login the user with auth token header
697
+     *
698
+     * @param IRequest $request
699
+     * @todo check remember me cookie
700
+     * @return boolean
701
+     */
702
+    public function tryTokenLogin(IRequest $request) {
703
+        $authHeader = $request->getHeader('Authorization');
704
+        if (strpos($authHeader, 'token ') === false) {
705
+            // No auth header, let's try session id
706
+            try {
707
+                $token = $this->session->getId();
708
+            } catch (SessionNotAvailableException $ex) {
709
+                return false;
710
+            }
711
+        } else {
712
+            $token = substr($authHeader, 6);
713
+        }
714
+
715
+        if (!$this->loginWithToken($token)) {
716
+            return false;
717
+        }
718
+        if(!$this->validateToken($token)) {
719
+            return false;
720
+        }
721
+        return true;
722
+    }
723
+
724
+    /**
725
+     * perform login using the magic cookie (remember login)
726
+     *
727
+     * @param string $uid the username
728
+     * @param string $currentToken
729
+     * @param string $oldSessionId
730
+     * @return bool
731
+     */
732
+    public function loginWithCookie($uid, $currentToken, $oldSessionId) {
733
+        $this->session->regenerateId();
734
+        $this->manager->emit('\OC\User', 'preRememberedLogin', array($uid));
735
+        $user = $this->manager->get($uid);
736
+        if (is_null($user)) {
737
+            // user does not exist
738
+            return false;
739
+        }
740
+
741
+        // get stored tokens
742
+        $tokens = $this->config->getUserKeys($uid, 'login_token');
743
+        // test cookies token against stored tokens
744
+        if (!in_array($currentToken, $tokens, true)) {
745
+            return false;
746
+        }
747
+        // replace successfully used token with a new one
748
+        $this->config->deleteUserValue($uid, 'login_token', $currentToken);
749
+        $newToken = $this->random->generate(32);
750
+        $this->config->setUserValue($uid, 'login_token', $newToken, $this->timeFacory->getTime());
751
+
752
+        try {
753
+            $sessionId = $this->session->getId();
754
+            $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
755
+        } catch (SessionNotAvailableException $ex) {
756
+            return false;
757
+        } catch (InvalidTokenException $ex) {
758
+            \OC::$server->getLogger()->warning('Renewing session token failed', ['app' => 'core']);
759
+            return false;
760
+        }
761
+
762
+        $this->setMagicInCookie($user->getUID(), $newToken);
763
+        $token = $this->tokenProvider->getToken($sessionId);
764
+
765
+        //login
766
+        $this->setUser($user);
767
+        $this->setLoginName($token->getLoginName());
768
+        $this->setToken($token->getId());
769
+        $user->updateLastLoginTimestamp();
770
+        $this->manager->emit('\OC\User', 'postRememberedLogin', [$user]);
771
+        return true;
772
+    }
773
+
774
+    /**
775
+     * @param IUser $user
776
+     */
777
+    public function createRememberMeToken(IUser $user) {
778
+        $token = $this->random->generate(32);
779
+        $this->config->setUserValue($user->getUID(), 'login_token', $token, $this->timeFacory->getTime());
780
+        $this->setMagicInCookie($user->getUID(), $token);
781
+    }
782
+
783
+    /**
784
+     * logout the user from the session
785
+     */
786
+    public function logout() {
787
+        $this->manager->emit('\OC\User', 'logout');
788
+        $user = $this->getUser();
789
+        if (!is_null($user)) {
790
+            try {
791
+                $this->tokenProvider->invalidateToken($this->session->getId());
792
+            } catch (SessionNotAvailableException $ex) {
793
+
794
+            }
795
+        }
796
+        $this->setUser(null);
797
+        $this->setLoginName(null);
798
+        $this->setToken(null);
799
+        $this->unsetMagicInCookie();
800
+        $this->session->clear();
801
+        $this->manager->emit('\OC\User', 'postLogout');
802
+    }
803
+
804
+    /**
805
+     * Set cookie value to use in next page load
806
+     *
807
+     * @param string $username username to be set
808
+     * @param string $token
809
+     */
810
+    public function setMagicInCookie($username, $token) {
811
+        $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
812
+        $webRoot = \OC::$WEBROOT;
813
+        if ($webRoot === '') {
814
+            $webRoot = '/';
815
+        }
816
+
817
+        $expires = $this->timeFacory->getTime() + $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
818
+        setcookie('nc_username', $username, $expires, $webRoot, '', $secureCookie, true);
819
+        setcookie('nc_token', $token, $expires, $webRoot, '', $secureCookie, true);
820
+        try {
821
+            setcookie('nc_session_id', $this->session->getId(), $expires, $webRoot, '', $secureCookie, true);
822
+        } catch (SessionNotAvailableException $ex) {
823
+            // ignore
824
+        }
825
+    }
826
+
827
+    /**
828
+     * Remove cookie for "remember username"
829
+     */
830
+    public function unsetMagicInCookie() {
831
+        //TODO: DI for cookies and IRequest
832
+        $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
833
+
834
+        unset($_COOKIE['nc_username']); //TODO: DI
835
+        unset($_COOKIE['nc_token']);
836
+        unset($_COOKIE['nc_session_id']);
837
+        setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
838
+        setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
839
+        setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
840
+        // old cookies might be stored under /webroot/ instead of /webroot
841
+        // and Firefox doesn't like it!
842
+        setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
843
+        setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
844
+        setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
845
+    }
846
+
847
+    /**
848
+     * Update password of the browser session token if there is one
849
+     *
850
+     * @param string $password
851
+     */
852
+    public function updateSessionTokenPassword($password) {
853
+        try {
854
+            $sessionId = $this->session->getId();
855
+            $token = $this->tokenProvider->getToken($sessionId);
856
+            $this->tokenProvider->setPassword($token, $sessionId, $password);
857
+        } catch (SessionNotAvailableException $ex) {
858
+            // Nothing to do
859
+        } catch (InvalidTokenException $ex) {
860
+            // Nothing to do
861
+        }
862
+    }
863 863
 
864 864
 
865 865
 }
Please login to merge, or discard this patch.
apps/dav/lib/Files/FileSearchBackend.php 3 patches
Doc Comments   +4 added lines patch added patch discarded remove patch
@@ -104,6 +104,10 @@
 block discarded – undo
104 104
 		}
105 105
 	}
106 106
 
107
+	/**
108
+	 * @param string $href
109
+	 * @param string $path
110
+	 */
107 111
 	public function getPropertyDefinitionsForScope($href, $path) {
108 112
 		// all valid scopes support the same schema
109 113
 
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 		/** @var Folder $folder $results */
156 156
 		$results = $folder->search($query);
157 157
 
158
-		return array_map(function (Node $node) {
158
+		return array_map(function(Node $node) {
159 159
 			if ($node instanceof Folder) {
160 160
 				return new SearchResult(new \OCA\DAV\Connector\Sabre\Directory($this->view, $node, $this->tree, $this->shareManager), $this->getHrefForNode($node));
161 161
 			} else {
@@ -169,8 +169,8 @@  discard block
 block discarded – undo
169 169
 	 * @return string
170 170
 	 */
171 171
 	private function getHrefForNode(Node $node) {
172
-		$base = '/files/' . $this->user->getUID();
173
-		return $base . $this->view->getRelativePath($node->getPath());
172
+		$base = '/files/'.$this->user->getUID();
173
+		return $base.$this->view->getRelativePath($node->getPath());
174 174
 	}
175 175
 
176 176
 	/**
@@ -210,19 +210,19 @@  discard block
 block discarded – undo
210 210
 			case Operator::OPERATION_LESS_THAN:
211 211
 			case Operator::OPERATION_IS_LIKE:
212 212
 				if (count($operator->arguments) !== 2) {
213
-					throw new \InvalidArgumentException('Invalid number of arguments for ' . $trimmedType . ' operation');
213
+					throw new \InvalidArgumentException('Invalid number of arguments for '.$trimmedType.' operation');
214 214
 				}
215 215
 				if (!is_string($operator->arguments[0])) {
216
-					throw new \InvalidArgumentException('Invalid argument 1 for ' . $trimmedType . ' operation, expected property');
216
+					throw new \InvalidArgumentException('Invalid argument 1 for '.$trimmedType.' operation, expected property');
217 217
 				}
218 218
 				if (!($operator->arguments[1] instanceof Literal)) {
219
-					throw new \InvalidArgumentException('Invalid argument 2 for ' . $trimmedType . ' operation, expected literal');
219
+					throw new \InvalidArgumentException('Invalid argument 2 for '.$trimmedType.' operation, expected literal');
220 220
 				}
221 221
 				return new SearchComparison($trimmedType, $this->mapPropertyNameToColumn($operator->arguments[0]), $this->castValue($operator->arguments[0], $operator->arguments[1]->value));
222 222
 			case Operator::OPERATION_IS_COLLECTION:
223 223
 				return new SearchComparison('eq', 'mimetype', ICacheEntry::DIRECTORY_MIMETYPE);
224 224
 			default:
225
-				throw new \InvalidArgumentException('Unsupported operation ' . $trimmedType.  ' (' . $operator->type . ')');
225
+				throw new \InvalidArgumentException('Unsupported operation '.$trimmedType.' ('.$operator->type.')');
226 226
 		}
227 227
 	}
228 228
 
@@ -245,7 +245,7 @@  discard block
 block discarded – undo
245 245
 			case TagsPlugin::TAGS_PROPERTYNAME:
246 246
 				return 'tagname';
247 247
 			default:
248
-				throw new \InvalidArgumentException('Unsupported property for search or order: ' . $propertyName);
248
+				throw new \InvalidArgumentException('Unsupported property for search or order: '.$propertyName);
249 249
 		}
250 250
 	}
251 251
 
Please login to merge, or discard this patch.
Indentation   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -49,229 +49,229 @@
 block discarded – undo
49 49
 use SearchDAV\XML\Order;
50 50
 
51 51
 class FileSearchBackend implements ISearchBackend {
52
-	/** @var Tree */
53
-	private $tree;
52
+    /** @var Tree */
53
+    private $tree;
54 54
 
55
-	/** @var IUser */
56
-	private $user;
55
+    /** @var IUser */
56
+    private $user;
57 57
 
58
-	/** @var IRootFolder */
59
-	private $rootFolder;
58
+    /** @var IRootFolder */
59
+    private $rootFolder;
60 60
 
61
-	/** @var IManager */
62
-	private $shareManager;
61
+    /** @var IManager */
62
+    private $shareManager;
63 63
 
64
-	/** @var View */
65
-	private $view;
64
+    /** @var View */
65
+    private $view;
66 66
 
67
-	/**
68
-	 * FileSearchBackend constructor.
69
-	 *
70
-	 * @param Tree $tree
71
-	 * @param IUser $user
72
-	 * @param IRootFolder $rootFolder
73
-	 * @param IManager $shareManager
74
-	 * @param View $view
75
-	 * @internal param IRootFolder $rootFolder
76
-	 */
77
-	public function __construct(Tree $tree, IUser $user, IRootFolder $rootFolder, IManager $shareManager, View $view) {
78
-		$this->tree = $tree;
79
-		$this->user = $user;
80
-		$this->rootFolder = $rootFolder;
81
-		$this->shareManager = $shareManager;
82
-		$this->view = $view;
83
-	}
67
+    /**
68
+     * FileSearchBackend constructor.
69
+     *
70
+     * @param Tree $tree
71
+     * @param IUser $user
72
+     * @param IRootFolder $rootFolder
73
+     * @param IManager $shareManager
74
+     * @param View $view
75
+     * @internal param IRootFolder $rootFolder
76
+     */
77
+    public function __construct(Tree $tree, IUser $user, IRootFolder $rootFolder, IManager $shareManager, View $view) {
78
+        $this->tree = $tree;
79
+        $this->user = $user;
80
+        $this->rootFolder = $rootFolder;
81
+        $this->shareManager = $shareManager;
82
+        $this->view = $view;
83
+    }
84 84
 
85
-	/**
86
-	 * Search endpoint will be remote.php/dav
87
-	 *
88
-	 * @return string
89
-	 */
90
-	public function getArbiterPath() {
91
-		return '';
92
-	}
85
+    /**
86
+     * Search endpoint will be remote.php/dav
87
+     *
88
+     * @return string
89
+     */
90
+    public function getArbiterPath() {
91
+        return '';
92
+    }
93 93
 
94
-	public function isValidScope($href, $depth, $path) {
95
-		// only allow scopes inside the dav server
96
-		if (is_null($path)) {
97
-			return false;
98
-		}
94
+    public function isValidScope($href, $depth, $path) {
95
+        // only allow scopes inside the dav server
96
+        if (is_null($path)) {
97
+            return false;
98
+        }
99 99
 
100
-		try {
101
-			$node = $this->tree->getNodeForPath($path);
102
-			return $node instanceof Directory;
103
-		} catch (NotFound $e) {
104
-			return false;
105
-		}
106
-	}
100
+        try {
101
+            $node = $this->tree->getNodeForPath($path);
102
+            return $node instanceof Directory;
103
+        } catch (NotFound $e) {
104
+            return false;
105
+        }
106
+    }
107 107
 
108
-	public function getPropertyDefinitionsForScope($href, $path) {
109
-		// all valid scopes support the same schema
108
+    public function getPropertyDefinitionsForScope($href, $path) {
109
+        // all valid scopes support the same schema
110 110
 
111
-		//todo dynamically load all propfind properties that are supported
112
-		return [
113
-			// queryable properties
114
-			new SearchPropertyDefinition('{DAV:}displayname', true, false, true),
115
-			new SearchPropertyDefinition('{DAV:}getcontenttype', true, true, true),
116
-			new SearchPropertyDefinition('{DAV:}getlastmodified', true, true, true, SearchPropertyDefinition::DATATYPE_DATETIME),
117
-			new SearchPropertyDefinition(FilesPlugin::SIZE_PROPERTYNAME, true, true, true, SearchPropertyDefinition::DATATYPE_NONNEGATIVE_INTEGER),
118
-			new SearchPropertyDefinition(TagsPlugin::FAVORITE_PROPERTYNAME, true, true, true, SearchPropertyDefinition::DATATYPE_BOOLEAN),
111
+        //todo dynamically load all propfind properties that are supported
112
+        return [
113
+            // queryable properties
114
+            new SearchPropertyDefinition('{DAV:}displayname', true, false, true),
115
+            new SearchPropertyDefinition('{DAV:}getcontenttype', true, true, true),
116
+            new SearchPropertyDefinition('{DAV:}getlastmodified', true, true, true, SearchPropertyDefinition::DATATYPE_DATETIME),
117
+            new SearchPropertyDefinition(FilesPlugin::SIZE_PROPERTYNAME, true, true, true, SearchPropertyDefinition::DATATYPE_NONNEGATIVE_INTEGER),
118
+            new SearchPropertyDefinition(TagsPlugin::FAVORITE_PROPERTYNAME, true, true, true, SearchPropertyDefinition::DATATYPE_BOOLEAN),
119 119
 
120
-			// select only properties
121
-			new SearchPropertyDefinition('{DAV:}resourcetype', false, true, false),
122
-			new SearchPropertyDefinition('{DAV:}getcontentlength', false, true, false),
123
-			new SearchPropertyDefinition(FilesPlugin::CHECKSUMS_PROPERTYNAME, false, true, false),
124
-			new SearchPropertyDefinition(FilesPlugin::PERMISSIONS_PROPERTYNAME, false, true, false),
125
-			new SearchPropertyDefinition(FilesPlugin::GETETAG_PROPERTYNAME, false, true, false),
126
-			new SearchPropertyDefinition(FilesPlugin::OWNER_ID_PROPERTYNAME, false, true, false),
127
-			new SearchPropertyDefinition(FilesPlugin::OWNER_DISPLAY_NAME_PROPERTYNAME, false, true, false),
128
-			new SearchPropertyDefinition(FilesPlugin::DATA_FINGERPRINT_PROPERTYNAME, false, true, false),
129
-			new SearchPropertyDefinition(FilesPlugin::HAS_PREVIEW_PROPERTYNAME, false, true, false, SearchPropertyDefinition::DATATYPE_BOOLEAN),
130
-			new SearchPropertyDefinition(FilesPlugin::INTERNAL_FILEID_PROPERTYNAME, false, true, false, SearchPropertyDefinition::DATATYPE_NONNEGATIVE_INTEGER),
131
-			new SearchPropertyDefinition(FilesPlugin::FILEID_PROPERTYNAME, false, true, false, SearchPropertyDefinition::DATATYPE_NONNEGATIVE_INTEGER),
132
-		];
133
-	}
120
+            // select only properties
121
+            new SearchPropertyDefinition('{DAV:}resourcetype', false, true, false),
122
+            new SearchPropertyDefinition('{DAV:}getcontentlength', false, true, false),
123
+            new SearchPropertyDefinition(FilesPlugin::CHECKSUMS_PROPERTYNAME, false, true, false),
124
+            new SearchPropertyDefinition(FilesPlugin::PERMISSIONS_PROPERTYNAME, false, true, false),
125
+            new SearchPropertyDefinition(FilesPlugin::GETETAG_PROPERTYNAME, false, true, false),
126
+            new SearchPropertyDefinition(FilesPlugin::OWNER_ID_PROPERTYNAME, false, true, false),
127
+            new SearchPropertyDefinition(FilesPlugin::OWNER_DISPLAY_NAME_PROPERTYNAME, false, true, false),
128
+            new SearchPropertyDefinition(FilesPlugin::DATA_FINGERPRINT_PROPERTYNAME, false, true, false),
129
+            new SearchPropertyDefinition(FilesPlugin::HAS_PREVIEW_PROPERTYNAME, false, true, false, SearchPropertyDefinition::DATATYPE_BOOLEAN),
130
+            new SearchPropertyDefinition(FilesPlugin::INTERNAL_FILEID_PROPERTYNAME, false, true, false, SearchPropertyDefinition::DATATYPE_NONNEGATIVE_INTEGER),
131
+            new SearchPropertyDefinition(FilesPlugin::FILEID_PROPERTYNAME, false, true, false, SearchPropertyDefinition::DATATYPE_NONNEGATIVE_INTEGER),
132
+        ];
133
+    }
134 134
 
135
-	/**
136
-	 * @param BasicSearch $search
137
-	 * @return SearchResult[]
138
-	 */
139
-	public function search(BasicSearch $search) {
140
-		if (count($search->from) !== 1) {
141
-			throw new \InvalidArgumentException('Searching more than one folder is not supported');
142
-		}
143
-		$query = $this->transformQuery($search);
144
-		$scope = $search->from[0];
145
-		if ($scope->path === null) {
146
-			throw new \InvalidArgumentException('Using uri\'s as scope is not supported, please use a path relative to the search arbiter instead');
147
-		}
148
-		$node = $this->tree->getNodeForPath($scope->path);
149
-		if (!$node instanceof Directory) {
150
-			throw new \InvalidArgumentException('Search is only supported on directories');
151
-		}
135
+    /**
136
+     * @param BasicSearch $search
137
+     * @return SearchResult[]
138
+     */
139
+    public function search(BasicSearch $search) {
140
+        if (count($search->from) !== 1) {
141
+            throw new \InvalidArgumentException('Searching more than one folder is not supported');
142
+        }
143
+        $query = $this->transformQuery($search);
144
+        $scope = $search->from[0];
145
+        if ($scope->path === null) {
146
+            throw new \InvalidArgumentException('Using uri\'s as scope is not supported, please use a path relative to the search arbiter instead');
147
+        }
148
+        $node = $this->tree->getNodeForPath($scope->path);
149
+        if (!$node instanceof Directory) {
150
+            throw new \InvalidArgumentException('Search is only supported on directories');
151
+        }
152 152
 
153
-		$fileInfo = $node->getFileInfo();
154
-		$folder = $this->rootFolder->get($fileInfo->getPath());
155
-		/** @var Folder $folder $results */
156
-		$results = $folder->search($query);
153
+        $fileInfo = $node->getFileInfo();
154
+        $folder = $this->rootFolder->get($fileInfo->getPath());
155
+        /** @var Folder $folder $results */
156
+        $results = $folder->search($query);
157 157
 
158
-		return array_map(function (Node $node) {
159
-			if ($node instanceof Folder) {
160
-				return new SearchResult(new \OCA\DAV\Connector\Sabre\Directory($this->view, $node, $this->tree, $this->shareManager), $this->getHrefForNode($node));
161
-			} else {
162
-				return new SearchResult(new \OCA\DAV\Connector\Sabre\File($this->view, $node, $this->shareManager), $this->getHrefForNode($node));
163
-			}
164
-		}, $results);
165
-	}
158
+        return array_map(function (Node $node) {
159
+            if ($node instanceof Folder) {
160
+                return new SearchResult(new \OCA\DAV\Connector\Sabre\Directory($this->view, $node, $this->tree, $this->shareManager), $this->getHrefForNode($node));
161
+            } else {
162
+                return new SearchResult(new \OCA\DAV\Connector\Sabre\File($this->view, $node, $this->shareManager), $this->getHrefForNode($node));
163
+            }
164
+        }, $results);
165
+    }
166 166
 
167
-	/**
168
-	 * @param Node $node
169
-	 * @return string
170
-	 */
171
-	private function getHrefForNode(Node $node) {
172
-		$base = '/files/' . $this->user->getUID();
173
-		return $base . $this->view->getRelativePath($node->getPath());
174
-	}
167
+    /**
168
+     * @param Node $node
169
+     * @return string
170
+     */
171
+    private function getHrefForNode(Node $node) {
172
+        $base = '/files/' . $this->user->getUID();
173
+        return $base . $this->view->getRelativePath($node->getPath());
174
+    }
175 175
 
176
-	/**
177
-	 * @param BasicSearch $query
178
-	 * @return ISearchQuery
179
-	 */
180
-	private function transformQuery(BasicSearch $query) {
181
-		// TODO offset, limit
182
-		$orders = array_map([$this, 'mapSearchOrder'], $query->orderBy);
183
-		return new SearchQuery($this->transformSearchOperation($query->where), 0, 0, $orders, $this->user);
184
-	}
176
+    /**
177
+     * @param BasicSearch $query
178
+     * @return ISearchQuery
179
+     */
180
+    private function transformQuery(BasicSearch $query) {
181
+        // TODO offset, limit
182
+        $orders = array_map([$this, 'mapSearchOrder'], $query->orderBy);
183
+        return new SearchQuery($this->transformSearchOperation($query->where), 0, 0, $orders, $this->user);
184
+    }
185 185
 
186
-	/**
187
-	 * @param Order $order
188
-	 * @return ISearchOrder
189
-	 */
190
-	private function mapSearchOrder(Order $order) {
191
-		return new SearchOrder($order->order === Order::ASC ? ISearchOrder::DIRECTION_ASCENDING : ISearchOrder::DIRECTION_DESCENDING, $this->mapPropertyNameToColumn($order->property));
192
-	}
186
+    /**
187
+     * @param Order $order
188
+     * @return ISearchOrder
189
+     */
190
+    private function mapSearchOrder(Order $order) {
191
+        return new SearchOrder($order->order === Order::ASC ? ISearchOrder::DIRECTION_ASCENDING : ISearchOrder::DIRECTION_DESCENDING, $this->mapPropertyNameToColumn($order->property));
192
+    }
193 193
 
194
-	/**
195
-	 * @param Operator $operator
196
-	 * @return ISearchOperator
197
-	 */
198
-	private function transformSearchOperation(Operator $operator) {
199
-		list(, $trimmedType) = explode('}', $operator->type);
200
-		switch ($operator->type) {
201
-			case Operator::OPERATION_AND:
202
-			case Operator::OPERATION_OR:
203
-			case Operator::OPERATION_NOT:
204
-				$arguments = array_map([$this, 'transformSearchOperation'], $operator->arguments);
205
-				return new SearchBinaryOperator($trimmedType, $arguments);
206
-			case Operator::OPERATION_EQUAL:
207
-			case Operator::OPERATION_GREATER_OR_EQUAL_THAN:
208
-			case Operator::OPERATION_GREATER_THAN:
209
-			case Operator::OPERATION_LESS_OR_EQUAL_THAN:
210
-			case Operator::OPERATION_LESS_THAN:
211
-			case Operator::OPERATION_IS_LIKE:
212
-				if (count($operator->arguments) !== 2) {
213
-					throw new \InvalidArgumentException('Invalid number of arguments for ' . $trimmedType . ' operation');
214
-				}
215
-				if (!is_string($operator->arguments[0])) {
216
-					throw new \InvalidArgumentException('Invalid argument 1 for ' . $trimmedType . ' operation, expected property');
217
-				}
218
-				if (!($operator->arguments[1] instanceof Literal)) {
219
-					throw new \InvalidArgumentException('Invalid argument 2 for ' . $trimmedType . ' operation, expected literal');
220
-				}
221
-				return new SearchComparison($trimmedType, $this->mapPropertyNameToColumn($operator->arguments[0]), $this->castValue($operator->arguments[0], $operator->arguments[1]->value));
222
-			case Operator::OPERATION_IS_COLLECTION:
223
-				return new SearchComparison('eq', 'mimetype', ICacheEntry::DIRECTORY_MIMETYPE);
224
-			default:
225
-				throw new \InvalidArgumentException('Unsupported operation ' . $trimmedType.  ' (' . $operator->type . ')');
226
-		}
227
-	}
194
+    /**
195
+     * @param Operator $operator
196
+     * @return ISearchOperator
197
+     */
198
+    private function transformSearchOperation(Operator $operator) {
199
+        list(, $trimmedType) = explode('}', $operator->type);
200
+        switch ($operator->type) {
201
+            case Operator::OPERATION_AND:
202
+            case Operator::OPERATION_OR:
203
+            case Operator::OPERATION_NOT:
204
+                $arguments = array_map([$this, 'transformSearchOperation'], $operator->arguments);
205
+                return new SearchBinaryOperator($trimmedType, $arguments);
206
+            case Operator::OPERATION_EQUAL:
207
+            case Operator::OPERATION_GREATER_OR_EQUAL_THAN:
208
+            case Operator::OPERATION_GREATER_THAN:
209
+            case Operator::OPERATION_LESS_OR_EQUAL_THAN:
210
+            case Operator::OPERATION_LESS_THAN:
211
+            case Operator::OPERATION_IS_LIKE:
212
+                if (count($operator->arguments) !== 2) {
213
+                    throw new \InvalidArgumentException('Invalid number of arguments for ' . $trimmedType . ' operation');
214
+                }
215
+                if (!is_string($operator->arguments[0])) {
216
+                    throw new \InvalidArgumentException('Invalid argument 1 for ' . $trimmedType . ' operation, expected property');
217
+                }
218
+                if (!($operator->arguments[1] instanceof Literal)) {
219
+                    throw new \InvalidArgumentException('Invalid argument 2 for ' . $trimmedType . ' operation, expected literal');
220
+                }
221
+                return new SearchComparison($trimmedType, $this->mapPropertyNameToColumn($operator->arguments[0]), $this->castValue($operator->arguments[0], $operator->arguments[1]->value));
222
+            case Operator::OPERATION_IS_COLLECTION:
223
+                return new SearchComparison('eq', 'mimetype', ICacheEntry::DIRECTORY_MIMETYPE);
224
+            default:
225
+                throw new \InvalidArgumentException('Unsupported operation ' . $trimmedType.  ' (' . $operator->type . ')');
226
+        }
227
+    }
228 228
 
229
-	/**
230
-	 * @param string $propertyName
231
-	 * @return string
232
-	 */
233
-	private function mapPropertyNameToColumn($propertyName) {
234
-		switch ($propertyName) {
235
-			case '{DAV:}displayname':
236
-				return 'name';
237
-			case '{DAV:}getcontenttype':
238
-				return 'mimetype';
239
-			case '{DAV:}getlastmodified':
240
-				return 'mtime';
241
-			case FilesPlugin::SIZE_PROPERTYNAME:
242
-				return 'size';
243
-			case TagsPlugin::FAVORITE_PROPERTYNAME:
244
-				return 'favorite';
245
-			case TagsPlugin::TAGS_PROPERTYNAME:
246
-				return 'tagname';
247
-			default:
248
-				throw new \InvalidArgumentException('Unsupported property for search or order: ' . $propertyName);
249
-		}
250
-	}
229
+    /**
230
+     * @param string $propertyName
231
+     * @return string
232
+     */
233
+    private function mapPropertyNameToColumn($propertyName) {
234
+        switch ($propertyName) {
235
+            case '{DAV:}displayname':
236
+                return 'name';
237
+            case '{DAV:}getcontenttype':
238
+                return 'mimetype';
239
+            case '{DAV:}getlastmodified':
240
+                return 'mtime';
241
+            case FilesPlugin::SIZE_PROPERTYNAME:
242
+                return 'size';
243
+            case TagsPlugin::FAVORITE_PROPERTYNAME:
244
+                return 'favorite';
245
+            case TagsPlugin::TAGS_PROPERTYNAME:
246
+                return 'tagname';
247
+            default:
248
+                throw new \InvalidArgumentException('Unsupported property for search or order: ' . $propertyName);
249
+        }
250
+    }
251 251
 
252
-	private function castValue($propertyName, $value) {
253
-		$allProps = $this->getPropertyDefinitionsForScope('', '');
254
-		foreach ($allProps as $prop) {
255
-			if ($prop->name === $propertyName) {
256
-				$dataType = $prop->dataType;
257
-				switch ($dataType) {
258
-					case SearchPropertyDefinition::DATATYPE_BOOLEAN:
259
-						return $value === 'yes';
260
-					case SearchPropertyDefinition::DATATYPE_DECIMAL:
261
-					case SearchPropertyDefinition::DATATYPE_INTEGER:
262
-					case SearchPropertyDefinition::DATATYPE_NONNEGATIVE_INTEGER:
263
-						return 0 + $value;
264
-					case SearchPropertyDefinition::DATATYPE_DATETIME:
265
-						if (is_numeric($value)) {
266
-							return 0 + $value;
267
-						}
268
-						$date = \DateTime::createFromFormat(\DateTime::ATOM, $value);
269
-						return ($date instanceof  \DateTime) ? $date->getTimestamp() : 0;
270
-					default:
271
-						return $value;
272
-				}
273
-			}
274
-		}
275
-		return $value;
276
-	}
252
+    private function castValue($propertyName, $value) {
253
+        $allProps = $this->getPropertyDefinitionsForScope('', '');
254
+        foreach ($allProps as $prop) {
255
+            if ($prop->name === $propertyName) {
256
+                $dataType = $prop->dataType;
257
+                switch ($dataType) {
258
+                    case SearchPropertyDefinition::DATATYPE_BOOLEAN:
259
+                        return $value === 'yes';
260
+                    case SearchPropertyDefinition::DATATYPE_DECIMAL:
261
+                    case SearchPropertyDefinition::DATATYPE_INTEGER:
262
+                    case SearchPropertyDefinition::DATATYPE_NONNEGATIVE_INTEGER:
263
+                        return 0 + $value;
264
+                    case SearchPropertyDefinition::DATATYPE_DATETIME:
265
+                        if (is_numeric($value)) {
266
+                            return 0 + $value;
267
+                        }
268
+                        $date = \DateTime::createFromFormat(\DateTime::ATOM, $value);
269
+                        return ($date instanceof  \DateTime) ? $date->getTimestamp() : 0;
270
+                    default:
271
+                        return $value;
272
+                }
273
+            }
274
+        }
275
+        return $value;
276
+    }
277 277
 }
Please login to merge, or discard this patch.
lib/private/Lockdown/Filesystem/NullCache.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -22,7 +22,6 @@
 block discarded – undo
22 22
 use OC\Files\Cache\CacheEntry;
23 23
 use OCP\Constants;
24 24
 use OCP\Files\Cache\ICache;
25
-use OCP\Files\Cache\ICacheEntry;
26 25
 use OCP\Files\FileInfo;
27 26
 use OCP\Files\Search\ISearchQuery;
28 27
 
Please login to merge, or discard this patch.
Spacing   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -31,8 +31,7 @@
 block discarded – undo
31 31
 	}
32 32
 
33 33
 	public function get($file) {
34
-		return $file !== '' ? null :
35
-			new CacheEntry([
34
+		return $file !== '' ? null : new CacheEntry([
36 35
 				'fileid' => -1,
37 36
 				'parent' => -1,
38 37
 				'name' => '',
Please login to merge, or discard this patch.
Indentation   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -27,101 +27,101 @@
 block discarded – undo
27 27
 use OCP\Files\Search\ISearchQuery;
28 28
 
29 29
 class NullCache implements ICache {
30
-	public function getNumericStorageId() {
31
-		return -1;
32
-	}
33
-
34
-	public function get($file) {
35
-		return $file !== '' ? null :
36
-			new CacheEntry([
37
-				'fileid' => -1,
38
-				'parent' => -1,
39
-				'name' => '',
40
-				'path' => '',
41
-				'size' => '0',
42
-				'mtime' => time(),
43
-				'storage_mtime' => time(),
44
-				'etag' => '',
45
-				'mimetype' => FileInfo::MIMETYPE_FOLDER,
46
-				'mimepart' => 'httpd',
47
-				'permissions' => Constants::PERMISSION_READ
48
-			]);
49
-	}
50
-
51
-	public function getFolderContents($folder) {
52
-		return [];
53
-	}
54
-
55
-	public function getFolderContentsById($fileId) {
56
-		return [];
57
-	}
58
-
59
-	public function put($file, array $data) {
60
-		throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
61
-	}
62
-
63
-	public function insert($file, array $data) {
64
-		throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
65
-	}
66
-
67
-	public function update($id, array $data) {
68
-		throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
69
-	}
70
-
71
-	public function getId($file) {
72
-		return -1;
73
-	}
74
-
75
-	public function getParentId($file) {
76
-		return -1;
77
-	}
78
-
79
-	public function inCache($file) {
80
-		return $file === '';
81
-	}
82
-
83
-	public function remove($file) {
84
-		throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
85
-	}
86
-
87
-	public function move($source, $target) {
88
-		throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
89
-	}
90
-
91
-	public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
92
-		throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
93
-	}
94
-
95
-	public function getStatus($file) {
96
-		return ICache::COMPLETE;
97
-	}
98
-
99
-	public function search($pattern) {
100
-		return [];
101
-	}
102
-
103
-	public function searchByMime($mimetype) {
104
-		return [];
105
-	}
106
-
107
-	public function searchQuery(ISearchQuery $query) {
108
-		return [];
109
-	}
110
-
111
-	public function searchByTag($tag, $userId) {
112
-		return [];
113
-	}
114
-
115
-	public function getIncomplete() {
116
-		return [];
117
-	}
118
-
119
-	public function getPathById($id) {
120
-		return '';
121
-	}
122
-
123
-	public function normalize($path) {
124
-		return $path;
125
-	}
30
+    public function getNumericStorageId() {
31
+        return -1;
32
+    }
33
+
34
+    public function get($file) {
35
+        return $file !== '' ? null :
36
+            new CacheEntry([
37
+                'fileid' => -1,
38
+                'parent' => -1,
39
+                'name' => '',
40
+                'path' => '',
41
+                'size' => '0',
42
+                'mtime' => time(),
43
+                'storage_mtime' => time(),
44
+                'etag' => '',
45
+                'mimetype' => FileInfo::MIMETYPE_FOLDER,
46
+                'mimepart' => 'httpd',
47
+                'permissions' => Constants::PERMISSION_READ
48
+            ]);
49
+    }
50
+
51
+    public function getFolderContents($folder) {
52
+        return [];
53
+    }
54
+
55
+    public function getFolderContentsById($fileId) {
56
+        return [];
57
+    }
58
+
59
+    public function put($file, array $data) {
60
+        throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
61
+    }
62
+
63
+    public function insert($file, array $data) {
64
+        throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
65
+    }
66
+
67
+    public function update($id, array $data) {
68
+        throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
69
+    }
70
+
71
+    public function getId($file) {
72
+        return -1;
73
+    }
74
+
75
+    public function getParentId($file) {
76
+        return -1;
77
+    }
78
+
79
+    public function inCache($file) {
80
+        return $file === '';
81
+    }
82
+
83
+    public function remove($file) {
84
+        throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
85
+    }
86
+
87
+    public function move($source, $target) {
88
+        throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
89
+    }
90
+
91
+    public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
92
+        throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
93
+    }
94
+
95
+    public function getStatus($file) {
96
+        return ICache::COMPLETE;
97
+    }
98
+
99
+    public function search($pattern) {
100
+        return [];
101
+    }
102
+
103
+    public function searchByMime($mimetype) {
104
+        return [];
105
+    }
106
+
107
+    public function searchQuery(ISearchQuery $query) {
108
+        return [];
109
+    }
110
+
111
+    public function searchByTag($tag, $userId) {
112
+        return [];
113
+    }
114
+
115
+    public function getIncomplete() {
116
+        return [];
117
+    }
118
+
119
+    public function getPathById($id) {
120
+        return '';
121
+    }
122
+
123
+    public function normalize($path) {
124
+        return $path;
125
+    }
126 126
 
127 127
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/StreamResponse.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@
 block discarded – undo
37 37
 	private $filePath;
38 38
 
39 39
 	/**
40
-	 * @param string|resource $filePath the path to the file or a file handle which should be streamed
40
+	 * @param string $filePath the path to the file or a file handle which should be streamed
41 41
 	 * @since 8.1.0
42 42
 	 */
43 43
 	public function __construct ($filePath) {
Please login to merge, or discard this patch.
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -33,33 +33,33 @@
 block discarded – undo
33 33
  * @since 8.1.0
34 34
  */
35 35
 class StreamResponse extends Response implements ICallbackResponse {
36
-	/** @var string */
37
-	private $filePath;
36
+    /** @var string */
37
+    private $filePath;
38 38
 
39
-	/**
40
-	 * @param string|resource $filePath the path to the file or a file handle which should be streamed
41
-	 * @since 8.1.0
42
-	 */
43
-	public function __construct ($filePath) {
44
-		$this->filePath = $filePath;
45
-	}
39
+    /**
40
+     * @param string|resource $filePath the path to the file or a file handle which should be streamed
41
+     * @since 8.1.0
42
+     */
43
+    public function __construct ($filePath) {
44
+        $this->filePath = $filePath;
45
+    }
46 46
 
47 47
 
48
-	/**
49
-	 * Streams the file using readfile
50
-	 *
51
-	 * @param IOutput $output a small wrapper that handles output
52
-	 * @since 8.1.0
53
-	 */
54
-	public function callback (IOutput $output) {
55
-		// handle caching
56
-		if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
57
-			if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
58
-				$output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
59
-			} elseif ($output->setReadfile($this->filePath) === false) {
60
-				$output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
61
-			}
62
-		}
63
-	}
48
+    /**
49
+     * Streams the file using readfile
50
+     *
51
+     * @param IOutput $output a small wrapper that handles output
52
+     * @since 8.1.0
53
+     */
54
+    public function callback (IOutput $output) {
55
+        // handle caching
56
+        if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
57
+            if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
58
+                $output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
59
+            } elseif ($output->setReadfile($this->filePath) === false) {
60
+                $output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
61
+            }
62
+        }
63
+    }
64 64
 
65 65
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
 	 * @param string|resource $filePath the path to the file or a file handle which should be streamed
41 41
 	 * @since 8.1.0
42 42
 	 */
43
-	public function __construct ($filePath) {
43
+	public function __construct($filePath) {
44 44
 		$this->filePath = $filePath;
45 45
 	}
46 46
 
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 	 * @param IOutput $output a small wrapper that handles output
52 52
 	 * @since 8.1.0
53 53
 	 */
54
-	public function callback (IOutput $output) {
54
+	public function callback(IOutput $output) {
55 55
 		// handle caching
56 56
 		if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
57 57
 			if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/DavAclPlugin.php 4 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -47,6 +47,9 @@
 block discarded – undo
47 47
 		$this->allowUnauthenticatedAccess = false;
48 48
 	}
49 49
 
50
+	/**
51
+	 * @param string $privileges
52
+	 */
50 53
 	function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
51 54
 		$access = parent::checkPrivileges($uri, $privileges, $recursion, false);
52 55
 		if($access === false && $throwExceptions) {
Please login to merge, or discard this patch.
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -25,14 +25,11 @@
 block discarded – undo
25 25
 
26 26
 use Sabre\CalDAV\Principal\User;
27 27
 use Sabre\DAV\Exception\NotFound;
28
-use Sabre\DAV\IFile;
29 28
 use Sabre\DAV\INode;
30 29
 use \Sabre\DAV\PropFind;
31 30
 use \Sabre\DAV\PropPatch;
32
-use Sabre\DAVACL\Exception\NeedPrivileges;
33 31
 use \Sabre\HTTP\RequestInterface;
34 32
 use \Sabre\HTTP\ResponseInterface;
35
-use Sabre\HTTP\URLUtil;
36 33
 
37 34
 /**
38 35
  * Class DavAclPlugin is a wrapper around \Sabre\DAVACL\Plugin that returns 404
Please login to merge, or discard this patch.
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -43,50 +43,50 @@
 block discarded – undo
43 43
  * @package OCA\DAV\Connector\Sabre
44 44
  */
45 45
 class DavAclPlugin extends \Sabre\DAVACL\Plugin {
46
-	public function __construct() {
47
-		$this->hideNodesFromListings = true;
48
-		$this->allowUnauthenticatedAccess = false;
49
-	}
46
+    public function __construct() {
47
+        $this->hideNodesFromListings = true;
48
+        $this->allowUnauthenticatedAccess = false;
49
+    }
50 50
 
51
-	function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
52
-		$access = parent::checkPrivileges($uri, $privileges, $recursion, false);
53
-		if($access === false && $throwExceptions) {
54
-			/** @var INode $node */
55
-			$node = $this->server->tree->getNodeForPath($uri);
51
+    function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
52
+        $access = parent::checkPrivileges($uri, $privileges, $recursion, false);
53
+        if($access === false && $throwExceptions) {
54
+            /** @var INode $node */
55
+            $node = $this->server->tree->getNodeForPath($uri);
56 56
 
57
-			switch(get_class($node)) {
58
-				case 'OCA\DAV\CardDAV\AddressBook':
59
-					$type = 'Addressbook';
60
-					break;
61
-				default:
62
-					$type = 'Node';
63
-					break;
64
-			}
65
-			throw new NotFound(
66
-				sprintf(
67
-					"%s with name '%s' could not be found",
68
-					$type,
69
-					$node->getName()
70
-				)
71
-			);
72
-		}
57
+            switch(get_class($node)) {
58
+                case 'OCA\DAV\CardDAV\AddressBook':
59
+                    $type = 'Addressbook';
60
+                    break;
61
+                default:
62
+                    $type = 'Node';
63
+                    break;
64
+            }
65
+            throw new NotFound(
66
+                sprintf(
67
+                    "%s with name '%s' could not be found",
68
+                    $type,
69
+                    $node->getName()
70
+                )
71
+            );
72
+        }
73 73
 
74
-		return $access;
75
-	}
74
+        return $access;
75
+    }
76 76
 
77
-	public function propFind(PropFind $propFind, INode $node) {
78
-		// If the node is neither readable nor writable then fail unless its of
79
-		// the standard user-principal
80
-		if(!($node instanceof User)) {
81
-			$path = $propFind->getPath();
82
-			$readPermissions = $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, false);
83
-			$writePermissions = $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, false);
84
-			if ($readPermissions === false && $writePermissions === false) {
85
-				$this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, true);
86
-				$this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, true);
87
-			}
88
-		}
77
+    public function propFind(PropFind $propFind, INode $node) {
78
+        // If the node is neither readable nor writable then fail unless its of
79
+        // the standard user-principal
80
+        if(!($node instanceof User)) {
81
+            $path = $propFind->getPath();
82
+            $readPermissions = $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, false);
83
+            $writePermissions = $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, false);
84
+            if ($readPermissions === false && $writePermissions === false) {
85
+                $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, true);
86
+                $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, true);
87
+            }
88
+        }
89 89
 
90
-		return parent::propFind($propFind, $node);
91
-	}
90
+        return parent::propFind($propFind, $node);
91
+    }
92 92
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -50,11 +50,11 @@  discard block
 block discarded – undo
50 50
 
51 51
 	function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
52 52
 		$access = parent::checkPrivileges($uri, $privileges, $recursion, false);
53
-		if($access === false && $throwExceptions) {
53
+		if ($access === false && $throwExceptions) {
54 54
 			/** @var INode $node */
55 55
 			$node = $this->server->tree->getNodeForPath($uri);
56 56
 
57
-			switch(get_class($node)) {
57
+			switch (get_class($node)) {
58 58
 				case 'OCA\DAV\CardDAV\AddressBook':
59 59
 					$type = 'Addressbook';
60 60
 					break;
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 	public function propFind(PropFind $propFind, INode $node) {
78 78
 		// If the node is neither readable nor writable then fail unless its of
79 79
 		// the standard user-principal
80
-		if(!($node instanceof User)) {
80
+		if (!($node instanceof User)) {
81 81
 			$path = $propFind->getPath();
82 82
 			$readPermissions = $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, false);
83 83
 			$writePermissions = $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, false);
Please login to merge, or discard this patch.
lib/private/Files/Storage/Storage.php 2 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -100,6 +100,7 @@  discard block
 block discarded – undo
100 100
 	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
101 101
 	 * @param \OCP\Lock\ILockingProvider $provider
102 102
 	 * @throws \OCP\Lock\LockedException
103
+	 * @return void
103 104
 	 */
104 105
 	public function acquireLock($path, $type, ILockingProvider $provider);
105 106
 
@@ -108,6 +109,7 @@  discard block
 block discarded – undo
108 109
 	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
109 110
 	 * @param \OCP\Lock\ILockingProvider $provider
110 111
 	 * @throws \OCP\Lock\LockedException
112
+	 * @return void
111 113
 	 */
112 114
 	public function releaseLock($path, $type, ILockingProvider $provider);
113 115
 
@@ -116,6 +118,7 @@  discard block
 block discarded – undo
116 118
 	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
117 119
 	 * @param \OCP\Lock\ILockingProvider $provider
118 120
 	 * @throws \OCP\Lock\LockedException
121
+	 * @return void
119 122
 	 */
120 123
 	public function changeLock($path, $type, ILockingProvider $provider);
121 124
 }
Please login to merge, or discard this patch.
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -32,90 +32,90 @@
 block discarded – undo
32 32
  */
33 33
 interface Storage extends \OCP\Files\Storage {
34 34
 
35
-	/**
36
-	 * get a cache instance for the storage
37
-	 *
38
-	 * @param string $path
39
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the cache
40
-	 * @return \OC\Files\Cache\Cache
41
-	 */
42
-	public function getCache($path = '', $storage = null);
35
+    /**
36
+     * get a cache instance for the storage
37
+     *
38
+     * @param string $path
39
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the cache
40
+     * @return \OC\Files\Cache\Cache
41
+     */
42
+    public function getCache($path = '', $storage = null);
43 43
 
44
-	/**
45
-	 * get a scanner instance for the storage
46
-	 *
47
-	 * @param string $path
48
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
49
-	 * @return \OC\Files\Cache\Scanner
50
-	 */
51
-	public function getScanner($path = '', $storage = null);
44
+    /**
45
+     * get a scanner instance for the storage
46
+     *
47
+     * @param string $path
48
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
49
+     * @return \OC\Files\Cache\Scanner
50
+     */
51
+    public function getScanner($path = '', $storage = null);
52 52
 
53 53
 
54
-	/**
55
-	 * get the user id of the owner of a file or folder
56
-	 *
57
-	 * @param string $path
58
-	 * @return string
59
-	 */
60
-	public function getOwner($path);
54
+    /**
55
+     * get the user id of the owner of a file or folder
56
+     *
57
+     * @param string $path
58
+     * @return string
59
+     */
60
+    public function getOwner($path);
61 61
 
62
-	/**
63
-	 * get a watcher instance for the cache
64
-	 *
65
-	 * @param string $path
66
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
67
-	 * @return \OC\Files\Cache\Watcher
68
-	 */
69
-	public function getWatcher($path = '', $storage = null);
62
+    /**
63
+     * get a watcher instance for the cache
64
+     *
65
+     * @param string $path
66
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
67
+     * @return \OC\Files\Cache\Watcher
68
+     */
69
+    public function getWatcher($path = '', $storage = null);
70 70
 
71
-	/**
72
-	 * get a propagator instance for the cache
73
-	 *
74
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
75
-	 * @return \OC\Files\Cache\Propagator
76
-	 */
77
-	public function getPropagator($storage = null);
71
+    /**
72
+     * get a propagator instance for the cache
73
+     *
74
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
75
+     * @return \OC\Files\Cache\Propagator
76
+     */
77
+    public function getPropagator($storage = null);
78 78
 
79
-	/**
80
-	 * get a updater instance for the cache
81
-	 *
82
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
83
-	 * @return \OC\Files\Cache\Updater
84
-	 */
85
-	public function getUpdater($storage = null);
79
+    /**
80
+     * get a updater instance for the cache
81
+     *
82
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
83
+     * @return \OC\Files\Cache\Updater
84
+     */
85
+    public function getUpdater($storage = null);
86 86
 
87
-	/**
88
-	 * @return \OC\Files\Cache\Storage
89
-	 */
90
-	public function getStorageCache();
87
+    /**
88
+     * @return \OC\Files\Cache\Storage
89
+     */
90
+    public function getStorageCache();
91 91
 
92
-	/**
93
-	 * @param string $path
94
-	 * @return array
95
-	 */
96
-	public function getMetaData($path);
92
+    /**
93
+     * @param string $path
94
+     * @return array
95
+     */
96
+    public function getMetaData($path);
97 97
 
98
-	/**
99
-	 * @param string $path The path of the file to acquire the lock for
100
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
101
-	 * @param \OCP\Lock\ILockingProvider $provider
102
-	 * @throws \OCP\Lock\LockedException
103
-	 */
104
-	public function acquireLock($path, $type, ILockingProvider $provider);
98
+    /**
99
+     * @param string $path The path of the file to acquire the lock for
100
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
101
+     * @param \OCP\Lock\ILockingProvider $provider
102
+     * @throws \OCP\Lock\LockedException
103
+     */
104
+    public function acquireLock($path, $type, ILockingProvider $provider);
105 105
 
106
-	/**
107
-	 * @param string $path The path of the file to release the lock for
108
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
109
-	 * @param \OCP\Lock\ILockingProvider $provider
110
-	 * @throws \OCP\Lock\LockedException
111
-	 */
112
-	public function releaseLock($path, $type, ILockingProvider $provider);
106
+    /**
107
+     * @param string $path The path of the file to release the lock for
108
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
109
+     * @param \OCP\Lock\ILockingProvider $provider
110
+     * @throws \OCP\Lock\LockedException
111
+     */
112
+    public function releaseLock($path, $type, ILockingProvider $provider);
113 113
 
114
-	/**
115
-	 * @param string $path The path of the file to change the lock for
116
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
117
-	 * @param \OCP\Lock\ILockingProvider $provider
118
-	 * @throws \OCP\Lock\LockedException
119
-	 */
120
-	public function changeLock($path, $type, ILockingProvider $provider);
114
+    /**
115
+     * @param string $path The path of the file to change the lock for
116
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
117
+     * @param \OCP\Lock\ILockingProvider $provider
118
+     * @throws \OCP\Lock\LockedException
119
+     */
120
+    public function changeLock($path, $type, ILockingProvider $provider);
121 121
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/CardDavBackend.php 4 patches
Doc Comments   +11 added lines, -3 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 	/**
105 105
 	 * Return the number of address books for a principal
106 106
 	 *
107
-	 * @param $principalUri
107
+	 * @param string $principalUri
108 108
 	 * @return int
109 109
 	 */
110 110
 	public function getAddressBooksForUserCount($principalUri) {
@@ -195,6 +195,9 @@  discard block
 block discarded – undo
195 195
 		return array_values($addressBooks);
196 196
 	}
197 197
 
198
+	/**
199
+	 * @param string $principalUri
200
+	 */
198 201
 	public function getUsersOwnAddressBooks($principalUri) {
199 202
 		$principalUriOriginal = $principalUri;
200 203
 		$principalUri = $this->convertPrincipal($principalUri, true);
@@ -264,7 +267,8 @@  discard block
 block discarded – undo
264 267
 	}
265 268
 
266 269
 	/**
267
-	 * @param $addressBookUri
270
+	 * @param string $addressBookUri
271
+	 * @param string $principal
268 272
 	 * @return array|null
269 273
 	 */
270 274
 	public function getAddressBooksByUri($principal, $addressBookUri) {
@@ -953,6 +957,7 @@  discard block
 block discarded – undo
953 957
 	 *   * readOnly - boolean
954 958
 	 *   * summary - Optional, a description for the share
955 959
 	 *
960
+	 * @param integer $addressBookId
956 961
 	 * @return array
957 962
 	 */
958 963
 	public function getShares($addressBookId) {
@@ -1052,7 +1057,7 @@  discard block
 block discarded – undo
1052 1057
 
1053 1058
 	/**
1054 1059
 	 * For shared address books the sharee is set in the ACL of the address book
1055
-	 * @param $addressBookId
1060
+	 * @param integer $addressBookId
1056 1061
 	 * @param $acl
1057 1062
 	 * @return array
1058 1063
 	 */
@@ -1060,6 +1065,9 @@  discard block
 block discarded – undo
1060 1065
 		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1061 1066
 	}
1062 1067
 
1068
+	/**
1069
+	 * @param boolean $toV2
1070
+	 */
1063 1071
 	private function convertPrincipal($principalUri, $toV2) {
1064 1072
 		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1065 1073
 			list(, $name) = URLUtil::splitPath($principalUri);
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -745,7 +745,9 @@
 block discarded – undo
745 745
 		$stmt->execute([ $addressBookId ]);
746 746
 		$currentToken = $stmt->fetchColumn(0);
747 747
 
748
-		if (is_null($currentToken)) return null;
748
+		if (is_null($currentToken)) {
749
+		    return null;
750
+		}
749 751
 
750 752
 		$result = [
751 753
 			'syncToken' => $currentToken,
Please login to merge, or discard this patch.
Indentation   +1035 added lines, -1035 removed lines patch added patch discarded remove patch
@@ -48,1039 +48,1039 @@
 block discarded – undo
48 48
 
49 49
 class CardDavBackend implements BackendInterface, SyncSupport {
50 50
 
51
-	const PERSONAL_ADDRESSBOOK_URI = 'contacts';
52
-	const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
53
-
54
-	/** @var Principal */
55
-	private $principalBackend;
56
-
57
-	/** @var string */
58
-	private $dbCardsTable = 'cards';
59
-
60
-	/** @var string */
61
-	private $dbCardsPropertiesTable = 'cards_properties';
62
-
63
-	/** @var IDBConnection */
64
-	private $db;
65
-
66
-	/** @var Backend */
67
-	private $sharingBackend;
68
-
69
-	/** @var array properties to index */
70
-	public static $indexProperties = array(
71
-			'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
72
-			'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
73
-
74
-	/**
75
-	 * @var string[] Map of uid => display name
76
-	 */
77
-	protected $userDisplayNames;
78
-
79
-	/** @var IUserManager */
80
-	private $userManager;
81
-
82
-	/** @var EventDispatcherInterface */
83
-	private $dispatcher;
84
-
85
-	/**
86
-	 * CardDavBackend constructor.
87
-	 *
88
-	 * @param IDBConnection $db
89
-	 * @param Principal $principalBackend
90
-	 * @param IUserManager $userManager
91
-	 * @param EventDispatcherInterface $dispatcher
92
-	 */
93
-	public function __construct(IDBConnection $db,
94
-								Principal $principalBackend,
95
-								IUserManager $userManager,
96
-								EventDispatcherInterface $dispatcher = null) {
97
-		$this->db = $db;
98
-		$this->principalBackend = $principalBackend;
99
-		$this->userManager = $userManager;
100
-		$this->dispatcher = $dispatcher;
101
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'addressbook');
102
-	}
103
-
104
-	/**
105
-	 * Return the number of address books for a principal
106
-	 *
107
-	 * @param $principalUri
108
-	 * @return int
109
-	 */
110
-	public function getAddressBooksForUserCount($principalUri) {
111
-		$principalUri = $this->convertPrincipal($principalUri, true);
112
-		$query = $this->db->getQueryBuilder();
113
-		$query->select($query->createFunction('COUNT(*)'))
114
-			->from('addressbooks')
115
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
116
-
117
-		return (int)$query->execute()->fetchColumn();
118
-	}
119
-
120
-	/**
121
-	 * Returns the list of address books for a specific user.
122
-	 *
123
-	 * Every addressbook should have the following properties:
124
-	 *   id - an arbitrary unique id
125
-	 *   uri - the 'basename' part of the url
126
-	 *   principaluri - Same as the passed parameter
127
-	 *
128
-	 * Any additional clark-notation property may be passed besides this. Some
129
-	 * common ones are :
130
-	 *   {DAV:}displayname
131
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
132
-	 *   {http://calendarserver.org/ns/}getctag
133
-	 *
134
-	 * @param string $principalUri
135
-	 * @return array
136
-	 */
137
-	function getAddressBooksForUser($principalUri) {
138
-		$principalUriOriginal = $principalUri;
139
-		$principalUri = $this->convertPrincipal($principalUri, true);
140
-		$query = $this->db->getQueryBuilder();
141
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
142
-			->from('addressbooks')
143
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
144
-
145
-		$addressBooks = [];
146
-
147
-		$result = $query->execute();
148
-		while($row = $result->fetch()) {
149
-			$addressBooks[$row['id']] = [
150
-				'id'  => $row['id'],
151
-				'uri' => $row['uri'],
152
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
153
-				'{DAV:}displayname' => $row['displayname'],
154
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
155
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
156
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
157
-			];
158
-		}
159
-		$result->closeCursor();
160
-
161
-		// query for shared calendars
162
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
163
-		$principals[]= $principalUri;
164
-
165
-		$query = $this->db->getQueryBuilder();
166
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
167
-			->from('dav_shares', 's')
168
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
169
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
170
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
171
-			->setParameter('type', 'addressbook')
172
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173
-			->execute();
174
-
175
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
176
-		while($row = $result->fetch()) {
177
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
178
-			if (isset($addressBooks[$row['id']])) {
179
-				if ($readOnly) {
180
-					// New share can not have more permissions then the old one.
181
-					continue;
182
-				}
183
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
184
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
185
-					// Old share is already read-write, no more permissions can be gained
186
-					continue;
187
-				}
188
-			}
189
-
190
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
191
-			$uri = $row['uri'] . '_shared_by_' . $name;
192
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
193
-
194
-			$addressBooks[$row['id']] = [
195
-				'id'  => $row['id'],
196
-				'uri' => $uri,
197
-				'principaluri' => $principalUriOriginal,
198
-				'{DAV:}displayname' => $displayName,
199
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
200
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
201
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
202
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
203
-				$readOnlyPropertyName => $readOnly,
204
-			];
205
-		}
206
-		$result->closeCursor();
207
-
208
-		return array_values($addressBooks);
209
-	}
210
-
211
-	public function getUsersOwnAddressBooks($principalUri) {
212
-		$principalUriOriginal = $principalUri;
213
-		$principalUri = $this->convertPrincipal($principalUri, true);
214
-		$query = $this->db->getQueryBuilder();
215
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
216
-			  ->from('addressbooks')
217
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
218
-
219
-		$addressBooks = [];
220
-
221
-		$result = $query->execute();
222
-		while($row = $result->fetch()) {
223
-			$addressBooks[$row['id']] = [
224
-				'id'  => $row['id'],
225
-				'uri' => $row['uri'],
226
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
227
-				'{DAV:}displayname' => $row['displayname'],
228
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
229
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
230
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
231
-			];
232
-		}
233
-		$result->closeCursor();
234
-
235
-		return array_values($addressBooks);
236
-	}
237
-
238
-	private function getUserDisplayName($uid) {
239
-		if (!isset($this->userDisplayNames[$uid])) {
240
-			$user = $this->userManager->get($uid);
241
-
242
-			if ($user instanceof IUser) {
243
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
244
-			} else {
245
-				$this->userDisplayNames[$uid] = $uid;
246
-			}
247
-		}
248
-
249
-		return $this->userDisplayNames[$uid];
250
-	}
251
-
252
-	/**
253
-	 * @param int $addressBookId
254
-	 */
255
-	public function getAddressBookById($addressBookId) {
256
-		$query = $this->db->getQueryBuilder();
257
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
258
-			->from('addressbooks')
259
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
260
-			->execute();
261
-
262
-		$row = $result->fetch();
263
-		$result->closeCursor();
264
-		if ($row === false) {
265
-			return null;
266
-		}
267
-
268
-		return [
269
-			'id'  => $row['id'],
270
-			'uri' => $row['uri'],
271
-			'principaluri' => $row['principaluri'],
272
-			'{DAV:}displayname' => $row['displayname'],
273
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
274
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
275
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
276
-		];
277
-	}
278
-
279
-	/**
280
-	 * @param $addressBookUri
281
-	 * @return array|null
282
-	 */
283
-	public function getAddressBooksByUri($principal, $addressBookUri) {
284
-		$query = $this->db->getQueryBuilder();
285
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
286
-			->from('addressbooks')
287
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
288
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
289
-			->setMaxResults(1)
290
-			->execute();
291
-
292
-		$row = $result->fetch();
293
-		$result->closeCursor();
294
-		if ($row === false) {
295
-			return null;
296
-		}
297
-
298
-		return [
299
-				'id'  => $row['id'],
300
-				'uri' => $row['uri'],
301
-				'principaluri' => $row['principaluri'],
302
-				'{DAV:}displayname' => $row['displayname'],
303
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
304
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
305
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
306
-			];
307
-	}
308
-
309
-	/**
310
-	 * Updates properties for an address book.
311
-	 *
312
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
313
-	 * To do the actual updates, you must tell this object which properties
314
-	 * you're going to process with the handle() method.
315
-	 *
316
-	 * Calling the handle method is like telling the PropPatch object "I
317
-	 * promise I can handle updating this property".
318
-	 *
319
-	 * Read the PropPatch documentation for more info and examples.
320
-	 *
321
-	 * @param string $addressBookId
322
-	 * @param \Sabre\DAV\PropPatch $propPatch
323
-	 * @return void
324
-	 */
325
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
326
-		$supportedProperties = [
327
-			'{DAV:}displayname',
328
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
329
-		];
330
-
331
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
332
-
333
-			$updates = [];
334
-			foreach($mutations as $property=>$newValue) {
335
-
336
-				switch($property) {
337
-					case '{DAV:}displayname' :
338
-						$updates['displayname'] = $newValue;
339
-						break;
340
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
341
-						$updates['description'] = $newValue;
342
-						break;
343
-				}
344
-			}
345
-			$query = $this->db->getQueryBuilder();
346
-			$query->update('addressbooks');
347
-
348
-			foreach($updates as $key=>$value) {
349
-				$query->set($key, $query->createNamedParameter($value));
350
-			}
351
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
352
-			->execute();
353
-
354
-			$this->addChange($addressBookId, "", 2);
355
-
356
-			return true;
357
-
358
-		});
359
-	}
360
-
361
-	/**
362
-	 * Creates a new address book
363
-	 *
364
-	 * @param string $principalUri
365
-	 * @param string $url Just the 'basename' of the url.
366
-	 * @param array $properties
367
-	 * @return int
368
-	 * @throws BadRequest
369
-	 */
370
-	function createAddressBook($principalUri, $url, array $properties) {
371
-		$values = [
372
-			'displayname' => null,
373
-			'description' => null,
374
-			'principaluri' => $principalUri,
375
-			'uri' => $url,
376
-			'synctoken' => 1
377
-		];
378
-
379
-		foreach($properties as $property=>$newValue) {
380
-
381
-			switch($property) {
382
-				case '{DAV:}displayname' :
383
-					$values['displayname'] = $newValue;
384
-					break;
385
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
386
-					$values['description'] = $newValue;
387
-					break;
388
-				default :
389
-					throw new BadRequest('Unknown property: ' . $property);
390
-			}
391
-
392
-		}
393
-
394
-		// Fallback to make sure the displayname is set. Some clients may refuse
395
-		// to work with addressbooks not having a displayname.
396
-		if(is_null($values['displayname'])) {
397
-			$values['displayname'] = $url;
398
-		}
399
-
400
-		$query = $this->db->getQueryBuilder();
401
-		$query->insert('addressbooks')
402
-			->values([
403
-				'uri' => $query->createParameter('uri'),
404
-				'displayname' => $query->createParameter('displayname'),
405
-				'description' => $query->createParameter('description'),
406
-				'principaluri' => $query->createParameter('principaluri'),
407
-				'synctoken' => $query->createParameter('synctoken'),
408
-			])
409
-			->setParameters($values)
410
-			->execute();
411
-
412
-		return $query->getLastInsertId();
413
-	}
414
-
415
-	/**
416
-	 * Deletes an entire addressbook and all its contents
417
-	 *
418
-	 * @param mixed $addressBookId
419
-	 * @return void
420
-	 */
421
-	function deleteAddressBook($addressBookId) {
422
-		$query = $this->db->getQueryBuilder();
423
-		$query->delete('cards')
424
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
425
-			->setParameter('addressbookid', $addressBookId)
426
-			->execute();
427
-
428
-		$query->delete('addressbookchanges')
429
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
430
-			->setParameter('addressbookid', $addressBookId)
431
-			->execute();
432
-
433
-		$query->delete('addressbooks')
434
-			->where($query->expr()->eq('id', $query->createParameter('id')))
435
-			->setParameter('id', $addressBookId)
436
-			->execute();
437
-
438
-		$this->sharingBackend->deleteAllShares($addressBookId);
439
-
440
-		$query->delete($this->dbCardsPropertiesTable)
441
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
442
-			->execute();
443
-
444
-	}
445
-
446
-	/**
447
-	 * Returns all cards for a specific addressbook id.
448
-	 *
449
-	 * This method should return the following properties for each card:
450
-	 *   * carddata - raw vcard data
451
-	 *   * uri - Some unique url
452
-	 *   * lastmodified - A unix timestamp
453
-	 *
454
-	 * It's recommended to also return the following properties:
455
-	 *   * etag - A unique etag. This must change every time the card changes.
456
-	 *   * size - The size of the card in bytes.
457
-	 *
458
-	 * If these last two properties are provided, less time will be spent
459
-	 * calculating them. If they are specified, you can also ommit carddata.
460
-	 * This may speed up certain requests, especially with large cards.
461
-	 *
462
-	 * @param mixed $addressBookId
463
-	 * @return array
464
-	 */
465
-	function getCards($addressBookId) {
466
-		$query = $this->db->getQueryBuilder();
467
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
468
-			->from('cards')
469
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
470
-
471
-		$cards = [];
472
-
473
-		$result = $query->execute();
474
-		while($row = $result->fetch()) {
475
-			$row['etag'] = '"' . $row['etag'] . '"';
476
-			$row['carddata'] = $this->readBlob($row['carddata']);
477
-			$cards[] = $row;
478
-		}
479
-		$result->closeCursor();
480
-
481
-		return $cards;
482
-	}
483
-
484
-	/**
485
-	 * Returns a specific card.
486
-	 *
487
-	 * The same set of properties must be returned as with getCards. The only
488
-	 * exception is that 'carddata' is absolutely required.
489
-	 *
490
-	 * If the card does not exist, you must return false.
491
-	 *
492
-	 * @param mixed $addressBookId
493
-	 * @param string $cardUri
494
-	 * @return array
495
-	 */
496
-	function getCard($addressBookId, $cardUri) {
497
-		$query = $this->db->getQueryBuilder();
498
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
499
-			->from('cards')
500
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
501
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
502
-			->setMaxResults(1);
503
-
504
-		$result = $query->execute();
505
-		$row = $result->fetch();
506
-		if (!$row) {
507
-			return false;
508
-		}
509
-		$row['etag'] = '"' . $row['etag'] . '"';
510
-		$row['carddata'] = $this->readBlob($row['carddata']);
511
-
512
-		return $row;
513
-	}
514
-
515
-	/**
516
-	 * Returns a list of cards.
517
-	 *
518
-	 * This method should work identical to getCard, but instead return all the
519
-	 * cards in the list as an array.
520
-	 *
521
-	 * If the backend supports this, it may allow for some speed-ups.
522
-	 *
523
-	 * @param mixed $addressBookId
524
-	 * @param string[] $uris
525
-	 * @return array
526
-	 */
527
-	function getMultipleCards($addressBookId, array $uris) {
528
-		if (empty($uris)) {
529
-			return [];
530
-		}
531
-
532
-		$chunks = array_chunk($uris, 100);
533
-		$cards = [];
534
-
535
-		$query = $this->db->getQueryBuilder();
536
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
537
-			->from('cards')
538
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
539
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
540
-
541
-		foreach ($chunks as $uris) {
542
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
543
-			$result = $query->execute();
544
-
545
-			while ($row = $result->fetch()) {
546
-				$row['etag'] = '"' . $row['etag'] . '"';
547
-				$row['carddata'] = $this->readBlob($row['carddata']);
548
-				$cards[] = $row;
549
-			}
550
-			$result->closeCursor();
551
-		}
552
-		return $cards;
553
-	}
554
-
555
-	/**
556
-	 * Creates a new card.
557
-	 *
558
-	 * The addressbook id will be passed as the first argument. This is the
559
-	 * same id as it is returned from the getAddressBooksForUser method.
560
-	 *
561
-	 * The cardUri is a base uri, and doesn't include the full path. The
562
-	 * cardData argument is the vcard body, and is passed as a string.
563
-	 *
564
-	 * It is possible to return an ETag from this method. This ETag is for the
565
-	 * newly created resource, and must be enclosed with double quotes (that
566
-	 * is, the string itself must contain the double quotes).
567
-	 *
568
-	 * You should only return the ETag if you store the carddata as-is. If a
569
-	 * subsequent GET request on the same card does not have the same body,
570
-	 * byte-by-byte and you did return an ETag here, clients tend to get
571
-	 * confused.
572
-	 *
573
-	 * If you don't return an ETag, you can just return null.
574
-	 *
575
-	 * @param mixed $addressBookId
576
-	 * @param string $cardUri
577
-	 * @param string $cardData
578
-	 * @return string
579
-	 */
580
-	function createCard($addressBookId, $cardUri, $cardData) {
581
-		$etag = md5($cardData);
582
-
583
-		$query = $this->db->getQueryBuilder();
584
-		$query->insert('cards')
585
-			->values([
586
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
587
-				'uri' => $query->createNamedParameter($cardUri),
588
-				'lastmodified' => $query->createNamedParameter(time()),
589
-				'addressbookid' => $query->createNamedParameter($addressBookId),
590
-				'size' => $query->createNamedParameter(strlen($cardData)),
591
-				'etag' => $query->createNamedParameter($etag),
592
-			])
593
-			->execute();
594
-
595
-		$this->addChange($addressBookId, $cardUri, 1);
596
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
597
-
598
-		if (!is_null($this->dispatcher)) {
599
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
600
-				new GenericEvent(null, [
601
-					'addressBookId' => $addressBookId,
602
-					'cardUri' => $cardUri,
603
-					'cardData' => $cardData]));
604
-		}
605
-
606
-		return '"' . $etag . '"';
607
-	}
608
-
609
-	/**
610
-	 * Updates a card.
611
-	 *
612
-	 * The addressbook id will be passed as the first argument. This is the
613
-	 * same id as it is returned from the getAddressBooksForUser method.
614
-	 *
615
-	 * The cardUri is a base uri, and doesn't include the full path. The
616
-	 * cardData argument is the vcard body, and is passed as a string.
617
-	 *
618
-	 * It is possible to return an ETag from this method. This ETag should
619
-	 * match that of the updated resource, and must be enclosed with double
620
-	 * quotes (that is: the string itself must contain the actual quotes).
621
-	 *
622
-	 * You should only return the ETag if you store the carddata as-is. If a
623
-	 * subsequent GET request on the same card does not have the same body,
624
-	 * byte-by-byte and you did return an ETag here, clients tend to get
625
-	 * confused.
626
-	 *
627
-	 * If you don't return an ETag, you can just return null.
628
-	 *
629
-	 * @param mixed $addressBookId
630
-	 * @param string $cardUri
631
-	 * @param string $cardData
632
-	 * @return string
633
-	 */
634
-	function updateCard($addressBookId, $cardUri, $cardData) {
635
-
636
-		$etag = md5($cardData);
637
-		$query = $this->db->getQueryBuilder();
638
-		$query->update('cards')
639
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
640
-			->set('lastmodified', $query->createNamedParameter(time()))
641
-			->set('size', $query->createNamedParameter(strlen($cardData)))
642
-			->set('etag', $query->createNamedParameter($etag))
643
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
644
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
645
-			->execute();
646
-
647
-		$this->addChange($addressBookId, $cardUri, 2);
648
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
649
-
650
-		if (!is_null($this->dispatcher)) {
651
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
652
-				new GenericEvent(null, [
653
-					'addressBookId' => $addressBookId,
654
-					'cardUri' => $cardUri,
655
-					'cardData' => $cardData]));
656
-		}
657
-
658
-		return '"' . $etag . '"';
659
-	}
660
-
661
-	/**
662
-	 * Deletes a card
663
-	 *
664
-	 * @param mixed $addressBookId
665
-	 * @param string $cardUri
666
-	 * @return bool
667
-	 */
668
-	function deleteCard($addressBookId, $cardUri) {
669
-		try {
670
-			$cardId = $this->getCardId($addressBookId, $cardUri);
671
-		} catch (\InvalidArgumentException $e) {
672
-			$cardId = null;
673
-		}
674
-		$query = $this->db->getQueryBuilder();
675
-		$ret = $query->delete('cards')
676
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
677
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
678
-			->execute();
679
-
680
-		$this->addChange($addressBookId, $cardUri, 3);
681
-
682
-		if (!is_null($this->dispatcher)) {
683
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
684
-				new GenericEvent(null, [
685
-					'addressBookId' => $addressBookId,
686
-					'cardUri' => $cardUri]));
687
-		}
688
-
689
-		if ($ret === 1) {
690
-			if ($cardId !== null) {
691
-				$this->purgeProperties($addressBookId, $cardId);
692
-			}
693
-			return true;
694
-		}
695
-
696
-		return false;
697
-	}
698
-
699
-	/**
700
-	 * The getChanges method returns all the changes that have happened, since
701
-	 * the specified syncToken in the specified address book.
702
-	 *
703
-	 * This function should return an array, such as the following:
704
-	 *
705
-	 * [
706
-	 *   'syncToken' => 'The current synctoken',
707
-	 *   'added'   => [
708
-	 *      'new.txt',
709
-	 *   ],
710
-	 *   'modified'   => [
711
-	 *      'modified.txt',
712
-	 *   ],
713
-	 *   'deleted' => [
714
-	 *      'foo.php.bak',
715
-	 *      'old.txt'
716
-	 *   ]
717
-	 * ];
718
-	 *
719
-	 * The returned syncToken property should reflect the *current* syncToken
720
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
721
-	 * property. This is needed here too, to ensure the operation is atomic.
722
-	 *
723
-	 * If the $syncToken argument is specified as null, this is an initial
724
-	 * sync, and all members should be reported.
725
-	 *
726
-	 * The modified property is an array of nodenames that have changed since
727
-	 * the last token.
728
-	 *
729
-	 * The deleted property is an array with nodenames, that have been deleted
730
-	 * from collection.
731
-	 *
732
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
733
-	 * 1, you only have to report changes that happened only directly in
734
-	 * immediate descendants. If it's 2, it should also include changes from
735
-	 * the nodes below the child collections. (grandchildren)
736
-	 *
737
-	 * The $limit argument allows a client to specify how many results should
738
-	 * be returned at most. If the limit is not specified, it should be treated
739
-	 * as infinite.
740
-	 *
741
-	 * If the limit (infinite or not) is higher than you're willing to return,
742
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
743
-	 *
744
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
745
-	 * return null.
746
-	 *
747
-	 * The limit is 'suggestive'. You are free to ignore it.
748
-	 *
749
-	 * @param string $addressBookId
750
-	 * @param string $syncToken
751
-	 * @param int $syncLevel
752
-	 * @param int $limit
753
-	 * @return array
754
-	 */
755
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
756
-		// Current synctoken
757
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
758
-		$stmt->execute([ $addressBookId ]);
759
-		$currentToken = $stmt->fetchColumn(0);
760
-
761
-		if (is_null($currentToken)) return null;
762
-
763
-		$result = [
764
-			'syncToken' => $currentToken,
765
-			'added'     => [],
766
-			'modified'  => [],
767
-			'deleted'   => [],
768
-		];
769
-
770
-		if ($syncToken) {
771
-
772
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
773
-			if ($limit>0) {
774
-				$query .= " `LIMIT` " . (int)$limit;
775
-			}
776
-
777
-			// Fetching all changes
778
-			$stmt = $this->db->prepare($query);
779
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
780
-
781
-			$changes = [];
782
-
783
-			// This loop ensures that any duplicates are overwritten, only the
784
-			// last change on a node is relevant.
785
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
786
-
787
-				$changes[$row['uri']] = $row['operation'];
788
-
789
-			}
790
-
791
-			foreach($changes as $uri => $operation) {
792
-
793
-				switch($operation) {
794
-					case 1:
795
-						$result['added'][] = $uri;
796
-						break;
797
-					case 2:
798
-						$result['modified'][] = $uri;
799
-						break;
800
-					case 3:
801
-						$result['deleted'][] = $uri;
802
-						break;
803
-				}
804
-
805
-			}
806
-		} else {
807
-			// No synctoken supplied, this is the initial sync.
808
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
809
-			$stmt = $this->db->prepare($query);
810
-			$stmt->execute([$addressBookId]);
811
-
812
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
813
-		}
814
-		return $result;
815
-	}
816
-
817
-	/**
818
-	 * Adds a change record to the addressbookchanges table.
819
-	 *
820
-	 * @param mixed $addressBookId
821
-	 * @param string $objectUri
822
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
823
-	 * @return void
824
-	 */
825
-	protected function addChange($addressBookId, $objectUri, $operation) {
826
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
827
-		$stmt = $this->db->prepare($sql);
828
-		$stmt->execute([
829
-			$objectUri,
830
-			$addressBookId,
831
-			$operation,
832
-			$addressBookId
833
-		]);
834
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
835
-		$stmt->execute([
836
-			$addressBookId
837
-		]);
838
-	}
839
-
840
-	private function readBlob($cardData) {
841
-		if (is_resource($cardData)) {
842
-			return stream_get_contents($cardData);
843
-		}
844
-
845
-		return $cardData;
846
-	}
847
-
848
-	/**
849
-	 * @param IShareable $shareable
850
-	 * @param string[] $add
851
-	 * @param string[] $remove
852
-	 */
853
-	public function updateShares(IShareable $shareable, $add, $remove) {
854
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
855
-	}
856
-
857
-	/**
858
-	 * search contact
859
-	 *
860
-	 * @param int $addressBookId
861
-	 * @param string $pattern which should match within the $searchProperties
862
-	 * @param array $searchProperties defines the properties within the query pattern should match
863
-	 * @return array an array of contacts which are arrays of key-value-pairs
864
-	 */
865
-	public function search($addressBookId, $pattern, $searchProperties) {
866
-		$query = $this->db->getQueryBuilder();
867
-		$query2 = $this->db->getQueryBuilder();
868
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
869
-		foreach ($searchProperties as $property) {
870
-			$query2->orWhere(
871
-				$query2->expr()->andX(
872
-					$query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
873
-					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
874
-				)
875
-			);
876
-		}
877
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
878
-
879
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
880
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
881
-
882
-		$result = $query->execute();
883
-		$cards = $result->fetchAll();
884
-
885
-		$result->closeCursor();
886
-
887
-		return array_map(function($array) {
888
-			$array['carddata'] = $this->readBlob($array['carddata']);
889
-			return $array;
890
-		}, $cards);
891
-	}
892
-
893
-	/**
894
-	 * @param int $bookId
895
-	 * @param string $name
896
-	 * @return array
897
-	 */
898
-	public function collectCardProperties($bookId, $name) {
899
-		$query = $this->db->getQueryBuilder();
900
-		$result = $query->selectDistinct('value')
901
-			->from($this->dbCardsPropertiesTable)
902
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
903
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
904
-			->execute();
905
-
906
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
907
-		$result->closeCursor();
908
-
909
-		return $all;
910
-	}
911
-
912
-	/**
913
-	 * get URI from a given contact
914
-	 *
915
-	 * @param int $id
916
-	 * @return string
917
-	 */
918
-	public function getCardUri($id) {
919
-		$query = $this->db->getQueryBuilder();
920
-		$query->select('uri')->from($this->dbCardsTable)
921
-				->where($query->expr()->eq('id', $query->createParameter('id')))
922
-				->setParameter('id', $id);
923
-
924
-		$result = $query->execute();
925
-		$uri = $result->fetch();
926
-		$result->closeCursor();
927
-
928
-		if (!isset($uri['uri'])) {
929
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
930
-		}
931
-
932
-		return $uri['uri'];
933
-	}
934
-
935
-	/**
936
-	 * return contact with the given URI
937
-	 *
938
-	 * @param int $addressBookId
939
-	 * @param string $uri
940
-	 * @returns array
941
-	 */
942
-	public function getContact($addressBookId, $uri) {
943
-		$result = [];
944
-		$query = $this->db->getQueryBuilder();
945
-		$query->select('*')->from($this->dbCardsTable)
946
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
947
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
948
-		$queryResult = $query->execute();
949
-		$contact = $queryResult->fetch();
950
-		$queryResult->closeCursor();
951
-
952
-		if (is_array($contact)) {
953
-			$result = $contact;
954
-		}
955
-
956
-		return $result;
957
-	}
958
-
959
-	/**
960
-	 * Returns the list of people whom this address book is shared with.
961
-	 *
962
-	 * Every element in this array should have the following properties:
963
-	 *   * href - Often a mailto: address
964
-	 *   * commonName - Optional, for example a first + last name
965
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
966
-	 *   * readOnly - boolean
967
-	 *   * summary - Optional, a description for the share
968
-	 *
969
-	 * @return array
970
-	 */
971
-	public function getShares($addressBookId) {
972
-		return $this->sharingBackend->getShares($addressBookId);
973
-	}
974
-
975
-	/**
976
-	 * update properties table
977
-	 *
978
-	 * @param int $addressBookId
979
-	 * @param string $cardUri
980
-	 * @param string $vCardSerialized
981
-	 */
982
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
983
-		$cardId = $this->getCardId($addressBookId, $cardUri);
984
-		$vCard = $this->readCard($vCardSerialized);
985
-
986
-		$this->purgeProperties($addressBookId, $cardId);
987
-
988
-		$query = $this->db->getQueryBuilder();
989
-		$query->insert($this->dbCardsPropertiesTable)
990
-			->values(
991
-				[
992
-					'addressbookid' => $query->createNamedParameter($addressBookId),
993
-					'cardid' => $query->createNamedParameter($cardId),
994
-					'name' => $query->createParameter('name'),
995
-					'value' => $query->createParameter('value'),
996
-					'preferred' => $query->createParameter('preferred')
997
-				]
998
-			);
999
-
1000
-		foreach ($vCard->children() as $property) {
1001
-			if(!in_array($property->name, self::$indexProperties)) {
1002
-				continue;
1003
-			}
1004
-			$preferred = 0;
1005
-			foreach($property->parameters as $parameter) {
1006
-				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1007
-					$preferred = 1;
1008
-					break;
1009
-				}
1010
-			}
1011
-			$query->setParameter('name', $property->name);
1012
-			$query->setParameter('value', substr($property->getValue(), 0, 254));
1013
-			$query->setParameter('preferred', $preferred);
1014
-			$query->execute();
1015
-		}
1016
-	}
1017
-
1018
-	/**
1019
-	 * read vCard data into a vCard object
1020
-	 *
1021
-	 * @param string $cardData
1022
-	 * @return VCard
1023
-	 */
1024
-	protected function readCard($cardData) {
1025
-		return  Reader::read($cardData);
1026
-	}
1027
-
1028
-	/**
1029
-	 * delete all properties from a given card
1030
-	 *
1031
-	 * @param int $addressBookId
1032
-	 * @param int $cardId
1033
-	 */
1034
-	protected function purgeProperties($addressBookId, $cardId) {
1035
-		$query = $this->db->getQueryBuilder();
1036
-		$query->delete($this->dbCardsPropertiesTable)
1037
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1038
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1039
-		$query->execute();
1040
-	}
1041
-
1042
-	/**
1043
-	 * get ID from a given contact
1044
-	 *
1045
-	 * @param int $addressBookId
1046
-	 * @param string $uri
1047
-	 * @return int
1048
-	 */
1049
-	protected function getCardId($addressBookId, $uri) {
1050
-		$query = $this->db->getQueryBuilder();
1051
-		$query->select('id')->from($this->dbCardsTable)
1052
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1053
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1054
-
1055
-		$result = $query->execute();
1056
-		$cardIds = $result->fetch();
1057
-		$result->closeCursor();
1058
-
1059
-		if (!isset($cardIds['id'])) {
1060
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1061
-		}
1062
-
1063
-		return (int)$cardIds['id'];
1064
-	}
1065
-
1066
-	/**
1067
-	 * For shared address books the sharee is set in the ACL of the address book
1068
-	 * @param $addressBookId
1069
-	 * @param $acl
1070
-	 * @return array
1071
-	 */
1072
-	public function applyShareAcl($addressBookId, $acl) {
1073
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1074
-	}
1075
-
1076
-	private function convertPrincipal($principalUri, $toV2) {
1077
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1078
-			list(, $name) = URLUtil::splitPath($principalUri);
1079
-			if ($toV2 === true) {
1080
-				return "principals/users/$name";
1081
-			}
1082
-			return "principals/$name";
1083
-		}
1084
-		return $principalUri;
1085
-	}
51
+    const PERSONAL_ADDRESSBOOK_URI = 'contacts';
52
+    const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
53
+
54
+    /** @var Principal */
55
+    private $principalBackend;
56
+
57
+    /** @var string */
58
+    private $dbCardsTable = 'cards';
59
+
60
+    /** @var string */
61
+    private $dbCardsPropertiesTable = 'cards_properties';
62
+
63
+    /** @var IDBConnection */
64
+    private $db;
65
+
66
+    /** @var Backend */
67
+    private $sharingBackend;
68
+
69
+    /** @var array properties to index */
70
+    public static $indexProperties = array(
71
+            'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
72
+            'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
73
+
74
+    /**
75
+     * @var string[] Map of uid => display name
76
+     */
77
+    protected $userDisplayNames;
78
+
79
+    /** @var IUserManager */
80
+    private $userManager;
81
+
82
+    /** @var EventDispatcherInterface */
83
+    private $dispatcher;
84
+
85
+    /**
86
+     * CardDavBackend constructor.
87
+     *
88
+     * @param IDBConnection $db
89
+     * @param Principal $principalBackend
90
+     * @param IUserManager $userManager
91
+     * @param EventDispatcherInterface $dispatcher
92
+     */
93
+    public function __construct(IDBConnection $db,
94
+                                Principal $principalBackend,
95
+                                IUserManager $userManager,
96
+                                EventDispatcherInterface $dispatcher = null) {
97
+        $this->db = $db;
98
+        $this->principalBackend = $principalBackend;
99
+        $this->userManager = $userManager;
100
+        $this->dispatcher = $dispatcher;
101
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'addressbook');
102
+    }
103
+
104
+    /**
105
+     * Return the number of address books for a principal
106
+     *
107
+     * @param $principalUri
108
+     * @return int
109
+     */
110
+    public function getAddressBooksForUserCount($principalUri) {
111
+        $principalUri = $this->convertPrincipal($principalUri, true);
112
+        $query = $this->db->getQueryBuilder();
113
+        $query->select($query->createFunction('COUNT(*)'))
114
+            ->from('addressbooks')
115
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
116
+
117
+        return (int)$query->execute()->fetchColumn();
118
+    }
119
+
120
+    /**
121
+     * Returns the list of address books for a specific user.
122
+     *
123
+     * Every addressbook should have the following properties:
124
+     *   id - an arbitrary unique id
125
+     *   uri - the 'basename' part of the url
126
+     *   principaluri - Same as the passed parameter
127
+     *
128
+     * Any additional clark-notation property may be passed besides this. Some
129
+     * common ones are :
130
+     *   {DAV:}displayname
131
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
132
+     *   {http://calendarserver.org/ns/}getctag
133
+     *
134
+     * @param string $principalUri
135
+     * @return array
136
+     */
137
+    function getAddressBooksForUser($principalUri) {
138
+        $principalUriOriginal = $principalUri;
139
+        $principalUri = $this->convertPrincipal($principalUri, true);
140
+        $query = $this->db->getQueryBuilder();
141
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
142
+            ->from('addressbooks')
143
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
144
+
145
+        $addressBooks = [];
146
+
147
+        $result = $query->execute();
148
+        while($row = $result->fetch()) {
149
+            $addressBooks[$row['id']] = [
150
+                'id'  => $row['id'],
151
+                'uri' => $row['uri'],
152
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
153
+                '{DAV:}displayname' => $row['displayname'],
154
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
155
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
156
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
157
+            ];
158
+        }
159
+        $result->closeCursor();
160
+
161
+        // query for shared calendars
162
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
163
+        $principals[]= $principalUri;
164
+
165
+        $query = $this->db->getQueryBuilder();
166
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
167
+            ->from('dav_shares', 's')
168
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
169
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
170
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
171
+            ->setParameter('type', 'addressbook')
172
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173
+            ->execute();
174
+
175
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
176
+        while($row = $result->fetch()) {
177
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
178
+            if (isset($addressBooks[$row['id']])) {
179
+                if ($readOnly) {
180
+                    // New share can not have more permissions then the old one.
181
+                    continue;
182
+                }
183
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
184
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
185
+                    // Old share is already read-write, no more permissions can be gained
186
+                    continue;
187
+                }
188
+            }
189
+
190
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
191
+            $uri = $row['uri'] . '_shared_by_' . $name;
192
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
193
+
194
+            $addressBooks[$row['id']] = [
195
+                'id'  => $row['id'],
196
+                'uri' => $uri,
197
+                'principaluri' => $principalUriOriginal,
198
+                '{DAV:}displayname' => $displayName,
199
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
200
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
201
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
202
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
203
+                $readOnlyPropertyName => $readOnly,
204
+            ];
205
+        }
206
+        $result->closeCursor();
207
+
208
+        return array_values($addressBooks);
209
+    }
210
+
211
+    public function getUsersOwnAddressBooks($principalUri) {
212
+        $principalUriOriginal = $principalUri;
213
+        $principalUri = $this->convertPrincipal($principalUri, true);
214
+        $query = $this->db->getQueryBuilder();
215
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
216
+                ->from('addressbooks')
217
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
218
+
219
+        $addressBooks = [];
220
+
221
+        $result = $query->execute();
222
+        while($row = $result->fetch()) {
223
+            $addressBooks[$row['id']] = [
224
+                'id'  => $row['id'],
225
+                'uri' => $row['uri'],
226
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
227
+                '{DAV:}displayname' => $row['displayname'],
228
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
229
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
230
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
231
+            ];
232
+        }
233
+        $result->closeCursor();
234
+
235
+        return array_values($addressBooks);
236
+    }
237
+
238
+    private function getUserDisplayName($uid) {
239
+        if (!isset($this->userDisplayNames[$uid])) {
240
+            $user = $this->userManager->get($uid);
241
+
242
+            if ($user instanceof IUser) {
243
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
244
+            } else {
245
+                $this->userDisplayNames[$uid] = $uid;
246
+            }
247
+        }
248
+
249
+        return $this->userDisplayNames[$uid];
250
+    }
251
+
252
+    /**
253
+     * @param int $addressBookId
254
+     */
255
+    public function getAddressBookById($addressBookId) {
256
+        $query = $this->db->getQueryBuilder();
257
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
258
+            ->from('addressbooks')
259
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
260
+            ->execute();
261
+
262
+        $row = $result->fetch();
263
+        $result->closeCursor();
264
+        if ($row === false) {
265
+            return null;
266
+        }
267
+
268
+        return [
269
+            'id'  => $row['id'],
270
+            'uri' => $row['uri'],
271
+            'principaluri' => $row['principaluri'],
272
+            '{DAV:}displayname' => $row['displayname'],
273
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
274
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
275
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
276
+        ];
277
+    }
278
+
279
+    /**
280
+     * @param $addressBookUri
281
+     * @return array|null
282
+     */
283
+    public function getAddressBooksByUri($principal, $addressBookUri) {
284
+        $query = $this->db->getQueryBuilder();
285
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
286
+            ->from('addressbooks')
287
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
288
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
289
+            ->setMaxResults(1)
290
+            ->execute();
291
+
292
+        $row = $result->fetch();
293
+        $result->closeCursor();
294
+        if ($row === false) {
295
+            return null;
296
+        }
297
+
298
+        return [
299
+                'id'  => $row['id'],
300
+                'uri' => $row['uri'],
301
+                'principaluri' => $row['principaluri'],
302
+                '{DAV:}displayname' => $row['displayname'],
303
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
304
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
305
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
306
+            ];
307
+    }
308
+
309
+    /**
310
+     * Updates properties for an address book.
311
+     *
312
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
313
+     * To do the actual updates, you must tell this object which properties
314
+     * you're going to process with the handle() method.
315
+     *
316
+     * Calling the handle method is like telling the PropPatch object "I
317
+     * promise I can handle updating this property".
318
+     *
319
+     * Read the PropPatch documentation for more info and examples.
320
+     *
321
+     * @param string $addressBookId
322
+     * @param \Sabre\DAV\PropPatch $propPatch
323
+     * @return void
324
+     */
325
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
326
+        $supportedProperties = [
327
+            '{DAV:}displayname',
328
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
329
+        ];
330
+
331
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
332
+
333
+            $updates = [];
334
+            foreach($mutations as $property=>$newValue) {
335
+
336
+                switch($property) {
337
+                    case '{DAV:}displayname' :
338
+                        $updates['displayname'] = $newValue;
339
+                        break;
340
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
341
+                        $updates['description'] = $newValue;
342
+                        break;
343
+                }
344
+            }
345
+            $query = $this->db->getQueryBuilder();
346
+            $query->update('addressbooks');
347
+
348
+            foreach($updates as $key=>$value) {
349
+                $query->set($key, $query->createNamedParameter($value));
350
+            }
351
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
352
+            ->execute();
353
+
354
+            $this->addChange($addressBookId, "", 2);
355
+
356
+            return true;
357
+
358
+        });
359
+    }
360
+
361
+    /**
362
+     * Creates a new address book
363
+     *
364
+     * @param string $principalUri
365
+     * @param string $url Just the 'basename' of the url.
366
+     * @param array $properties
367
+     * @return int
368
+     * @throws BadRequest
369
+     */
370
+    function createAddressBook($principalUri, $url, array $properties) {
371
+        $values = [
372
+            'displayname' => null,
373
+            'description' => null,
374
+            'principaluri' => $principalUri,
375
+            'uri' => $url,
376
+            'synctoken' => 1
377
+        ];
378
+
379
+        foreach($properties as $property=>$newValue) {
380
+
381
+            switch($property) {
382
+                case '{DAV:}displayname' :
383
+                    $values['displayname'] = $newValue;
384
+                    break;
385
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
386
+                    $values['description'] = $newValue;
387
+                    break;
388
+                default :
389
+                    throw new BadRequest('Unknown property: ' . $property);
390
+            }
391
+
392
+        }
393
+
394
+        // Fallback to make sure the displayname is set. Some clients may refuse
395
+        // to work with addressbooks not having a displayname.
396
+        if(is_null($values['displayname'])) {
397
+            $values['displayname'] = $url;
398
+        }
399
+
400
+        $query = $this->db->getQueryBuilder();
401
+        $query->insert('addressbooks')
402
+            ->values([
403
+                'uri' => $query->createParameter('uri'),
404
+                'displayname' => $query->createParameter('displayname'),
405
+                'description' => $query->createParameter('description'),
406
+                'principaluri' => $query->createParameter('principaluri'),
407
+                'synctoken' => $query->createParameter('synctoken'),
408
+            ])
409
+            ->setParameters($values)
410
+            ->execute();
411
+
412
+        return $query->getLastInsertId();
413
+    }
414
+
415
+    /**
416
+     * Deletes an entire addressbook and all its contents
417
+     *
418
+     * @param mixed $addressBookId
419
+     * @return void
420
+     */
421
+    function deleteAddressBook($addressBookId) {
422
+        $query = $this->db->getQueryBuilder();
423
+        $query->delete('cards')
424
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
425
+            ->setParameter('addressbookid', $addressBookId)
426
+            ->execute();
427
+
428
+        $query->delete('addressbookchanges')
429
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
430
+            ->setParameter('addressbookid', $addressBookId)
431
+            ->execute();
432
+
433
+        $query->delete('addressbooks')
434
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
435
+            ->setParameter('id', $addressBookId)
436
+            ->execute();
437
+
438
+        $this->sharingBackend->deleteAllShares($addressBookId);
439
+
440
+        $query->delete($this->dbCardsPropertiesTable)
441
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
442
+            ->execute();
443
+
444
+    }
445
+
446
+    /**
447
+     * Returns all cards for a specific addressbook id.
448
+     *
449
+     * This method should return the following properties for each card:
450
+     *   * carddata - raw vcard data
451
+     *   * uri - Some unique url
452
+     *   * lastmodified - A unix timestamp
453
+     *
454
+     * It's recommended to also return the following properties:
455
+     *   * etag - A unique etag. This must change every time the card changes.
456
+     *   * size - The size of the card in bytes.
457
+     *
458
+     * If these last two properties are provided, less time will be spent
459
+     * calculating them. If they are specified, you can also ommit carddata.
460
+     * This may speed up certain requests, especially with large cards.
461
+     *
462
+     * @param mixed $addressBookId
463
+     * @return array
464
+     */
465
+    function getCards($addressBookId) {
466
+        $query = $this->db->getQueryBuilder();
467
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
468
+            ->from('cards')
469
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
470
+
471
+        $cards = [];
472
+
473
+        $result = $query->execute();
474
+        while($row = $result->fetch()) {
475
+            $row['etag'] = '"' . $row['etag'] . '"';
476
+            $row['carddata'] = $this->readBlob($row['carddata']);
477
+            $cards[] = $row;
478
+        }
479
+        $result->closeCursor();
480
+
481
+        return $cards;
482
+    }
483
+
484
+    /**
485
+     * Returns a specific card.
486
+     *
487
+     * The same set of properties must be returned as with getCards. The only
488
+     * exception is that 'carddata' is absolutely required.
489
+     *
490
+     * If the card does not exist, you must return false.
491
+     *
492
+     * @param mixed $addressBookId
493
+     * @param string $cardUri
494
+     * @return array
495
+     */
496
+    function getCard($addressBookId, $cardUri) {
497
+        $query = $this->db->getQueryBuilder();
498
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
499
+            ->from('cards')
500
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
501
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
502
+            ->setMaxResults(1);
503
+
504
+        $result = $query->execute();
505
+        $row = $result->fetch();
506
+        if (!$row) {
507
+            return false;
508
+        }
509
+        $row['etag'] = '"' . $row['etag'] . '"';
510
+        $row['carddata'] = $this->readBlob($row['carddata']);
511
+
512
+        return $row;
513
+    }
514
+
515
+    /**
516
+     * Returns a list of cards.
517
+     *
518
+     * This method should work identical to getCard, but instead return all the
519
+     * cards in the list as an array.
520
+     *
521
+     * If the backend supports this, it may allow for some speed-ups.
522
+     *
523
+     * @param mixed $addressBookId
524
+     * @param string[] $uris
525
+     * @return array
526
+     */
527
+    function getMultipleCards($addressBookId, array $uris) {
528
+        if (empty($uris)) {
529
+            return [];
530
+        }
531
+
532
+        $chunks = array_chunk($uris, 100);
533
+        $cards = [];
534
+
535
+        $query = $this->db->getQueryBuilder();
536
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
537
+            ->from('cards')
538
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
539
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
540
+
541
+        foreach ($chunks as $uris) {
542
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
543
+            $result = $query->execute();
544
+
545
+            while ($row = $result->fetch()) {
546
+                $row['etag'] = '"' . $row['etag'] . '"';
547
+                $row['carddata'] = $this->readBlob($row['carddata']);
548
+                $cards[] = $row;
549
+            }
550
+            $result->closeCursor();
551
+        }
552
+        return $cards;
553
+    }
554
+
555
+    /**
556
+     * Creates a new card.
557
+     *
558
+     * The addressbook id will be passed as the first argument. This is the
559
+     * same id as it is returned from the getAddressBooksForUser method.
560
+     *
561
+     * The cardUri is a base uri, and doesn't include the full path. The
562
+     * cardData argument is the vcard body, and is passed as a string.
563
+     *
564
+     * It is possible to return an ETag from this method. This ETag is for the
565
+     * newly created resource, and must be enclosed with double quotes (that
566
+     * is, the string itself must contain the double quotes).
567
+     *
568
+     * You should only return the ETag if you store the carddata as-is. If a
569
+     * subsequent GET request on the same card does not have the same body,
570
+     * byte-by-byte and you did return an ETag here, clients tend to get
571
+     * confused.
572
+     *
573
+     * If you don't return an ETag, you can just return null.
574
+     *
575
+     * @param mixed $addressBookId
576
+     * @param string $cardUri
577
+     * @param string $cardData
578
+     * @return string
579
+     */
580
+    function createCard($addressBookId, $cardUri, $cardData) {
581
+        $etag = md5($cardData);
582
+
583
+        $query = $this->db->getQueryBuilder();
584
+        $query->insert('cards')
585
+            ->values([
586
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
587
+                'uri' => $query->createNamedParameter($cardUri),
588
+                'lastmodified' => $query->createNamedParameter(time()),
589
+                'addressbookid' => $query->createNamedParameter($addressBookId),
590
+                'size' => $query->createNamedParameter(strlen($cardData)),
591
+                'etag' => $query->createNamedParameter($etag),
592
+            ])
593
+            ->execute();
594
+
595
+        $this->addChange($addressBookId, $cardUri, 1);
596
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
597
+
598
+        if (!is_null($this->dispatcher)) {
599
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
600
+                new GenericEvent(null, [
601
+                    'addressBookId' => $addressBookId,
602
+                    'cardUri' => $cardUri,
603
+                    'cardData' => $cardData]));
604
+        }
605
+
606
+        return '"' . $etag . '"';
607
+    }
608
+
609
+    /**
610
+     * Updates a card.
611
+     *
612
+     * The addressbook id will be passed as the first argument. This is the
613
+     * same id as it is returned from the getAddressBooksForUser method.
614
+     *
615
+     * The cardUri is a base uri, and doesn't include the full path. The
616
+     * cardData argument is the vcard body, and is passed as a string.
617
+     *
618
+     * It is possible to return an ETag from this method. This ETag should
619
+     * match that of the updated resource, and must be enclosed with double
620
+     * quotes (that is: the string itself must contain the actual quotes).
621
+     *
622
+     * You should only return the ETag if you store the carddata as-is. If a
623
+     * subsequent GET request on the same card does not have the same body,
624
+     * byte-by-byte and you did return an ETag here, clients tend to get
625
+     * confused.
626
+     *
627
+     * If you don't return an ETag, you can just return null.
628
+     *
629
+     * @param mixed $addressBookId
630
+     * @param string $cardUri
631
+     * @param string $cardData
632
+     * @return string
633
+     */
634
+    function updateCard($addressBookId, $cardUri, $cardData) {
635
+
636
+        $etag = md5($cardData);
637
+        $query = $this->db->getQueryBuilder();
638
+        $query->update('cards')
639
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
640
+            ->set('lastmodified', $query->createNamedParameter(time()))
641
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
642
+            ->set('etag', $query->createNamedParameter($etag))
643
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
644
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
645
+            ->execute();
646
+
647
+        $this->addChange($addressBookId, $cardUri, 2);
648
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
649
+
650
+        if (!is_null($this->dispatcher)) {
651
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
652
+                new GenericEvent(null, [
653
+                    'addressBookId' => $addressBookId,
654
+                    'cardUri' => $cardUri,
655
+                    'cardData' => $cardData]));
656
+        }
657
+
658
+        return '"' . $etag . '"';
659
+    }
660
+
661
+    /**
662
+     * Deletes a card
663
+     *
664
+     * @param mixed $addressBookId
665
+     * @param string $cardUri
666
+     * @return bool
667
+     */
668
+    function deleteCard($addressBookId, $cardUri) {
669
+        try {
670
+            $cardId = $this->getCardId($addressBookId, $cardUri);
671
+        } catch (\InvalidArgumentException $e) {
672
+            $cardId = null;
673
+        }
674
+        $query = $this->db->getQueryBuilder();
675
+        $ret = $query->delete('cards')
676
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
677
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
678
+            ->execute();
679
+
680
+        $this->addChange($addressBookId, $cardUri, 3);
681
+
682
+        if (!is_null($this->dispatcher)) {
683
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
684
+                new GenericEvent(null, [
685
+                    'addressBookId' => $addressBookId,
686
+                    'cardUri' => $cardUri]));
687
+        }
688
+
689
+        if ($ret === 1) {
690
+            if ($cardId !== null) {
691
+                $this->purgeProperties($addressBookId, $cardId);
692
+            }
693
+            return true;
694
+        }
695
+
696
+        return false;
697
+    }
698
+
699
+    /**
700
+     * The getChanges method returns all the changes that have happened, since
701
+     * the specified syncToken in the specified address book.
702
+     *
703
+     * This function should return an array, such as the following:
704
+     *
705
+     * [
706
+     *   'syncToken' => 'The current synctoken',
707
+     *   'added'   => [
708
+     *      'new.txt',
709
+     *   ],
710
+     *   'modified'   => [
711
+     *      'modified.txt',
712
+     *   ],
713
+     *   'deleted' => [
714
+     *      'foo.php.bak',
715
+     *      'old.txt'
716
+     *   ]
717
+     * ];
718
+     *
719
+     * The returned syncToken property should reflect the *current* syncToken
720
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
721
+     * property. This is needed here too, to ensure the operation is atomic.
722
+     *
723
+     * If the $syncToken argument is specified as null, this is an initial
724
+     * sync, and all members should be reported.
725
+     *
726
+     * The modified property is an array of nodenames that have changed since
727
+     * the last token.
728
+     *
729
+     * The deleted property is an array with nodenames, that have been deleted
730
+     * from collection.
731
+     *
732
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
733
+     * 1, you only have to report changes that happened only directly in
734
+     * immediate descendants. If it's 2, it should also include changes from
735
+     * the nodes below the child collections. (grandchildren)
736
+     *
737
+     * The $limit argument allows a client to specify how many results should
738
+     * be returned at most. If the limit is not specified, it should be treated
739
+     * as infinite.
740
+     *
741
+     * If the limit (infinite or not) is higher than you're willing to return,
742
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
743
+     *
744
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
745
+     * return null.
746
+     *
747
+     * The limit is 'suggestive'. You are free to ignore it.
748
+     *
749
+     * @param string $addressBookId
750
+     * @param string $syncToken
751
+     * @param int $syncLevel
752
+     * @param int $limit
753
+     * @return array
754
+     */
755
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
756
+        // Current synctoken
757
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
758
+        $stmt->execute([ $addressBookId ]);
759
+        $currentToken = $stmt->fetchColumn(0);
760
+
761
+        if (is_null($currentToken)) return null;
762
+
763
+        $result = [
764
+            'syncToken' => $currentToken,
765
+            'added'     => [],
766
+            'modified'  => [],
767
+            'deleted'   => [],
768
+        ];
769
+
770
+        if ($syncToken) {
771
+
772
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
773
+            if ($limit>0) {
774
+                $query .= " `LIMIT` " . (int)$limit;
775
+            }
776
+
777
+            // Fetching all changes
778
+            $stmt = $this->db->prepare($query);
779
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
780
+
781
+            $changes = [];
782
+
783
+            // This loop ensures that any duplicates are overwritten, only the
784
+            // last change on a node is relevant.
785
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
786
+
787
+                $changes[$row['uri']] = $row['operation'];
788
+
789
+            }
790
+
791
+            foreach($changes as $uri => $operation) {
792
+
793
+                switch($operation) {
794
+                    case 1:
795
+                        $result['added'][] = $uri;
796
+                        break;
797
+                    case 2:
798
+                        $result['modified'][] = $uri;
799
+                        break;
800
+                    case 3:
801
+                        $result['deleted'][] = $uri;
802
+                        break;
803
+                }
804
+
805
+            }
806
+        } else {
807
+            // No synctoken supplied, this is the initial sync.
808
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
809
+            $stmt = $this->db->prepare($query);
810
+            $stmt->execute([$addressBookId]);
811
+
812
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
813
+        }
814
+        return $result;
815
+    }
816
+
817
+    /**
818
+     * Adds a change record to the addressbookchanges table.
819
+     *
820
+     * @param mixed $addressBookId
821
+     * @param string $objectUri
822
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
823
+     * @return void
824
+     */
825
+    protected function addChange($addressBookId, $objectUri, $operation) {
826
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
827
+        $stmt = $this->db->prepare($sql);
828
+        $stmt->execute([
829
+            $objectUri,
830
+            $addressBookId,
831
+            $operation,
832
+            $addressBookId
833
+        ]);
834
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
835
+        $stmt->execute([
836
+            $addressBookId
837
+        ]);
838
+    }
839
+
840
+    private function readBlob($cardData) {
841
+        if (is_resource($cardData)) {
842
+            return stream_get_contents($cardData);
843
+        }
844
+
845
+        return $cardData;
846
+    }
847
+
848
+    /**
849
+     * @param IShareable $shareable
850
+     * @param string[] $add
851
+     * @param string[] $remove
852
+     */
853
+    public function updateShares(IShareable $shareable, $add, $remove) {
854
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
855
+    }
856
+
857
+    /**
858
+     * search contact
859
+     *
860
+     * @param int $addressBookId
861
+     * @param string $pattern which should match within the $searchProperties
862
+     * @param array $searchProperties defines the properties within the query pattern should match
863
+     * @return array an array of contacts which are arrays of key-value-pairs
864
+     */
865
+    public function search($addressBookId, $pattern, $searchProperties) {
866
+        $query = $this->db->getQueryBuilder();
867
+        $query2 = $this->db->getQueryBuilder();
868
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
869
+        foreach ($searchProperties as $property) {
870
+            $query2->orWhere(
871
+                $query2->expr()->andX(
872
+                    $query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
873
+                    $query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
874
+                )
875
+            );
876
+        }
877
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
878
+
879
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
880
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
881
+
882
+        $result = $query->execute();
883
+        $cards = $result->fetchAll();
884
+
885
+        $result->closeCursor();
886
+
887
+        return array_map(function($array) {
888
+            $array['carddata'] = $this->readBlob($array['carddata']);
889
+            return $array;
890
+        }, $cards);
891
+    }
892
+
893
+    /**
894
+     * @param int $bookId
895
+     * @param string $name
896
+     * @return array
897
+     */
898
+    public function collectCardProperties($bookId, $name) {
899
+        $query = $this->db->getQueryBuilder();
900
+        $result = $query->selectDistinct('value')
901
+            ->from($this->dbCardsPropertiesTable)
902
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
903
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
904
+            ->execute();
905
+
906
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
907
+        $result->closeCursor();
908
+
909
+        return $all;
910
+    }
911
+
912
+    /**
913
+     * get URI from a given contact
914
+     *
915
+     * @param int $id
916
+     * @return string
917
+     */
918
+    public function getCardUri($id) {
919
+        $query = $this->db->getQueryBuilder();
920
+        $query->select('uri')->from($this->dbCardsTable)
921
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
922
+                ->setParameter('id', $id);
923
+
924
+        $result = $query->execute();
925
+        $uri = $result->fetch();
926
+        $result->closeCursor();
927
+
928
+        if (!isset($uri['uri'])) {
929
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
930
+        }
931
+
932
+        return $uri['uri'];
933
+    }
934
+
935
+    /**
936
+     * return contact with the given URI
937
+     *
938
+     * @param int $addressBookId
939
+     * @param string $uri
940
+     * @returns array
941
+     */
942
+    public function getContact($addressBookId, $uri) {
943
+        $result = [];
944
+        $query = $this->db->getQueryBuilder();
945
+        $query->select('*')->from($this->dbCardsTable)
946
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
947
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
948
+        $queryResult = $query->execute();
949
+        $contact = $queryResult->fetch();
950
+        $queryResult->closeCursor();
951
+
952
+        if (is_array($contact)) {
953
+            $result = $contact;
954
+        }
955
+
956
+        return $result;
957
+    }
958
+
959
+    /**
960
+     * Returns the list of people whom this address book is shared with.
961
+     *
962
+     * Every element in this array should have the following properties:
963
+     *   * href - Often a mailto: address
964
+     *   * commonName - Optional, for example a first + last name
965
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
966
+     *   * readOnly - boolean
967
+     *   * summary - Optional, a description for the share
968
+     *
969
+     * @return array
970
+     */
971
+    public function getShares($addressBookId) {
972
+        return $this->sharingBackend->getShares($addressBookId);
973
+    }
974
+
975
+    /**
976
+     * update properties table
977
+     *
978
+     * @param int $addressBookId
979
+     * @param string $cardUri
980
+     * @param string $vCardSerialized
981
+     */
982
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
983
+        $cardId = $this->getCardId($addressBookId, $cardUri);
984
+        $vCard = $this->readCard($vCardSerialized);
985
+
986
+        $this->purgeProperties($addressBookId, $cardId);
987
+
988
+        $query = $this->db->getQueryBuilder();
989
+        $query->insert($this->dbCardsPropertiesTable)
990
+            ->values(
991
+                [
992
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
993
+                    'cardid' => $query->createNamedParameter($cardId),
994
+                    'name' => $query->createParameter('name'),
995
+                    'value' => $query->createParameter('value'),
996
+                    'preferred' => $query->createParameter('preferred')
997
+                ]
998
+            );
999
+
1000
+        foreach ($vCard->children() as $property) {
1001
+            if(!in_array($property->name, self::$indexProperties)) {
1002
+                continue;
1003
+            }
1004
+            $preferred = 0;
1005
+            foreach($property->parameters as $parameter) {
1006
+                if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1007
+                    $preferred = 1;
1008
+                    break;
1009
+                }
1010
+            }
1011
+            $query->setParameter('name', $property->name);
1012
+            $query->setParameter('value', substr($property->getValue(), 0, 254));
1013
+            $query->setParameter('preferred', $preferred);
1014
+            $query->execute();
1015
+        }
1016
+    }
1017
+
1018
+    /**
1019
+     * read vCard data into a vCard object
1020
+     *
1021
+     * @param string $cardData
1022
+     * @return VCard
1023
+     */
1024
+    protected function readCard($cardData) {
1025
+        return  Reader::read($cardData);
1026
+    }
1027
+
1028
+    /**
1029
+     * delete all properties from a given card
1030
+     *
1031
+     * @param int $addressBookId
1032
+     * @param int $cardId
1033
+     */
1034
+    protected function purgeProperties($addressBookId, $cardId) {
1035
+        $query = $this->db->getQueryBuilder();
1036
+        $query->delete($this->dbCardsPropertiesTable)
1037
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1038
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1039
+        $query->execute();
1040
+    }
1041
+
1042
+    /**
1043
+     * get ID from a given contact
1044
+     *
1045
+     * @param int $addressBookId
1046
+     * @param string $uri
1047
+     * @return int
1048
+     */
1049
+    protected function getCardId($addressBookId, $uri) {
1050
+        $query = $this->db->getQueryBuilder();
1051
+        $query->select('id')->from($this->dbCardsTable)
1052
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1053
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1054
+
1055
+        $result = $query->execute();
1056
+        $cardIds = $result->fetch();
1057
+        $result->closeCursor();
1058
+
1059
+        if (!isset($cardIds['id'])) {
1060
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1061
+        }
1062
+
1063
+        return (int)$cardIds['id'];
1064
+    }
1065
+
1066
+    /**
1067
+     * For shared address books the sharee is set in the ACL of the address book
1068
+     * @param $addressBookId
1069
+     * @param $acl
1070
+     * @return array
1071
+     */
1072
+    public function applyShareAcl($addressBookId, $acl) {
1073
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1074
+    }
1075
+
1076
+    private function convertPrincipal($principalUri, $toV2) {
1077
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1078
+            list(, $name) = URLUtil::splitPath($principalUri);
1079
+            if ($toV2 === true) {
1080
+                return "principals/users/$name";
1081
+            }
1082
+            return "principals/$name";
1083
+        }
1084
+        return $principalUri;
1085
+    }
1086 1086
 }
Please login to merge, or discard this patch.
Spacing   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 			->from('addressbooks')
115 115
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
116 116
 
117
-		return (int)$query->execute()->fetchColumn();
117
+		return (int) $query->execute()->fetchColumn();
118 118
 	}
119 119
 
120 120
 	/**
@@ -145,22 +145,22 @@  discard block
 block discarded – undo
145 145
 		$addressBooks = [];
146 146
 
147 147
 		$result = $query->execute();
148
-		while($row = $result->fetch()) {
148
+		while ($row = $result->fetch()) {
149 149
 			$addressBooks[$row['id']] = [
150 150
 				'id'  => $row['id'],
151 151
 				'uri' => $row['uri'],
152 152
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
153 153
 				'{DAV:}displayname' => $row['displayname'],
154
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
154
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
155 155
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
156
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
156
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
157 157
 			];
158 158
 		}
159 159
 		$result->closeCursor();
160 160
 
161 161
 		// query for shared calendars
162 162
 		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
163
-		$principals[]= $principalUri;
163
+		$principals[] = $principalUri;
164 164
 
165 165
 		$query = $this->db->getQueryBuilder();
166 166
 		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
@@ -172,8 +172,8 @@  discard block
 block discarded – undo
172 172
 			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173 173
 			->execute();
174 174
 
175
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
176
-		while($row = $result->fetch()) {
175
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
176
+		while ($row = $result->fetch()) {
177 177
 			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
178 178
 			if (isset($addressBooks[$row['id']])) {
179 179
 				if ($readOnly) {
@@ -188,18 +188,18 @@  discard block
 block discarded – undo
188 188
 			}
189 189
 
190 190
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
191
-			$uri = $row['uri'] . '_shared_by_' . $name;
192
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
191
+			$uri = $row['uri'].'_shared_by_'.$name;
192
+			$displayName = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
193 193
 
194 194
 			$addressBooks[$row['id']] = [
195 195
 				'id'  => $row['id'],
196 196
 				'uri' => $uri,
197 197
 				'principaluri' => $principalUriOriginal,
198 198
 				'{DAV:}displayname' => $displayName,
199
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
199
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
200 200
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
201
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
202
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
201
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
202
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $row['principaluri'],
203 203
 				$readOnlyPropertyName => $readOnly,
204 204
 			];
205 205
 		}
@@ -219,15 +219,15 @@  discard block
 block discarded – undo
219 219
 		$addressBooks = [];
220 220
 
221 221
 		$result = $query->execute();
222
-		while($row = $result->fetch()) {
222
+		while ($row = $result->fetch()) {
223 223
 			$addressBooks[$row['id']] = [
224 224
 				'id'  => $row['id'],
225 225
 				'uri' => $row['uri'],
226 226
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
227 227
 				'{DAV:}displayname' => $row['displayname'],
228
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
228
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
229 229
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
230
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
230
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
231 231
 			];
232 232
 		}
233 233
 		$result->closeCursor();
@@ -270,9 +270,9 @@  discard block
 block discarded – undo
270 270
 			'uri' => $row['uri'],
271 271
 			'principaluri' => $row['principaluri'],
272 272
 			'{DAV:}displayname' => $row['displayname'],
273
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
273
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
274 274
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
275
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
275
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
276 276
 		];
277 277
 	}
278 278
 
@@ -300,9 +300,9 @@  discard block
 block discarded – undo
300 300
 				'uri' => $row['uri'],
301 301
 				'principaluri' => $row['principaluri'],
302 302
 				'{DAV:}displayname' => $row['displayname'],
303
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
303
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
304 304
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
305
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
305
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
306 306
 			];
307 307
 	}
308 308
 
@@ -325,19 +325,19 @@  discard block
 block discarded – undo
325 325
 	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
326 326
 		$supportedProperties = [
327 327
 			'{DAV:}displayname',
328
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
328
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description',
329 329
 		];
330 330
 
331 331
 		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
332 332
 
333 333
 			$updates = [];
334
-			foreach($mutations as $property=>$newValue) {
334
+			foreach ($mutations as $property=>$newValue) {
335 335
 
336
-				switch($property) {
336
+				switch ($property) {
337 337
 					case '{DAV:}displayname' :
338 338
 						$updates['displayname'] = $newValue;
339 339
 						break;
340
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
340
+					case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
341 341
 						$updates['description'] = $newValue;
342 342
 						break;
343 343
 				}
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
 			$query = $this->db->getQueryBuilder();
346 346
 			$query->update('addressbooks');
347 347
 
348
-			foreach($updates as $key=>$value) {
348
+			foreach ($updates as $key=>$value) {
349 349
 				$query->set($key, $query->createNamedParameter($value));
350 350
 			}
351 351
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
@@ -376,24 +376,24 @@  discard block
 block discarded – undo
376 376
 			'synctoken' => 1
377 377
 		];
378 378
 
379
-		foreach($properties as $property=>$newValue) {
379
+		foreach ($properties as $property=>$newValue) {
380 380
 
381
-			switch($property) {
381
+			switch ($property) {
382 382
 				case '{DAV:}displayname' :
383 383
 					$values['displayname'] = $newValue;
384 384
 					break;
385
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
385
+				case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
386 386
 					$values['description'] = $newValue;
387 387
 					break;
388 388
 				default :
389
-					throw new BadRequest('Unknown property: ' . $property);
389
+					throw new BadRequest('Unknown property: '.$property);
390 390
 			}
391 391
 
392 392
 		}
393 393
 
394 394
 		// Fallback to make sure the displayname is set. Some clients may refuse
395 395
 		// to work with addressbooks not having a displayname.
396
-		if(is_null($values['displayname'])) {
396
+		if (is_null($values['displayname'])) {
397 397
 			$values['displayname'] = $url;
398 398
 		}
399 399
 
@@ -471,8 +471,8 @@  discard block
 block discarded – undo
471 471
 		$cards = [];
472 472
 
473 473
 		$result = $query->execute();
474
-		while($row = $result->fetch()) {
475
-			$row['etag'] = '"' . $row['etag'] . '"';
474
+		while ($row = $result->fetch()) {
475
+			$row['etag'] = '"'.$row['etag'].'"';
476 476
 			$row['carddata'] = $this->readBlob($row['carddata']);
477 477
 			$cards[] = $row;
478 478
 		}
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
 		if (!$row) {
507 507
 			return false;
508 508
 		}
509
-		$row['etag'] = '"' . $row['etag'] . '"';
509
+		$row['etag'] = '"'.$row['etag'].'"';
510 510
 		$row['carddata'] = $this->readBlob($row['carddata']);
511 511
 
512 512
 		return $row;
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
 			$result = $query->execute();
544 544
 
545 545
 			while ($row = $result->fetch()) {
546
-				$row['etag'] = '"' . $row['etag'] . '"';
546
+				$row['etag'] = '"'.$row['etag'].'"';
547 547
 				$row['carddata'] = $this->readBlob($row['carddata']);
548 548
 				$cards[] = $row;
549 549
 			}
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
 					'cardData' => $cardData]));
604 604
 		}
605 605
 
606
-		return '"' . $etag . '"';
606
+		return '"'.$etag.'"';
607 607
 	}
608 608
 
609 609
 	/**
@@ -655,7 +655,7 @@  discard block
 block discarded – undo
655 655
 					'cardData' => $cardData]));
656 656
 		}
657 657
 
658
-		return '"' . $etag . '"';
658
+		return '"'.$etag.'"';
659 659
 	}
660 660
 
661 661
 	/**
@@ -755,7 +755,7 @@  discard block
 block discarded – undo
755 755
 	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
756 756
 		// Current synctoken
757 757
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
758
-		$stmt->execute([ $addressBookId ]);
758
+		$stmt->execute([$addressBookId]);
759 759
 		$currentToken = $stmt->fetchColumn(0);
760 760
 
761 761
 		if (is_null($currentToken)) return null;
@@ -770,8 +770,8 @@  discard block
 block discarded – undo
770 770
 		if ($syncToken) {
771 771
 
772 772
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
773
-			if ($limit>0) {
774
-				$query .= " `LIMIT` " . (int)$limit;
773
+			if ($limit > 0) {
774
+				$query .= " `LIMIT` ".(int) $limit;
775 775
 			}
776 776
 
777 777
 			// Fetching all changes
@@ -782,15 +782,15 @@  discard block
 block discarded – undo
782 782
 
783 783
 			// This loop ensures that any duplicates are overwritten, only the
784 784
 			// last change on a node is relevant.
785
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
785
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
786 786
 
787 787
 				$changes[$row['uri']] = $row['operation'];
788 788
 
789 789
 			}
790 790
 
791
-			foreach($changes as $uri => $operation) {
791
+			foreach ($changes as $uri => $operation) {
792 792
 
793
-				switch($operation) {
793
+				switch ($operation) {
794 794
 					case 1:
795 795
 						$result['added'][] = $uri;
796 796
 						break;
@@ -870,7 +870,7 @@  discard block
 block discarded – undo
870 870
 			$query2->orWhere(
871 871
 				$query2->expr()->andX(
872 872
 					$query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
873
-					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
873
+					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%'))
874 874
 				)
875 875
 			);
876 876
 		}
@@ -926,7 +926,7 @@  discard block
 block discarded – undo
926 926
 		$result->closeCursor();
927 927
 
928 928
 		if (!isset($uri['uri'])) {
929
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
929
+			throw new \InvalidArgumentException('Card does not exists: '.$id);
930 930
 		}
931 931
 
932 932
 		return $uri['uri'];
@@ -998,11 +998,11 @@  discard block
 block discarded – undo
998 998
 			);
999 999
 
1000 1000
 		foreach ($vCard->children() as $property) {
1001
-			if(!in_array($property->name, self::$indexProperties)) {
1001
+			if (!in_array($property->name, self::$indexProperties)) {
1002 1002
 				continue;
1003 1003
 			}
1004 1004
 			$preferred = 0;
1005
-			foreach($property->parameters as $parameter) {
1005
+			foreach ($property->parameters as $parameter) {
1006 1006
 				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1007 1007
 					$preferred = 1;
1008 1008
 					break;
@@ -1057,10 +1057,10 @@  discard block
 block discarded – undo
1057 1057
 		$result->closeCursor();
1058 1058
 
1059 1059
 		if (!isset($cardIds['id'])) {
1060
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1060
+			throw new \InvalidArgumentException('Card does not exists: '.$uri);
1061 1061
 		}
1062 1062
 
1063
-		return (int)$cardIds['id'];
1063
+		return (int) $cardIds['id'];
1064 1064
 	}
1065 1065
 
1066 1066
 	/**
Please login to merge, or discard this patch.