Completed
Pull Request — master (#4266)
by Georg
11:33
created
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   +1039 added lines, -1039 removed lines patch added patch discarded remove patch
@@ -48,1043 +48,1043 @@
 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
-			if ($row['principaluri'] === $principalUri) {
178
-				continue;
179
-			}
180
-
181
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
182
-			if (isset($addressBooks[$row['id']])) {
183
-				if ($readOnly) {
184
-					// New share can not have more permissions then the old one.
185
-					continue;
186
-				}
187
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
188
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
189
-					// Old share is already read-write, no more permissions can be gained
190
-					continue;
191
-				}
192
-			}
193
-
194
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
195
-			$uri = $row['uri'] . '_shared_by_' . $name;
196
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
197
-
198
-			$addressBooks[$row['id']] = [
199
-				'id'  => $row['id'],
200
-				'uri' => $uri,
201
-				'principaluri' => $principalUriOriginal,
202
-				'{DAV:}displayname' => $displayName,
203
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
204
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
205
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
206
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
207
-				$readOnlyPropertyName => $readOnly,
208
-			];
209
-		}
210
-		$result->closeCursor();
211
-
212
-		return array_values($addressBooks);
213
-	}
214
-
215
-	public function getUsersOwnAddressBooks($principalUri) {
216
-		$principalUriOriginal = $principalUri;
217
-		$principalUri = $this->convertPrincipal($principalUri, true);
218
-		$query = $this->db->getQueryBuilder();
219
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
220
-			  ->from('addressbooks')
221
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
222
-
223
-		$addressBooks = [];
224
-
225
-		$result = $query->execute();
226
-		while($row = $result->fetch()) {
227
-			$addressBooks[$row['id']] = [
228
-				'id'  => $row['id'],
229
-				'uri' => $row['uri'],
230
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
231
-				'{DAV:}displayname' => $row['displayname'],
232
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
233
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
234
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
235
-			];
236
-		}
237
-		$result->closeCursor();
238
-
239
-		return array_values($addressBooks);
240
-	}
241
-
242
-	private function getUserDisplayName($uid) {
243
-		if (!isset($this->userDisplayNames[$uid])) {
244
-			$user = $this->userManager->get($uid);
245
-
246
-			if ($user instanceof IUser) {
247
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
248
-			} else {
249
-				$this->userDisplayNames[$uid] = $uid;
250
-			}
251
-		}
252
-
253
-		return $this->userDisplayNames[$uid];
254
-	}
255
-
256
-	/**
257
-	 * @param int $addressBookId
258
-	 */
259
-	public function getAddressBookById($addressBookId) {
260
-		$query = $this->db->getQueryBuilder();
261
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
262
-			->from('addressbooks')
263
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
264
-			->execute();
265
-
266
-		$row = $result->fetch();
267
-		$result->closeCursor();
268
-		if ($row === false) {
269
-			return null;
270
-		}
271
-
272
-		return [
273
-			'id'  => $row['id'],
274
-			'uri' => $row['uri'],
275
-			'principaluri' => $row['principaluri'],
276
-			'{DAV:}displayname' => $row['displayname'],
277
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
278
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
279
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
280
-		];
281
-	}
282
-
283
-	/**
284
-	 * @param $addressBookUri
285
-	 * @return array|null
286
-	 */
287
-	public function getAddressBooksByUri($principal, $addressBookUri) {
288
-		$query = $this->db->getQueryBuilder();
289
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
290
-			->from('addressbooks')
291
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
292
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
293
-			->setMaxResults(1)
294
-			->execute();
295
-
296
-		$row = $result->fetch();
297
-		$result->closeCursor();
298
-		if ($row === false) {
299
-			return null;
300
-		}
301
-
302
-		return [
303
-				'id'  => $row['id'],
304
-				'uri' => $row['uri'],
305
-				'principaluri' => $row['principaluri'],
306
-				'{DAV:}displayname' => $row['displayname'],
307
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
308
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
309
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
310
-			];
311
-	}
312
-
313
-	/**
314
-	 * Updates properties for an address book.
315
-	 *
316
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
317
-	 * To do the actual updates, you must tell this object which properties
318
-	 * you're going to process with the handle() method.
319
-	 *
320
-	 * Calling the handle method is like telling the PropPatch object "I
321
-	 * promise I can handle updating this property".
322
-	 *
323
-	 * Read the PropPatch documentation for more info and examples.
324
-	 *
325
-	 * @param string $addressBookId
326
-	 * @param \Sabre\DAV\PropPatch $propPatch
327
-	 * @return void
328
-	 */
329
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
330
-		$supportedProperties = [
331
-			'{DAV:}displayname',
332
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
333
-		];
334
-
335
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
336
-
337
-			$updates = [];
338
-			foreach($mutations as $property=>$newValue) {
339
-
340
-				switch($property) {
341
-					case '{DAV:}displayname' :
342
-						$updates['displayname'] = $newValue;
343
-						break;
344
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
345
-						$updates['description'] = $newValue;
346
-						break;
347
-				}
348
-			}
349
-			$query = $this->db->getQueryBuilder();
350
-			$query->update('addressbooks');
351
-
352
-			foreach($updates as $key=>$value) {
353
-				$query->set($key, $query->createNamedParameter($value));
354
-			}
355
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
356
-			->execute();
357
-
358
-			$this->addChange($addressBookId, "", 2);
359
-
360
-			return true;
361
-
362
-		});
363
-	}
364
-
365
-	/**
366
-	 * Creates a new address book
367
-	 *
368
-	 * @param string $principalUri
369
-	 * @param string $url Just the 'basename' of the url.
370
-	 * @param array $properties
371
-	 * @return int
372
-	 * @throws BadRequest
373
-	 */
374
-	function createAddressBook($principalUri, $url, array $properties) {
375
-		$values = [
376
-			'displayname' => null,
377
-			'description' => null,
378
-			'principaluri' => $principalUri,
379
-			'uri' => $url,
380
-			'synctoken' => 1
381
-		];
382
-
383
-		foreach($properties as $property=>$newValue) {
384
-
385
-			switch($property) {
386
-				case '{DAV:}displayname' :
387
-					$values['displayname'] = $newValue;
388
-					break;
389
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
390
-					$values['description'] = $newValue;
391
-					break;
392
-				default :
393
-					throw new BadRequest('Unknown property: ' . $property);
394
-			}
395
-
396
-		}
397
-
398
-		// Fallback to make sure the displayname is set. Some clients may refuse
399
-		// to work with addressbooks not having a displayname.
400
-		if(is_null($values['displayname'])) {
401
-			$values['displayname'] = $url;
402
-		}
403
-
404
-		$query = $this->db->getQueryBuilder();
405
-		$query->insert('addressbooks')
406
-			->values([
407
-				'uri' => $query->createParameter('uri'),
408
-				'displayname' => $query->createParameter('displayname'),
409
-				'description' => $query->createParameter('description'),
410
-				'principaluri' => $query->createParameter('principaluri'),
411
-				'synctoken' => $query->createParameter('synctoken'),
412
-			])
413
-			->setParameters($values)
414
-			->execute();
415
-
416
-		return $query->getLastInsertId();
417
-	}
418
-
419
-	/**
420
-	 * Deletes an entire addressbook and all its contents
421
-	 *
422
-	 * @param mixed $addressBookId
423
-	 * @return void
424
-	 */
425
-	function deleteAddressBook($addressBookId) {
426
-		$query = $this->db->getQueryBuilder();
427
-		$query->delete('cards')
428
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
429
-			->setParameter('addressbookid', $addressBookId)
430
-			->execute();
431
-
432
-		$query->delete('addressbookchanges')
433
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
434
-			->setParameter('addressbookid', $addressBookId)
435
-			->execute();
436
-
437
-		$query->delete('addressbooks')
438
-			->where($query->expr()->eq('id', $query->createParameter('id')))
439
-			->setParameter('id', $addressBookId)
440
-			->execute();
441
-
442
-		$this->sharingBackend->deleteAllShares($addressBookId);
443
-
444
-		$query->delete($this->dbCardsPropertiesTable)
445
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
446
-			->execute();
447
-
448
-	}
449
-
450
-	/**
451
-	 * Returns all cards for a specific addressbook id.
452
-	 *
453
-	 * This method should return the following properties for each card:
454
-	 *   * carddata - raw vcard data
455
-	 *   * uri - Some unique url
456
-	 *   * lastmodified - A unix timestamp
457
-	 *
458
-	 * It's recommended to also return the following properties:
459
-	 *   * etag - A unique etag. This must change every time the card changes.
460
-	 *   * size - The size of the card in bytes.
461
-	 *
462
-	 * If these last two properties are provided, less time will be spent
463
-	 * calculating them. If they are specified, you can also ommit carddata.
464
-	 * This may speed up certain requests, especially with large cards.
465
-	 *
466
-	 * @param mixed $addressBookId
467
-	 * @return array
468
-	 */
469
-	function getCards($addressBookId) {
470
-		$query = $this->db->getQueryBuilder();
471
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
472
-			->from('cards')
473
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
474
-
475
-		$cards = [];
476
-
477
-		$result = $query->execute();
478
-		while($row = $result->fetch()) {
479
-			$row['etag'] = '"' . $row['etag'] . '"';
480
-			$row['carddata'] = $this->readBlob($row['carddata']);
481
-			$cards[] = $row;
482
-		}
483
-		$result->closeCursor();
484
-
485
-		return $cards;
486
-	}
487
-
488
-	/**
489
-	 * Returns a specific card.
490
-	 *
491
-	 * The same set of properties must be returned as with getCards. The only
492
-	 * exception is that 'carddata' is absolutely required.
493
-	 *
494
-	 * If the card does not exist, you must return false.
495
-	 *
496
-	 * @param mixed $addressBookId
497
-	 * @param string $cardUri
498
-	 * @return array
499
-	 */
500
-	function getCard($addressBookId, $cardUri) {
501
-		$query = $this->db->getQueryBuilder();
502
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
503
-			->from('cards')
504
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
505
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
506
-			->setMaxResults(1);
507
-
508
-		$result = $query->execute();
509
-		$row = $result->fetch();
510
-		if (!$row) {
511
-			return false;
512
-		}
513
-		$row['etag'] = '"' . $row['etag'] . '"';
514
-		$row['carddata'] = $this->readBlob($row['carddata']);
515
-
516
-		return $row;
517
-	}
518
-
519
-	/**
520
-	 * Returns a list of cards.
521
-	 *
522
-	 * This method should work identical to getCard, but instead return all the
523
-	 * cards in the list as an array.
524
-	 *
525
-	 * If the backend supports this, it may allow for some speed-ups.
526
-	 *
527
-	 * @param mixed $addressBookId
528
-	 * @param string[] $uris
529
-	 * @return array
530
-	 */
531
-	function getMultipleCards($addressBookId, array $uris) {
532
-		if (empty($uris)) {
533
-			return [];
534
-		}
535
-
536
-		$chunks = array_chunk($uris, 100);
537
-		$cards = [];
538
-
539
-		$query = $this->db->getQueryBuilder();
540
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
541
-			->from('cards')
542
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
543
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
544
-
545
-		foreach ($chunks as $uris) {
546
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
547
-			$result = $query->execute();
548
-
549
-			while ($row = $result->fetch()) {
550
-				$row['etag'] = '"' . $row['etag'] . '"';
551
-				$row['carddata'] = $this->readBlob($row['carddata']);
552
-				$cards[] = $row;
553
-			}
554
-			$result->closeCursor();
555
-		}
556
-		return $cards;
557
-	}
558
-
559
-	/**
560
-	 * Creates a new card.
561
-	 *
562
-	 * The addressbook id will be passed as the first argument. This is the
563
-	 * same id as it is returned from the getAddressBooksForUser method.
564
-	 *
565
-	 * The cardUri is a base uri, and doesn't include the full path. The
566
-	 * cardData argument is the vcard body, and is passed as a string.
567
-	 *
568
-	 * It is possible to return an ETag from this method. This ETag is for the
569
-	 * newly created resource, and must be enclosed with double quotes (that
570
-	 * is, the string itself must contain the double quotes).
571
-	 *
572
-	 * You should only return the ETag if you store the carddata as-is. If a
573
-	 * subsequent GET request on the same card does not have the same body,
574
-	 * byte-by-byte and you did return an ETag here, clients tend to get
575
-	 * confused.
576
-	 *
577
-	 * If you don't return an ETag, you can just return null.
578
-	 *
579
-	 * @param mixed $addressBookId
580
-	 * @param string $cardUri
581
-	 * @param string $cardData
582
-	 * @return string
583
-	 */
584
-	function createCard($addressBookId, $cardUri, $cardData) {
585
-		$etag = md5($cardData);
586
-
587
-		$query = $this->db->getQueryBuilder();
588
-		$query->insert('cards')
589
-			->values([
590
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
591
-				'uri' => $query->createNamedParameter($cardUri),
592
-				'lastmodified' => $query->createNamedParameter(time()),
593
-				'addressbookid' => $query->createNamedParameter($addressBookId),
594
-				'size' => $query->createNamedParameter(strlen($cardData)),
595
-				'etag' => $query->createNamedParameter($etag),
596
-			])
597
-			->execute();
598
-
599
-		$this->addChange($addressBookId, $cardUri, 1);
600
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
601
-
602
-		if (!is_null($this->dispatcher)) {
603
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
604
-				new GenericEvent(null, [
605
-					'addressBookId' => $addressBookId,
606
-					'cardUri' => $cardUri,
607
-					'cardData' => $cardData]));
608
-		}
609
-
610
-		return '"' . $etag . '"';
611
-	}
612
-
613
-	/**
614
-	 * Updates a card.
615
-	 *
616
-	 * The addressbook id will be passed as the first argument. This is the
617
-	 * same id as it is returned from the getAddressBooksForUser method.
618
-	 *
619
-	 * The cardUri is a base uri, and doesn't include the full path. The
620
-	 * cardData argument is the vcard body, and is passed as a string.
621
-	 *
622
-	 * It is possible to return an ETag from this method. This ETag should
623
-	 * match that of the updated resource, and must be enclosed with double
624
-	 * quotes (that is: the string itself must contain the actual quotes).
625
-	 *
626
-	 * You should only return the ETag if you store the carddata as-is. If a
627
-	 * subsequent GET request on the same card does not have the same body,
628
-	 * byte-by-byte and you did return an ETag here, clients tend to get
629
-	 * confused.
630
-	 *
631
-	 * If you don't return an ETag, you can just return null.
632
-	 *
633
-	 * @param mixed $addressBookId
634
-	 * @param string $cardUri
635
-	 * @param string $cardData
636
-	 * @return string
637
-	 */
638
-	function updateCard($addressBookId, $cardUri, $cardData) {
639
-
640
-		$etag = md5($cardData);
641
-		$query = $this->db->getQueryBuilder();
642
-		$query->update('cards')
643
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
644
-			->set('lastmodified', $query->createNamedParameter(time()))
645
-			->set('size', $query->createNamedParameter(strlen($cardData)))
646
-			->set('etag', $query->createNamedParameter($etag))
647
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
648
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
649
-			->execute();
650
-
651
-		$this->addChange($addressBookId, $cardUri, 2);
652
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
653
-
654
-		if (!is_null($this->dispatcher)) {
655
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
656
-				new GenericEvent(null, [
657
-					'addressBookId' => $addressBookId,
658
-					'cardUri' => $cardUri,
659
-					'cardData' => $cardData]));
660
-		}
661
-
662
-		return '"' . $etag . '"';
663
-	}
664
-
665
-	/**
666
-	 * Deletes a card
667
-	 *
668
-	 * @param mixed $addressBookId
669
-	 * @param string $cardUri
670
-	 * @return bool
671
-	 */
672
-	function deleteCard($addressBookId, $cardUri) {
673
-		try {
674
-			$cardId = $this->getCardId($addressBookId, $cardUri);
675
-		} catch (\InvalidArgumentException $e) {
676
-			$cardId = null;
677
-		}
678
-		$query = $this->db->getQueryBuilder();
679
-		$ret = $query->delete('cards')
680
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
681
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
682
-			->execute();
683
-
684
-		$this->addChange($addressBookId, $cardUri, 3);
685
-
686
-		if (!is_null($this->dispatcher)) {
687
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
688
-				new GenericEvent(null, [
689
-					'addressBookId' => $addressBookId,
690
-					'cardUri' => $cardUri]));
691
-		}
692
-
693
-		if ($ret === 1) {
694
-			if ($cardId !== null) {
695
-				$this->purgeProperties($addressBookId, $cardId);
696
-			}
697
-			return true;
698
-		}
699
-
700
-		return false;
701
-	}
702
-
703
-	/**
704
-	 * The getChanges method returns all the changes that have happened, since
705
-	 * the specified syncToken in the specified address book.
706
-	 *
707
-	 * This function should return an array, such as the following:
708
-	 *
709
-	 * [
710
-	 *   'syncToken' => 'The current synctoken',
711
-	 *   'added'   => [
712
-	 *      'new.txt',
713
-	 *   ],
714
-	 *   'modified'   => [
715
-	 *      'modified.txt',
716
-	 *   ],
717
-	 *   'deleted' => [
718
-	 *      'foo.php.bak',
719
-	 *      'old.txt'
720
-	 *   ]
721
-	 * ];
722
-	 *
723
-	 * The returned syncToken property should reflect the *current* syncToken
724
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
725
-	 * property. This is needed here too, to ensure the operation is atomic.
726
-	 *
727
-	 * If the $syncToken argument is specified as null, this is an initial
728
-	 * sync, and all members should be reported.
729
-	 *
730
-	 * The modified property is an array of nodenames that have changed since
731
-	 * the last token.
732
-	 *
733
-	 * The deleted property is an array with nodenames, that have been deleted
734
-	 * from collection.
735
-	 *
736
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
737
-	 * 1, you only have to report changes that happened only directly in
738
-	 * immediate descendants. If it's 2, it should also include changes from
739
-	 * the nodes below the child collections. (grandchildren)
740
-	 *
741
-	 * The $limit argument allows a client to specify how many results should
742
-	 * be returned at most. If the limit is not specified, it should be treated
743
-	 * as infinite.
744
-	 *
745
-	 * If the limit (infinite or not) is higher than you're willing to return,
746
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
747
-	 *
748
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
749
-	 * return null.
750
-	 *
751
-	 * The limit is 'suggestive'. You are free to ignore it.
752
-	 *
753
-	 * @param string $addressBookId
754
-	 * @param string $syncToken
755
-	 * @param int $syncLevel
756
-	 * @param int $limit
757
-	 * @return array
758
-	 */
759
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
760
-		// Current synctoken
761
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
762
-		$stmt->execute([ $addressBookId ]);
763
-		$currentToken = $stmt->fetchColumn(0);
764
-
765
-		if (is_null($currentToken)) return null;
766
-
767
-		$result = [
768
-			'syncToken' => $currentToken,
769
-			'added'     => [],
770
-			'modified'  => [],
771
-			'deleted'   => [],
772
-		];
773
-
774
-		if ($syncToken) {
775
-
776
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
777
-			if ($limit>0) {
778
-				$query .= " `LIMIT` " . (int)$limit;
779
-			}
780
-
781
-			// Fetching all changes
782
-			$stmt = $this->db->prepare($query);
783
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
784
-
785
-			$changes = [];
786
-
787
-			// This loop ensures that any duplicates are overwritten, only the
788
-			// last change on a node is relevant.
789
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
790
-
791
-				$changes[$row['uri']] = $row['operation'];
792
-
793
-			}
794
-
795
-			foreach($changes as $uri => $operation) {
796
-
797
-				switch($operation) {
798
-					case 1:
799
-						$result['added'][] = $uri;
800
-						break;
801
-					case 2:
802
-						$result['modified'][] = $uri;
803
-						break;
804
-					case 3:
805
-						$result['deleted'][] = $uri;
806
-						break;
807
-				}
808
-
809
-			}
810
-		} else {
811
-			// No synctoken supplied, this is the initial sync.
812
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
813
-			$stmt = $this->db->prepare($query);
814
-			$stmt->execute([$addressBookId]);
815
-
816
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
817
-		}
818
-		return $result;
819
-	}
820
-
821
-	/**
822
-	 * Adds a change record to the addressbookchanges table.
823
-	 *
824
-	 * @param mixed $addressBookId
825
-	 * @param string $objectUri
826
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
827
-	 * @return void
828
-	 */
829
-	protected function addChange($addressBookId, $objectUri, $operation) {
830
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
831
-		$stmt = $this->db->prepare($sql);
832
-		$stmt->execute([
833
-			$objectUri,
834
-			$addressBookId,
835
-			$operation,
836
-			$addressBookId
837
-		]);
838
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
839
-		$stmt->execute([
840
-			$addressBookId
841
-		]);
842
-	}
843
-
844
-	private function readBlob($cardData) {
845
-		if (is_resource($cardData)) {
846
-			return stream_get_contents($cardData);
847
-		}
848
-
849
-		return $cardData;
850
-	}
851
-
852
-	/**
853
-	 * @param IShareable $shareable
854
-	 * @param string[] $add
855
-	 * @param string[] $remove
856
-	 */
857
-	public function updateShares(IShareable $shareable, $add, $remove) {
858
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
859
-	}
860
-
861
-	/**
862
-	 * search contact
863
-	 *
864
-	 * @param int $addressBookId
865
-	 * @param string $pattern which should match within the $searchProperties
866
-	 * @param array $searchProperties defines the properties within the query pattern should match
867
-	 * @return array an array of contacts which are arrays of key-value-pairs
868
-	 */
869
-	public function search($addressBookId, $pattern, $searchProperties) {
870
-		$query = $this->db->getQueryBuilder();
871
-		$query2 = $this->db->getQueryBuilder();
872
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
873
-		foreach ($searchProperties as $property) {
874
-			$query2->orWhere(
875
-				$query2->expr()->andX(
876
-					$query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
877
-					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
878
-				)
879
-			);
880
-		}
881
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
882
-
883
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
884
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
885
-
886
-		$result = $query->execute();
887
-		$cards = $result->fetchAll();
888
-
889
-		$result->closeCursor();
890
-
891
-		return array_map(function($array) {
892
-			$array['carddata'] = $this->readBlob($array['carddata']);
893
-			return $array;
894
-		}, $cards);
895
-	}
896
-
897
-	/**
898
-	 * @param int $bookId
899
-	 * @param string $name
900
-	 * @return array
901
-	 */
902
-	public function collectCardProperties($bookId, $name) {
903
-		$query = $this->db->getQueryBuilder();
904
-		$result = $query->selectDistinct('value')
905
-			->from($this->dbCardsPropertiesTable)
906
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
907
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
908
-			->execute();
909
-
910
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
911
-		$result->closeCursor();
912
-
913
-		return $all;
914
-	}
915
-
916
-	/**
917
-	 * get URI from a given contact
918
-	 *
919
-	 * @param int $id
920
-	 * @return string
921
-	 */
922
-	public function getCardUri($id) {
923
-		$query = $this->db->getQueryBuilder();
924
-		$query->select('uri')->from($this->dbCardsTable)
925
-				->where($query->expr()->eq('id', $query->createParameter('id')))
926
-				->setParameter('id', $id);
927
-
928
-		$result = $query->execute();
929
-		$uri = $result->fetch();
930
-		$result->closeCursor();
931
-
932
-		if (!isset($uri['uri'])) {
933
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
934
-		}
935
-
936
-		return $uri['uri'];
937
-	}
938
-
939
-	/**
940
-	 * return contact with the given URI
941
-	 *
942
-	 * @param int $addressBookId
943
-	 * @param string $uri
944
-	 * @returns array
945
-	 */
946
-	public function getContact($addressBookId, $uri) {
947
-		$result = [];
948
-		$query = $this->db->getQueryBuilder();
949
-		$query->select('*')->from($this->dbCardsTable)
950
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
951
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
952
-		$queryResult = $query->execute();
953
-		$contact = $queryResult->fetch();
954
-		$queryResult->closeCursor();
955
-
956
-		if (is_array($contact)) {
957
-			$result = $contact;
958
-		}
959
-
960
-		return $result;
961
-	}
962
-
963
-	/**
964
-	 * Returns the list of people whom this address book is shared with.
965
-	 *
966
-	 * Every element in this array should have the following properties:
967
-	 *   * href - Often a mailto: address
968
-	 *   * commonName - Optional, for example a first + last name
969
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
970
-	 *   * readOnly - boolean
971
-	 *   * summary - Optional, a description for the share
972
-	 *
973
-	 * @return array
974
-	 */
975
-	public function getShares($addressBookId) {
976
-		return $this->sharingBackend->getShares($addressBookId);
977
-	}
978
-
979
-	/**
980
-	 * update properties table
981
-	 *
982
-	 * @param int $addressBookId
983
-	 * @param string $cardUri
984
-	 * @param string $vCardSerialized
985
-	 */
986
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
987
-		$cardId = $this->getCardId($addressBookId, $cardUri);
988
-		$vCard = $this->readCard($vCardSerialized);
989
-
990
-		$this->purgeProperties($addressBookId, $cardId);
991
-
992
-		$query = $this->db->getQueryBuilder();
993
-		$query->insert($this->dbCardsPropertiesTable)
994
-			->values(
995
-				[
996
-					'addressbookid' => $query->createNamedParameter($addressBookId),
997
-					'cardid' => $query->createNamedParameter($cardId),
998
-					'name' => $query->createParameter('name'),
999
-					'value' => $query->createParameter('value'),
1000
-					'preferred' => $query->createParameter('preferred')
1001
-				]
1002
-			);
1003
-
1004
-		foreach ($vCard->children() as $property) {
1005
-			if(!in_array($property->name, self::$indexProperties)) {
1006
-				continue;
1007
-			}
1008
-			$preferred = 0;
1009
-			foreach($property->parameters as $parameter) {
1010
-				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1011
-					$preferred = 1;
1012
-					break;
1013
-				}
1014
-			}
1015
-			$query->setParameter('name', $property->name);
1016
-			$query->setParameter('value', substr($property->getValue(), 0, 254));
1017
-			$query->setParameter('preferred', $preferred);
1018
-			$query->execute();
1019
-		}
1020
-	}
1021
-
1022
-	/**
1023
-	 * read vCard data into a vCard object
1024
-	 *
1025
-	 * @param string $cardData
1026
-	 * @return VCard
1027
-	 */
1028
-	protected function readCard($cardData) {
1029
-		return  Reader::read($cardData);
1030
-	}
1031
-
1032
-	/**
1033
-	 * delete all properties from a given card
1034
-	 *
1035
-	 * @param int $addressBookId
1036
-	 * @param int $cardId
1037
-	 */
1038
-	protected function purgeProperties($addressBookId, $cardId) {
1039
-		$query = $this->db->getQueryBuilder();
1040
-		$query->delete($this->dbCardsPropertiesTable)
1041
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1042
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1043
-		$query->execute();
1044
-	}
1045
-
1046
-	/**
1047
-	 * get ID from a given contact
1048
-	 *
1049
-	 * @param int $addressBookId
1050
-	 * @param string $uri
1051
-	 * @return int
1052
-	 */
1053
-	protected function getCardId($addressBookId, $uri) {
1054
-		$query = $this->db->getQueryBuilder();
1055
-		$query->select('id')->from($this->dbCardsTable)
1056
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1057
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1058
-
1059
-		$result = $query->execute();
1060
-		$cardIds = $result->fetch();
1061
-		$result->closeCursor();
1062
-
1063
-		if (!isset($cardIds['id'])) {
1064
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1065
-		}
1066
-
1067
-		return (int)$cardIds['id'];
1068
-	}
1069
-
1070
-	/**
1071
-	 * For shared address books the sharee is set in the ACL of the address book
1072
-	 * @param $addressBookId
1073
-	 * @param $acl
1074
-	 * @return array
1075
-	 */
1076
-	public function applyShareAcl($addressBookId, $acl) {
1077
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1078
-	}
1079
-
1080
-	private function convertPrincipal($principalUri, $toV2) {
1081
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1082
-			list(, $name) = URLUtil::splitPath($principalUri);
1083
-			if ($toV2 === true) {
1084
-				return "principals/users/$name";
1085
-			}
1086
-			return "principals/$name";
1087
-		}
1088
-		return $principalUri;
1089
-	}
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
+            if ($row['principaluri'] === $principalUri) {
178
+                continue;
179
+            }
180
+
181
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
182
+            if (isset($addressBooks[$row['id']])) {
183
+                if ($readOnly) {
184
+                    // New share can not have more permissions then the old one.
185
+                    continue;
186
+                }
187
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
188
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
189
+                    // Old share is already read-write, no more permissions can be gained
190
+                    continue;
191
+                }
192
+            }
193
+
194
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
195
+            $uri = $row['uri'] . '_shared_by_' . $name;
196
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
197
+
198
+            $addressBooks[$row['id']] = [
199
+                'id'  => $row['id'],
200
+                'uri' => $uri,
201
+                'principaluri' => $principalUriOriginal,
202
+                '{DAV:}displayname' => $displayName,
203
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
204
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
205
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
206
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
207
+                $readOnlyPropertyName => $readOnly,
208
+            ];
209
+        }
210
+        $result->closeCursor();
211
+
212
+        return array_values($addressBooks);
213
+    }
214
+
215
+    public function getUsersOwnAddressBooks($principalUri) {
216
+        $principalUriOriginal = $principalUri;
217
+        $principalUri = $this->convertPrincipal($principalUri, true);
218
+        $query = $this->db->getQueryBuilder();
219
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
220
+                ->from('addressbooks')
221
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
222
+
223
+        $addressBooks = [];
224
+
225
+        $result = $query->execute();
226
+        while($row = $result->fetch()) {
227
+            $addressBooks[$row['id']] = [
228
+                'id'  => $row['id'],
229
+                'uri' => $row['uri'],
230
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
231
+                '{DAV:}displayname' => $row['displayname'],
232
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
233
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
234
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
235
+            ];
236
+        }
237
+        $result->closeCursor();
238
+
239
+        return array_values($addressBooks);
240
+    }
241
+
242
+    private function getUserDisplayName($uid) {
243
+        if (!isset($this->userDisplayNames[$uid])) {
244
+            $user = $this->userManager->get($uid);
245
+
246
+            if ($user instanceof IUser) {
247
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
248
+            } else {
249
+                $this->userDisplayNames[$uid] = $uid;
250
+            }
251
+        }
252
+
253
+        return $this->userDisplayNames[$uid];
254
+    }
255
+
256
+    /**
257
+     * @param int $addressBookId
258
+     */
259
+    public function getAddressBookById($addressBookId) {
260
+        $query = $this->db->getQueryBuilder();
261
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
262
+            ->from('addressbooks')
263
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
264
+            ->execute();
265
+
266
+        $row = $result->fetch();
267
+        $result->closeCursor();
268
+        if ($row === false) {
269
+            return null;
270
+        }
271
+
272
+        return [
273
+            'id'  => $row['id'],
274
+            'uri' => $row['uri'],
275
+            'principaluri' => $row['principaluri'],
276
+            '{DAV:}displayname' => $row['displayname'],
277
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
278
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
279
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
280
+        ];
281
+    }
282
+
283
+    /**
284
+     * @param $addressBookUri
285
+     * @return array|null
286
+     */
287
+    public function getAddressBooksByUri($principal, $addressBookUri) {
288
+        $query = $this->db->getQueryBuilder();
289
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
290
+            ->from('addressbooks')
291
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
292
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
293
+            ->setMaxResults(1)
294
+            ->execute();
295
+
296
+        $row = $result->fetch();
297
+        $result->closeCursor();
298
+        if ($row === false) {
299
+            return null;
300
+        }
301
+
302
+        return [
303
+                'id'  => $row['id'],
304
+                'uri' => $row['uri'],
305
+                'principaluri' => $row['principaluri'],
306
+                '{DAV:}displayname' => $row['displayname'],
307
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
308
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
309
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
310
+            ];
311
+    }
312
+
313
+    /**
314
+     * Updates properties for an address book.
315
+     *
316
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
317
+     * To do the actual updates, you must tell this object which properties
318
+     * you're going to process with the handle() method.
319
+     *
320
+     * Calling the handle method is like telling the PropPatch object "I
321
+     * promise I can handle updating this property".
322
+     *
323
+     * Read the PropPatch documentation for more info and examples.
324
+     *
325
+     * @param string $addressBookId
326
+     * @param \Sabre\DAV\PropPatch $propPatch
327
+     * @return void
328
+     */
329
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
330
+        $supportedProperties = [
331
+            '{DAV:}displayname',
332
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
333
+        ];
334
+
335
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
336
+
337
+            $updates = [];
338
+            foreach($mutations as $property=>$newValue) {
339
+
340
+                switch($property) {
341
+                    case '{DAV:}displayname' :
342
+                        $updates['displayname'] = $newValue;
343
+                        break;
344
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
345
+                        $updates['description'] = $newValue;
346
+                        break;
347
+                }
348
+            }
349
+            $query = $this->db->getQueryBuilder();
350
+            $query->update('addressbooks');
351
+
352
+            foreach($updates as $key=>$value) {
353
+                $query->set($key, $query->createNamedParameter($value));
354
+            }
355
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
356
+            ->execute();
357
+
358
+            $this->addChange($addressBookId, "", 2);
359
+
360
+            return true;
361
+
362
+        });
363
+    }
364
+
365
+    /**
366
+     * Creates a new address book
367
+     *
368
+     * @param string $principalUri
369
+     * @param string $url Just the 'basename' of the url.
370
+     * @param array $properties
371
+     * @return int
372
+     * @throws BadRequest
373
+     */
374
+    function createAddressBook($principalUri, $url, array $properties) {
375
+        $values = [
376
+            'displayname' => null,
377
+            'description' => null,
378
+            'principaluri' => $principalUri,
379
+            'uri' => $url,
380
+            'synctoken' => 1
381
+        ];
382
+
383
+        foreach($properties as $property=>$newValue) {
384
+
385
+            switch($property) {
386
+                case '{DAV:}displayname' :
387
+                    $values['displayname'] = $newValue;
388
+                    break;
389
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
390
+                    $values['description'] = $newValue;
391
+                    break;
392
+                default :
393
+                    throw new BadRequest('Unknown property: ' . $property);
394
+            }
395
+
396
+        }
397
+
398
+        // Fallback to make sure the displayname is set. Some clients may refuse
399
+        // to work with addressbooks not having a displayname.
400
+        if(is_null($values['displayname'])) {
401
+            $values['displayname'] = $url;
402
+        }
403
+
404
+        $query = $this->db->getQueryBuilder();
405
+        $query->insert('addressbooks')
406
+            ->values([
407
+                'uri' => $query->createParameter('uri'),
408
+                'displayname' => $query->createParameter('displayname'),
409
+                'description' => $query->createParameter('description'),
410
+                'principaluri' => $query->createParameter('principaluri'),
411
+                'synctoken' => $query->createParameter('synctoken'),
412
+            ])
413
+            ->setParameters($values)
414
+            ->execute();
415
+
416
+        return $query->getLastInsertId();
417
+    }
418
+
419
+    /**
420
+     * Deletes an entire addressbook and all its contents
421
+     *
422
+     * @param mixed $addressBookId
423
+     * @return void
424
+     */
425
+    function deleteAddressBook($addressBookId) {
426
+        $query = $this->db->getQueryBuilder();
427
+        $query->delete('cards')
428
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
429
+            ->setParameter('addressbookid', $addressBookId)
430
+            ->execute();
431
+
432
+        $query->delete('addressbookchanges')
433
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
434
+            ->setParameter('addressbookid', $addressBookId)
435
+            ->execute();
436
+
437
+        $query->delete('addressbooks')
438
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
439
+            ->setParameter('id', $addressBookId)
440
+            ->execute();
441
+
442
+        $this->sharingBackend->deleteAllShares($addressBookId);
443
+
444
+        $query->delete($this->dbCardsPropertiesTable)
445
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
446
+            ->execute();
447
+
448
+    }
449
+
450
+    /**
451
+     * Returns all cards for a specific addressbook id.
452
+     *
453
+     * This method should return the following properties for each card:
454
+     *   * carddata - raw vcard data
455
+     *   * uri - Some unique url
456
+     *   * lastmodified - A unix timestamp
457
+     *
458
+     * It's recommended to also return the following properties:
459
+     *   * etag - A unique etag. This must change every time the card changes.
460
+     *   * size - The size of the card in bytes.
461
+     *
462
+     * If these last two properties are provided, less time will be spent
463
+     * calculating them. If they are specified, you can also ommit carddata.
464
+     * This may speed up certain requests, especially with large cards.
465
+     *
466
+     * @param mixed $addressBookId
467
+     * @return array
468
+     */
469
+    function getCards($addressBookId) {
470
+        $query = $this->db->getQueryBuilder();
471
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
472
+            ->from('cards')
473
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
474
+
475
+        $cards = [];
476
+
477
+        $result = $query->execute();
478
+        while($row = $result->fetch()) {
479
+            $row['etag'] = '"' . $row['etag'] . '"';
480
+            $row['carddata'] = $this->readBlob($row['carddata']);
481
+            $cards[] = $row;
482
+        }
483
+        $result->closeCursor();
484
+
485
+        return $cards;
486
+    }
487
+
488
+    /**
489
+     * Returns a specific card.
490
+     *
491
+     * The same set of properties must be returned as with getCards. The only
492
+     * exception is that 'carddata' is absolutely required.
493
+     *
494
+     * If the card does not exist, you must return false.
495
+     *
496
+     * @param mixed $addressBookId
497
+     * @param string $cardUri
498
+     * @return array
499
+     */
500
+    function getCard($addressBookId, $cardUri) {
501
+        $query = $this->db->getQueryBuilder();
502
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
503
+            ->from('cards')
504
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
505
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
506
+            ->setMaxResults(1);
507
+
508
+        $result = $query->execute();
509
+        $row = $result->fetch();
510
+        if (!$row) {
511
+            return false;
512
+        }
513
+        $row['etag'] = '"' . $row['etag'] . '"';
514
+        $row['carddata'] = $this->readBlob($row['carddata']);
515
+
516
+        return $row;
517
+    }
518
+
519
+    /**
520
+     * Returns a list of cards.
521
+     *
522
+     * This method should work identical to getCard, but instead return all the
523
+     * cards in the list as an array.
524
+     *
525
+     * If the backend supports this, it may allow for some speed-ups.
526
+     *
527
+     * @param mixed $addressBookId
528
+     * @param string[] $uris
529
+     * @return array
530
+     */
531
+    function getMultipleCards($addressBookId, array $uris) {
532
+        if (empty($uris)) {
533
+            return [];
534
+        }
535
+
536
+        $chunks = array_chunk($uris, 100);
537
+        $cards = [];
538
+
539
+        $query = $this->db->getQueryBuilder();
540
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
541
+            ->from('cards')
542
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
543
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
544
+
545
+        foreach ($chunks as $uris) {
546
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
547
+            $result = $query->execute();
548
+
549
+            while ($row = $result->fetch()) {
550
+                $row['etag'] = '"' . $row['etag'] . '"';
551
+                $row['carddata'] = $this->readBlob($row['carddata']);
552
+                $cards[] = $row;
553
+            }
554
+            $result->closeCursor();
555
+        }
556
+        return $cards;
557
+    }
558
+
559
+    /**
560
+     * Creates a new card.
561
+     *
562
+     * The addressbook id will be passed as the first argument. This is the
563
+     * same id as it is returned from the getAddressBooksForUser method.
564
+     *
565
+     * The cardUri is a base uri, and doesn't include the full path. The
566
+     * cardData argument is the vcard body, and is passed as a string.
567
+     *
568
+     * It is possible to return an ETag from this method. This ETag is for the
569
+     * newly created resource, and must be enclosed with double quotes (that
570
+     * is, the string itself must contain the double quotes).
571
+     *
572
+     * You should only return the ETag if you store the carddata as-is. If a
573
+     * subsequent GET request on the same card does not have the same body,
574
+     * byte-by-byte and you did return an ETag here, clients tend to get
575
+     * confused.
576
+     *
577
+     * If you don't return an ETag, you can just return null.
578
+     *
579
+     * @param mixed $addressBookId
580
+     * @param string $cardUri
581
+     * @param string $cardData
582
+     * @return string
583
+     */
584
+    function createCard($addressBookId, $cardUri, $cardData) {
585
+        $etag = md5($cardData);
586
+
587
+        $query = $this->db->getQueryBuilder();
588
+        $query->insert('cards')
589
+            ->values([
590
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
591
+                'uri' => $query->createNamedParameter($cardUri),
592
+                'lastmodified' => $query->createNamedParameter(time()),
593
+                'addressbookid' => $query->createNamedParameter($addressBookId),
594
+                'size' => $query->createNamedParameter(strlen($cardData)),
595
+                'etag' => $query->createNamedParameter($etag),
596
+            ])
597
+            ->execute();
598
+
599
+        $this->addChange($addressBookId, $cardUri, 1);
600
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
601
+
602
+        if (!is_null($this->dispatcher)) {
603
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
604
+                new GenericEvent(null, [
605
+                    'addressBookId' => $addressBookId,
606
+                    'cardUri' => $cardUri,
607
+                    'cardData' => $cardData]));
608
+        }
609
+
610
+        return '"' . $etag . '"';
611
+    }
612
+
613
+    /**
614
+     * Updates a card.
615
+     *
616
+     * The addressbook id will be passed as the first argument. This is the
617
+     * same id as it is returned from the getAddressBooksForUser method.
618
+     *
619
+     * The cardUri is a base uri, and doesn't include the full path. The
620
+     * cardData argument is the vcard body, and is passed as a string.
621
+     *
622
+     * It is possible to return an ETag from this method. This ETag should
623
+     * match that of the updated resource, and must be enclosed with double
624
+     * quotes (that is: the string itself must contain the actual quotes).
625
+     *
626
+     * You should only return the ETag if you store the carddata as-is. If a
627
+     * subsequent GET request on the same card does not have the same body,
628
+     * byte-by-byte and you did return an ETag here, clients tend to get
629
+     * confused.
630
+     *
631
+     * If you don't return an ETag, you can just return null.
632
+     *
633
+     * @param mixed $addressBookId
634
+     * @param string $cardUri
635
+     * @param string $cardData
636
+     * @return string
637
+     */
638
+    function updateCard($addressBookId, $cardUri, $cardData) {
639
+
640
+        $etag = md5($cardData);
641
+        $query = $this->db->getQueryBuilder();
642
+        $query->update('cards')
643
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
644
+            ->set('lastmodified', $query->createNamedParameter(time()))
645
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
646
+            ->set('etag', $query->createNamedParameter($etag))
647
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
648
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
649
+            ->execute();
650
+
651
+        $this->addChange($addressBookId, $cardUri, 2);
652
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
653
+
654
+        if (!is_null($this->dispatcher)) {
655
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
656
+                new GenericEvent(null, [
657
+                    'addressBookId' => $addressBookId,
658
+                    'cardUri' => $cardUri,
659
+                    'cardData' => $cardData]));
660
+        }
661
+
662
+        return '"' . $etag . '"';
663
+    }
664
+
665
+    /**
666
+     * Deletes a card
667
+     *
668
+     * @param mixed $addressBookId
669
+     * @param string $cardUri
670
+     * @return bool
671
+     */
672
+    function deleteCard($addressBookId, $cardUri) {
673
+        try {
674
+            $cardId = $this->getCardId($addressBookId, $cardUri);
675
+        } catch (\InvalidArgumentException $e) {
676
+            $cardId = null;
677
+        }
678
+        $query = $this->db->getQueryBuilder();
679
+        $ret = $query->delete('cards')
680
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
681
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
682
+            ->execute();
683
+
684
+        $this->addChange($addressBookId, $cardUri, 3);
685
+
686
+        if (!is_null($this->dispatcher)) {
687
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
688
+                new GenericEvent(null, [
689
+                    'addressBookId' => $addressBookId,
690
+                    'cardUri' => $cardUri]));
691
+        }
692
+
693
+        if ($ret === 1) {
694
+            if ($cardId !== null) {
695
+                $this->purgeProperties($addressBookId, $cardId);
696
+            }
697
+            return true;
698
+        }
699
+
700
+        return false;
701
+    }
702
+
703
+    /**
704
+     * The getChanges method returns all the changes that have happened, since
705
+     * the specified syncToken in the specified address book.
706
+     *
707
+     * This function should return an array, such as the following:
708
+     *
709
+     * [
710
+     *   'syncToken' => 'The current synctoken',
711
+     *   'added'   => [
712
+     *      'new.txt',
713
+     *   ],
714
+     *   'modified'   => [
715
+     *      'modified.txt',
716
+     *   ],
717
+     *   'deleted' => [
718
+     *      'foo.php.bak',
719
+     *      'old.txt'
720
+     *   ]
721
+     * ];
722
+     *
723
+     * The returned syncToken property should reflect the *current* syncToken
724
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
725
+     * property. This is needed here too, to ensure the operation is atomic.
726
+     *
727
+     * If the $syncToken argument is specified as null, this is an initial
728
+     * sync, and all members should be reported.
729
+     *
730
+     * The modified property is an array of nodenames that have changed since
731
+     * the last token.
732
+     *
733
+     * The deleted property is an array with nodenames, that have been deleted
734
+     * from collection.
735
+     *
736
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
737
+     * 1, you only have to report changes that happened only directly in
738
+     * immediate descendants. If it's 2, it should also include changes from
739
+     * the nodes below the child collections. (grandchildren)
740
+     *
741
+     * The $limit argument allows a client to specify how many results should
742
+     * be returned at most. If the limit is not specified, it should be treated
743
+     * as infinite.
744
+     *
745
+     * If the limit (infinite or not) is higher than you're willing to return,
746
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
747
+     *
748
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
749
+     * return null.
750
+     *
751
+     * The limit is 'suggestive'. You are free to ignore it.
752
+     *
753
+     * @param string $addressBookId
754
+     * @param string $syncToken
755
+     * @param int $syncLevel
756
+     * @param int $limit
757
+     * @return array
758
+     */
759
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
760
+        // Current synctoken
761
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
762
+        $stmt->execute([ $addressBookId ]);
763
+        $currentToken = $stmt->fetchColumn(0);
764
+
765
+        if (is_null($currentToken)) return null;
766
+
767
+        $result = [
768
+            'syncToken' => $currentToken,
769
+            'added'     => [],
770
+            'modified'  => [],
771
+            'deleted'   => [],
772
+        ];
773
+
774
+        if ($syncToken) {
775
+
776
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
777
+            if ($limit>0) {
778
+                $query .= " `LIMIT` " . (int)$limit;
779
+            }
780
+
781
+            // Fetching all changes
782
+            $stmt = $this->db->prepare($query);
783
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
784
+
785
+            $changes = [];
786
+
787
+            // This loop ensures that any duplicates are overwritten, only the
788
+            // last change on a node is relevant.
789
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
790
+
791
+                $changes[$row['uri']] = $row['operation'];
792
+
793
+            }
794
+
795
+            foreach($changes as $uri => $operation) {
796
+
797
+                switch($operation) {
798
+                    case 1:
799
+                        $result['added'][] = $uri;
800
+                        break;
801
+                    case 2:
802
+                        $result['modified'][] = $uri;
803
+                        break;
804
+                    case 3:
805
+                        $result['deleted'][] = $uri;
806
+                        break;
807
+                }
808
+
809
+            }
810
+        } else {
811
+            // No synctoken supplied, this is the initial sync.
812
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
813
+            $stmt = $this->db->prepare($query);
814
+            $stmt->execute([$addressBookId]);
815
+
816
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
817
+        }
818
+        return $result;
819
+    }
820
+
821
+    /**
822
+     * Adds a change record to the addressbookchanges table.
823
+     *
824
+     * @param mixed $addressBookId
825
+     * @param string $objectUri
826
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
827
+     * @return void
828
+     */
829
+    protected function addChange($addressBookId, $objectUri, $operation) {
830
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
831
+        $stmt = $this->db->prepare($sql);
832
+        $stmt->execute([
833
+            $objectUri,
834
+            $addressBookId,
835
+            $operation,
836
+            $addressBookId
837
+        ]);
838
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
839
+        $stmt->execute([
840
+            $addressBookId
841
+        ]);
842
+    }
843
+
844
+    private function readBlob($cardData) {
845
+        if (is_resource($cardData)) {
846
+            return stream_get_contents($cardData);
847
+        }
848
+
849
+        return $cardData;
850
+    }
851
+
852
+    /**
853
+     * @param IShareable $shareable
854
+     * @param string[] $add
855
+     * @param string[] $remove
856
+     */
857
+    public function updateShares(IShareable $shareable, $add, $remove) {
858
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
859
+    }
860
+
861
+    /**
862
+     * search contact
863
+     *
864
+     * @param int $addressBookId
865
+     * @param string $pattern which should match within the $searchProperties
866
+     * @param array $searchProperties defines the properties within the query pattern should match
867
+     * @return array an array of contacts which are arrays of key-value-pairs
868
+     */
869
+    public function search($addressBookId, $pattern, $searchProperties) {
870
+        $query = $this->db->getQueryBuilder();
871
+        $query2 = $this->db->getQueryBuilder();
872
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
873
+        foreach ($searchProperties as $property) {
874
+            $query2->orWhere(
875
+                $query2->expr()->andX(
876
+                    $query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
877
+                    $query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
878
+                )
879
+            );
880
+        }
881
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
882
+
883
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
884
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
885
+
886
+        $result = $query->execute();
887
+        $cards = $result->fetchAll();
888
+
889
+        $result->closeCursor();
890
+
891
+        return array_map(function($array) {
892
+            $array['carddata'] = $this->readBlob($array['carddata']);
893
+            return $array;
894
+        }, $cards);
895
+    }
896
+
897
+    /**
898
+     * @param int $bookId
899
+     * @param string $name
900
+     * @return array
901
+     */
902
+    public function collectCardProperties($bookId, $name) {
903
+        $query = $this->db->getQueryBuilder();
904
+        $result = $query->selectDistinct('value')
905
+            ->from($this->dbCardsPropertiesTable)
906
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
907
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
908
+            ->execute();
909
+
910
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
911
+        $result->closeCursor();
912
+
913
+        return $all;
914
+    }
915
+
916
+    /**
917
+     * get URI from a given contact
918
+     *
919
+     * @param int $id
920
+     * @return string
921
+     */
922
+    public function getCardUri($id) {
923
+        $query = $this->db->getQueryBuilder();
924
+        $query->select('uri')->from($this->dbCardsTable)
925
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
926
+                ->setParameter('id', $id);
927
+
928
+        $result = $query->execute();
929
+        $uri = $result->fetch();
930
+        $result->closeCursor();
931
+
932
+        if (!isset($uri['uri'])) {
933
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
934
+        }
935
+
936
+        return $uri['uri'];
937
+    }
938
+
939
+    /**
940
+     * return contact with the given URI
941
+     *
942
+     * @param int $addressBookId
943
+     * @param string $uri
944
+     * @returns array
945
+     */
946
+    public function getContact($addressBookId, $uri) {
947
+        $result = [];
948
+        $query = $this->db->getQueryBuilder();
949
+        $query->select('*')->from($this->dbCardsTable)
950
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
951
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
952
+        $queryResult = $query->execute();
953
+        $contact = $queryResult->fetch();
954
+        $queryResult->closeCursor();
955
+
956
+        if (is_array($contact)) {
957
+            $result = $contact;
958
+        }
959
+
960
+        return $result;
961
+    }
962
+
963
+    /**
964
+     * Returns the list of people whom this address book is shared with.
965
+     *
966
+     * Every element in this array should have the following properties:
967
+     *   * href - Often a mailto: address
968
+     *   * commonName - Optional, for example a first + last name
969
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
970
+     *   * readOnly - boolean
971
+     *   * summary - Optional, a description for the share
972
+     *
973
+     * @return array
974
+     */
975
+    public function getShares($addressBookId) {
976
+        return $this->sharingBackend->getShares($addressBookId);
977
+    }
978
+
979
+    /**
980
+     * update properties table
981
+     *
982
+     * @param int $addressBookId
983
+     * @param string $cardUri
984
+     * @param string $vCardSerialized
985
+     */
986
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
987
+        $cardId = $this->getCardId($addressBookId, $cardUri);
988
+        $vCard = $this->readCard($vCardSerialized);
989
+
990
+        $this->purgeProperties($addressBookId, $cardId);
991
+
992
+        $query = $this->db->getQueryBuilder();
993
+        $query->insert($this->dbCardsPropertiesTable)
994
+            ->values(
995
+                [
996
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
997
+                    'cardid' => $query->createNamedParameter($cardId),
998
+                    'name' => $query->createParameter('name'),
999
+                    'value' => $query->createParameter('value'),
1000
+                    'preferred' => $query->createParameter('preferred')
1001
+                ]
1002
+            );
1003
+
1004
+        foreach ($vCard->children() as $property) {
1005
+            if(!in_array($property->name, self::$indexProperties)) {
1006
+                continue;
1007
+            }
1008
+            $preferred = 0;
1009
+            foreach($property->parameters as $parameter) {
1010
+                if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1011
+                    $preferred = 1;
1012
+                    break;
1013
+                }
1014
+            }
1015
+            $query->setParameter('name', $property->name);
1016
+            $query->setParameter('value', substr($property->getValue(), 0, 254));
1017
+            $query->setParameter('preferred', $preferred);
1018
+            $query->execute();
1019
+        }
1020
+    }
1021
+
1022
+    /**
1023
+     * read vCard data into a vCard object
1024
+     *
1025
+     * @param string $cardData
1026
+     * @return VCard
1027
+     */
1028
+    protected function readCard($cardData) {
1029
+        return  Reader::read($cardData);
1030
+    }
1031
+
1032
+    /**
1033
+     * delete all properties from a given card
1034
+     *
1035
+     * @param int $addressBookId
1036
+     * @param int $cardId
1037
+     */
1038
+    protected function purgeProperties($addressBookId, $cardId) {
1039
+        $query = $this->db->getQueryBuilder();
1040
+        $query->delete($this->dbCardsPropertiesTable)
1041
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1042
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1043
+        $query->execute();
1044
+    }
1045
+
1046
+    /**
1047
+     * get ID from a given contact
1048
+     *
1049
+     * @param int $addressBookId
1050
+     * @param string $uri
1051
+     * @return int
1052
+     */
1053
+    protected function getCardId($addressBookId, $uri) {
1054
+        $query = $this->db->getQueryBuilder();
1055
+        $query->select('id')->from($this->dbCardsTable)
1056
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1057
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1058
+
1059
+        $result = $query->execute();
1060
+        $cardIds = $result->fetch();
1061
+        $result->closeCursor();
1062
+
1063
+        if (!isset($cardIds['id'])) {
1064
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1065
+        }
1066
+
1067
+        return (int)$cardIds['id'];
1068
+    }
1069
+
1070
+    /**
1071
+     * For shared address books the sharee is set in the ACL of the address book
1072
+     * @param $addressBookId
1073
+     * @param $acl
1074
+     * @return array
1075
+     */
1076
+    public function applyShareAcl($addressBookId, $acl) {
1077
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1078
+    }
1079
+
1080
+    private function convertPrincipal($principalUri, $toV2) {
1081
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1082
+            list(, $name) = URLUtil::splitPath($principalUri);
1083
+            if ($toV2 === true) {
1084
+                return "principals/users/$name";
1085
+            }
1086
+            return "principals/$name";
1087
+        }
1088
+        return $principalUri;
1089
+    }
1090 1090
 }
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
 			if ($row['principaluri'] === $principalUri) {
178 178
 				continue;
179 179
 			}
@@ -192,18 +192,18 @@  discard block
 block discarded – undo
192 192
 			}
193 193
 
194 194
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
195
-			$uri = $row['uri'] . '_shared_by_' . $name;
196
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
195
+			$uri = $row['uri'].'_shared_by_'.$name;
196
+			$displayName = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
197 197
 
198 198
 			$addressBooks[$row['id']] = [
199 199
 				'id'  => $row['id'],
200 200
 				'uri' => $uri,
201 201
 				'principaluri' => $principalUriOriginal,
202 202
 				'{DAV:}displayname' => $displayName,
203
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
203
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
204 204
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
205
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
206
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
205
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
206
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $row['principaluri'],
207 207
 				$readOnlyPropertyName => $readOnly,
208 208
 			];
209 209
 		}
@@ -223,15 +223,15 @@  discard block
 block discarded – undo
223 223
 		$addressBooks = [];
224 224
 
225 225
 		$result = $query->execute();
226
-		while($row = $result->fetch()) {
226
+		while ($row = $result->fetch()) {
227 227
 			$addressBooks[$row['id']] = [
228 228
 				'id'  => $row['id'],
229 229
 				'uri' => $row['uri'],
230 230
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
231 231
 				'{DAV:}displayname' => $row['displayname'],
232
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
232
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
233 233
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
234
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
234
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
235 235
 			];
236 236
 		}
237 237
 		$result->closeCursor();
@@ -274,9 +274,9 @@  discard block
 block discarded – undo
274 274
 			'uri' => $row['uri'],
275 275
 			'principaluri' => $row['principaluri'],
276 276
 			'{DAV:}displayname' => $row['displayname'],
277
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
277
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
278 278
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
279
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
279
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
280 280
 		];
281 281
 	}
282 282
 
@@ -304,9 +304,9 @@  discard block
 block discarded – undo
304 304
 				'uri' => $row['uri'],
305 305
 				'principaluri' => $row['principaluri'],
306 306
 				'{DAV:}displayname' => $row['displayname'],
307
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
307
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
308 308
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
309
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
309
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
310 310
 			];
311 311
 	}
312 312
 
@@ -329,19 +329,19 @@  discard block
 block discarded – undo
329 329
 	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
330 330
 		$supportedProperties = [
331 331
 			'{DAV:}displayname',
332
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
332
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description',
333 333
 		];
334 334
 
335 335
 		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
336 336
 
337 337
 			$updates = [];
338
-			foreach($mutations as $property=>$newValue) {
338
+			foreach ($mutations as $property=>$newValue) {
339 339
 
340
-				switch($property) {
340
+				switch ($property) {
341 341
 					case '{DAV:}displayname' :
342 342
 						$updates['displayname'] = $newValue;
343 343
 						break;
344
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
344
+					case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
345 345
 						$updates['description'] = $newValue;
346 346
 						break;
347 347
 				}
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
 			$query = $this->db->getQueryBuilder();
350 350
 			$query->update('addressbooks');
351 351
 
352
-			foreach($updates as $key=>$value) {
352
+			foreach ($updates as $key=>$value) {
353 353
 				$query->set($key, $query->createNamedParameter($value));
354 354
 			}
355 355
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
@@ -380,24 +380,24 @@  discard block
 block discarded – undo
380 380
 			'synctoken' => 1
381 381
 		];
382 382
 
383
-		foreach($properties as $property=>$newValue) {
383
+		foreach ($properties as $property=>$newValue) {
384 384
 
385
-			switch($property) {
385
+			switch ($property) {
386 386
 				case '{DAV:}displayname' :
387 387
 					$values['displayname'] = $newValue;
388 388
 					break;
389
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
389
+				case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
390 390
 					$values['description'] = $newValue;
391 391
 					break;
392 392
 				default :
393
-					throw new BadRequest('Unknown property: ' . $property);
393
+					throw new BadRequest('Unknown property: '.$property);
394 394
 			}
395 395
 
396 396
 		}
397 397
 
398 398
 		// Fallback to make sure the displayname is set. Some clients may refuse
399 399
 		// to work with addressbooks not having a displayname.
400
-		if(is_null($values['displayname'])) {
400
+		if (is_null($values['displayname'])) {
401 401
 			$values['displayname'] = $url;
402 402
 		}
403 403
 
@@ -475,8 +475,8 @@  discard block
 block discarded – undo
475 475
 		$cards = [];
476 476
 
477 477
 		$result = $query->execute();
478
-		while($row = $result->fetch()) {
479
-			$row['etag'] = '"' . $row['etag'] . '"';
478
+		while ($row = $result->fetch()) {
479
+			$row['etag'] = '"'.$row['etag'].'"';
480 480
 			$row['carddata'] = $this->readBlob($row['carddata']);
481 481
 			$cards[] = $row;
482 482
 		}
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
 		if (!$row) {
511 511
 			return false;
512 512
 		}
513
-		$row['etag'] = '"' . $row['etag'] . '"';
513
+		$row['etag'] = '"'.$row['etag'].'"';
514 514
 		$row['carddata'] = $this->readBlob($row['carddata']);
515 515
 
516 516
 		return $row;
@@ -547,7 +547,7 @@  discard block
 block discarded – undo
547 547
 			$result = $query->execute();
548 548
 
549 549
 			while ($row = $result->fetch()) {
550
-				$row['etag'] = '"' . $row['etag'] . '"';
550
+				$row['etag'] = '"'.$row['etag'].'"';
551 551
 				$row['carddata'] = $this->readBlob($row['carddata']);
552 552
 				$cards[] = $row;
553 553
 			}
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
 					'cardData' => $cardData]));
608 608
 		}
609 609
 
610
-		return '"' . $etag . '"';
610
+		return '"'.$etag.'"';
611 611
 	}
612 612
 
613 613
 	/**
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 					'cardData' => $cardData]));
660 660
 		}
661 661
 
662
-		return '"' . $etag . '"';
662
+		return '"'.$etag.'"';
663 663
 	}
664 664
 
665 665
 	/**
@@ -759,7 +759,7 @@  discard block
 block discarded – undo
759 759
 	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
760 760
 		// Current synctoken
761 761
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
762
-		$stmt->execute([ $addressBookId ]);
762
+		$stmt->execute([$addressBookId]);
763 763
 		$currentToken = $stmt->fetchColumn(0);
764 764
 
765 765
 		if (is_null($currentToken)) return null;
@@ -774,8 +774,8 @@  discard block
 block discarded – undo
774 774
 		if ($syncToken) {
775 775
 
776 776
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
777
-			if ($limit>0) {
778
-				$query .= " `LIMIT` " . (int)$limit;
777
+			if ($limit > 0) {
778
+				$query .= " `LIMIT` ".(int) $limit;
779 779
 			}
780 780
 
781 781
 			// Fetching all changes
@@ -786,15 +786,15 @@  discard block
 block discarded – undo
786 786
 
787 787
 			// This loop ensures that any duplicates are overwritten, only the
788 788
 			// last change on a node is relevant.
789
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
789
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
790 790
 
791 791
 				$changes[$row['uri']] = $row['operation'];
792 792
 
793 793
 			}
794 794
 
795
-			foreach($changes as $uri => $operation) {
795
+			foreach ($changes as $uri => $operation) {
796 796
 
797
-				switch($operation) {
797
+				switch ($operation) {
798 798
 					case 1:
799 799
 						$result['added'][] = $uri;
800 800
 						break;
@@ -874,7 +874,7 @@  discard block
 block discarded – undo
874 874
 			$query2->orWhere(
875 875
 				$query2->expr()->andX(
876 876
 					$query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
877
-					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
877
+					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%'))
878 878
 				)
879 879
 			);
880 880
 		}
@@ -930,7 +930,7 @@  discard block
 block discarded – undo
930 930
 		$result->closeCursor();
931 931
 
932 932
 		if (!isset($uri['uri'])) {
933
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
933
+			throw new \InvalidArgumentException('Card does not exists: '.$id);
934 934
 		}
935 935
 
936 936
 		return $uri['uri'];
@@ -1002,11 +1002,11 @@  discard block
 block discarded – undo
1002 1002
 			);
1003 1003
 
1004 1004
 		foreach ($vCard->children() as $property) {
1005
-			if(!in_array($property->name, self::$indexProperties)) {
1005
+			if (!in_array($property->name, self::$indexProperties)) {
1006 1006
 				continue;
1007 1007
 			}
1008 1008
 			$preferred = 0;
1009
-			foreach($property->parameters as $parameter) {
1009
+			foreach ($property->parameters as $parameter) {
1010 1010
 				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1011 1011
 					$preferred = 1;
1012 1012
 					break;
@@ -1061,10 +1061,10 @@  discard block
 block discarded – undo
1061 1061
 		$result->closeCursor();
1062 1062
 
1063 1063
 		if (!isset($cardIds['id'])) {
1064
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1064
+			throw new \InvalidArgumentException('Card does not exists: '.$uri);
1065 1065
 		}
1066 1066
 
1067
-		return (int)$cardIds['id'];
1067
+		return (int) $cardIds['id'];
1068 1068
 	}
1069 1069
 
1070 1070
 	/**
Please login to merge, or discard this patch.
apps/files/lib/Controller/ViewController.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -35,7 +35,6 @@
 block discarded – undo
35 35
 use OCP\Files\NotFoundException;
36 36
 use OCP\IConfig;
37 37
 use OCP\IL10N;
38
-use OCP\INavigationManager;
39 38
 use OCP\IRequest;
40 39
 use OCP\IURLGenerator;
41 40
 use OCP\IUserSession;
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 	protected function renderScript($appName, $scriptName) {
110 110
 		$content = '';
111 111
 		$appPath = \OC_App::getAppPath($appName);
112
-		$scriptPath = $appPath . '/' . $scriptName;
112
+		$scriptPath = $appPath.'/'.$scriptName;
113 113
 		if (file_exists($scriptPath)) {
114 114
 			// TODO: sanitize path / script name ?
115 115
 			ob_start();
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 		$this->eventDispatcher->dispatch('OCA\Files::loadAdditionalScripts');
227 227
 
228 228
 		$params = [];
229
-		$params['usedSpacePercent'] = (int)$storageInfo['relative'];
229
+		$params['usedSpacePercent'] = (int) $storageInfo['relative'];
230 230
 		$params['owner'] = $storageInfo['owner'];
231 231
 		$params['ownerDisplayName'] = $storageInfo['ownerDisplayName'];
232 232
 		$params['isPublic'] = false;
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 		$params = [];
267 267
 
268 268
 		if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
269
-			$baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
269
+			$baseFolder = $this->rootFolder->get($uid.'/files_trashbin/files/');
270 270
 			$files = $baseFolder->getById($fileId);
271 271
 			$params['view'] = 'trashbin';
272 272
 		}
Please login to merge, or discard this patch.
Indentation   +203 added lines, -203 removed lines patch added patch discarded remove patch
@@ -49,207 +49,207 @@
 block discarded – undo
49 49
  * @package OCA\Files\Controller
50 50
  */
51 51
 class ViewController extends Controller {
52
-	/** @var string */
53
-	protected $appName;
54
-	/** @var IRequest */
55
-	protected $request;
56
-	/** @var IURLGenerator */
57
-	protected $urlGenerator;
58
-	/** @var IL10N */
59
-	protected $l10n;
60
-	/** @var IConfig */
61
-	protected $config;
62
-	/** @var EventDispatcherInterface */
63
-	protected $eventDispatcher;
64
-	/** @var IUserSession */
65
-	protected $userSession;
66
-	/** @var IAppManager */
67
-	protected $appManager;
68
-	/** @var IRootFolder */
69
-	protected $rootFolder;
70
-
71
-	/**
72
-	 * @param string $appName
73
-	 * @param IRequest $request
74
-	 * @param IURLGenerator $urlGenerator
75
-	 * @param IL10N $l10n
76
-	 * @param IConfig $config
77
-	 * @param EventDispatcherInterface $eventDispatcherInterface
78
-	 * @param IUserSession $userSession
79
-	 * @param IAppManager $appManager
80
-	 * @param IRootFolder $rootFolder
81
-	 */
82
-	public function __construct($appName,
83
-								IRequest $request,
84
-								IURLGenerator $urlGenerator,
85
-								IL10N $l10n,
86
-								IConfig $config,
87
-								EventDispatcherInterface $eventDispatcherInterface,
88
-								IUserSession $userSession,
89
-								IAppManager $appManager,
90
-								IRootFolder $rootFolder
91
-	) {
92
-		parent::__construct($appName, $request);
93
-		$this->appName = $appName;
94
-		$this->request = $request;
95
-		$this->urlGenerator = $urlGenerator;
96
-		$this->l10n = $l10n;
97
-		$this->config = $config;
98
-		$this->eventDispatcher = $eventDispatcherInterface;
99
-		$this->userSession = $userSession;
100
-		$this->appManager = $appManager;
101
-		$this->rootFolder = $rootFolder;
102
-	}
103
-
104
-	/**
105
-	 * @param string $appName
106
-	 * @param string $scriptName
107
-	 * @return string
108
-	 */
109
-	protected function renderScript($appName, $scriptName) {
110
-		$content = '';
111
-		$appPath = \OC_App::getAppPath($appName);
112
-		$scriptPath = $appPath . '/' . $scriptName;
113
-		if (file_exists($scriptPath)) {
114
-			// TODO: sanitize path / script name ?
115
-			ob_start();
116
-			include $scriptPath;
117
-			$content = ob_get_contents();
118
-			@ob_end_clean();
119
-		}
120
-		return $content;
121
-	}
122
-
123
-	/**
124
-	 * FIXME: Replace with non static code
125
-	 *
126
-	 * @return array
127
-	 * @throws \OCP\Files\NotFoundException
128
-	 */
129
-	protected function getStorageInfo() {
130
-		$dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
131
-		return \OC_Helper::getStorageInfo('/', $dirInfo);
132
-	}
133
-
134
-	/**
135
-	 * @NoCSRFRequired
136
-	 * @NoAdminRequired
137
-	 *
138
-	 * @param string $dir
139
-	 * @param string $view
140
-	 * @param string $fileid
141
-	 * @return TemplateResponse|RedirectResponse
142
-	 */
143
-	public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
144
-		if ($fileid !== null) {
145
-			try {
146
-				return $this->showFile($fileid);
147
-			} catch (NotFoundException $e) {
148
-				return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
149
-			}
150
-		}
151
-
152
-		$nav = new \OCP\Template('files', 'appnavigation', '');
153
-
154
-		// Load the files we need
155
-		\OCP\Util::addStyle('files', 'merged');
156
-		\OCP\Util::addScript('files', 'merged-index');
157
-
158
-		// mostly for the home storage's free space
159
-		// FIXME: Make non static
160
-		$storageInfo = $this->getStorageInfo();
161
-
162
-		\OCA\Files\App::getNavigationManager()->add(
163
-			[
164
-				'id' => 'favorites',
165
-				'appname' => 'files',
166
-				'script' => 'simplelist.php',
167
-				'order' => 5,
168
-				'name' => $this->l10n->t('Favorites')
169
-			]
170
-		);
171
-
172
-		$navItems = \OCA\Files\App::getNavigationManager()->getAll();
173
-		usort($navItems, function($item1, $item2) {
174
-			return $item1['order'] - $item2['order'];
175
-		});
176
-		$nav->assign('navigationItems', $navItems);
177
-
178
-		$contentItems = [];
179
-
180
-		// render the container content for every navigation item
181
-		foreach ($navItems as $item) {
182
-			$content = '';
183
-			if (isset($item['script'])) {
184
-				$content = $this->renderScript($item['appname'], $item['script']);
185
-			}
186
-			$contentItem = [];
187
-			$contentItem['id'] = $item['id'];
188
-			$contentItem['content'] = $content;
189
-			$contentItems[] = $contentItem;
190
-		}
191
-
192
-		$this->eventDispatcher->dispatch('OCA\Files::loadAdditionalScripts');
193
-
194
-		$params = [];
195
-		$params['usedSpacePercent'] = (int)$storageInfo['relative'];
196
-		$params['owner'] = $storageInfo['owner'];
197
-		$params['ownerDisplayName'] = $storageInfo['ownerDisplayName'];
198
-		$params['isPublic'] = false;
199
-		$params['allowShareWithLink'] = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes');
200
-		$user = $this->userSession->getUser()->getUID();
201
-		$params['defaultFileSorting'] = $this->config->getUserValue($user, 'files', 'file_sorting', 'name');
202
-		$params['defaultFileSortingDirection'] = $this->config->getUserValue($user, 'files', 'file_sorting_direction', 'asc');
203
-		$showHidden = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', false);
204
-		$params['showHiddenFiles'] = $showHidden ? 1 : 0;
205
-		$params['fileNotFound'] = $fileNotFound ? 1 : 0;
206
-		$params['appNavigation'] = $nav;
207
-		$params['appContents'] = $contentItems;
208
-
209
-		$response = new TemplateResponse(
210
-			$this->appName,
211
-			'index',
212
-			$params
213
-		);
214
-		$policy = new ContentSecurityPolicy();
215
-		$policy->addAllowedFrameDomain('\'self\'');
216
-		$response->setContentSecurityPolicy($policy);
217
-
218
-		return $response;
219
-	}
220
-
221
-	/**
222
-	 * Redirects to the file list and highlight the given file id
223
-	 *
224
-	 * @param string $fileId file id to show
225
-	 * @return RedirectResponse redirect response or not found response
226
-	 * @throws \OCP\Files\NotFoundException
227
-	 */
228
-	private function showFile($fileId) {
229
-		$uid = $this->userSession->getUser()->getUID();
230
-		$baseFolder = $this->rootFolder->getUserFolder($uid);
231
-		$files = $baseFolder->getById($fileId);
232
-		$params = [];
233
-
234
-		if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
235
-			$baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
236
-			$files = $baseFolder->getById($fileId);
237
-			$params['view'] = 'trashbin';
238
-		}
239
-
240
-		if (!empty($files)) {
241
-			$file = current($files);
242
-			if ($file instanceof Folder) {
243
-				// set the full path to enter the folder
244
-				$params['dir'] = $baseFolder->getRelativePath($file->getPath());
245
-			} else {
246
-				// set parent path as dir
247
-				$params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
248
-				// and scroll to the entry
249
-				$params['scrollto'] = $file->getName();
250
-			}
251
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
252
-		}
253
-		throw new \OCP\Files\NotFoundException();
254
-	}
52
+    /** @var string */
53
+    protected $appName;
54
+    /** @var IRequest */
55
+    protected $request;
56
+    /** @var IURLGenerator */
57
+    protected $urlGenerator;
58
+    /** @var IL10N */
59
+    protected $l10n;
60
+    /** @var IConfig */
61
+    protected $config;
62
+    /** @var EventDispatcherInterface */
63
+    protected $eventDispatcher;
64
+    /** @var IUserSession */
65
+    protected $userSession;
66
+    /** @var IAppManager */
67
+    protected $appManager;
68
+    /** @var IRootFolder */
69
+    protected $rootFolder;
70
+
71
+    /**
72
+     * @param string $appName
73
+     * @param IRequest $request
74
+     * @param IURLGenerator $urlGenerator
75
+     * @param IL10N $l10n
76
+     * @param IConfig $config
77
+     * @param EventDispatcherInterface $eventDispatcherInterface
78
+     * @param IUserSession $userSession
79
+     * @param IAppManager $appManager
80
+     * @param IRootFolder $rootFolder
81
+     */
82
+    public function __construct($appName,
83
+                                IRequest $request,
84
+                                IURLGenerator $urlGenerator,
85
+                                IL10N $l10n,
86
+                                IConfig $config,
87
+                                EventDispatcherInterface $eventDispatcherInterface,
88
+                                IUserSession $userSession,
89
+                                IAppManager $appManager,
90
+                                IRootFolder $rootFolder
91
+    ) {
92
+        parent::__construct($appName, $request);
93
+        $this->appName = $appName;
94
+        $this->request = $request;
95
+        $this->urlGenerator = $urlGenerator;
96
+        $this->l10n = $l10n;
97
+        $this->config = $config;
98
+        $this->eventDispatcher = $eventDispatcherInterface;
99
+        $this->userSession = $userSession;
100
+        $this->appManager = $appManager;
101
+        $this->rootFolder = $rootFolder;
102
+    }
103
+
104
+    /**
105
+     * @param string $appName
106
+     * @param string $scriptName
107
+     * @return string
108
+     */
109
+    protected function renderScript($appName, $scriptName) {
110
+        $content = '';
111
+        $appPath = \OC_App::getAppPath($appName);
112
+        $scriptPath = $appPath . '/' . $scriptName;
113
+        if (file_exists($scriptPath)) {
114
+            // TODO: sanitize path / script name ?
115
+            ob_start();
116
+            include $scriptPath;
117
+            $content = ob_get_contents();
118
+            @ob_end_clean();
119
+        }
120
+        return $content;
121
+    }
122
+
123
+    /**
124
+     * FIXME: Replace with non static code
125
+     *
126
+     * @return array
127
+     * @throws \OCP\Files\NotFoundException
128
+     */
129
+    protected function getStorageInfo() {
130
+        $dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
131
+        return \OC_Helper::getStorageInfo('/', $dirInfo);
132
+    }
133
+
134
+    /**
135
+     * @NoCSRFRequired
136
+     * @NoAdminRequired
137
+     *
138
+     * @param string $dir
139
+     * @param string $view
140
+     * @param string $fileid
141
+     * @return TemplateResponse|RedirectResponse
142
+     */
143
+    public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
144
+        if ($fileid !== null) {
145
+            try {
146
+                return $this->showFile($fileid);
147
+            } catch (NotFoundException $e) {
148
+                return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
149
+            }
150
+        }
151
+
152
+        $nav = new \OCP\Template('files', 'appnavigation', '');
153
+
154
+        // Load the files we need
155
+        \OCP\Util::addStyle('files', 'merged');
156
+        \OCP\Util::addScript('files', 'merged-index');
157
+
158
+        // mostly for the home storage's free space
159
+        // FIXME: Make non static
160
+        $storageInfo = $this->getStorageInfo();
161
+
162
+        \OCA\Files\App::getNavigationManager()->add(
163
+            [
164
+                'id' => 'favorites',
165
+                'appname' => 'files',
166
+                'script' => 'simplelist.php',
167
+                'order' => 5,
168
+                'name' => $this->l10n->t('Favorites')
169
+            ]
170
+        );
171
+
172
+        $navItems = \OCA\Files\App::getNavigationManager()->getAll();
173
+        usort($navItems, function($item1, $item2) {
174
+            return $item1['order'] - $item2['order'];
175
+        });
176
+        $nav->assign('navigationItems', $navItems);
177
+
178
+        $contentItems = [];
179
+
180
+        // render the container content for every navigation item
181
+        foreach ($navItems as $item) {
182
+            $content = '';
183
+            if (isset($item['script'])) {
184
+                $content = $this->renderScript($item['appname'], $item['script']);
185
+            }
186
+            $contentItem = [];
187
+            $contentItem['id'] = $item['id'];
188
+            $contentItem['content'] = $content;
189
+            $contentItems[] = $contentItem;
190
+        }
191
+
192
+        $this->eventDispatcher->dispatch('OCA\Files::loadAdditionalScripts');
193
+
194
+        $params = [];
195
+        $params['usedSpacePercent'] = (int)$storageInfo['relative'];
196
+        $params['owner'] = $storageInfo['owner'];
197
+        $params['ownerDisplayName'] = $storageInfo['ownerDisplayName'];
198
+        $params['isPublic'] = false;
199
+        $params['allowShareWithLink'] = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes');
200
+        $user = $this->userSession->getUser()->getUID();
201
+        $params['defaultFileSorting'] = $this->config->getUserValue($user, 'files', 'file_sorting', 'name');
202
+        $params['defaultFileSortingDirection'] = $this->config->getUserValue($user, 'files', 'file_sorting_direction', 'asc');
203
+        $showHidden = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', false);
204
+        $params['showHiddenFiles'] = $showHidden ? 1 : 0;
205
+        $params['fileNotFound'] = $fileNotFound ? 1 : 0;
206
+        $params['appNavigation'] = $nav;
207
+        $params['appContents'] = $contentItems;
208
+
209
+        $response = new TemplateResponse(
210
+            $this->appName,
211
+            'index',
212
+            $params
213
+        );
214
+        $policy = new ContentSecurityPolicy();
215
+        $policy->addAllowedFrameDomain('\'self\'');
216
+        $response->setContentSecurityPolicy($policy);
217
+
218
+        return $response;
219
+    }
220
+
221
+    /**
222
+     * Redirects to the file list and highlight the given file id
223
+     *
224
+     * @param string $fileId file id to show
225
+     * @return RedirectResponse redirect response or not found response
226
+     * @throws \OCP\Files\NotFoundException
227
+     */
228
+    private function showFile($fileId) {
229
+        $uid = $this->userSession->getUser()->getUID();
230
+        $baseFolder = $this->rootFolder->getUserFolder($uid);
231
+        $files = $baseFolder->getById($fileId);
232
+        $params = [];
233
+
234
+        if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
235
+            $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
236
+            $files = $baseFolder->getById($fileId);
237
+            $params['view'] = 'trashbin';
238
+        }
239
+
240
+        if (!empty($files)) {
241
+            $file = current($files);
242
+            if ($file instanceof Folder) {
243
+                // set the full path to enter the folder
244
+                $params['dir'] = $baseFolder->getRelativePath($file->getPath());
245
+            } else {
246
+                // set parent path as dir
247
+                $params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
248
+                // and scroll to the entry
249
+                $params['scrollto'] = $file->getName();
250
+            }
251
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
252
+        }
253
+        throw new \OCP\Files\NotFoundException();
254
+    }
255 255
 }
Please login to merge, or discard this patch.
apps/files/templates/admin.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -2,17 +2,17 @@
 block discarded – undo
2 2
 
3 3
 	<div class="section">
4 4
 		<h2><?php p($l->t('File handling')); ?></h2>
5
-		<label for="maxUploadSize"><?php p($l->t( 'Maximum upload size' )); ?> </label>
5
+		<label for="maxUploadSize"><?php p($l->t('Maximum upload size')); ?> </label>
6 6
 		<span id="maxUploadSizeSettingsMsg" class="msg"></span>
7 7
 		<br />
8
-		<input type="text" name='maxUploadSize' id="maxUploadSize" value='<?php p($_['uploadMaxFilesize']) ?>' <?php if(!$_['uploadChangable']) { p('disabled'); } ?> />
9
-		<?php if($_['displayMaxPossibleUploadSize']):?>
8
+		<input type="text" name='maxUploadSize' id="maxUploadSize" value='<?php p($_['uploadMaxFilesize']) ?>' <?php if (!$_['uploadChangable']) { p('disabled'); } ?> />
9
+		<?php if ($_['displayMaxPossibleUploadSize']):?>
10 10
 			(<?php p($l->t('max. possible: ')); p($_['maxPossibleUploadSize']) ?>)
11
-		<?php endif;?>
11
+		<?php endif; ?>
12 12
 		<input type="hidden" value="<?php p($_['requesttoken']); ?>" name="requesttoken" />
13
-		<?php if($_['uploadChangable']): ?>
13
+		<?php if ($_['uploadChangable']): ?>
14 14
 			<input type="submit" id="submitMaxUpload"
15
-				   value="<?php p($l->t( 'Save' )); ?>"/>
15
+				   value="<?php p($l->t('Save')); ?>"/>
16 16
 			<p><em><?php p($l->t('With PHP-FPM it might take 5 minutes for changes to be applied.')); ?></em></p>
17 17
 		<?php else: ?>
18 18
 			<p><em><?php p($l->t('Missing permissions to edit from here.')); ?></em></p>
Please login to merge, or discard this patch.
Braces   +5 added lines, -2 removed lines patch added patch discarded remove patch
@@ -14,7 +14,10 @@
 block discarded – undo
14 14
 			<input type="submit" id="submitMaxUpload"
15 15
 				   value="<?php p($l->t( 'Save' )); ?>"/>
16 16
 			<p><em><?php p($l->t('With PHP-FPM it might take 5 minutes for changes to be applied.')); ?></em></p>
17
-		<?php else: ?>
18
-			<p><em><?php p($l->t('Missing permissions to edit from here.')); ?></em></p>
17
+		<?php else {
18
+    : ?>
19
+			<p><em><?php p($l->t('Missing permissions to edit from here.'));
20
+}
21
+?></em></p>
19 22
 		<?php endif; ?>
20 23
 	</div>
Please login to merge, or discard this patch.
apps/files/templates/list.php 1 patch
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 		<div class="actions creatable hidden">
3 3
 			<div id="uploadprogresswrapper">
4 4
 				<div id="uploadprogressbar">
5
-					<em class="label outer" style="display:none"><span class="desktop"><?php p($l->t('Uploading...'));?></span><span class="mobile"><?php p($l->t('...'));?></span></em>
5
+					<em class="label outer" style="display:none"><span class="desktop"><?php p($l->t('Uploading...')); ?></span><span class="mobile"><?php p($l->t('...')); ?></span></em>
6 6
 				</div>
7 7
 				<input type="button" class="stop icon-close" style="display:none" value="" />
8 8
 			</div>
@@ -16,10 +16,10 @@  discard block
 block discarded – undo
16 16
 	*/ ?>
17 17
 	<input type="hidden" name="permissions" value="" id="permissions">
18 18
 	<input type="hidden" id="free_space" value="<?php isset($_['freeSpace']) ? p($_['freeSpace']) : '' ?>">
19
-	<?php if(isset($_['dirToken'])):?>
19
+	<?php if (isset($_['dirToken'])):?>
20 20
 	<input type="hidden" id="publicUploadRequestToken" name="requesttoken" value="<?php p($_['requesttoken']) ?>" />
21 21
 	<input type="hidden" id="dirToken" name="dirToken" value="<?php p($_['dirToken']) ?>" />
22
-	<?php endif;?>
22
+	<?php endif; ?>
23 23
 	<input type="hidden" class="max_human_file_size"
24 24
 		   value="(max <?php isset($_['uploadMaxHumanFilesize']) ? p($_['uploadMaxHumanFilesize']) : ''; ?>)">
25 25
 </div>
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
 					<label for="select_all_files">
46 46
 						<span class="hidden-visually"><?php p($l->t('Select all'))?></span>
47 47
 					</label>
48
-					<a class="name sort columntitle" data-sort="name"><span><?php p($l->t( 'Name' )); ?></span><span class="sort-indicator"></span></a>
48
+					<a class="name sort columntitle" data-sort="name"><span><?php p($l->t('Name')); ?></span><span class="sort-indicator"></span></a>
49 49
 					<span id="selectedActionsList" class="selectedActions">
50 50
 						<a href="" class="download">
51 51
 							<span class="icon icon-download"></span>
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 				<a class="size sort columntitle" data-sort="size"><span><?php p($l->t('Size')); ?></span><span class="sort-indicator"></span></a>
59 59
 			</th>
60 60
 			<th id="headerDate" class="hidden column-mtime">
61
-				<a id="modified" class="columntitle" data-sort="mtime"><span><?php p($l->t( 'Modified' )); ?></span><span class="sort-indicator"></span></a>
61
+				<a id="modified" class="columntitle" data-sort="mtime"><span><?php p($l->t('Modified')); ?></span><span class="sort-indicator"></span></a>
62 62
 					<span class="selectedActions"><a href="" class="delete-selected">
63 63
 						<span><?php p($l->t('Delete'))?></span>
64 64
 						<span class="icon icon-delete"></span>
@@ -78,6 +78,6 @@  discard block
 block discarded – undo
78 78
 <div id="editor"></div><!-- FIXME Do not use this div in your app! It is deprecated and will be removed in the future! -->
79 79
 <div id="uploadsize-message" title="<?php p($l->t('Upload too large'))?>">
80 80
 	<p>
81
-	<?php p($l->t('The files you are trying to upload exceed the maximum size for file uploads on this server.'));?>
81
+	<?php p($l->t('The files you are trying to upload exceed the maximum size for file uploads on this server.')); ?>
82 82
 	</p>
83 83
 </div>
Please login to merge, or discard this patch.