Completed
Push — stable13 ( 2d5d8b...1a016f )
by Roeland
17:00
created
lib/private/Cache/CappedMemoryCache.php 1 patch
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -31,66 +31,66 @@
 block discarded – undo
31 31
  */
32 32
 class CappedMemoryCache implements ICache, \ArrayAccess {
33 33
 
34
-	private $capacity;
35
-	private $cache = [];
36
-
37
-	public function __construct($capacity = 512) {
38
-		$this->capacity = $capacity;
39
-	}
40
-
41
-	public function hasKey($key) {
42
-		return isset($this->cache[$key]);
43
-	}
44
-
45
-	public function get($key) {
46
-		return isset($this->cache[$key]) ? $this->cache[$key] : null;
47
-	}
48
-
49
-	public function set($key, $value, $ttl = 0) {
50
-		if (is_null($key)) {
51
-			$this->cache[] = $value;
52
-		} else {
53
-			$this->cache[$key] = $value;
54
-		}
55
-		$this->garbageCollect();
56
-	}
57
-
58
-	public function remove($key) {
59
-		unset($this->cache[$key]);
60
-		return true;
61
-	}
62
-
63
-	public function clear($prefix = '') {
64
-		$this->cache = [];
65
-		return true;
66
-	}
67
-
68
-	public function offsetExists($offset) {
69
-		return $this->hasKey($offset);
70
-	}
71
-
72
-	public function &offsetGet($offset) {
73
-		return $this->cache[$offset];
74
-	}
75
-
76
-	public function offsetSet($offset, $value) {
77
-		$this->set($offset, $value);
78
-	}
79
-
80
-	public function offsetUnset($offset) {
81
-		$this->remove($offset);
82
-	}
83
-
84
-	public function getData() {
85
-		return $this->cache;
86
-	}
87
-
88
-
89
-	private function garbageCollect() {
90
-		while (count($this->cache) > $this->capacity) {
91
-			reset($this->cache);
92
-			$key = key($this->cache);
93
-			$this->remove($key);
94
-		}
95
-	}
34
+    private $capacity;
35
+    private $cache = [];
36
+
37
+    public function __construct($capacity = 512) {
38
+        $this->capacity = $capacity;
39
+    }
40
+
41
+    public function hasKey($key) {
42
+        return isset($this->cache[$key]);
43
+    }
44
+
45
+    public function get($key) {
46
+        return isset($this->cache[$key]) ? $this->cache[$key] : null;
47
+    }
48
+
49
+    public function set($key, $value, $ttl = 0) {
50
+        if (is_null($key)) {
51
+            $this->cache[] = $value;
52
+        } else {
53
+            $this->cache[$key] = $value;
54
+        }
55
+        $this->garbageCollect();
56
+    }
57
+
58
+    public function remove($key) {
59
+        unset($this->cache[$key]);
60
+        return true;
61
+    }
62
+
63
+    public function clear($prefix = '') {
64
+        $this->cache = [];
65
+        return true;
66
+    }
67
+
68
+    public function offsetExists($offset) {
69
+        return $this->hasKey($offset);
70
+    }
71
+
72
+    public function &offsetGet($offset) {
73
+        return $this->cache[$offset];
74
+    }
75
+
76
+    public function offsetSet($offset, $value) {
77
+        $this->set($offset, $value);
78
+    }
79
+
80
+    public function offsetUnset($offset) {
81
+        $this->remove($offset);
82
+    }
83
+
84
+    public function getData() {
85
+        return $this->cache;
86
+    }
87
+
88
+
89
+    private function garbageCollect() {
90
+        while (count($this->cache) > $this->capacity) {
91
+            reset($this->cache);
92
+            $key = key($this->cache);
93
+            $this->remove($key);
94
+        }
95
+    }
96 96
 }
Please login to merge, or discard this patch.
core/Controller/JsController.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 			$folder = $this->appData->getFolder($appName);
67 67
 			$gzip = false;
68 68
 			$file = $this->getFile($folder, $fileName, $gzip);
69
-		} catch(NotFoundException $e) {
69
+		} catch (NotFoundException $e) {
70 70
 			return new NotFoundResponse();
71 71
 		}
72 72
 
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		if ($encoding !== null && strpos($encoding, 'gzip') !== false) {
96 96
 			try {
97 97
 				$gzip = true;
98
-				return $folder->getFile($fileName . '.gzip'); # Safari doesn't like .gz
98
+				return $folder->getFile($fileName.'.gzip'); # Safari doesn't like .gz
99 99
 			} catch (NotFoundException $e) {
100 100
 				// continue
101 101
 			}
Please login to merge, or discard this patch.
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -36,74 +36,74 @@
 block discarded – undo
36 36
 
37 37
 class JsController extends Controller {
38 38
 
39
-	/** @var IAppData */
40
-	protected $appData;
39
+    /** @var IAppData */
40
+    protected $appData;
41 41
 
42
-	/** @var ITimeFactory */
43
-	protected $timeFactory;
42
+    /** @var ITimeFactory */
43
+    protected $timeFactory;
44 44
 
45
-	/**
46
-	 * @param string $appName
47
-	 * @param IRequest $request
48
-	 * @param Factory $appDataFactory
49
-	 * @param ITimeFactory $timeFactory
50
-	 */
51
-	public function __construct($appName, IRequest $request, Factory $appDataFactory, ITimeFactory $timeFactory) {
52
-		parent::__construct($appName, $request);
45
+    /**
46
+     * @param string $appName
47
+     * @param IRequest $request
48
+     * @param Factory $appDataFactory
49
+     * @param ITimeFactory $timeFactory
50
+     */
51
+    public function __construct($appName, IRequest $request, Factory $appDataFactory, ITimeFactory $timeFactory) {
52
+        parent::__construct($appName, $request);
53 53
 
54
-		$this->appData = $appDataFactory->get('js');
55
-		$this->timeFactory = $timeFactory;
56
-	}
54
+        $this->appData = $appDataFactory->get('js');
55
+        $this->timeFactory = $timeFactory;
56
+    }
57 57
 
58
-	/**
59
-	 * @PublicPage
60
-	 * @NoCSRFRequired
61
-	 *
62
-	 * @param string $fileName css filename with extension
63
-	 * @param string $appName css folder name
64
-	 * @return FileDisplayResponse|NotFoundResponse
65
-	 */
66
-	public function getJs($fileName, $appName) {
67
-		try {
68
-			$folder = $this->appData->getFolder($appName);
69
-			$gzip = false;
70
-			$file = $this->getFile($folder, $fileName, $gzip);
71
-		} catch(NotFoundException $e) {
72
-			return new NotFoundResponse();
73
-		}
58
+    /**
59
+     * @PublicPage
60
+     * @NoCSRFRequired
61
+     *
62
+     * @param string $fileName css filename with extension
63
+     * @param string $appName css folder name
64
+     * @return FileDisplayResponse|NotFoundResponse
65
+     */
66
+    public function getJs($fileName, $appName) {
67
+        try {
68
+            $folder = $this->appData->getFolder($appName);
69
+            $gzip = false;
70
+            $file = $this->getFile($folder, $fileName, $gzip);
71
+        } catch(NotFoundException $e) {
72
+            return new NotFoundResponse();
73
+        }
74 74
 
75
-		$response = new FileDisplayResponse($file, Http::STATUS_OK, ['Content-Type' => 'application/javascript']);
76
-		if ($gzip) {
77
-			$response->addHeader('Content-Encoding', 'gzip');
78
-		}
79
-		$response->cacheFor(86400);
80
-		$expires = new \DateTime();
81
-		$expires->setTimestamp($this->timeFactory->getTime());
82
-		$expires->add(new \DateInterval('PT24H'));
83
-		$response->addHeader('Expires', $expires->format(\DateTime::RFC1123));
84
-		$response->addHeader('Pragma', 'cache');
85
-		return $response;
86
-	}
75
+        $response = new FileDisplayResponse($file, Http::STATUS_OK, ['Content-Type' => 'application/javascript']);
76
+        if ($gzip) {
77
+            $response->addHeader('Content-Encoding', 'gzip');
78
+        }
79
+        $response->cacheFor(86400);
80
+        $expires = new \DateTime();
81
+        $expires->setTimestamp($this->timeFactory->getTime());
82
+        $expires->add(new \DateInterval('PT24H'));
83
+        $response->addHeader('Expires', $expires->format(\DateTime::RFC1123));
84
+        $response->addHeader('Pragma', 'cache');
85
+        return $response;
86
+    }
87 87
 
88
-	/**
89
-	 * @param ISimpleFolder $folder
90
-	 * @param string $fileName
91
-	 * @param bool $gzip is set to true if we use the gzip file
92
-	 * @return ISimpleFile
93
-	 */
94
-	private function getFile(ISimpleFolder $folder, $fileName, &$gzip) {
95
-		$encoding = $this->request->getHeader('Accept-Encoding');
88
+    /**
89
+     * @param ISimpleFolder $folder
90
+     * @param string $fileName
91
+     * @param bool $gzip is set to true if we use the gzip file
92
+     * @return ISimpleFile
93
+     */
94
+    private function getFile(ISimpleFolder $folder, $fileName, &$gzip) {
95
+        $encoding = $this->request->getHeader('Accept-Encoding');
96 96
 
97
-		if ($encoding !== null && strpos($encoding, 'gzip') !== false) {
98
-			try {
99
-				$gzip = true;
100
-				return $folder->getFile($fileName . '.gzip'); # Safari doesn't like .gz
101
-			} catch (NotFoundException $e) {
102
-				// continue
103
-			}
104
-		}
97
+        if ($encoding !== null && strpos($encoding, 'gzip') !== false) {
98
+            try {
99
+                $gzip = true;
100
+                return $folder->getFile($fileName . '.gzip'); # Safari doesn't like .gz
101
+            } catch (NotFoundException $e) {
102
+                // continue
103
+            }
104
+        }
105 105
 
106
-		$gzip = false;
107
-		return $folder->getFile($fileName);
108
-	}
106
+        $gzip = false;
107
+        return $folder->getFile($fileName);
108
+    }
109 109
 }
Please login to merge, or discard this patch.
lib/private/Repair/CleanTags.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -171,14 +171,14 @@
 block discarded – undo
171 171
 	protected function deleteOrphanEntries(IOutput $output, $repairInfo, $deleteTable, $deleteId, $sourceTable, $sourceId, $sourceNullColumn) {
172 172
 		$qb = $this->connection->getQueryBuilder();
173 173
 
174
-		$qb->select('d.' . $deleteId)
174
+		$qb->select('d.'.$deleteId)
175 175
 			->from($deleteTable, 'd')
176
-			->leftJoin('d', $sourceTable, 's', $qb->expr()->eq('d.' . $deleteId, 's.' . $sourceId))
176
+			->leftJoin('d', $sourceTable, 's', $qb->expr()->eq('d.'.$deleteId, 's.'.$sourceId))
177 177
 			->where(
178 178
 				$qb->expr()->eq('d.type', $qb->expr()->literal('files'))
179 179
 			)
180 180
 			->andWhere(
181
-				$qb->expr()->isNull('s.' . $sourceNullColumn)
181
+				$qb->expr()->isNull('s.'.$sourceNullColumn)
182 182
 			);
183 183
 		$result = $qb->execute();
184 184
 
Please login to merge, or discard this patch.
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -37,172 +37,172 @@
 block discarded – undo
37 37
  */
38 38
 class CleanTags implements IRepairStep {
39 39
 
40
-	/** @var IDBConnection */
41
-	protected $connection;
42
-
43
-	/** @var IUserManager */
44
-	protected $userManager;
45
-
46
-	protected $deletedTags = 0;
47
-
48
-	/**
49
-	 * @param IDBConnection $connection
50
-	 * @param IUserManager $userManager
51
-	 */
52
-	public function __construct(IDBConnection $connection, IUserManager $userManager) {
53
-		$this->connection = $connection;
54
-		$this->userManager = $userManager;
55
-	}
56
-
57
-	/**
58
-	 * @return string
59
-	 */
60
-	public function getName() {
61
-		return 'Clean tags and favorites';
62
-	}
63
-
64
-	/**
65
-	 * Updates the configuration after running an update
66
-	 */
67
-	public function run(IOutput $output) {
68
-		$this->deleteOrphanTags($output);
69
-		$this->deleteOrphanFileEntries($output);
70
-		$this->deleteOrphanTagEntries($output);
71
-		$this->deleteOrphanCategoryEntries($output);
72
-	}
73
-
74
-	/**
75
-	 * Delete tags for deleted users
76
-	 */
77
-	protected function deleteOrphanTags(IOutput $output) {
78
-		$offset = 0;
79
-		while ($this->checkTags($offset)) {
80
-			$offset += 50;
81
-		}
82
-
83
-		$output->info(sprintf('%d tags of deleted users have been removed.', $this->deletedTags));
84
-	}
85
-
86
-	protected function checkTags($offset) {
87
-		$query = $this->connection->getQueryBuilder();
88
-		$query->select('uid')
89
-			->from('vcategory')
90
-			->groupBy('uid')
91
-			->orderBy('uid')
92
-			->setMaxResults(50)
93
-			->setFirstResult($offset);
94
-		$result = $query->execute();
95
-
96
-		$users = [];
97
-		$hadResults = false;
98
-		while ($row = $result->fetch()) {
99
-			$hadResults = true;
100
-			if (!$this->userManager->userExists($row['uid'])) {
101
-				$users[] = $row['uid'];
102
-			}
103
-		}
104
-		$result->closeCursor();
105
-
106
-		if (!$hadResults) {
107
-			// No more tags, stop looping
108
-			return false;
109
-		}
110
-
111
-		if (!empty($users)) {
112
-			$query = $this->connection->getQueryBuilder();
113
-			$query->delete('vcategory')
114
-				->where($query->expr()->in('uid', $query->createNamedParameter($users, IQueryBuilder::PARAM_STR_ARRAY)));
115
-			$this->deletedTags += $query->execute();
116
-		}
117
-		return true;
118
-	}
119
-
120
-	/**
121
-	 * Delete tag entries for deleted files
122
-	 */
123
-	protected function deleteOrphanFileEntries(IOutput $output) {
124
-		$this->deleteOrphanEntries(
125
-			$output,
126
-			'%d tags for delete files have been removed.',
127
-			'vcategory_to_object', 'objid',
128
-			'filecache', 'fileid', 'path_hash'
129
-		);
130
-	}
131
-
132
-	/**
133
-	 * Delete tag entries for deleted tags
134
-	 */
135
-	protected function deleteOrphanTagEntries(IOutput $output) {
136
-		$this->deleteOrphanEntries(
137
-			$output,
138
-			'%d tag entries for deleted tags have been removed.',
139
-			'vcategory_to_object', 'categoryid',
140
-			'vcategory', 'id', 'uid'
141
-		);
142
-	}
143
-
144
-	/**
145
-	 * Delete tags that have no entries
146
-	 */
147
-	protected function deleteOrphanCategoryEntries(IOutput $output) {
148
-		$this->deleteOrphanEntries(
149
-			$output,
150
-			'%d tags with no entries have been removed.',
151
-			'vcategory', 'id',
152
-			'vcategory_to_object', 'categoryid', 'type'
153
-		);
154
-	}
155
-
156
-	/**
157
-	 * Deletes all entries from $deleteTable that do not have a matching entry in $sourceTable
158
-	 *
159
-	 * A query joins $deleteTable.$deleteId = $sourceTable.$sourceId and checks
160
-	 * whether $sourceNullColumn is null. If it is null, the entry in $deleteTable
161
-	 * is being deleted.
162
-	 *
163
-	 * @param string $repairInfo
164
-	 * @param string $deleteTable
165
-	 * @param string $deleteId
166
-	 * @param string $sourceTable
167
-	 * @param string $sourceId
168
-	 * @param string $sourceNullColumn	If this column is null in the source table,
169
-	 * 								the entry is deleted in the $deleteTable
170
-	 * @suppress SqlInjectionChecker
171
-	 */
172
-	protected function deleteOrphanEntries(IOutput $output, $repairInfo, $deleteTable, $deleteId, $sourceTable, $sourceId, $sourceNullColumn) {
173
-		$qb = $this->connection->getQueryBuilder();
174
-
175
-		$qb->select('d.' . $deleteId)
176
-			->from($deleteTable, 'd')
177
-			->leftJoin('d', $sourceTable, 's', $qb->expr()->eq('d.' . $deleteId, 's.' . $sourceId))
178
-			->where(
179
-				$qb->expr()->eq('d.type', $qb->expr()->literal('files'))
180
-			)
181
-			->andWhere(
182
-				$qb->expr()->isNull('s.' . $sourceNullColumn)
183
-			);
184
-		$result = $qb->execute();
185
-
186
-		$orphanItems = array();
187
-		while ($row = $result->fetch()) {
188
-			$orphanItems[] = (int) $row[$deleteId];
189
-		}
190
-
191
-		if (!empty($orphanItems)) {
192
-			$orphanItemsBatch = array_chunk($orphanItems, 200);
193
-			foreach ($orphanItemsBatch as $items) {
194
-				$qb->delete($deleteTable)
195
-					->where(
196
-						$qb->expr()->eq('type', $qb->expr()->literal('files'))
197
-					)
198
-					->andWhere($qb->expr()->in($deleteId, $qb->createParameter('ids')));
199
-				$qb->setParameter('ids', $items, IQueryBuilder::PARAM_INT_ARRAY);
200
-				$qb->execute();
201
-			}
202
-		}
203
-
204
-		if ($repairInfo) {
205
-			$output->info(sprintf($repairInfo, count($orphanItems)));
206
-		}
207
-	}
40
+    /** @var IDBConnection */
41
+    protected $connection;
42
+
43
+    /** @var IUserManager */
44
+    protected $userManager;
45
+
46
+    protected $deletedTags = 0;
47
+
48
+    /**
49
+     * @param IDBConnection $connection
50
+     * @param IUserManager $userManager
51
+     */
52
+    public function __construct(IDBConnection $connection, IUserManager $userManager) {
53
+        $this->connection = $connection;
54
+        $this->userManager = $userManager;
55
+    }
56
+
57
+    /**
58
+     * @return string
59
+     */
60
+    public function getName() {
61
+        return 'Clean tags and favorites';
62
+    }
63
+
64
+    /**
65
+     * Updates the configuration after running an update
66
+     */
67
+    public function run(IOutput $output) {
68
+        $this->deleteOrphanTags($output);
69
+        $this->deleteOrphanFileEntries($output);
70
+        $this->deleteOrphanTagEntries($output);
71
+        $this->deleteOrphanCategoryEntries($output);
72
+    }
73
+
74
+    /**
75
+     * Delete tags for deleted users
76
+     */
77
+    protected function deleteOrphanTags(IOutput $output) {
78
+        $offset = 0;
79
+        while ($this->checkTags($offset)) {
80
+            $offset += 50;
81
+        }
82
+
83
+        $output->info(sprintf('%d tags of deleted users have been removed.', $this->deletedTags));
84
+    }
85
+
86
+    protected function checkTags($offset) {
87
+        $query = $this->connection->getQueryBuilder();
88
+        $query->select('uid')
89
+            ->from('vcategory')
90
+            ->groupBy('uid')
91
+            ->orderBy('uid')
92
+            ->setMaxResults(50)
93
+            ->setFirstResult($offset);
94
+        $result = $query->execute();
95
+
96
+        $users = [];
97
+        $hadResults = false;
98
+        while ($row = $result->fetch()) {
99
+            $hadResults = true;
100
+            if (!$this->userManager->userExists($row['uid'])) {
101
+                $users[] = $row['uid'];
102
+            }
103
+        }
104
+        $result->closeCursor();
105
+
106
+        if (!$hadResults) {
107
+            // No more tags, stop looping
108
+            return false;
109
+        }
110
+
111
+        if (!empty($users)) {
112
+            $query = $this->connection->getQueryBuilder();
113
+            $query->delete('vcategory')
114
+                ->where($query->expr()->in('uid', $query->createNamedParameter($users, IQueryBuilder::PARAM_STR_ARRAY)));
115
+            $this->deletedTags += $query->execute();
116
+        }
117
+        return true;
118
+    }
119
+
120
+    /**
121
+     * Delete tag entries for deleted files
122
+     */
123
+    protected function deleteOrphanFileEntries(IOutput $output) {
124
+        $this->deleteOrphanEntries(
125
+            $output,
126
+            '%d tags for delete files have been removed.',
127
+            'vcategory_to_object', 'objid',
128
+            'filecache', 'fileid', 'path_hash'
129
+        );
130
+    }
131
+
132
+    /**
133
+     * Delete tag entries for deleted tags
134
+     */
135
+    protected function deleteOrphanTagEntries(IOutput $output) {
136
+        $this->deleteOrphanEntries(
137
+            $output,
138
+            '%d tag entries for deleted tags have been removed.',
139
+            'vcategory_to_object', 'categoryid',
140
+            'vcategory', 'id', 'uid'
141
+        );
142
+    }
143
+
144
+    /**
145
+     * Delete tags that have no entries
146
+     */
147
+    protected function deleteOrphanCategoryEntries(IOutput $output) {
148
+        $this->deleteOrphanEntries(
149
+            $output,
150
+            '%d tags with no entries have been removed.',
151
+            'vcategory', 'id',
152
+            'vcategory_to_object', 'categoryid', 'type'
153
+        );
154
+    }
155
+
156
+    /**
157
+     * Deletes all entries from $deleteTable that do not have a matching entry in $sourceTable
158
+     *
159
+     * A query joins $deleteTable.$deleteId = $sourceTable.$sourceId and checks
160
+     * whether $sourceNullColumn is null. If it is null, the entry in $deleteTable
161
+     * is being deleted.
162
+     *
163
+     * @param string $repairInfo
164
+     * @param string $deleteTable
165
+     * @param string $deleteId
166
+     * @param string $sourceTable
167
+     * @param string $sourceId
168
+     * @param string $sourceNullColumn	If this column is null in the source table,
169
+     * 								the entry is deleted in the $deleteTable
170
+     * @suppress SqlInjectionChecker
171
+     */
172
+    protected function deleteOrphanEntries(IOutput $output, $repairInfo, $deleteTable, $deleteId, $sourceTable, $sourceId, $sourceNullColumn) {
173
+        $qb = $this->connection->getQueryBuilder();
174
+
175
+        $qb->select('d.' . $deleteId)
176
+            ->from($deleteTable, 'd')
177
+            ->leftJoin('d', $sourceTable, 's', $qb->expr()->eq('d.' . $deleteId, 's.' . $sourceId))
178
+            ->where(
179
+                $qb->expr()->eq('d.type', $qb->expr()->literal('files'))
180
+            )
181
+            ->andWhere(
182
+                $qb->expr()->isNull('s.' . $sourceNullColumn)
183
+            );
184
+        $result = $qb->execute();
185
+
186
+        $orphanItems = array();
187
+        while ($row = $result->fetch()) {
188
+            $orphanItems[] = (int) $row[$deleteId];
189
+        }
190
+
191
+        if (!empty($orphanItems)) {
192
+            $orphanItemsBatch = array_chunk($orphanItems, 200);
193
+            foreach ($orphanItemsBatch as $items) {
194
+                $qb->delete($deleteTable)
195
+                    ->where(
196
+                        $qb->expr()->eq('type', $qb->expr()->literal('files'))
197
+                    )
198
+                    ->andWhere($qb->expr()->in($deleteId, $qb->createParameter('ids')));
199
+                $qb->setParameter('ids', $items, IQueryBuilder::PARAM_INT_ARRAY);
200
+                $qb->execute();
201
+            }
202
+        }
203
+
204
+        if ($repairInfo) {
205
+            $output->info(sprintf($repairInfo, count($orphanItems)));
206
+        }
207
+    }
208 208
 }
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -1100,6 +1100,9 @@
 block discarded – undo
1100 1100
 		return $share;
1101 1101
 	}
1102 1102
 
1103
+	/**
1104
+	 * @param \OCP\Share\IShare $share
1105
+	 */
1103 1106
 	protected function checkExpireDate($share) {
1104 1107
 		if ($share->getExpirationDate() !== null &&
1105 1108
 			$share->getExpirationDate() <= new \DateTime()) {
Please login to merge, or discard this patch.
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
 
346 346
 		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
347 347
 			$expirationDate = new \DateTime();
348
-			$expirationDate->setTime(0,0,0);
348
+			$expirationDate->setTime(0, 0, 0);
349 349
 			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
350 350
 		}
351 351
 
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 
358 358
 			$date = new \DateTime();
359 359
 			$date->setTime(0, 0, 0);
360
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
360
+			$date->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
361 361
 			if ($date < $expirationDate) {
362 362
 				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
363 363
 				throw new GenericShareException($message, $message, 404);
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
 		 */
411 411
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
412 412
 		$existingShares = $provider->getSharesByPath($share->getNode());
413
-		foreach($existingShares as $existingShare) {
413
+		foreach ($existingShares as $existingShare) {
414 414
 			// Ignore if it is the same share
415 415
 			try {
416 416
 				if ($existingShare->getFullId() === $share->getFullId()) {
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
 		 */
468 468
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
469 469
 		$existingShares = $provider->getSharesByPath($share->getNode());
470
-		foreach($existingShares as $existingShare) {
470
+		foreach ($existingShares as $existingShare) {
471 471
 			try {
472 472
 				if ($existingShare->getFullId() === $share->getFullId()) {
473 473
 					continue;
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
 		// Make sure that we do not share a path that contains a shared mountpoint
537 537
 		if ($path instanceof \OCP\Files\Folder) {
538 538
 			$mounts = $this->mountManager->findIn($path->getPath());
539
-			foreach($mounts as $mount) {
539
+			foreach ($mounts as $mount) {
540 540
 				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
541 541
 					throw new \InvalidArgumentException('Path contains files shared with you');
542 542
 				}
@@ -584,7 +584,7 @@  discard block
 block discarded – undo
584 584
 		$storage = $share->getNode()->getStorage();
585 585
 		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
586 586
 			$parent = $share->getNode()->getParent();
587
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
587
+			while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
588 588
 				$parent = $parent->getParent();
589 589
 			}
590 590
 			$share->setShareOwner($parent->getOwner()->getUID());
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
 		}
638 638
 
639 639
 		// Generate the target
640
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
640
+		$target = $this->config->getSystemValue('share_folder', '/').'/'.$share->getNode()->getName();
641 641
 		$target = \OC\Files\Filesystem::normalizePath($target);
642 642
 		$share->setTarget($target);
643 643
 
@@ -660,7 +660,7 @@  discard block
 block discarded – undo
660 660
 
661 661
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
662 662
 			$mailSend = $share->getMailSend();
663
-			if($mailSend === true) {
663
+			if ($mailSend === true) {
664 664
 				$user = $this->userManager->get($share->getSharedWith());
665 665
 				if ($user !== null) {
666 666
 					$emailAddress = $user->getEMailAddress();
@@ -675,12 +675,12 @@  discard block
 block discarded – undo
675 675
 							$emailAddress,
676 676
 							$share->getExpirationDate()
677 677
 						);
678
-						$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
678
+						$this->logger->debug('Send share notification to '.$emailAddress.' for share with ID '.$share->getId(), ['app' => 'share']);
679 679
 					} else {
680
-						$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
680
+						$this->logger->debug('Share notification not send to '.$share->getSharedWith().' because email address is not set.', ['app' => 'share']);
681 681
 					}
682 682
 				} else {
683
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
683
+					$this->logger->debug('Share notification not send to '.$share->getSharedWith().' because user could not be found.', ['app' => 'share']);
684 684
 				}
685 685
 			} else {
686 686
 				$this->logger->debug('Share notification not send because mailsend is false.', ['app' => 'share']);
@@ -724,7 +724,7 @@  discard block
 block discarded – undo
724 724
 		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
725 725
 
726 726
 		$emailTemplate->addBodyText(
727
-			$text . ' ' . $l->t('Click the button below to open it.'),
727
+			$text.' '.$l->t('Click the button below to open it.'),
728 728
 			$text
729 729
 		);
730 730
 		$emailTemplate->addBodyButton(
@@ -748,9 +748,9 @@  discard block
 block discarded – undo
748 748
 		// The "Reply-To" is set to the sharer if an mail address is configured
749 749
 		// also the default footer contains a "Do not reply" which needs to be adjusted.
750 750
 		$initiatorEmail = $initiatorUser->getEMailAddress();
751
-		if($initiatorEmail !== null) {
751
+		if ($initiatorEmail !== null) {
752 752
 			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
753
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
753
+			$emailTemplate->addFooter($instanceName.($this->defaults->getSlogan() !== '' ? ' - '.$this->defaults->getSlogan() : ''));
754 754
 		} else {
755 755
 			$emailTemplate->addFooter();
756 756
 		}
@@ -959,7 +959,7 @@  discard block
 block discarded – undo
959 959
 	 * @param string $recipientId
960 960
 	 */
961 961
 	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
962
-		list($providerId, ) = $this->splitFullId($share->getFullId());
962
+		list($providerId,) = $this->splitFullId($share->getFullId());
963 963
 		$provider = $this->factory->getProvider($providerId);
964 964
 
965 965
 		$provider->deleteFromSelf($share, $recipientId);
@@ -982,7 +982,7 @@  discard block
 block discarded – undo
982 982
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
983 983
 			$sharedWith = $this->groupManager->get($share->getSharedWith());
984 984
 			if (is_null($sharedWith)) {
985
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
985
+				throw new \InvalidArgumentException('Group "'.$share->getSharedWith().'" does not exist');
986 986
 			}
987 987
 			$recipient = $this->userManager->get($recipientId);
988 988
 			if (!$sharedWith->inGroup($recipient)) {
@@ -990,7 +990,7 @@  discard block
 block discarded – undo
990 990
 			}
991 991
 		}
992 992
 
993
-		list($providerId, ) = $this->splitFullId($share->getFullId());
993
+		list($providerId,) = $this->splitFullId($share->getFullId());
994 994
 		$provider = $this->factory->getProvider($providerId);
995 995
 
996 996
 		$provider->move($share, $recipientId);
@@ -1037,7 +1037,7 @@  discard block
 block discarded – undo
1037 1037
 
1038 1038
 		$shares2 = [];
1039 1039
 
1040
-		while(true) {
1040
+		while (true) {
1041 1041
 			$added = 0;
1042 1042
 			foreach ($shares as $share) {
1043 1043
 
@@ -1142,7 +1142,7 @@  discard block
 block discarded – undo
1142 1142
 	 *
1143 1143
 	 * @return Share[]
1144 1144
 	 */
1145
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1145
+	public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
1146 1146
 		return [];
1147 1147
 	}
1148 1148
 
@@ -1157,7 +1157,7 @@  discard block
 block discarded – undo
1157 1157
 	public function getShareByToken($token) {
1158 1158
 		$share = null;
1159 1159
 		try {
1160
-			if($this->shareApiAllowLinks()) {
1160
+			if ($this->shareApiAllowLinks()) {
1161 1161
 				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1162 1162
 				$share = $provider->getShareByToken($token);
1163 1163
 			}
@@ -1364,7 +1364,7 @@  discard block
 block discarded – undo
1364 1364
 			}
1365 1365
 			$al['users'][$owner] = [
1366 1366
 				'node_id' => $path->getId(),
1367
-				'node_path' => '/' . $ownerPath,
1367
+				'node_path' => '/'.$ownerPath,
1368 1368
 			];
1369 1369
 		} else {
1370 1370
 			$al['users'][] = $owner;
@@ -1458,7 +1458,7 @@  discard block
 block discarded – undo
1458 1458
 	 * @return int
1459 1459
 	 */
1460 1460
 	public function shareApiLinkDefaultExpireDays() {
1461
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1461
+		return (int) $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1462 1462
 	}
1463 1463
 
1464 1464
 	/**
Please login to merge, or discard this patch.
Indentation   +1470 added lines, -1470 removed lines patch added patch discarded remove patch
@@ -70,1498 +70,1498 @@
 block discarded – undo
70 70
  */
71 71
 class Manager implements IManager {
72 72
 
73
-	/** @var IProviderFactory */
74
-	private $factory;
75
-	/** @var ILogger */
76
-	private $logger;
77
-	/** @var IConfig */
78
-	private $config;
79
-	/** @var ISecureRandom */
80
-	private $secureRandom;
81
-	/** @var IHasher */
82
-	private $hasher;
83
-	/** @var IMountManager */
84
-	private $mountManager;
85
-	/** @var IGroupManager */
86
-	private $groupManager;
87
-	/** @var IL10N */
88
-	private $l;
89
-	/** @var IFactory */
90
-	private $l10nFactory;
91
-	/** @var IUserManager */
92
-	private $userManager;
93
-	/** @var IRootFolder */
94
-	private $rootFolder;
95
-	/** @var CappedMemoryCache */
96
-	private $sharingDisabledForUsersCache;
97
-	/** @var EventDispatcher */
98
-	private $eventDispatcher;
99
-	/** @var LegacyHooks */
100
-	private $legacyHooks;
101
-	/** @var IMailer */
102
-	private $mailer;
103
-	/** @var IURLGenerator */
104
-	private $urlGenerator;
105
-	/** @var \OC_Defaults */
106
-	private $defaults;
107
-
108
-
109
-	/**
110
-	 * Manager constructor.
111
-	 *
112
-	 * @param ILogger $logger
113
-	 * @param IConfig $config
114
-	 * @param ISecureRandom $secureRandom
115
-	 * @param IHasher $hasher
116
-	 * @param IMountManager $mountManager
117
-	 * @param IGroupManager $groupManager
118
-	 * @param IL10N $l
119
-	 * @param IFactory $l10nFactory
120
-	 * @param IProviderFactory $factory
121
-	 * @param IUserManager $userManager
122
-	 * @param IRootFolder $rootFolder
123
-	 * @param EventDispatcher $eventDispatcher
124
-	 * @param IMailer $mailer
125
-	 * @param IURLGenerator $urlGenerator
126
-	 * @param \OC_Defaults $defaults
127
-	 */
128
-	public function __construct(
129
-			ILogger $logger,
130
-			IConfig $config,
131
-			ISecureRandom $secureRandom,
132
-			IHasher $hasher,
133
-			IMountManager $mountManager,
134
-			IGroupManager $groupManager,
135
-			IL10N $l,
136
-			IFactory $l10nFactory,
137
-			IProviderFactory $factory,
138
-			IUserManager $userManager,
139
-			IRootFolder $rootFolder,
140
-			EventDispatcher $eventDispatcher,
141
-			IMailer $mailer,
142
-			IURLGenerator $urlGenerator,
143
-			\OC_Defaults $defaults
144
-	) {
145
-		$this->logger = $logger;
146
-		$this->config = $config;
147
-		$this->secureRandom = $secureRandom;
148
-		$this->hasher = $hasher;
149
-		$this->mountManager = $mountManager;
150
-		$this->groupManager = $groupManager;
151
-		$this->l = $l;
152
-		$this->l10nFactory = $l10nFactory;
153
-		$this->factory = $factory;
154
-		$this->userManager = $userManager;
155
-		$this->rootFolder = $rootFolder;
156
-		$this->eventDispatcher = $eventDispatcher;
157
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
158
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
159
-		$this->mailer = $mailer;
160
-		$this->urlGenerator = $urlGenerator;
161
-		$this->defaults = $defaults;
162
-	}
163
-
164
-	/**
165
-	 * Convert from a full share id to a tuple (providerId, shareId)
166
-	 *
167
-	 * @param string $id
168
-	 * @return string[]
169
-	 */
170
-	private function splitFullId($id) {
171
-		return explode(':', $id, 2);
172
-	}
173
-
174
-	/**
175
-	 * Verify if a password meets all requirements
176
-	 *
177
-	 * @param string $password
178
-	 * @throws \Exception
179
-	 */
180
-	protected function verifyPassword($password) {
181
-		if ($password === null) {
182
-			// No password is set, check if this is allowed.
183
-			if ($this->shareApiLinkEnforcePassword()) {
184
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
185
-			}
186
-
187
-			return;
188
-		}
189
-
190
-		// Let others verify the password
191
-		try {
192
-			$event = new GenericEvent($password);
193
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
194
-		} catch (HintException $e) {
195
-			throw new \Exception($e->getHint());
196
-		}
197
-	}
198
-
199
-	/**
200
-	 * Check for generic requirements before creating a share
201
-	 *
202
-	 * @param \OCP\Share\IShare $share
203
-	 * @throws \InvalidArgumentException
204
-	 * @throws GenericShareException
205
-	 *
206
-	 * @suppress PhanUndeclaredClassMethod
207
-	 */
208
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
209
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
210
-			// We expect a valid user as sharedWith for user shares
211
-			if (!$this->userManager->userExists($share->getSharedWith())) {
212
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
213
-			}
214
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
215
-			// We expect a valid group as sharedWith for group shares
216
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
217
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
218
-			}
219
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
220
-			if ($share->getSharedWith() !== null) {
221
-				throw new \InvalidArgumentException('SharedWith should be empty');
222
-			}
223
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
224
-			if ($share->getSharedWith() === null) {
225
-				throw new \InvalidArgumentException('SharedWith should not be empty');
226
-			}
227
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
228
-			if ($share->getSharedWith() === null) {
229
-				throw new \InvalidArgumentException('SharedWith should not be empty');
230
-			}
231
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
232
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
233
-			if ($circle === null) {
234
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
235
-			}
236
-		} else {
237
-			// We can't handle other types yet
238
-			throw new \InvalidArgumentException('unknown share type');
239
-		}
240
-
241
-		// Verify the initiator of the share is set
242
-		if ($share->getSharedBy() === null) {
243
-			throw new \InvalidArgumentException('SharedBy should be set');
244
-		}
245
-
246
-		// Cannot share with yourself
247
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
248
-			$share->getSharedWith() === $share->getSharedBy()) {
249
-			throw new \InvalidArgumentException('Can’t share with yourself');
250
-		}
251
-
252
-		// The path should be set
253
-		if ($share->getNode() === null) {
254
-			throw new \InvalidArgumentException('Path should be set');
255
-		}
256
-
257
-		// And it should be a file or a folder
258
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
259
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
260
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
261
-		}
262
-
263
-		// And you can't share your rootfolder
264
-		if ($this->userManager->userExists($share->getSharedBy())) {
265
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
266
-		} else {
267
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
268
-		}
269
-		if ($sharedPath === $share->getNode()->getPath()) {
270
-			throw new \InvalidArgumentException('You can’t share your root folder');
271
-		}
272
-
273
-		// Check if we actually have share permissions
274
-		if (!$share->getNode()->isShareable()) {
275
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
276
-			throw new GenericShareException($message_t, $message_t, 404);
277
-		}
278
-
279
-		// Permissions should be set
280
-		if ($share->getPermissions() === null) {
281
-			throw new \InvalidArgumentException('A share requires permissions');
282
-		}
283
-
284
-		/*
73
+    /** @var IProviderFactory */
74
+    private $factory;
75
+    /** @var ILogger */
76
+    private $logger;
77
+    /** @var IConfig */
78
+    private $config;
79
+    /** @var ISecureRandom */
80
+    private $secureRandom;
81
+    /** @var IHasher */
82
+    private $hasher;
83
+    /** @var IMountManager */
84
+    private $mountManager;
85
+    /** @var IGroupManager */
86
+    private $groupManager;
87
+    /** @var IL10N */
88
+    private $l;
89
+    /** @var IFactory */
90
+    private $l10nFactory;
91
+    /** @var IUserManager */
92
+    private $userManager;
93
+    /** @var IRootFolder */
94
+    private $rootFolder;
95
+    /** @var CappedMemoryCache */
96
+    private $sharingDisabledForUsersCache;
97
+    /** @var EventDispatcher */
98
+    private $eventDispatcher;
99
+    /** @var LegacyHooks */
100
+    private $legacyHooks;
101
+    /** @var IMailer */
102
+    private $mailer;
103
+    /** @var IURLGenerator */
104
+    private $urlGenerator;
105
+    /** @var \OC_Defaults */
106
+    private $defaults;
107
+
108
+
109
+    /**
110
+     * Manager constructor.
111
+     *
112
+     * @param ILogger $logger
113
+     * @param IConfig $config
114
+     * @param ISecureRandom $secureRandom
115
+     * @param IHasher $hasher
116
+     * @param IMountManager $mountManager
117
+     * @param IGroupManager $groupManager
118
+     * @param IL10N $l
119
+     * @param IFactory $l10nFactory
120
+     * @param IProviderFactory $factory
121
+     * @param IUserManager $userManager
122
+     * @param IRootFolder $rootFolder
123
+     * @param EventDispatcher $eventDispatcher
124
+     * @param IMailer $mailer
125
+     * @param IURLGenerator $urlGenerator
126
+     * @param \OC_Defaults $defaults
127
+     */
128
+    public function __construct(
129
+            ILogger $logger,
130
+            IConfig $config,
131
+            ISecureRandom $secureRandom,
132
+            IHasher $hasher,
133
+            IMountManager $mountManager,
134
+            IGroupManager $groupManager,
135
+            IL10N $l,
136
+            IFactory $l10nFactory,
137
+            IProviderFactory $factory,
138
+            IUserManager $userManager,
139
+            IRootFolder $rootFolder,
140
+            EventDispatcher $eventDispatcher,
141
+            IMailer $mailer,
142
+            IURLGenerator $urlGenerator,
143
+            \OC_Defaults $defaults
144
+    ) {
145
+        $this->logger = $logger;
146
+        $this->config = $config;
147
+        $this->secureRandom = $secureRandom;
148
+        $this->hasher = $hasher;
149
+        $this->mountManager = $mountManager;
150
+        $this->groupManager = $groupManager;
151
+        $this->l = $l;
152
+        $this->l10nFactory = $l10nFactory;
153
+        $this->factory = $factory;
154
+        $this->userManager = $userManager;
155
+        $this->rootFolder = $rootFolder;
156
+        $this->eventDispatcher = $eventDispatcher;
157
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
158
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
159
+        $this->mailer = $mailer;
160
+        $this->urlGenerator = $urlGenerator;
161
+        $this->defaults = $defaults;
162
+    }
163
+
164
+    /**
165
+     * Convert from a full share id to a tuple (providerId, shareId)
166
+     *
167
+     * @param string $id
168
+     * @return string[]
169
+     */
170
+    private function splitFullId($id) {
171
+        return explode(':', $id, 2);
172
+    }
173
+
174
+    /**
175
+     * Verify if a password meets all requirements
176
+     *
177
+     * @param string $password
178
+     * @throws \Exception
179
+     */
180
+    protected function verifyPassword($password) {
181
+        if ($password === null) {
182
+            // No password is set, check if this is allowed.
183
+            if ($this->shareApiLinkEnforcePassword()) {
184
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
185
+            }
186
+
187
+            return;
188
+        }
189
+
190
+        // Let others verify the password
191
+        try {
192
+            $event = new GenericEvent($password);
193
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
194
+        } catch (HintException $e) {
195
+            throw new \Exception($e->getHint());
196
+        }
197
+    }
198
+
199
+    /**
200
+     * Check for generic requirements before creating a share
201
+     *
202
+     * @param \OCP\Share\IShare $share
203
+     * @throws \InvalidArgumentException
204
+     * @throws GenericShareException
205
+     *
206
+     * @suppress PhanUndeclaredClassMethod
207
+     */
208
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
209
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
210
+            // We expect a valid user as sharedWith for user shares
211
+            if (!$this->userManager->userExists($share->getSharedWith())) {
212
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
213
+            }
214
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
215
+            // We expect a valid group as sharedWith for group shares
216
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
217
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
218
+            }
219
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
220
+            if ($share->getSharedWith() !== null) {
221
+                throw new \InvalidArgumentException('SharedWith should be empty');
222
+            }
223
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
224
+            if ($share->getSharedWith() === null) {
225
+                throw new \InvalidArgumentException('SharedWith should not be empty');
226
+            }
227
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
228
+            if ($share->getSharedWith() === null) {
229
+                throw new \InvalidArgumentException('SharedWith should not be empty');
230
+            }
231
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
232
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
233
+            if ($circle === null) {
234
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
235
+            }
236
+        } else {
237
+            // We can't handle other types yet
238
+            throw new \InvalidArgumentException('unknown share type');
239
+        }
240
+
241
+        // Verify the initiator of the share is set
242
+        if ($share->getSharedBy() === null) {
243
+            throw new \InvalidArgumentException('SharedBy should be set');
244
+        }
245
+
246
+        // Cannot share with yourself
247
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
248
+            $share->getSharedWith() === $share->getSharedBy()) {
249
+            throw new \InvalidArgumentException('Can’t share with yourself');
250
+        }
251
+
252
+        // The path should be set
253
+        if ($share->getNode() === null) {
254
+            throw new \InvalidArgumentException('Path should be set');
255
+        }
256
+
257
+        // And it should be a file or a folder
258
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
259
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
260
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
261
+        }
262
+
263
+        // And you can't share your rootfolder
264
+        if ($this->userManager->userExists($share->getSharedBy())) {
265
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
266
+        } else {
267
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
268
+        }
269
+        if ($sharedPath === $share->getNode()->getPath()) {
270
+            throw new \InvalidArgumentException('You can’t share your root folder');
271
+        }
272
+
273
+        // Check if we actually have share permissions
274
+        if (!$share->getNode()->isShareable()) {
275
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
276
+            throw new GenericShareException($message_t, $message_t, 404);
277
+        }
278
+
279
+        // Permissions should be set
280
+        if ($share->getPermissions() === null) {
281
+            throw new \InvalidArgumentException('A share requires permissions');
282
+        }
283
+
284
+        /*
285 285
 		 * Quick fix for #23536
286 286
 		 * Non moveable mount points do not have update and delete permissions
287 287
 		 * while we 'most likely' do have that on the storage.
288 288
 		 */
289
-		$permissions = $share->getNode()->getPermissions();
290
-		$mount = $share->getNode()->getMountPoint();
291
-		if (!($mount instanceof MoveableMount)) {
292
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
293
-		}
294
-
295
-		// Check that we do not share with more permissions than we have
296
-		if ($share->getPermissions() & ~$permissions) {
297
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
298
-			throw new GenericShareException($message_t, $message_t, 404);
299
-		}
300
-
301
-
302
-		// Check that read permissions are always set
303
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
304
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
305
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
306
-		if (!$noReadPermissionRequired &&
307
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
308
-			throw new \InvalidArgumentException('Shares need at least read permissions');
309
-		}
310
-
311
-		if ($share->getNode() instanceof \OCP\Files\File) {
312
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
313
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
314
-				throw new GenericShareException($message_t);
315
-			}
316
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
317
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
318
-				throw new GenericShareException($message_t);
319
-			}
320
-		}
321
-	}
322
-
323
-	/**
324
-	 * Validate if the expiration date fits the system settings
325
-	 *
326
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
327
-	 * @return \OCP\Share\IShare The modified share object
328
-	 * @throws GenericShareException
329
-	 * @throws \InvalidArgumentException
330
-	 * @throws \Exception
331
-	 */
332
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
333
-
334
-		$expirationDate = $share->getExpirationDate();
335
-
336
-		if ($expirationDate !== null) {
337
-			//Make sure the expiration date is a date
338
-			$expirationDate->setTime(0, 0, 0);
339
-
340
-			$date = new \DateTime();
341
-			$date->setTime(0, 0, 0);
342
-			if ($date >= $expirationDate) {
343
-				$message = $this->l->t('Expiration date is in the past');
344
-				throw new GenericShareException($message, $message, 404);
345
-			}
346
-		}
347
-
348
-		// If expiredate is empty set a default one if there is a default
349
-		$fullId = null;
350
-		try {
351
-			$fullId = $share->getFullId();
352
-		} catch (\UnexpectedValueException $e) {
353
-			// This is a new share
354
-		}
355
-
356
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
357
-			$expirationDate = new \DateTime();
358
-			$expirationDate->setTime(0,0,0);
359
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
360
-		}
361
-
362
-		// If we enforce the expiration date check that is does not exceed
363
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
364
-			if ($expirationDate === null) {
365
-				throw new \InvalidArgumentException('Expiration date is enforced');
366
-			}
367
-
368
-			$date = new \DateTime();
369
-			$date->setTime(0, 0, 0);
370
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
371
-			if ($date < $expirationDate) {
372
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
373
-				throw new GenericShareException($message, $message, 404);
374
-			}
375
-		}
376
-
377
-		$accepted = true;
378
-		$message = '';
379
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
380
-			'expirationDate' => &$expirationDate,
381
-			'accepted' => &$accepted,
382
-			'message' => &$message,
383
-			'passwordSet' => $share->getPassword() !== null,
384
-		]);
385
-
386
-		if (!$accepted) {
387
-			throw new \Exception($message);
388
-		}
389
-
390
-		$share->setExpirationDate($expirationDate);
391
-
392
-		return $share;
393
-	}
394
-
395
-	/**
396
-	 * Check for pre share requirements for user shares
397
-	 *
398
-	 * @param \OCP\Share\IShare $share
399
-	 * @throws \Exception
400
-	 */
401
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
402
-		// Check if we can share with group members only
403
-		if ($this->shareWithGroupMembersOnly()) {
404
-			$sharedBy = $this->userManager->get($share->getSharedBy());
405
-			$sharedWith = $this->userManager->get($share->getSharedWith());
406
-			// Verify we can share with this user
407
-			$groups = array_intersect(
408
-					$this->groupManager->getUserGroupIds($sharedBy),
409
-					$this->groupManager->getUserGroupIds($sharedWith)
410
-			);
411
-			if (empty($groups)) {
412
-				throw new \Exception('Sharing is only allowed with group members');
413
-			}
414
-		}
415
-
416
-		/*
289
+        $permissions = $share->getNode()->getPermissions();
290
+        $mount = $share->getNode()->getMountPoint();
291
+        if (!($mount instanceof MoveableMount)) {
292
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
293
+        }
294
+
295
+        // Check that we do not share with more permissions than we have
296
+        if ($share->getPermissions() & ~$permissions) {
297
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
298
+            throw new GenericShareException($message_t, $message_t, 404);
299
+        }
300
+
301
+
302
+        // Check that read permissions are always set
303
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
304
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
305
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
306
+        if (!$noReadPermissionRequired &&
307
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
308
+            throw new \InvalidArgumentException('Shares need at least read permissions');
309
+        }
310
+
311
+        if ($share->getNode() instanceof \OCP\Files\File) {
312
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
313
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
314
+                throw new GenericShareException($message_t);
315
+            }
316
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
317
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
318
+                throw new GenericShareException($message_t);
319
+            }
320
+        }
321
+    }
322
+
323
+    /**
324
+     * Validate if the expiration date fits the system settings
325
+     *
326
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
327
+     * @return \OCP\Share\IShare The modified share object
328
+     * @throws GenericShareException
329
+     * @throws \InvalidArgumentException
330
+     * @throws \Exception
331
+     */
332
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
333
+
334
+        $expirationDate = $share->getExpirationDate();
335
+
336
+        if ($expirationDate !== null) {
337
+            //Make sure the expiration date is a date
338
+            $expirationDate->setTime(0, 0, 0);
339
+
340
+            $date = new \DateTime();
341
+            $date->setTime(0, 0, 0);
342
+            if ($date >= $expirationDate) {
343
+                $message = $this->l->t('Expiration date is in the past');
344
+                throw new GenericShareException($message, $message, 404);
345
+            }
346
+        }
347
+
348
+        // If expiredate is empty set a default one if there is a default
349
+        $fullId = null;
350
+        try {
351
+            $fullId = $share->getFullId();
352
+        } catch (\UnexpectedValueException $e) {
353
+            // This is a new share
354
+        }
355
+
356
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
357
+            $expirationDate = new \DateTime();
358
+            $expirationDate->setTime(0,0,0);
359
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
360
+        }
361
+
362
+        // If we enforce the expiration date check that is does not exceed
363
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
364
+            if ($expirationDate === null) {
365
+                throw new \InvalidArgumentException('Expiration date is enforced');
366
+            }
367
+
368
+            $date = new \DateTime();
369
+            $date->setTime(0, 0, 0);
370
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
371
+            if ($date < $expirationDate) {
372
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
373
+                throw new GenericShareException($message, $message, 404);
374
+            }
375
+        }
376
+
377
+        $accepted = true;
378
+        $message = '';
379
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
380
+            'expirationDate' => &$expirationDate,
381
+            'accepted' => &$accepted,
382
+            'message' => &$message,
383
+            'passwordSet' => $share->getPassword() !== null,
384
+        ]);
385
+
386
+        if (!$accepted) {
387
+            throw new \Exception($message);
388
+        }
389
+
390
+        $share->setExpirationDate($expirationDate);
391
+
392
+        return $share;
393
+    }
394
+
395
+    /**
396
+     * Check for pre share requirements for user shares
397
+     *
398
+     * @param \OCP\Share\IShare $share
399
+     * @throws \Exception
400
+     */
401
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
402
+        // Check if we can share with group members only
403
+        if ($this->shareWithGroupMembersOnly()) {
404
+            $sharedBy = $this->userManager->get($share->getSharedBy());
405
+            $sharedWith = $this->userManager->get($share->getSharedWith());
406
+            // Verify we can share with this user
407
+            $groups = array_intersect(
408
+                    $this->groupManager->getUserGroupIds($sharedBy),
409
+                    $this->groupManager->getUserGroupIds($sharedWith)
410
+            );
411
+            if (empty($groups)) {
412
+                throw new \Exception('Sharing is only allowed with group members');
413
+            }
414
+        }
415
+
416
+        /*
417 417
 		 * TODO: Could be costly, fix
418 418
 		 *
419 419
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
420 420
 		 */
421
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
422
-		$existingShares = $provider->getSharesByPath($share->getNode());
423
-		foreach($existingShares as $existingShare) {
424
-			// Ignore if it is the same share
425
-			try {
426
-				if ($existingShare->getFullId() === $share->getFullId()) {
427
-					continue;
428
-				}
429
-			} catch (\UnexpectedValueException $e) {
430
-				//Shares are not identical
431
-			}
432
-
433
-			// Identical share already existst
434
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
435
-				throw new \Exception('Path is already shared with this user');
436
-			}
437
-
438
-			// The share is already shared with this user via a group share
439
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
440
-				$group = $this->groupManager->get($existingShare->getSharedWith());
441
-				if (!is_null($group)) {
442
-					$user = $this->userManager->get($share->getSharedWith());
443
-
444
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
445
-						throw new \Exception('Path is already shared with this user');
446
-					}
447
-				}
448
-			}
449
-		}
450
-	}
451
-
452
-	/**
453
-	 * Check for pre share requirements for group shares
454
-	 *
455
-	 * @param \OCP\Share\IShare $share
456
-	 * @throws \Exception
457
-	 */
458
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
459
-		// Verify group shares are allowed
460
-		if (!$this->allowGroupSharing()) {
461
-			throw new \Exception('Group sharing is now allowed');
462
-		}
463
-
464
-		// Verify if the user can share with this group
465
-		if ($this->shareWithGroupMembersOnly()) {
466
-			$sharedBy = $this->userManager->get($share->getSharedBy());
467
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
468
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
469
-				throw new \Exception('Sharing is only allowed within your own groups');
470
-			}
471
-		}
472
-
473
-		/*
421
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
422
+        $existingShares = $provider->getSharesByPath($share->getNode());
423
+        foreach($existingShares as $existingShare) {
424
+            // Ignore if it is the same share
425
+            try {
426
+                if ($existingShare->getFullId() === $share->getFullId()) {
427
+                    continue;
428
+                }
429
+            } catch (\UnexpectedValueException $e) {
430
+                //Shares are not identical
431
+            }
432
+
433
+            // Identical share already existst
434
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
435
+                throw new \Exception('Path is already shared with this user');
436
+            }
437
+
438
+            // The share is already shared with this user via a group share
439
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
440
+                $group = $this->groupManager->get($existingShare->getSharedWith());
441
+                if (!is_null($group)) {
442
+                    $user = $this->userManager->get($share->getSharedWith());
443
+
444
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
445
+                        throw new \Exception('Path is already shared with this user');
446
+                    }
447
+                }
448
+            }
449
+        }
450
+    }
451
+
452
+    /**
453
+     * Check for pre share requirements for group shares
454
+     *
455
+     * @param \OCP\Share\IShare $share
456
+     * @throws \Exception
457
+     */
458
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
459
+        // Verify group shares are allowed
460
+        if (!$this->allowGroupSharing()) {
461
+            throw new \Exception('Group sharing is now allowed');
462
+        }
463
+
464
+        // Verify if the user can share with this group
465
+        if ($this->shareWithGroupMembersOnly()) {
466
+            $sharedBy = $this->userManager->get($share->getSharedBy());
467
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
468
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
469
+                throw new \Exception('Sharing is only allowed within your own groups');
470
+            }
471
+        }
472
+
473
+        /*
474 474
 		 * TODO: Could be costly, fix
475 475
 		 *
476 476
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
477 477
 		 */
478
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
479
-		$existingShares = $provider->getSharesByPath($share->getNode());
480
-		foreach($existingShares as $existingShare) {
481
-			try {
482
-				if ($existingShare->getFullId() === $share->getFullId()) {
483
-					continue;
484
-				}
485
-			} catch (\UnexpectedValueException $e) {
486
-				//It is a new share so just continue
487
-			}
488
-
489
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
490
-				throw new \Exception('Path is already shared with this group');
491
-			}
492
-		}
493
-	}
494
-
495
-	/**
496
-	 * Check for pre share requirements for link shares
497
-	 *
498
-	 * @param \OCP\Share\IShare $share
499
-	 * @throws \Exception
500
-	 */
501
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
502
-		// Are link shares allowed?
503
-		if (!$this->shareApiAllowLinks()) {
504
-			throw new \Exception('Link sharing is not allowed');
505
-		}
506
-
507
-		// Link shares by definition can't have share permissions
508
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
509
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
510
-		}
511
-
512
-		// Check if public upload is allowed
513
-		if (!$this->shareApiLinkAllowPublicUpload() &&
514
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
515
-			throw new \InvalidArgumentException('Public upload is not allowed');
516
-		}
517
-	}
518
-
519
-	/**
520
-	 * To make sure we don't get invisible link shares we set the parent
521
-	 * of a link if it is a reshare. This is a quick word around
522
-	 * until we can properly display multiple link shares in the UI
523
-	 *
524
-	 * See: https://github.com/owncloud/core/issues/22295
525
-	 *
526
-	 * FIXME: Remove once multiple link shares can be properly displayed
527
-	 *
528
-	 * @param \OCP\Share\IShare $share
529
-	 */
530
-	protected function setLinkParent(\OCP\Share\IShare $share) {
531
-
532
-		// No sense in checking if the method is not there.
533
-		if (method_exists($share, 'setParent')) {
534
-			$storage = $share->getNode()->getStorage();
535
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
536
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
537
-				$share->setParent($storage->getShareId());
538
-			}
539
-		};
540
-	}
541
-
542
-	/**
543
-	 * @param File|Folder $path
544
-	 */
545
-	protected function pathCreateChecks($path) {
546
-		// Make sure that we do not share a path that contains a shared mountpoint
547
-		if ($path instanceof \OCP\Files\Folder) {
548
-			$mounts = $this->mountManager->findIn($path->getPath());
549
-			foreach($mounts as $mount) {
550
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
551
-					throw new \InvalidArgumentException('Path contains files shared with you');
552
-				}
553
-			}
554
-		}
555
-	}
556
-
557
-	/**
558
-	 * Check if the user that is sharing can actually share
559
-	 *
560
-	 * @param \OCP\Share\IShare $share
561
-	 * @throws \Exception
562
-	 */
563
-	protected function canShare(\OCP\Share\IShare $share) {
564
-		if (!$this->shareApiEnabled()) {
565
-			throw new \Exception('Sharing is disabled');
566
-		}
567
-
568
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
569
-			throw new \Exception('Sharing is disabled for you');
570
-		}
571
-	}
572
-
573
-	/**
574
-	 * Share a path
575
-	 *
576
-	 * @param \OCP\Share\IShare $share
577
-	 * @return Share The share object
578
-	 * @throws \Exception
579
-	 *
580
-	 * TODO: handle link share permissions or check them
581
-	 */
582
-	public function createShare(\OCP\Share\IShare $share) {
583
-		$this->canShare($share);
584
-
585
-		$this->generalCreateChecks($share);
586
-
587
-		// Verify if there are any issues with the path
588
-		$this->pathCreateChecks($share->getNode());
589
-
590
-		/*
478
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
479
+        $existingShares = $provider->getSharesByPath($share->getNode());
480
+        foreach($existingShares as $existingShare) {
481
+            try {
482
+                if ($existingShare->getFullId() === $share->getFullId()) {
483
+                    continue;
484
+                }
485
+            } catch (\UnexpectedValueException $e) {
486
+                //It is a new share so just continue
487
+            }
488
+
489
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
490
+                throw new \Exception('Path is already shared with this group');
491
+            }
492
+        }
493
+    }
494
+
495
+    /**
496
+     * Check for pre share requirements for link shares
497
+     *
498
+     * @param \OCP\Share\IShare $share
499
+     * @throws \Exception
500
+     */
501
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
502
+        // Are link shares allowed?
503
+        if (!$this->shareApiAllowLinks()) {
504
+            throw new \Exception('Link sharing is not allowed');
505
+        }
506
+
507
+        // Link shares by definition can't have share permissions
508
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
509
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
510
+        }
511
+
512
+        // Check if public upload is allowed
513
+        if (!$this->shareApiLinkAllowPublicUpload() &&
514
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
515
+            throw new \InvalidArgumentException('Public upload is not allowed');
516
+        }
517
+    }
518
+
519
+    /**
520
+     * To make sure we don't get invisible link shares we set the parent
521
+     * of a link if it is a reshare. This is a quick word around
522
+     * until we can properly display multiple link shares in the UI
523
+     *
524
+     * See: https://github.com/owncloud/core/issues/22295
525
+     *
526
+     * FIXME: Remove once multiple link shares can be properly displayed
527
+     *
528
+     * @param \OCP\Share\IShare $share
529
+     */
530
+    protected function setLinkParent(\OCP\Share\IShare $share) {
531
+
532
+        // No sense in checking if the method is not there.
533
+        if (method_exists($share, 'setParent')) {
534
+            $storage = $share->getNode()->getStorage();
535
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
536
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
537
+                $share->setParent($storage->getShareId());
538
+            }
539
+        };
540
+    }
541
+
542
+    /**
543
+     * @param File|Folder $path
544
+     */
545
+    protected function pathCreateChecks($path) {
546
+        // Make sure that we do not share a path that contains a shared mountpoint
547
+        if ($path instanceof \OCP\Files\Folder) {
548
+            $mounts = $this->mountManager->findIn($path->getPath());
549
+            foreach($mounts as $mount) {
550
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
551
+                    throw new \InvalidArgumentException('Path contains files shared with you');
552
+                }
553
+            }
554
+        }
555
+    }
556
+
557
+    /**
558
+     * Check if the user that is sharing can actually share
559
+     *
560
+     * @param \OCP\Share\IShare $share
561
+     * @throws \Exception
562
+     */
563
+    protected function canShare(\OCP\Share\IShare $share) {
564
+        if (!$this->shareApiEnabled()) {
565
+            throw new \Exception('Sharing is disabled');
566
+        }
567
+
568
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
569
+            throw new \Exception('Sharing is disabled for you');
570
+        }
571
+    }
572
+
573
+    /**
574
+     * Share a path
575
+     *
576
+     * @param \OCP\Share\IShare $share
577
+     * @return Share The share object
578
+     * @throws \Exception
579
+     *
580
+     * TODO: handle link share permissions or check them
581
+     */
582
+    public function createShare(\OCP\Share\IShare $share) {
583
+        $this->canShare($share);
584
+
585
+        $this->generalCreateChecks($share);
586
+
587
+        // Verify if there are any issues with the path
588
+        $this->pathCreateChecks($share->getNode());
589
+
590
+        /*
591 591
 		 * On creation of a share the owner is always the owner of the path
592 592
 		 * Except for mounted federated shares.
593 593
 		 */
594
-		$storage = $share->getNode()->getStorage();
595
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
596
-			$parent = $share->getNode()->getParent();
597
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
598
-				$parent = $parent->getParent();
599
-			}
600
-			$share->setShareOwner($parent->getOwner()->getUID());
601
-		} else {
602
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
603
-		}
604
-
605
-		//Verify share type
606
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
607
-			$this->userCreateChecks($share);
608
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
609
-			$this->groupCreateChecks($share);
610
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
611
-			$this->linkCreateChecks($share);
612
-			$this->setLinkParent($share);
613
-
614
-			/*
594
+        $storage = $share->getNode()->getStorage();
595
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
596
+            $parent = $share->getNode()->getParent();
597
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
598
+                $parent = $parent->getParent();
599
+            }
600
+            $share->setShareOwner($parent->getOwner()->getUID());
601
+        } else {
602
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
603
+        }
604
+
605
+        //Verify share type
606
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
607
+            $this->userCreateChecks($share);
608
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
609
+            $this->groupCreateChecks($share);
610
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
611
+            $this->linkCreateChecks($share);
612
+            $this->setLinkParent($share);
613
+
614
+            /*
615 615
 			 * For now ignore a set token.
616 616
 			 */
617
-			$share->setToken(
618
-				$this->secureRandom->generate(
619
-					\OC\Share\Constants::TOKEN_LENGTH,
620
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
621
-				)
622
-			);
623
-
624
-			//Verify the expiration date
625
-			$this->validateExpirationDate($share);
626
-
627
-			//Verify the password
628
-			$this->verifyPassword($share->getPassword());
629
-
630
-			// If a password is set. Hash it!
631
-			if ($share->getPassword() !== null) {
632
-				$share->setPassword($this->hasher->hash($share->getPassword()));
633
-			}
634
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
635
-			$share->setToken(
636
-				$this->secureRandom->generate(
637
-					\OC\Share\Constants::TOKEN_LENGTH,
638
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
639
-				)
640
-			);
641
-		}
642
-
643
-		// Cannot share with the owner
644
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
645
-			$share->getSharedWith() === $share->getShareOwner()) {
646
-			throw new \InvalidArgumentException('Can’t share with the share owner');
647
-		}
648
-
649
-		// Generate the target
650
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
651
-		$target = \OC\Files\Filesystem::normalizePath($target);
652
-		$share->setTarget($target);
653
-
654
-		// Pre share event
655
-		$event = new GenericEvent($share);
656
-		$a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
657
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
658
-			throw new \Exception($event->getArgument('error'));
659
-		}
660
-
661
-		$oldShare = $share;
662
-		$provider = $this->factory->getProviderForType($share->getShareType());
663
-		$share = $provider->create($share);
664
-		//reuse the node we already have
665
-		$share->setNode($oldShare->getNode());
666
-
667
-		// Post share event
668
-		$event = new GenericEvent($share);
669
-		$this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
670
-
671
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
672
-			$mailSend = $share->getMailSend();
673
-			if($mailSend === true) {
674
-				$user = $this->userManager->get($share->getSharedWith());
675
-				if ($user !== null) {
676
-					$emailAddress = $user->getEMailAddress();
677
-					if ($emailAddress !== null && $emailAddress !== '') {
678
-						$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
679
-						$l = $this->l10nFactory->get('lib', $userLang);
680
-						$this->sendMailNotification(
681
-							$l,
682
-							$share->getNode()->getName(),
683
-							$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
684
-							$share->getSharedBy(),
685
-							$emailAddress,
686
-							$share->getExpirationDate()
687
-						);
688
-						$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
689
-					} else {
690
-						$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
691
-					}
692
-				} else {
693
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
694
-				}
695
-			} else {
696
-				$this->logger->debug('Share notification not send because mailsend is false.', ['app' => 'share']);
697
-			}
698
-		}
699
-
700
-		return $share;
701
-	}
702
-
703
-	/**
704
-	 * @param IL10N $l Language of the recipient
705
-	 * @param string $filename file/folder name
706
-	 * @param string $link link to the file/folder
707
-	 * @param string $initiator user ID of share sender
708
-	 * @param string $shareWith email address of share receiver
709
-	 * @param \DateTime|null $expiration
710
-	 * @throws \Exception If mail couldn't be sent
711
-	 */
712
-	protected function sendMailNotification(IL10N $l,
713
-											$filename,
714
-											$link,
715
-											$initiator,
716
-											$shareWith,
717
-											\DateTime $expiration = null) {
718
-		$initiatorUser = $this->userManager->get($initiator);
719
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
720
-
721
-		$message = $this->mailer->createMessage();
722
-
723
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
724
-			'filename' => $filename,
725
-			'link' => $link,
726
-			'initiator' => $initiatorDisplayName,
727
-			'expiration' => $expiration,
728
-			'shareWith' => $shareWith,
729
-		]);
730
-
731
-		$emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename)));
732
-		$emailTemplate->addHeader();
733
-		$emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
734
-		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
735
-
736
-		$emailTemplate->addBodyText(
737
-			$text . ' ' . $l->t('Click the button below to open it.'),
738
-			$text
739
-		);
740
-		$emailTemplate->addBodyButton(
741
-			$l->t('Open »%s«', [$filename]),
742
-			$link
743
-		);
744
-
745
-		$message->setTo([$shareWith]);
746
-
747
-		// The "From" contains the sharers name
748
-		$instanceName = $this->defaults->getName();
749
-		$senderName = $l->t(
750
-			'%s via %s',
751
-			[
752
-				$initiatorDisplayName,
753
-				$instanceName
754
-			]
755
-		);
756
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
757
-
758
-		// The "Reply-To" is set to the sharer if an mail address is configured
759
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
760
-		$initiatorEmail = $initiatorUser->getEMailAddress();
761
-		if($initiatorEmail !== null) {
762
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
763
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
764
-		} else {
765
-			$emailTemplate->addFooter();
766
-		}
767
-
768
-		$message->useTemplate($emailTemplate);
769
-		$this->mailer->send($message);
770
-	}
771
-
772
-	/**
773
-	 * Update a share
774
-	 *
775
-	 * @param \OCP\Share\IShare $share
776
-	 * @return \OCP\Share\IShare The share object
777
-	 * @throws \InvalidArgumentException
778
-	 */
779
-	public function updateShare(\OCP\Share\IShare $share) {
780
-		$expirationDateUpdated = false;
781
-
782
-		$this->canShare($share);
783
-
784
-		try {
785
-			$originalShare = $this->getShareById($share->getFullId());
786
-		} catch (\UnexpectedValueException $e) {
787
-			throw new \InvalidArgumentException('Share does not have a full id');
788
-		}
789
-
790
-		// We can't change the share type!
791
-		if ($share->getShareType() !== $originalShare->getShareType()) {
792
-			throw new \InvalidArgumentException('Can’t change share type');
793
-		}
794
-
795
-		// We can only change the recipient on user shares
796
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
797
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
798
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
799
-		}
800
-
801
-		// Cannot share with the owner
802
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
803
-			$share->getSharedWith() === $share->getShareOwner()) {
804
-			throw new \InvalidArgumentException('Can’t share with the share owner');
805
-		}
806
-
807
-		$this->generalCreateChecks($share);
808
-
809
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
810
-			$this->userCreateChecks($share);
811
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
812
-			$this->groupCreateChecks($share);
813
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
814
-			$this->linkCreateChecks($share);
815
-
816
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
817
-
818
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
819
-				//Verify the expiration date
820
-				$this->validateExpirationDate($share);
821
-				$expirationDateUpdated = true;
822
-			}
823
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
824
-			$plainTextPassword = $share->getPassword();
825
-			if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
826
-				$plainTextPassword = null;
827
-			}
828
-		}
829
-
830
-		$this->pathCreateChecks($share->getNode());
831
-
832
-		// Now update the share!
833
-		$provider = $this->factory->getProviderForType($share->getShareType());
834
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
835
-			$share = $provider->update($share, $plainTextPassword);
836
-		} else {
837
-			$share = $provider->update($share);
838
-		}
839
-
840
-		if ($expirationDateUpdated === true) {
841
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
842
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
843
-				'itemSource' => $share->getNode()->getId(),
844
-				'date' => $share->getExpirationDate(),
845
-				'uidOwner' => $share->getSharedBy(),
846
-			]);
847
-		}
848
-
849
-		if ($share->getPassword() !== $originalShare->getPassword()) {
850
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
851
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
852
-				'itemSource' => $share->getNode()->getId(),
853
-				'uidOwner' => $share->getSharedBy(),
854
-				'token' => $share->getToken(),
855
-				'disabled' => is_null($share->getPassword()),
856
-			]);
857
-		}
858
-
859
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
860
-			if ($this->userManager->userExists($share->getShareOwner())) {
861
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
862
-			} else {
863
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
864
-			}
865
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
866
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
867
-				'itemSource' => $share->getNode()->getId(),
868
-				'shareType' => $share->getShareType(),
869
-				'shareWith' => $share->getSharedWith(),
870
-				'uidOwner' => $share->getSharedBy(),
871
-				'permissions' => $share->getPermissions(),
872
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
873
-			));
874
-		}
875
-
876
-		return $share;
877
-	}
878
-
879
-	/**
880
-	 * Updates the password of the given share if it is not the same as the
881
-	 * password of the original share.
882
-	 *
883
-	 * @param \OCP\Share\IShare $share the share to update its password.
884
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
885
-	 *        password with.
886
-	 * @return boolean whether the password was updated or not.
887
-	 */
888
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
889
-		// Password updated.
890
-		if ($share->getPassword() !== $originalShare->getPassword()) {
891
-			//Verify the password
892
-			$this->verifyPassword($share->getPassword());
893
-
894
-			// If a password is set. Hash it!
895
-			if ($share->getPassword() !== null) {
896
-				$share->setPassword($this->hasher->hash($share->getPassword()));
897
-
898
-				return true;
899
-			}
900
-		}
901
-
902
-		return false;
903
-	}
904
-
905
-	/**
906
-	 * Delete all the children of this share
907
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
908
-	 *
909
-	 * @param \OCP\Share\IShare $share
910
-	 * @return \OCP\Share\IShare[] List of deleted shares
911
-	 */
912
-	protected function deleteChildren(\OCP\Share\IShare $share) {
913
-		$deletedShares = [];
914
-
915
-		$provider = $this->factory->getProviderForType($share->getShareType());
916
-
917
-		foreach ($provider->getChildren($share) as $child) {
918
-			$deletedChildren = $this->deleteChildren($child);
919
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
920
-
921
-			$provider->delete($child);
922
-			$deletedShares[] = $child;
923
-		}
924
-
925
-		return $deletedShares;
926
-	}
927
-
928
-	/**
929
-	 * Delete a share
930
-	 *
931
-	 * @param \OCP\Share\IShare $share
932
-	 * @throws ShareNotFound
933
-	 * @throws \InvalidArgumentException
934
-	 */
935
-	public function deleteShare(\OCP\Share\IShare $share) {
936
-
937
-		try {
938
-			$share->getFullId();
939
-		} catch (\UnexpectedValueException $e) {
940
-			throw new \InvalidArgumentException('Share does not have a full id');
941
-		}
942
-
943
-		$event = new GenericEvent($share);
944
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
945
-
946
-		// Get all children and delete them as well
947
-		$deletedShares = $this->deleteChildren($share);
948
-
949
-		// Do the actual delete
950
-		$provider = $this->factory->getProviderForType($share->getShareType());
951
-		$provider->delete($share);
952
-
953
-		// All the deleted shares caused by this delete
954
-		$deletedShares[] = $share;
955
-
956
-		// Emit post hook
957
-		$event->setArgument('deletedShares', $deletedShares);
958
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
959
-	}
960
-
961
-
962
-	/**
963
-	 * Unshare a file as the recipient.
964
-	 * This can be different from a regular delete for example when one of
965
-	 * the users in a groups deletes that share. But the provider should
966
-	 * handle this.
967
-	 *
968
-	 * @param \OCP\Share\IShare $share
969
-	 * @param string $recipientId
970
-	 */
971
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
972
-		list($providerId, ) = $this->splitFullId($share->getFullId());
973
-		$provider = $this->factory->getProvider($providerId);
974
-
975
-		$provider->deleteFromSelf($share, $recipientId);
976
-		$event = new GenericEvent($share);
977
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
978
-	}
979
-
980
-	/**
981
-	 * @inheritdoc
982
-	 */
983
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
984
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
985
-			throw new \InvalidArgumentException('Can’t change target of link share');
986
-		}
987
-
988
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
989
-			throw new \InvalidArgumentException('Invalid recipient');
990
-		}
991
-
992
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
993
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
994
-			if (is_null($sharedWith)) {
995
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
996
-			}
997
-			$recipient = $this->userManager->get($recipientId);
998
-			if (!$sharedWith->inGroup($recipient)) {
999
-				throw new \InvalidArgumentException('Invalid recipient');
1000
-			}
1001
-		}
1002
-
1003
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1004
-		$provider = $this->factory->getProvider($providerId);
1005
-
1006
-		$provider->move($share, $recipientId);
1007
-	}
1008
-
1009
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1010
-		$providers = $this->factory->getAllProviders();
1011
-
1012
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1013
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1014
-			foreach ($newShares as $fid => $data) {
1015
-				if (!isset($shares[$fid])) {
1016
-					$shares[$fid] = [];
1017
-				}
1018
-
1019
-				$shares[$fid] = array_merge($shares[$fid], $data);
1020
-			}
1021
-			return $shares;
1022
-		}, []);
1023
-	}
1024
-
1025
-	/**
1026
-	 * @inheritdoc
1027
-	 */
1028
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1029
-		if ($path !== null &&
1030
-				!($path instanceof \OCP\Files\File) &&
1031
-				!($path instanceof \OCP\Files\Folder)) {
1032
-			throw new \InvalidArgumentException('invalid path');
1033
-		}
1034
-
1035
-		try {
1036
-			$provider = $this->factory->getProviderForType($shareType);
1037
-		} catch (ProviderException $e) {
1038
-			return [];
1039
-		}
1040
-
1041
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1042
-
1043
-		/*
617
+            $share->setToken(
618
+                $this->secureRandom->generate(
619
+                    \OC\Share\Constants::TOKEN_LENGTH,
620
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
621
+                )
622
+            );
623
+
624
+            //Verify the expiration date
625
+            $this->validateExpirationDate($share);
626
+
627
+            //Verify the password
628
+            $this->verifyPassword($share->getPassword());
629
+
630
+            // If a password is set. Hash it!
631
+            if ($share->getPassword() !== null) {
632
+                $share->setPassword($this->hasher->hash($share->getPassword()));
633
+            }
634
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
635
+            $share->setToken(
636
+                $this->secureRandom->generate(
637
+                    \OC\Share\Constants::TOKEN_LENGTH,
638
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
639
+                )
640
+            );
641
+        }
642
+
643
+        // Cannot share with the owner
644
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
645
+            $share->getSharedWith() === $share->getShareOwner()) {
646
+            throw new \InvalidArgumentException('Can’t share with the share owner');
647
+        }
648
+
649
+        // Generate the target
650
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
651
+        $target = \OC\Files\Filesystem::normalizePath($target);
652
+        $share->setTarget($target);
653
+
654
+        // Pre share event
655
+        $event = new GenericEvent($share);
656
+        $a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
657
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
658
+            throw new \Exception($event->getArgument('error'));
659
+        }
660
+
661
+        $oldShare = $share;
662
+        $provider = $this->factory->getProviderForType($share->getShareType());
663
+        $share = $provider->create($share);
664
+        //reuse the node we already have
665
+        $share->setNode($oldShare->getNode());
666
+
667
+        // Post share event
668
+        $event = new GenericEvent($share);
669
+        $this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
670
+
671
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
672
+            $mailSend = $share->getMailSend();
673
+            if($mailSend === true) {
674
+                $user = $this->userManager->get($share->getSharedWith());
675
+                if ($user !== null) {
676
+                    $emailAddress = $user->getEMailAddress();
677
+                    if ($emailAddress !== null && $emailAddress !== '') {
678
+                        $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
679
+                        $l = $this->l10nFactory->get('lib', $userLang);
680
+                        $this->sendMailNotification(
681
+                            $l,
682
+                            $share->getNode()->getName(),
683
+                            $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
684
+                            $share->getSharedBy(),
685
+                            $emailAddress,
686
+                            $share->getExpirationDate()
687
+                        );
688
+                        $this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
689
+                    } else {
690
+                        $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
691
+                    }
692
+                } else {
693
+                    $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
694
+                }
695
+            } else {
696
+                $this->logger->debug('Share notification not send because mailsend is false.', ['app' => 'share']);
697
+            }
698
+        }
699
+
700
+        return $share;
701
+    }
702
+
703
+    /**
704
+     * @param IL10N $l Language of the recipient
705
+     * @param string $filename file/folder name
706
+     * @param string $link link to the file/folder
707
+     * @param string $initiator user ID of share sender
708
+     * @param string $shareWith email address of share receiver
709
+     * @param \DateTime|null $expiration
710
+     * @throws \Exception If mail couldn't be sent
711
+     */
712
+    protected function sendMailNotification(IL10N $l,
713
+                                            $filename,
714
+                                            $link,
715
+                                            $initiator,
716
+                                            $shareWith,
717
+                                            \DateTime $expiration = null) {
718
+        $initiatorUser = $this->userManager->get($initiator);
719
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
720
+
721
+        $message = $this->mailer->createMessage();
722
+
723
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
724
+            'filename' => $filename,
725
+            'link' => $link,
726
+            'initiator' => $initiatorDisplayName,
727
+            'expiration' => $expiration,
728
+            'shareWith' => $shareWith,
729
+        ]);
730
+
731
+        $emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename)));
732
+        $emailTemplate->addHeader();
733
+        $emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
734
+        $text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
735
+
736
+        $emailTemplate->addBodyText(
737
+            $text . ' ' . $l->t('Click the button below to open it.'),
738
+            $text
739
+        );
740
+        $emailTemplate->addBodyButton(
741
+            $l->t('Open »%s«', [$filename]),
742
+            $link
743
+        );
744
+
745
+        $message->setTo([$shareWith]);
746
+
747
+        // The "From" contains the sharers name
748
+        $instanceName = $this->defaults->getName();
749
+        $senderName = $l->t(
750
+            '%s via %s',
751
+            [
752
+                $initiatorDisplayName,
753
+                $instanceName
754
+            ]
755
+        );
756
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
757
+
758
+        // The "Reply-To" is set to the sharer if an mail address is configured
759
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
760
+        $initiatorEmail = $initiatorUser->getEMailAddress();
761
+        if($initiatorEmail !== null) {
762
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
763
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
764
+        } else {
765
+            $emailTemplate->addFooter();
766
+        }
767
+
768
+        $message->useTemplate($emailTemplate);
769
+        $this->mailer->send($message);
770
+    }
771
+
772
+    /**
773
+     * Update a share
774
+     *
775
+     * @param \OCP\Share\IShare $share
776
+     * @return \OCP\Share\IShare The share object
777
+     * @throws \InvalidArgumentException
778
+     */
779
+    public function updateShare(\OCP\Share\IShare $share) {
780
+        $expirationDateUpdated = false;
781
+
782
+        $this->canShare($share);
783
+
784
+        try {
785
+            $originalShare = $this->getShareById($share->getFullId());
786
+        } catch (\UnexpectedValueException $e) {
787
+            throw new \InvalidArgumentException('Share does not have a full id');
788
+        }
789
+
790
+        // We can't change the share type!
791
+        if ($share->getShareType() !== $originalShare->getShareType()) {
792
+            throw new \InvalidArgumentException('Can’t change share type');
793
+        }
794
+
795
+        // We can only change the recipient on user shares
796
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
797
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
798
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
799
+        }
800
+
801
+        // Cannot share with the owner
802
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
803
+            $share->getSharedWith() === $share->getShareOwner()) {
804
+            throw new \InvalidArgumentException('Can’t share with the share owner');
805
+        }
806
+
807
+        $this->generalCreateChecks($share);
808
+
809
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
810
+            $this->userCreateChecks($share);
811
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
812
+            $this->groupCreateChecks($share);
813
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
814
+            $this->linkCreateChecks($share);
815
+
816
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
817
+
818
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
819
+                //Verify the expiration date
820
+                $this->validateExpirationDate($share);
821
+                $expirationDateUpdated = true;
822
+            }
823
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
824
+            $plainTextPassword = $share->getPassword();
825
+            if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
826
+                $plainTextPassword = null;
827
+            }
828
+        }
829
+
830
+        $this->pathCreateChecks($share->getNode());
831
+
832
+        // Now update the share!
833
+        $provider = $this->factory->getProviderForType($share->getShareType());
834
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
835
+            $share = $provider->update($share, $plainTextPassword);
836
+        } else {
837
+            $share = $provider->update($share);
838
+        }
839
+
840
+        if ($expirationDateUpdated === true) {
841
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
842
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
843
+                'itemSource' => $share->getNode()->getId(),
844
+                'date' => $share->getExpirationDate(),
845
+                'uidOwner' => $share->getSharedBy(),
846
+            ]);
847
+        }
848
+
849
+        if ($share->getPassword() !== $originalShare->getPassword()) {
850
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
851
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
852
+                'itemSource' => $share->getNode()->getId(),
853
+                'uidOwner' => $share->getSharedBy(),
854
+                'token' => $share->getToken(),
855
+                'disabled' => is_null($share->getPassword()),
856
+            ]);
857
+        }
858
+
859
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
860
+            if ($this->userManager->userExists($share->getShareOwner())) {
861
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
862
+            } else {
863
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
864
+            }
865
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
866
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
867
+                'itemSource' => $share->getNode()->getId(),
868
+                'shareType' => $share->getShareType(),
869
+                'shareWith' => $share->getSharedWith(),
870
+                'uidOwner' => $share->getSharedBy(),
871
+                'permissions' => $share->getPermissions(),
872
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
873
+            ));
874
+        }
875
+
876
+        return $share;
877
+    }
878
+
879
+    /**
880
+     * Updates the password of the given share if it is not the same as the
881
+     * password of the original share.
882
+     *
883
+     * @param \OCP\Share\IShare $share the share to update its password.
884
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
885
+     *        password with.
886
+     * @return boolean whether the password was updated or not.
887
+     */
888
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
889
+        // Password updated.
890
+        if ($share->getPassword() !== $originalShare->getPassword()) {
891
+            //Verify the password
892
+            $this->verifyPassword($share->getPassword());
893
+
894
+            // If a password is set. Hash it!
895
+            if ($share->getPassword() !== null) {
896
+                $share->setPassword($this->hasher->hash($share->getPassword()));
897
+
898
+                return true;
899
+            }
900
+        }
901
+
902
+        return false;
903
+    }
904
+
905
+    /**
906
+     * Delete all the children of this share
907
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
908
+     *
909
+     * @param \OCP\Share\IShare $share
910
+     * @return \OCP\Share\IShare[] List of deleted shares
911
+     */
912
+    protected function deleteChildren(\OCP\Share\IShare $share) {
913
+        $deletedShares = [];
914
+
915
+        $provider = $this->factory->getProviderForType($share->getShareType());
916
+
917
+        foreach ($provider->getChildren($share) as $child) {
918
+            $deletedChildren = $this->deleteChildren($child);
919
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
920
+
921
+            $provider->delete($child);
922
+            $deletedShares[] = $child;
923
+        }
924
+
925
+        return $deletedShares;
926
+    }
927
+
928
+    /**
929
+     * Delete a share
930
+     *
931
+     * @param \OCP\Share\IShare $share
932
+     * @throws ShareNotFound
933
+     * @throws \InvalidArgumentException
934
+     */
935
+    public function deleteShare(\OCP\Share\IShare $share) {
936
+
937
+        try {
938
+            $share->getFullId();
939
+        } catch (\UnexpectedValueException $e) {
940
+            throw new \InvalidArgumentException('Share does not have a full id');
941
+        }
942
+
943
+        $event = new GenericEvent($share);
944
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
945
+
946
+        // Get all children and delete them as well
947
+        $deletedShares = $this->deleteChildren($share);
948
+
949
+        // Do the actual delete
950
+        $provider = $this->factory->getProviderForType($share->getShareType());
951
+        $provider->delete($share);
952
+
953
+        // All the deleted shares caused by this delete
954
+        $deletedShares[] = $share;
955
+
956
+        // Emit post hook
957
+        $event->setArgument('deletedShares', $deletedShares);
958
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
959
+    }
960
+
961
+
962
+    /**
963
+     * Unshare a file as the recipient.
964
+     * This can be different from a regular delete for example when one of
965
+     * the users in a groups deletes that share. But the provider should
966
+     * handle this.
967
+     *
968
+     * @param \OCP\Share\IShare $share
969
+     * @param string $recipientId
970
+     */
971
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
972
+        list($providerId, ) = $this->splitFullId($share->getFullId());
973
+        $provider = $this->factory->getProvider($providerId);
974
+
975
+        $provider->deleteFromSelf($share, $recipientId);
976
+        $event = new GenericEvent($share);
977
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
978
+    }
979
+
980
+    /**
981
+     * @inheritdoc
982
+     */
983
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
984
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
985
+            throw new \InvalidArgumentException('Can’t change target of link share');
986
+        }
987
+
988
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
989
+            throw new \InvalidArgumentException('Invalid recipient');
990
+        }
991
+
992
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
993
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
994
+            if (is_null($sharedWith)) {
995
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
996
+            }
997
+            $recipient = $this->userManager->get($recipientId);
998
+            if (!$sharedWith->inGroup($recipient)) {
999
+                throw new \InvalidArgumentException('Invalid recipient');
1000
+            }
1001
+        }
1002
+
1003
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1004
+        $provider = $this->factory->getProvider($providerId);
1005
+
1006
+        $provider->move($share, $recipientId);
1007
+    }
1008
+
1009
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1010
+        $providers = $this->factory->getAllProviders();
1011
+
1012
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1013
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1014
+            foreach ($newShares as $fid => $data) {
1015
+                if (!isset($shares[$fid])) {
1016
+                    $shares[$fid] = [];
1017
+                }
1018
+
1019
+                $shares[$fid] = array_merge($shares[$fid], $data);
1020
+            }
1021
+            return $shares;
1022
+        }, []);
1023
+    }
1024
+
1025
+    /**
1026
+     * @inheritdoc
1027
+     */
1028
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1029
+        if ($path !== null &&
1030
+                !($path instanceof \OCP\Files\File) &&
1031
+                !($path instanceof \OCP\Files\Folder)) {
1032
+            throw new \InvalidArgumentException('invalid path');
1033
+        }
1034
+
1035
+        try {
1036
+            $provider = $this->factory->getProviderForType($shareType);
1037
+        } catch (ProviderException $e) {
1038
+            return [];
1039
+        }
1040
+
1041
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1042
+
1043
+        /*
1044 1044
 		 * Work around so we don't return expired shares but still follow
1045 1045
 		 * proper pagination.
1046 1046
 		 */
1047 1047
 
1048
-		$shares2 = [];
1049
-
1050
-		while(true) {
1051
-			$added = 0;
1052
-			foreach ($shares as $share) {
1053
-
1054
-				try {
1055
-					$this->checkExpireDate($share);
1056
-				} catch (ShareNotFound $e) {
1057
-					//Ignore since this basically means the share is deleted
1058
-					continue;
1059
-				}
1060
-
1061
-				$added++;
1062
-				$shares2[] = $share;
1063
-
1064
-				if (count($shares2) === $limit) {
1065
-					break;
1066
-				}
1067
-			}
1068
-
1069
-			// If we did not fetch more shares than the limit then there are no more shares
1070
-			if (count($shares) < $limit) {
1071
-				break;
1072
-			}
1073
-
1074
-			if (count($shares2) === $limit) {
1075
-				break;
1076
-			}
1077
-
1078
-			// If there was no limit on the select we are done
1079
-			if ($limit === -1) {
1080
-				break;
1081
-			}
1082
-
1083
-			$offset += $added;
1084
-
1085
-			// Fetch again $limit shares
1086
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1087
-
1088
-			// No more shares means we are done
1089
-			if (empty($shares)) {
1090
-				break;
1091
-			}
1092
-		}
1093
-
1094
-		$shares = $shares2;
1095
-
1096
-		return $shares;
1097
-	}
1098
-
1099
-	/**
1100
-	 * @inheritdoc
1101
-	 */
1102
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1103
-		try {
1104
-			$provider = $this->factory->getProviderForType($shareType);
1105
-		} catch (ProviderException $e) {
1106
-			return [];
1107
-		}
1108
-
1109
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1110
-
1111
-		// remove all shares which are already expired
1112
-		foreach ($shares as $key => $share) {
1113
-			try {
1114
-				$this->checkExpireDate($share);
1115
-			} catch (ShareNotFound $e) {
1116
-				unset($shares[$key]);
1117
-			}
1118
-		}
1119
-
1120
-		return $shares;
1121
-	}
1122
-
1123
-	/**
1124
-	 * @inheritdoc
1125
-	 */
1126
-	public function getShareById($id, $recipient = null) {
1127
-		if ($id === null) {
1128
-			throw new ShareNotFound();
1129
-		}
1130
-
1131
-		list($providerId, $id) = $this->splitFullId($id);
1132
-
1133
-		try {
1134
-			$provider = $this->factory->getProvider($providerId);
1135
-		} catch (ProviderException $e) {
1136
-			throw new ShareNotFound();
1137
-		}
1138
-
1139
-		$share = $provider->getShareById($id, $recipient);
1140
-
1141
-		$this->checkExpireDate($share);
1142
-
1143
-		return $share;
1144
-	}
1145
-
1146
-	/**
1147
-	 * Get all the shares for a given path
1148
-	 *
1149
-	 * @param \OCP\Files\Node $path
1150
-	 * @param int $page
1151
-	 * @param int $perPage
1152
-	 *
1153
-	 * @return Share[]
1154
-	 */
1155
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1156
-		return [];
1157
-	}
1158
-
1159
-	/**
1160
-	 * Get the share by token possible with password
1161
-	 *
1162
-	 * @param string $token
1163
-	 * @return Share
1164
-	 *
1165
-	 * @throws ShareNotFound
1166
-	 */
1167
-	public function getShareByToken($token) {
1168
-		$share = null;
1169
-		try {
1170
-			if($this->shareApiAllowLinks()) {
1171
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1172
-				$share = $provider->getShareByToken($token);
1173
-			}
1174
-		} catch (ProviderException $e) {
1175
-		} catch (ShareNotFound $e) {
1176
-		}
1177
-
1178
-
1179
-		// If it is not a link share try to fetch a federated share by token
1180
-		if ($share === null) {
1181
-			try {
1182
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1183
-				$share = $provider->getShareByToken($token);
1184
-			} catch (ProviderException $e) {
1185
-			} catch (ShareNotFound $e) {
1186
-			}
1187
-		}
1188
-
1189
-		// If it is not a link share try to fetch a mail share by token
1190
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1191
-			try {
1192
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1193
-				$share = $provider->getShareByToken($token);
1194
-			} catch (ProviderException $e) {
1195
-			} catch (ShareNotFound $e) {
1196
-			}
1197
-		}
1198
-
1199
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1200
-			try {
1201
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1202
-				$share = $provider->getShareByToken($token);
1203
-			} catch (ProviderException $e) {
1204
-			} catch (ShareNotFound $e) {
1205
-			}
1206
-		}
1207
-
1208
-		if ($share === null) {
1209
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1210
-		}
1211
-
1212
-		$this->checkExpireDate($share);
1213
-
1214
-		/*
1048
+        $shares2 = [];
1049
+
1050
+        while(true) {
1051
+            $added = 0;
1052
+            foreach ($shares as $share) {
1053
+
1054
+                try {
1055
+                    $this->checkExpireDate($share);
1056
+                } catch (ShareNotFound $e) {
1057
+                    //Ignore since this basically means the share is deleted
1058
+                    continue;
1059
+                }
1060
+
1061
+                $added++;
1062
+                $shares2[] = $share;
1063
+
1064
+                if (count($shares2) === $limit) {
1065
+                    break;
1066
+                }
1067
+            }
1068
+
1069
+            // If we did not fetch more shares than the limit then there are no more shares
1070
+            if (count($shares) < $limit) {
1071
+                break;
1072
+            }
1073
+
1074
+            if (count($shares2) === $limit) {
1075
+                break;
1076
+            }
1077
+
1078
+            // If there was no limit on the select we are done
1079
+            if ($limit === -1) {
1080
+                break;
1081
+            }
1082
+
1083
+            $offset += $added;
1084
+
1085
+            // Fetch again $limit shares
1086
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1087
+
1088
+            // No more shares means we are done
1089
+            if (empty($shares)) {
1090
+                break;
1091
+            }
1092
+        }
1093
+
1094
+        $shares = $shares2;
1095
+
1096
+        return $shares;
1097
+    }
1098
+
1099
+    /**
1100
+     * @inheritdoc
1101
+     */
1102
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1103
+        try {
1104
+            $provider = $this->factory->getProviderForType($shareType);
1105
+        } catch (ProviderException $e) {
1106
+            return [];
1107
+        }
1108
+
1109
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1110
+
1111
+        // remove all shares which are already expired
1112
+        foreach ($shares as $key => $share) {
1113
+            try {
1114
+                $this->checkExpireDate($share);
1115
+            } catch (ShareNotFound $e) {
1116
+                unset($shares[$key]);
1117
+            }
1118
+        }
1119
+
1120
+        return $shares;
1121
+    }
1122
+
1123
+    /**
1124
+     * @inheritdoc
1125
+     */
1126
+    public function getShareById($id, $recipient = null) {
1127
+        if ($id === null) {
1128
+            throw new ShareNotFound();
1129
+        }
1130
+
1131
+        list($providerId, $id) = $this->splitFullId($id);
1132
+
1133
+        try {
1134
+            $provider = $this->factory->getProvider($providerId);
1135
+        } catch (ProviderException $e) {
1136
+            throw new ShareNotFound();
1137
+        }
1138
+
1139
+        $share = $provider->getShareById($id, $recipient);
1140
+
1141
+        $this->checkExpireDate($share);
1142
+
1143
+        return $share;
1144
+    }
1145
+
1146
+    /**
1147
+     * Get all the shares for a given path
1148
+     *
1149
+     * @param \OCP\Files\Node $path
1150
+     * @param int $page
1151
+     * @param int $perPage
1152
+     *
1153
+     * @return Share[]
1154
+     */
1155
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1156
+        return [];
1157
+    }
1158
+
1159
+    /**
1160
+     * Get the share by token possible with password
1161
+     *
1162
+     * @param string $token
1163
+     * @return Share
1164
+     *
1165
+     * @throws ShareNotFound
1166
+     */
1167
+    public function getShareByToken($token) {
1168
+        $share = null;
1169
+        try {
1170
+            if($this->shareApiAllowLinks()) {
1171
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1172
+                $share = $provider->getShareByToken($token);
1173
+            }
1174
+        } catch (ProviderException $e) {
1175
+        } catch (ShareNotFound $e) {
1176
+        }
1177
+
1178
+
1179
+        // If it is not a link share try to fetch a federated share by token
1180
+        if ($share === null) {
1181
+            try {
1182
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1183
+                $share = $provider->getShareByToken($token);
1184
+            } catch (ProviderException $e) {
1185
+            } catch (ShareNotFound $e) {
1186
+            }
1187
+        }
1188
+
1189
+        // If it is not a link share try to fetch a mail share by token
1190
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1191
+            try {
1192
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1193
+                $share = $provider->getShareByToken($token);
1194
+            } catch (ProviderException $e) {
1195
+            } catch (ShareNotFound $e) {
1196
+            }
1197
+        }
1198
+
1199
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1200
+            try {
1201
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1202
+                $share = $provider->getShareByToken($token);
1203
+            } catch (ProviderException $e) {
1204
+            } catch (ShareNotFound $e) {
1205
+            }
1206
+        }
1207
+
1208
+        if ($share === null) {
1209
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1210
+        }
1211
+
1212
+        $this->checkExpireDate($share);
1213
+
1214
+        /*
1215 1215
 		 * Reduce the permissions for link shares if public upload is not enabled
1216 1216
 		 */
1217
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1218
-			!$this->shareApiLinkAllowPublicUpload()) {
1219
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1220
-		}
1221
-
1222
-		return $share;
1223
-	}
1224
-
1225
-	protected function checkExpireDate($share) {
1226
-		if ($share->getExpirationDate() !== null &&
1227
-			$share->getExpirationDate() <= new \DateTime()) {
1228
-			$this->deleteShare($share);
1229
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1230
-		}
1231
-
1232
-	}
1233
-
1234
-	/**
1235
-	 * Verify the password of a public share
1236
-	 *
1237
-	 * @param \OCP\Share\IShare $share
1238
-	 * @param string $password
1239
-	 * @return bool
1240
-	 */
1241
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1242
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1243
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1244
-		if (!$passwordProtected) {
1245
-			//TODO maybe exception?
1246
-			return false;
1247
-		}
1248
-
1249
-		if ($password === null || $share->getPassword() === null) {
1250
-			return false;
1251
-		}
1252
-
1253
-		$newHash = '';
1254
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1255
-			return false;
1256
-		}
1257
-
1258
-		if (!empty($newHash)) {
1259
-			$share->setPassword($newHash);
1260
-			$provider = $this->factory->getProviderForType($share->getShareType());
1261
-			$provider->update($share);
1262
-		}
1263
-
1264
-		return true;
1265
-	}
1266
-
1267
-	/**
1268
-	 * @inheritdoc
1269
-	 */
1270
-	public function userDeleted($uid) {
1271
-		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1272
-
1273
-		foreach ($types as $type) {
1274
-			try {
1275
-				$provider = $this->factory->getProviderForType($type);
1276
-			} catch (ProviderException $e) {
1277
-				continue;
1278
-			}
1279
-			$provider->userDeleted($uid, $type);
1280
-		}
1281
-	}
1282
-
1283
-	/**
1284
-	 * @inheritdoc
1285
-	 */
1286
-	public function groupDeleted($gid) {
1287
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1288
-		$provider->groupDeleted($gid);
1289
-	}
1290
-
1291
-	/**
1292
-	 * @inheritdoc
1293
-	 */
1294
-	public function userDeletedFromGroup($uid, $gid) {
1295
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1296
-		$provider->userDeletedFromGroup($uid, $gid);
1297
-	}
1298
-
1299
-	/**
1300
-	 * Get access list to a path. This means
1301
-	 * all the users that can access a given path.
1302
-	 *
1303
-	 * Consider:
1304
-	 * -root
1305
-	 * |-folder1 (23)
1306
-	 *  |-folder2 (32)
1307
-	 *   |-fileA (42)
1308
-	 *
1309
-	 * fileA is shared with user1 and user1@server1
1310
-	 * folder2 is shared with group2 (user4 is a member of group2)
1311
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1312
-	 *
1313
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1314
-	 * [
1315
-	 *  users  => [
1316
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1317
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1318
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1319
-	 *  ],
1320
-	 *  remote => [
1321
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1322
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1323
-	 *  ],
1324
-	 *  public => bool
1325
-	 *  mail => bool
1326
-	 * ]
1327
-	 *
1328
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1329
-	 * [
1330
-	 *  users  => ['user1', 'user2', 'user4'],
1331
-	 *  remote => bool,
1332
-	 *  public => bool
1333
-	 *  mail => bool
1334
-	 * ]
1335
-	 *
1336
-	 * This is required for encryption/activity
1337
-	 *
1338
-	 * @param \OCP\Files\Node $path
1339
-	 * @param bool $recursive Should we check all parent folders as well
1340
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1341
-	 * @return array
1342
-	 */
1343
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1344
-		$owner = $path->getOwner()->getUID();
1345
-
1346
-		if ($currentAccess) {
1347
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1348
-		} else {
1349
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1350
-		}
1351
-		if (!$this->userManager->userExists($owner)) {
1352
-			return $al;
1353
-		}
1354
-
1355
-		//Get node for the owner
1356
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1357
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1358
-			$path = $userFolder->getById($path->getId())[0];
1359
-		}
1360
-
1361
-		$providers = $this->factory->getAllProviders();
1362
-
1363
-		/** @var Node[] $nodes */
1364
-		$nodes = [];
1365
-
1366
-
1367
-		if ($currentAccess) {
1368
-			$ownerPath = $path->getPath();
1369
-			$ownerPath = explode('/', $ownerPath, 4);
1370
-			if (count($ownerPath) < 4) {
1371
-				$ownerPath = '';
1372
-			} else {
1373
-				$ownerPath = $ownerPath[3];
1374
-			}
1375
-			$al['users'][$owner] = [
1376
-				'node_id' => $path->getId(),
1377
-				'node_path' => '/' . $ownerPath,
1378
-			];
1379
-		} else {
1380
-			$al['users'][] = $owner;
1381
-		}
1382
-
1383
-		// Collect all the shares
1384
-		while ($path->getPath() !== $userFolder->getPath()) {
1385
-			$nodes[] = $path;
1386
-			if (!$recursive) {
1387
-				break;
1388
-			}
1389
-			$path = $path->getParent();
1390
-		}
1391
-
1392
-		foreach ($providers as $provider) {
1393
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1394
-
1395
-			foreach ($tmp as $k => $v) {
1396
-				if (isset($al[$k])) {
1397
-					if (is_array($al[$k])) {
1398
-						if ($currentAccess) {
1399
-							$al[$k] += $v;
1400
-						} else {
1401
-							$al[$k] = array_merge($al[$k], $v);
1402
-							$al[$k] = array_unique($al[$k]);
1403
-							$al[$k] = array_values($al[$k]);
1404
-						}
1405
-					} else {
1406
-						$al[$k] = $al[$k] || $v;
1407
-					}
1408
-				} else {
1409
-					$al[$k] = $v;
1410
-				}
1411
-			}
1412
-		}
1413
-
1414
-		return $al;
1415
-	}
1416
-
1417
-	/**
1418
-	 * Create a new share
1419
-	 * @return \OCP\Share\IShare
1420
-	 */
1421
-	public function newShare() {
1422
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1423
-	}
1424
-
1425
-	/**
1426
-	 * Is the share API enabled
1427
-	 *
1428
-	 * @return bool
1429
-	 */
1430
-	public function shareApiEnabled() {
1431
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1432
-	}
1433
-
1434
-	/**
1435
-	 * Is public link sharing enabled
1436
-	 *
1437
-	 * @return bool
1438
-	 */
1439
-	public function shareApiAllowLinks() {
1440
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1441
-	}
1442
-
1443
-	/**
1444
-	 * Is password on public link requires
1445
-	 *
1446
-	 * @return bool
1447
-	 */
1448
-	public function shareApiLinkEnforcePassword() {
1449
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1450
-	}
1451
-
1452
-	/**
1453
-	 * Is default expire date enabled
1454
-	 *
1455
-	 * @return bool
1456
-	 */
1457
-	public function shareApiLinkDefaultExpireDate() {
1458
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1459
-	}
1460
-
1461
-	/**
1462
-	 * Is default expire date enforced
1463
-	 *`
1464
-	 * @return bool
1465
-	 */
1466
-	public function shareApiLinkDefaultExpireDateEnforced() {
1467
-		return $this->shareApiLinkDefaultExpireDate() &&
1468
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1469
-	}
1470
-
1471
-	/**
1472
-	 * Number of default expire days
1473
-	 *shareApiLinkAllowPublicUpload
1474
-	 * @return int
1475
-	 */
1476
-	public function shareApiLinkDefaultExpireDays() {
1477
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1478
-	}
1479
-
1480
-	/**
1481
-	 * Allow public upload on link shares
1482
-	 *
1483
-	 * @return bool
1484
-	 */
1485
-	public function shareApiLinkAllowPublicUpload() {
1486
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1487
-	}
1488
-
1489
-	/**
1490
-	 * check if user can only share with group members
1491
-	 * @return bool
1492
-	 */
1493
-	public function shareWithGroupMembersOnly() {
1494
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1495
-	}
1496
-
1497
-	/**
1498
-	 * Check if users can share with groups
1499
-	 * @return bool
1500
-	 */
1501
-	public function allowGroupSharing() {
1502
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1503
-	}
1504
-
1505
-	/**
1506
-	 * Copied from \OC_Util::isSharingDisabledForUser
1507
-	 *
1508
-	 * TODO: Deprecate fuction from OC_Util
1509
-	 *
1510
-	 * @param string $userId
1511
-	 * @return bool
1512
-	 */
1513
-	public function sharingDisabledForUser($userId) {
1514
-		if ($userId === null) {
1515
-			return false;
1516
-		}
1517
-
1518
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1519
-			return $this->sharingDisabledForUsersCache[$userId];
1520
-		}
1521
-
1522
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1523
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1524
-			$excludedGroups = json_decode($groupsList);
1525
-			if (is_null($excludedGroups)) {
1526
-				$excludedGroups = explode(',', $groupsList);
1527
-				$newValue = json_encode($excludedGroups);
1528
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1529
-			}
1530
-			$user = $this->userManager->get($userId);
1531
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1532
-			if (!empty($usersGroups)) {
1533
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1534
-				// if the user is only in groups which are disabled for sharing then
1535
-				// sharing is also disabled for the user
1536
-				if (empty($remainingGroups)) {
1537
-					$this->sharingDisabledForUsersCache[$userId] = true;
1538
-					return true;
1539
-				}
1540
-			}
1541
-		}
1542
-
1543
-		$this->sharingDisabledForUsersCache[$userId] = false;
1544
-		return false;
1545
-	}
1546
-
1547
-	/**
1548
-	 * @inheritdoc
1549
-	 */
1550
-	public function outgoingServer2ServerSharesAllowed() {
1551
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1552
-	}
1553
-
1554
-	/**
1555
-	 * @inheritdoc
1556
-	 */
1557
-	public function shareProviderExists($shareType) {
1558
-		try {
1559
-			$this->factory->getProviderForType($shareType);
1560
-		} catch (ProviderException $e) {
1561
-			return false;
1562
-		}
1563
-
1564
-		return true;
1565
-	}
1217
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1218
+            !$this->shareApiLinkAllowPublicUpload()) {
1219
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1220
+        }
1221
+
1222
+        return $share;
1223
+    }
1224
+
1225
+    protected function checkExpireDate($share) {
1226
+        if ($share->getExpirationDate() !== null &&
1227
+            $share->getExpirationDate() <= new \DateTime()) {
1228
+            $this->deleteShare($share);
1229
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1230
+        }
1231
+
1232
+    }
1233
+
1234
+    /**
1235
+     * Verify the password of a public share
1236
+     *
1237
+     * @param \OCP\Share\IShare $share
1238
+     * @param string $password
1239
+     * @return bool
1240
+     */
1241
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1242
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1243
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1244
+        if (!$passwordProtected) {
1245
+            //TODO maybe exception?
1246
+            return false;
1247
+        }
1248
+
1249
+        if ($password === null || $share->getPassword() === null) {
1250
+            return false;
1251
+        }
1252
+
1253
+        $newHash = '';
1254
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1255
+            return false;
1256
+        }
1257
+
1258
+        if (!empty($newHash)) {
1259
+            $share->setPassword($newHash);
1260
+            $provider = $this->factory->getProviderForType($share->getShareType());
1261
+            $provider->update($share);
1262
+        }
1263
+
1264
+        return true;
1265
+    }
1266
+
1267
+    /**
1268
+     * @inheritdoc
1269
+     */
1270
+    public function userDeleted($uid) {
1271
+        $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1272
+
1273
+        foreach ($types as $type) {
1274
+            try {
1275
+                $provider = $this->factory->getProviderForType($type);
1276
+            } catch (ProviderException $e) {
1277
+                continue;
1278
+            }
1279
+            $provider->userDeleted($uid, $type);
1280
+        }
1281
+    }
1282
+
1283
+    /**
1284
+     * @inheritdoc
1285
+     */
1286
+    public function groupDeleted($gid) {
1287
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1288
+        $provider->groupDeleted($gid);
1289
+    }
1290
+
1291
+    /**
1292
+     * @inheritdoc
1293
+     */
1294
+    public function userDeletedFromGroup($uid, $gid) {
1295
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1296
+        $provider->userDeletedFromGroup($uid, $gid);
1297
+    }
1298
+
1299
+    /**
1300
+     * Get access list to a path. This means
1301
+     * all the users that can access a given path.
1302
+     *
1303
+     * Consider:
1304
+     * -root
1305
+     * |-folder1 (23)
1306
+     *  |-folder2 (32)
1307
+     *   |-fileA (42)
1308
+     *
1309
+     * fileA is shared with user1 and user1@server1
1310
+     * folder2 is shared with group2 (user4 is a member of group2)
1311
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1312
+     *
1313
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1314
+     * [
1315
+     *  users  => [
1316
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1317
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1318
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1319
+     *  ],
1320
+     *  remote => [
1321
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1322
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1323
+     *  ],
1324
+     *  public => bool
1325
+     *  mail => bool
1326
+     * ]
1327
+     *
1328
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1329
+     * [
1330
+     *  users  => ['user1', 'user2', 'user4'],
1331
+     *  remote => bool,
1332
+     *  public => bool
1333
+     *  mail => bool
1334
+     * ]
1335
+     *
1336
+     * This is required for encryption/activity
1337
+     *
1338
+     * @param \OCP\Files\Node $path
1339
+     * @param bool $recursive Should we check all parent folders as well
1340
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1341
+     * @return array
1342
+     */
1343
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1344
+        $owner = $path->getOwner()->getUID();
1345
+
1346
+        if ($currentAccess) {
1347
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1348
+        } else {
1349
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1350
+        }
1351
+        if (!$this->userManager->userExists($owner)) {
1352
+            return $al;
1353
+        }
1354
+
1355
+        //Get node for the owner
1356
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1357
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1358
+            $path = $userFolder->getById($path->getId())[0];
1359
+        }
1360
+
1361
+        $providers = $this->factory->getAllProviders();
1362
+
1363
+        /** @var Node[] $nodes */
1364
+        $nodes = [];
1365
+
1366
+
1367
+        if ($currentAccess) {
1368
+            $ownerPath = $path->getPath();
1369
+            $ownerPath = explode('/', $ownerPath, 4);
1370
+            if (count($ownerPath) < 4) {
1371
+                $ownerPath = '';
1372
+            } else {
1373
+                $ownerPath = $ownerPath[3];
1374
+            }
1375
+            $al['users'][$owner] = [
1376
+                'node_id' => $path->getId(),
1377
+                'node_path' => '/' . $ownerPath,
1378
+            ];
1379
+        } else {
1380
+            $al['users'][] = $owner;
1381
+        }
1382
+
1383
+        // Collect all the shares
1384
+        while ($path->getPath() !== $userFolder->getPath()) {
1385
+            $nodes[] = $path;
1386
+            if (!$recursive) {
1387
+                break;
1388
+            }
1389
+            $path = $path->getParent();
1390
+        }
1391
+
1392
+        foreach ($providers as $provider) {
1393
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1394
+
1395
+            foreach ($tmp as $k => $v) {
1396
+                if (isset($al[$k])) {
1397
+                    if (is_array($al[$k])) {
1398
+                        if ($currentAccess) {
1399
+                            $al[$k] += $v;
1400
+                        } else {
1401
+                            $al[$k] = array_merge($al[$k], $v);
1402
+                            $al[$k] = array_unique($al[$k]);
1403
+                            $al[$k] = array_values($al[$k]);
1404
+                        }
1405
+                    } else {
1406
+                        $al[$k] = $al[$k] || $v;
1407
+                    }
1408
+                } else {
1409
+                    $al[$k] = $v;
1410
+                }
1411
+            }
1412
+        }
1413
+
1414
+        return $al;
1415
+    }
1416
+
1417
+    /**
1418
+     * Create a new share
1419
+     * @return \OCP\Share\IShare
1420
+     */
1421
+    public function newShare() {
1422
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1423
+    }
1424
+
1425
+    /**
1426
+     * Is the share API enabled
1427
+     *
1428
+     * @return bool
1429
+     */
1430
+    public function shareApiEnabled() {
1431
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1432
+    }
1433
+
1434
+    /**
1435
+     * Is public link sharing enabled
1436
+     *
1437
+     * @return bool
1438
+     */
1439
+    public function shareApiAllowLinks() {
1440
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1441
+    }
1442
+
1443
+    /**
1444
+     * Is password on public link requires
1445
+     *
1446
+     * @return bool
1447
+     */
1448
+    public function shareApiLinkEnforcePassword() {
1449
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1450
+    }
1451
+
1452
+    /**
1453
+     * Is default expire date enabled
1454
+     *
1455
+     * @return bool
1456
+     */
1457
+    public function shareApiLinkDefaultExpireDate() {
1458
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1459
+    }
1460
+
1461
+    /**
1462
+     * Is default expire date enforced
1463
+     *`
1464
+     * @return bool
1465
+     */
1466
+    public function shareApiLinkDefaultExpireDateEnforced() {
1467
+        return $this->shareApiLinkDefaultExpireDate() &&
1468
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1469
+    }
1470
+
1471
+    /**
1472
+     * Number of default expire days
1473
+     *shareApiLinkAllowPublicUpload
1474
+     * @return int
1475
+     */
1476
+    public function shareApiLinkDefaultExpireDays() {
1477
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1478
+    }
1479
+
1480
+    /**
1481
+     * Allow public upload on link shares
1482
+     *
1483
+     * @return bool
1484
+     */
1485
+    public function shareApiLinkAllowPublicUpload() {
1486
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1487
+    }
1488
+
1489
+    /**
1490
+     * check if user can only share with group members
1491
+     * @return bool
1492
+     */
1493
+    public function shareWithGroupMembersOnly() {
1494
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1495
+    }
1496
+
1497
+    /**
1498
+     * Check if users can share with groups
1499
+     * @return bool
1500
+     */
1501
+    public function allowGroupSharing() {
1502
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1503
+    }
1504
+
1505
+    /**
1506
+     * Copied from \OC_Util::isSharingDisabledForUser
1507
+     *
1508
+     * TODO: Deprecate fuction from OC_Util
1509
+     *
1510
+     * @param string $userId
1511
+     * @return bool
1512
+     */
1513
+    public function sharingDisabledForUser($userId) {
1514
+        if ($userId === null) {
1515
+            return false;
1516
+        }
1517
+
1518
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1519
+            return $this->sharingDisabledForUsersCache[$userId];
1520
+        }
1521
+
1522
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1523
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1524
+            $excludedGroups = json_decode($groupsList);
1525
+            if (is_null($excludedGroups)) {
1526
+                $excludedGroups = explode(',', $groupsList);
1527
+                $newValue = json_encode($excludedGroups);
1528
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1529
+            }
1530
+            $user = $this->userManager->get($userId);
1531
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1532
+            if (!empty($usersGroups)) {
1533
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1534
+                // if the user is only in groups which are disabled for sharing then
1535
+                // sharing is also disabled for the user
1536
+                if (empty($remainingGroups)) {
1537
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1538
+                    return true;
1539
+                }
1540
+            }
1541
+        }
1542
+
1543
+        $this->sharingDisabledForUsersCache[$userId] = false;
1544
+        return false;
1545
+    }
1546
+
1547
+    /**
1548
+     * @inheritdoc
1549
+     */
1550
+    public function outgoingServer2ServerSharesAllowed() {
1551
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1552
+    }
1553
+
1554
+    /**
1555
+     * @inheritdoc
1556
+     */
1557
+    public function shareProviderExists($shareType) {
1558
+        try {
1559
+            $this->factory->getProviderForType($shareType);
1560
+        } catch (ProviderException $e) {
1561
+            return false;
1562
+        }
1563
+
1564
+        return true;
1565
+    }
1566 1566
 
1567 1567
 }
Please login to merge, or discard this patch.
apps/workflowengine/lib/Check/FileSystemTags.php 1 patch
Indentation   +133 added lines, -133 removed lines patch added patch discarded remove patch
@@ -33,137 +33,137 @@
 block discarded – undo
33 33
 
34 34
 class FileSystemTags implements ICheck {
35 35
 
36
-	/** @var array */
37
-	protected $fileIds;
38
-
39
-	/** @var array */
40
-	protected $fileSystemTags;
41
-
42
-	/** @var IL10N */
43
-	protected $l;
44
-
45
-	/** @var ISystemTagManager */
46
-	protected $systemTagManager;
47
-
48
-	/** @var ISystemTagObjectMapper */
49
-	protected $systemTagObjectMapper;
50
-
51
-	/** @var IStorage */
52
-	protected $storage;
53
-
54
-	/** @var string */
55
-	protected $path;
56
-
57
-	/**
58
-	 * @param IL10N $l
59
-	 * @param ISystemTagManager $systemTagManager
60
-	 * @param ISystemTagObjectMapper $systemTagObjectMapper
61
-	 */
62
-	public function __construct(IL10N $l, ISystemTagManager $systemTagManager, ISystemTagObjectMapper $systemTagObjectMapper) {
63
-		$this->l = $l;
64
-		$this->systemTagManager = $systemTagManager;
65
-		$this->systemTagObjectMapper = $systemTagObjectMapper;
66
-	}
67
-
68
-	/**
69
-	 * @param IStorage $storage
70
-	 * @param string $path
71
-	 */
72
-	public function setFileInfo(IStorage $storage, $path) {
73
-		$this->storage = $storage;
74
-		$this->path = $path;
75
-	}
76
-
77
-	/**
78
-	 * @param string $operator
79
-	 * @param string $value
80
-	 * @return bool
81
-	 */
82
-	public function executeCheck($operator, $value) {
83
-		$systemTags = $this->getSystemTags();
84
-		return ($operator === 'is') === in_array($value, $systemTags);
85
-	}
86
-
87
-	/**
88
-	 * @param string $operator
89
-	 * @param string $value
90
-	 * @throws \UnexpectedValueException
91
-	 */
92
-	public function validateCheck($operator, $value) {
93
-		if (!in_array($operator, ['is', '!is'])) {
94
-			throw new \UnexpectedValueException($this->l->t('The given operator is invalid'), 1);
95
-		}
96
-
97
-		try {
98
-			$this->systemTagManager->getTagsByIds($value);
99
-		} catch (TagNotFoundException $e) {
100
-			throw new \UnexpectedValueException($this->l->t('The given tag id is invalid'), 2);
101
-		} catch (\InvalidArgumentException $e) {
102
-			throw new \UnexpectedValueException($this->l->t('The given tag id is invalid'), 3);
103
-		}
104
-	}
105
-
106
-	/**
107
-	 * Get the ids of the assigned system tags
108
-	 * @return string[]
109
-	 */
110
-	protected function getSystemTags() {
111
-		$cache = $this->storage->getCache();
112
-		$fileIds = $this->getFileIds($cache, $this->path, !$this->storage->instanceOfStorage(IHomeStorage::class));
113
-
114
-		$systemTags = [];
115
-		foreach ($fileIds as $i => $fileId) {
116
-			if (isset($this->fileSystemTags[$fileId])) {
117
-				$systemTags[] = $this->fileSystemTags[$fileId];
118
-				unset($fileIds[$i]);
119
-			}
120
-		}
121
-
122
-		if (!empty($fileIds)) {
123
-			$mappedSystemTags = $this->systemTagObjectMapper->getTagIdsForObjects($fileIds, 'files');
124
-			foreach ($mappedSystemTags as $fileId => $fileSystemTags) {
125
-				$this->fileSystemTags[$fileId] = $fileSystemTags;
126
-				$systemTags[] = $fileSystemTags;
127
-			}
128
-		}
129
-
130
-		$systemTags = call_user_func_array('array_merge', $systemTags);
131
-		$systemTags = array_unique($systemTags);
132
-		return $systemTags;
133
-	}
134
-
135
-	/**
136
-	 * Get the file ids of the given path and its parents
137
-	 * @param ICache $cache
138
-	 * @param string $path
139
-	 * @param bool $isExternalStorage
140
-	 * @return int[]
141
-	 */
142
-	protected function getFileIds(ICache $cache, $path, $isExternalStorage) {
143
-		$cacheId = $cache->getNumericStorageId();
144
-		if (isset($this->fileIds[$cacheId][$path])) {
145
-			return $this->fileIds[$cacheId][$path];
146
-		}
147
-
148
-		$parentIds = [];
149
-		if ($path !== $this->dirname($path)) {
150
-			$parentIds = $this->getFileIds($cache, $this->dirname($path), $isExternalStorage);
151
-		} else if (!$isExternalStorage) {
152
-			return [];
153
-		}
154
-
155
-		$fileId = $cache->getId($path);
156
-		if ($fileId !== -1) {
157
-			$parentIds[] = $cache->getId($path);
158
-		}
159
-
160
-		$this->fileIds[$cacheId][$path] = $parentIds;
161
-
162
-		return $parentIds;
163
-	}
164
-
165
-	protected function dirname($path) {
166
-		$dir = dirname($path);
167
-		return $dir === '.' ? '' : $dir;
168
-	}
36
+    /** @var array */
37
+    protected $fileIds;
38
+
39
+    /** @var array */
40
+    protected $fileSystemTags;
41
+
42
+    /** @var IL10N */
43
+    protected $l;
44
+
45
+    /** @var ISystemTagManager */
46
+    protected $systemTagManager;
47
+
48
+    /** @var ISystemTagObjectMapper */
49
+    protected $systemTagObjectMapper;
50
+
51
+    /** @var IStorage */
52
+    protected $storage;
53
+
54
+    /** @var string */
55
+    protected $path;
56
+
57
+    /**
58
+     * @param IL10N $l
59
+     * @param ISystemTagManager $systemTagManager
60
+     * @param ISystemTagObjectMapper $systemTagObjectMapper
61
+     */
62
+    public function __construct(IL10N $l, ISystemTagManager $systemTagManager, ISystemTagObjectMapper $systemTagObjectMapper) {
63
+        $this->l = $l;
64
+        $this->systemTagManager = $systemTagManager;
65
+        $this->systemTagObjectMapper = $systemTagObjectMapper;
66
+    }
67
+
68
+    /**
69
+     * @param IStorage $storage
70
+     * @param string $path
71
+     */
72
+    public function setFileInfo(IStorage $storage, $path) {
73
+        $this->storage = $storage;
74
+        $this->path = $path;
75
+    }
76
+
77
+    /**
78
+     * @param string $operator
79
+     * @param string $value
80
+     * @return bool
81
+     */
82
+    public function executeCheck($operator, $value) {
83
+        $systemTags = $this->getSystemTags();
84
+        return ($operator === 'is') === in_array($value, $systemTags);
85
+    }
86
+
87
+    /**
88
+     * @param string $operator
89
+     * @param string $value
90
+     * @throws \UnexpectedValueException
91
+     */
92
+    public function validateCheck($operator, $value) {
93
+        if (!in_array($operator, ['is', '!is'])) {
94
+            throw new \UnexpectedValueException($this->l->t('The given operator is invalid'), 1);
95
+        }
96
+
97
+        try {
98
+            $this->systemTagManager->getTagsByIds($value);
99
+        } catch (TagNotFoundException $e) {
100
+            throw new \UnexpectedValueException($this->l->t('The given tag id is invalid'), 2);
101
+        } catch (\InvalidArgumentException $e) {
102
+            throw new \UnexpectedValueException($this->l->t('The given tag id is invalid'), 3);
103
+        }
104
+    }
105
+
106
+    /**
107
+     * Get the ids of the assigned system tags
108
+     * @return string[]
109
+     */
110
+    protected function getSystemTags() {
111
+        $cache = $this->storage->getCache();
112
+        $fileIds = $this->getFileIds($cache, $this->path, !$this->storage->instanceOfStorage(IHomeStorage::class));
113
+
114
+        $systemTags = [];
115
+        foreach ($fileIds as $i => $fileId) {
116
+            if (isset($this->fileSystemTags[$fileId])) {
117
+                $systemTags[] = $this->fileSystemTags[$fileId];
118
+                unset($fileIds[$i]);
119
+            }
120
+        }
121
+
122
+        if (!empty($fileIds)) {
123
+            $mappedSystemTags = $this->systemTagObjectMapper->getTagIdsForObjects($fileIds, 'files');
124
+            foreach ($mappedSystemTags as $fileId => $fileSystemTags) {
125
+                $this->fileSystemTags[$fileId] = $fileSystemTags;
126
+                $systemTags[] = $fileSystemTags;
127
+            }
128
+        }
129
+
130
+        $systemTags = call_user_func_array('array_merge', $systemTags);
131
+        $systemTags = array_unique($systemTags);
132
+        return $systemTags;
133
+    }
134
+
135
+    /**
136
+     * Get the file ids of the given path and its parents
137
+     * @param ICache $cache
138
+     * @param string $path
139
+     * @param bool $isExternalStorage
140
+     * @return int[]
141
+     */
142
+    protected function getFileIds(ICache $cache, $path, $isExternalStorage) {
143
+        $cacheId = $cache->getNumericStorageId();
144
+        if (isset($this->fileIds[$cacheId][$path])) {
145
+            return $this->fileIds[$cacheId][$path];
146
+        }
147
+
148
+        $parentIds = [];
149
+        if ($path !== $this->dirname($path)) {
150
+            $parentIds = $this->getFileIds($cache, $this->dirname($path), $isExternalStorage);
151
+        } else if (!$isExternalStorage) {
152
+            return [];
153
+        }
154
+
155
+        $fileId = $cache->getId($path);
156
+        if ($fileId !== -1) {
157
+            $parentIds[] = $cache->getId($path);
158
+        }
159
+
160
+        $this->fileIds[$cacheId][$path] = $parentIds;
161
+
162
+        return $parentIds;
163
+    }
164
+
165
+    protected function dirname($path) {
166
+        $dir = dirname($path);
167
+        return $dir === '.' ? '' : $dir;
168
+    }
169 169
 }
Please login to merge, or discard this patch.
lib/public/Share/IShare.php 1 patch
Indentation   +304 added lines, -304 removed lines patch added patch discarded remove patch
@@ -37,308 +37,308 @@
 block discarded – undo
37 37
  */
38 38
 interface IShare {
39 39
 
40
-	/**
41
-	 * Set the internal id of the share
42
-	 * It is only allowed to set the internal id of a share once.
43
-	 * Attempts to override the internal id will result in an IllegalIDChangeException
44
-	 *
45
-	 * @param string $id
46
-	 * @return \OCP\Share\IShare
47
-	 * @throws IllegalIDChangeException
48
-	 * @throws \InvalidArgumentException
49
-	 * @since 9.1.0
50
-	 */
51
-	public function setId($id);
52
-
53
-	/**
54
-	 * Get the internal id of the share.
55
-	 *
56
-	 * @return string
57
-	 * @since 9.0.0
58
-	 */
59
-	public function getId();
60
-
61
-	/**
62
-	 * Get the full share id. This is the <providerid>:<internalid>.
63
-	 * The full id is unique in the system.
64
-	 *
65
-	 * @return string
66
-	 * @since 9.0.0
67
-	 * @throws \UnexpectedValueException If the fullId could not be constructed
68
-	 */
69
-	public function getFullId();
70
-
71
-	/**
72
-	 * Set the provider id of the share
73
-	 * It is only allowed to set the provider id of a share once.
74
-	 * Attempts to override the provider id will result in an IllegalIDChangeException
75
-	 *
76
-	 * @param string $id
77
-	 * @return \OCP\Share\IShare
78
-	 * @throws IllegalIDChangeException
79
-	 * @throws \InvalidArgumentException
80
-	 * @since 9.1.0
81
-	 */
82
-	public function setProviderId($id);
83
-
84
-	/**
85
-	 * Set the node of the file/folder that is shared
86
-	 *
87
-	 * @param Node $node
88
-	 * @return \OCP\Share\IShare The modified object
89
-	 * @since 9.0.0
90
-	 */
91
-	public function setNode(Node $node);
92
-
93
-	/**
94
-	 * Get the node of the file/folder that is shared
95
-	 *
96
-	 * @return File|Folder
97
-	 * @since 9.0.0
98
-	 * @throws NotFoundException
99
-	 */
100
-	public function getNode();
101
-
102
-	/**
103
-	 * Set file id for lazy evaluation of the node
104
-	 * @param int $fileId
105
-	 * @return \OCP\Share\IShare The modified object
106
-	 * @since 9.0.0
107
-	 */
108
-	public function setNodeId($fileId);
109
-
110
-	/**
111
-	 * Get the fileid of the node of this share
112
-	 * @return int
113
-	 * @since 9.0.0
114
-	 * @throws NotFoundException
115
-	 */
116
-	public function getNodeId();
117
-
118
-	/**
119
-	 * Set the type of node (file/folder)
120
-	 *
121
-	 * @param string $type
122
-	 * @return \OCP\Share\IShare The modified object
123
-	 * @since 9.0.0
124
-	 */
125
-	public function setNodeType($type);
126
-
127
-	/**
128
-	 * Get the type of node (file/folder)
129
-	 *
130
-	 * @return string
131
-	 * @since 9.0.0
132
-	 * @throws NotFoundException
133
-	 */
134
-	public function getNodeType();
135
-
136
-	/**
137
-	 * Set the shareType
138
-	 *
139
-	 * @param int $shareType
140
-	 * @return \OCP\Share\IShare The modified object
141
-	 * @since 9.0.0
142
-	 */
143
-	public function setShareType($shareType);
144
-
145
-	/**
146
-	 * Get the shareType
147
-	 *
148
-	 * @return int
149
-	 * @since 9.0.0
150
-	 */
151
-	public function getShareType();
152
-
153
-	/**
154
-	 * Set the receiver of this share.
155
-	 *
156
-	 * @param string $sharedWith
157
-	 * @return \OCP\Share\IShare The modified object
158
-	 * @since 9.0.0
159
-	 */
160
-	public function setSharedWith($sharedWith);
161
-
162
-	/**
163
-	 * Get the receiver of this share.
164
-	 *
165
-	 * @return string
166
-	 * @since 9.0.0
167
-	 */
168
-	public function getSharedWith();
169
-
170
-	/**
171
-	 * Set the permissions.
172
-	 * See \OCP\Constants::PERMISSION_*
173
-	 *
174
-	 * @param int $permissions
175
-	 * @return \OCP\Share\IShare The modified object
176
-	 * @since 9.0.0
177
-	 */
178
-	public function setPermissions($permissions);
179
-
180
-	/**
181
-	 * Get the share permissions
182
-	 * See \OCP\Constants::PERMISSION_*
183
-	 *
184
-	 * @return int
185
-	 * @since 9.0.0
186
-	 */
187
-	public function getPermissions();
188
-
189
-	/**
190
-	 * Set the expiration date
191
-	 *
192
-	 * @param null|\DateTime $expireDate
193
-	 * @return \OCP\Share\IShare The modified object
194
-	 * @since 9.0.0
195
-	 */
196
-	public function setExpirationDate($expireDate);
197
-
198
-	/**
199
-	 * Get the expiration date
200
-	 *
201
-	 * @return \DateTime
202
-	 * @since 9.0.0
203
-	 */
204
-	public function getExpirationDate();
205
-
206
-	/**
207
-	 * Set the sharer of the path.
208
-	 *
209
-	 * @param string $sharedBy
210
-	 * @return \OCP\Share\IShare The modified object
211
-	 * @since 9.0.0
212
-	 */
213
-	public function setSharedBy($sharedBy);
214
-
215
-	/**
216
-	 * Get share sharer
217
-	 *
218
-	 * @return string
219
-	 * @since 9.0.0
220
-	 */
221
-	public function getSharedBy();
222
-
223
-	/**
224
-	 * Set the original share owner (who owns the path that is shared)
225
-	 *
226
-	 * @param string $shareOwner
227
-	 * @return \OCP\Share\IShare The modified object
228
-	 * @since 9.0.0
229
-	 */
230
-	public function setShareOwner($shareOwner);
231
-
232
-	/**
233
-	 * Get the original share owner (who owns the path that is shared)
234
-	 *
235
-	 * @return string
236
-	 * @since 9.0.0
237
-	 */
238
-	public function getShareOwner();
239
-
240
-	/**
241
-	 * Set the password for this share.
242
-	 * When the share is passed to the share manager to be created
243
-	 * or updated the password will be hashed.
244
-	 *
245
-	 * @param string $password
246
-	 * @return \OCP\Share\IShare The modified object
247
-	 * @since 9.0.0
248
-	 */
249
-	public function setPassword($password);
250
-
251
-	/**
252
-	 * Get the password of this share.
253
-	 * If this share is obtained via a shareprovider the password is
254
-	 * hashed.
255
-	 *
256
-	 * @return string
257
-	 * @since 9.0.0
258
-	 */
259
-	public function getPassword();
260
-
261
-	/**
262
-	 * Set the public link token.
263
-	 *
264
-	 * @param string $token
265
-	 * @return \OCP\Share\IShare The modified object
266
-	 * @since 9.0.0
267
-	 */
268
-	public function setToken($token);
269
-
270
-	/**
271
-	 * Get the public link token.
272
-	 *
273
-	 * @return string
274
-	 * @since 9.0.0
275
-	 */
276
-	public function getToken();
277
-
278
-	/**
279
-	 * Set the target path of this share relative to the recipients user folder.
280
-	 *
281
-	 * @param string $target
282
-	 * @return \OCP\Share\IShare The modified object
283
-	 * @since 9.0.0
284
-	 */
285
-	public function setTarget($target);
286
-
287
-	/**
288
-	 * Get the target path of this share relative to the recipients user folder.
289
-	 *
290
-	 * @return string
291
-	 * @since 9.0.0
292
-	 */
293
-	public function getTarget();
294
-
295
-	/**
296
-	 * Set the time this share was created
297
-	 *
298
-	 * @param \DateTime $shareTime
299
-	 * @return \OCP\Share\IShare The modified object
300
-	 * @since 9.0.0
301
-	 */
302
-	public function setShareTime(\DateTime $shareTime);
303
-
304
-	/**
305
-	 * Get the timestamp this share was created
306
-	 *
307
-	 * @return \DateTime
308
-	 * @since 9.0.0
309
-	 */
310
-	public function getShareTime();
311
-
312
-	/**
313
-	 * Set if the recipient is informed by mail about the share.
314
-	 *
315
-	 * @param bool $mailSend
316
-	 * @return \OCP\Share\IShare The modified object
317
-	 * @since 9.0.0
318
-	 */
319
-	public function setMailSend($mailSend);
320
-
321
-	/**
322
-	 * Get if the recipient informed by mail about the share.
323
-	 *
324
-	 * @return bool
325
-	 * @since 9.0.0
326
-	 */
327
-	public function getMailSend();
328
-
329
-	/**
330
-	 * Set the cache entry for the shared node
331
-	 *
332
-	 * @param ICacheEntry $entry
333
-	 * @since 11.0.0
334
-	 */
335
-	public function setNodeCacheEntry(ICacheEntry $entry);
336
-
337
-	/**
338
-	 * Get the cache entry for the shared node
339
-	 *
340
-	 * @return null|ICacheEntry
341
-	 * @since 11.0.0
342
-	 */
343
-	public function getNodeCacheEntry();
40
+    /**
41
+     * Set the internal id of the share
42
+     * It is only allowed to set the internal id of a share once.
43
+     * Attempts to override the internal id will result in an IllegalIDChangeException
44
+     *
45
+     * @param string $id
46
+     * @return \OCP\Share\IShare
47
+     * @throws IllegalIDChangeException
48
+     * @throws \InvalidArgumentException
49
+     * @since 9.1.0
50
+     */
51
+    public function setId($id);
52
+
53
+    /**
54
+     * Get the internal id of the share.
55
+     *
56
+     * @return string
57
+     * @since 9.0.0
58
+     */
59
+    public function getId();
60
+
61
+    /**
62
+     * Get the full share id. This is the <providerid>:<internalid>.
63
+     * The full id is unique in the system.
64
+     *
65
+     * @return string
66
+     * @since 9.0.0
67
+     * @throws \UnexpectedValueException If the fullId could not be constructed
68
+     */
69
+    public function getFullId();
70
+
71
+    /**
72
+     * Set the provider id of the share
73
+     * It is only allowed to set the provider id of a share once.
74
+     * Attempts to override the provider id will result in an IllegalIDChangeException
75
+     *
76
+     * @param string $id
77
+     * @return \OCP\Share\IShare
78
+     * @throws IllegalIDChangeException
79
+     * @throws \InvalidArgumentException
80
+     * @since 9.1.0
81
+     */
82
+    public function setProviderId($id);
83
+
84
+    /**
85
+     * Set the node of the file/folder that is shared
86
+     *
87
+     * @param Node $node
88
+     * @return \OCP\Share\IShare The modified object
89
+     * @since 9.0.0
90
+     */
91
+    public function setNode(Node $node);
92
+
93
+    /**
94
+     * Get the node of the file/folder that is shared
95
+     *
96
+     * @return File|Folder
97
+     * @since 9.0.0
98
+     * @throws NotFoundException
99
+     */
100
+    public function getNode();
101
+
102
+    /**
103
+     * Set file id for lazy evaluation of the node
104
+     * @param int $fileId
105
+     * @return \OCP\Share\IShare The modified object
106
+     * @since 9.0.0
107
+     */
108
+    public function setNodeId($fileId);
109
+
110
+    /**
111
+     * Get the fileid of the node of this share
112
+     * @return int
113
+     * @since 9.0.0
114
+     * @throws NotFoundException
115
+     */
116
+    public function getNodeId();
117
+
118
+    /**
119
+     * Set the type of node (file/folder)
120
+     *
121
+     * @param string $type
122
+     * @return \OCP\Share\IShare The modified object
123
+     * @since 9.0.0
124
+     */
125
+    public function setNodeType($type);
126
+
127
+    /**
128
+     * Get the type of node (file/folder)
129
+     *
130
+     * @return string
131
+     * @since 9.0.0
132
+     * @throws NotFoundException
133
+     */
134
+    public function getNodeType();
135
+
136
+    /**
137
+     * Set the shareType
138
+     *
139
+     * @param int $shareType
140
+     * @return \OCP\Share\IShare The modified object
141
+     * @since 9.0.0
142
+     */
143
+    public function setShareType($shareType);
144
+
145
+    /**
146
+     * Get the shareType
147
+     *
148
+     * @return int
149
+     * @since 9.0.0
150
+     */
151
+    public function getShareType();
152
+
153
+    /**
154
+     * Set the receiver of this share.
155
+     *
156
+     * @param string $sharedWith
157
+     * @return \OCP\Share\IShare The modified object
158
+     * @since 9.0.0
159
+     */
160
+    public function setSharedWith($sharedWith);
161
+
162
+    /**
163
+     * Get the receiver of this share.
164
+     *
165
+     * @return string
166
+     * @since 9.0.0
167
+     */
168
+    public function getSharedWith();
169
+
170
+    /**
171
+     * Set the permissions.
172
+     * See \OCP\Constants::PERMISSION_*
173
+     *
174
+     * @param int $permissions
175
+     * @return \OCP\Share\IShare The modified object
176
+     * @since 9.0.0
177
+     */
178
+    public function setPermissions($permissions);
179
+
180
+    /**
181
+     * Get the share permissions
182
+     * See \OCP\Constants::PERMISSION_*
183
+     *
184
+     * @return int
185
+     * @since 9.0.0
186
+     */
187
+    public function getPermissions();
188
+
189
+    /**
190
+     * Set the expiration date
191
+     *
192
+     * @param null|\DateTime $expireDate
193
+     * @return \OCP\Share\IShare The modified object
194
+     * @since 9.0.0
195
+     */
196
+    public function setExpirationDate($expireDate);
197
+
198
+    /**
199
+     * Get the expiration date
200
+     *
201
+     * @return \DateTime
202
+     * @since 9.0.0
203
+     */
204
+    public function getExpirationDate();
205
+
206
+    /**
207
+     * Set the sharer of the path.
208
+     *
209
+     * @param string $sharedBy
210
+     * @return \OCP\Share\IShare The modified object
211
+     * @since 9.0.0
212
+     */
213
+    public function setSharedBy($sharedBy);
214
+
215
+    /**
216
+     * Get share sharer
217
+     *
218
+     * @return string
219
+     * @since 9.0.0
220
+     */
221
+    public function getSharedBy();
222
+
223
+    /**
224
+     * Set the original share owner (who owns the path that is shared)
225
+     *
226
+     * @param string $shareOwner
227
+     * @return \OCP\Share\IShare The modified object
228
+     * @since 9.0.0
229
+     */
230
+    public function setShareOwner($shareOwner);
231
+
232
+    /**
233
+     * Get the original share owner (who owns the path that is shared)
234
+     *
235
+     * @return string
236
+     * @since 9.0.0
237
+     */
238
+    public function getShareOwner();
239
+
240
+    /**
241
+     * Set the password for this share.
242
+     * When the share is passed to the share manager to be created
243
+     * or updated the password will be hashed.
244
+     *
245
+     * @param string $password
246
+     * @return \OCP\Share\IShare The modified object
247
+     * @since 9.0.0
248
+     */
249
+    public function setPassword($password);
250
+
251
+    /**
252
+     * Get the password of this share.
253
+     * If this share is obtained via a shareprovider the password is
254
+     * hashed.
255
+     *
256
+     * @return string
257
+     * @since 9.0.0
258
+     */
259
+    public function getPassword();
260
+
261
+    /**
262
+     * Set the public link token.
263
+     *
264
+     * @param string $token
265
+     * @return \OCP\Share\IShare The modified object
266
+     * @since 9.0.0
267
+     */
268
+    public function setToken($token);
269
+
270
+    /**
271
+     * Get the public link token.
272
+     *
273
+     * @return string
274
+     * @since 9.0.0
275
+     */
276
+    public function getToken();
277
+
278
+    /**
279
+     * Set the target path of this share relative to the recipients user folder.
280
+     *
281
+     * @param string $target
282
+     * @return \OCP\Share\IShare The modified object
283
+     * @since 9.0.0
284
+     */
285
+    public function setTarget($target);
286
+
287
+    /**
288
+     * Get the target path of this share relative to the recipients user folder.
289
+     *
290
+     * @return string
291
+     * @since 9.0.0
292
+     */
293
+    public function getTarget();
294
+
295
+    /**
296
+     * Set the time this share was created
297
+     *
298
+     * @param \DateTime $shareTime
299
+     * @return \OCP\Share\IShare The modified object
300
+     * @since 9.0.0
301
+     */
302
+    public function setShareTime(\DateTime $shareTime);
303
+
304
+    /**
305
+     * Get the timestamp this share was created
306
+     *
307
+     * @return \DateTime
308
+     * @since 9.0.0
309
+     */
310
+    public function getShareTime();
311
+
312
+    /**
313
+     * Set if the recipient is informed by mail about the share.
314
+     *
315
+     * @param bool $mailSend
316
+     * @return \OCP\Share\IShare The modified object
317
+     * @since 9.0.0
318
+     */
319
+    public function setMailSend($mailSend);
320
+
321
+    /**
322
+     * Get if the recipient informed by mail about the share.
323
+     *
324
+     * @return bool
325
+     * @since 9.0.0
326
+     */
327
+    public function getMailSend();
328
+
329
+    /**
330
+     * Set the cache entry for the shared node
331
+     *
332
+     * @param ICacheEntry $entry
333
+     * @since 11.0.0
334
+     */
335
+    public function setNodeCacheEntry(ICacheEntry $entry);
336
+
337
+    /**
338
+     * Get the cache entry for the shared node
339
+     *
340
+     * @return null|ICacheEntry
341
+     * @since 11.0.0
342
+     */
343
+    public function getNodeCacheEntry();
344 344
 }
Please login to merge, or discard this patch.
lib/private/Contacts/ContactsMenu/ActionProviderStore.php 1 patch
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -35,80 +35,80 @@
 block discarded – undo
35 35
 
36 36
 class ActionProviderStore {
37 37
 
38
-	/** @var IServerContainer */
39
-	private $serverContainer;
40
-
41
-	/** @var AppManager */
42
-	private $appManager;
43
-
44
-	/** @var ILogger */
45
-	private $logger;
46
-
47
-	/**
48
-	 * @param IServerContainer $serverContainer
49
-	 * @param AppManager $appManager
50
-	 * @param ILogger $logger
51
-	 */
52
-	public function __construct(IServerContainer $serverContainer, AppManager $appManager, ILogger $logger) {
53
-		$this->serverContainer = $serverContainer;
54
-		$this->appManager = $appManager;
55
-		$this->logger = $logger;
56
-	}
57
-
58
-	/**
59
-	 * @param IUser $user
60
-	 * @return IProvider[]
61
-	 * @throws Exception
62
-	 */
63
-	public function getProviders(IUser $user) {
64
-		$appClasses = $this->getAppProviderClasses($user);
65
-		$providerClasses = $this->getServerProviderClasses();
66
-		$allClasses = array_merge($providerClasses, $appClasses);
67
-		$providers = [];
68
-
69
-		foreach ($allClasses as $class) {
70
-			try {
71
-				$providers[] = $this->serverContainer->query($class);
72
-			} catch (QueryException $ex) {
73
-				$this->logger->logException($ex, [
74
-					'message' => "Could not load contacts menu action provider $class",
75
-					'app' => 'core',
76
-				]);
77
-				throw new Exception("Could not load contacts menu action provider");
78
-			}
79
-		}
80
-
81
-		return $providers;
82
-	}
83
-
84
-	/**
85
-	 * @return string[]
86
-	 */
87
-	private function getServerProviderClasses() {
88
-		return [
89
-			EMailProvider::class,
90
-		];
91
-	}
92
-
93
-	/**
94
-	 * @param IUser $user
95
-	 * @return string[]
96
-	 */
97
-	private function getAppProviderClasses(IUser $user) {
98
-		return array_reduce($this->appManager->getEnabledAppsForUser($user), function($all, $appId) {
99
-			$info = $this->appManager->getAppInfo($appId);
100
-
101
-			if (!isset($info['contactsmenu']) || !isset($info['contactsmenu'])) {
102
-				// Nothing to add
103
-				return $all;
104
-			}
105
-
106
-			$providers = array_reduce($info['contactsmenu'], function($all, $provider) {
107
-				return array_merge($all, [$provider]);
108
-			}, []);
109
-
110
-			return array_merge($all, $providers);
111
-		}, []);
112
-	}
38
+    /** @var IServerContainer */
39
+    private $serverContainer;
40
+
41
+    /** @var AppManager */
42
+    private $appManager;
43
+
44
+    /** @var ILogger */
45
+    private $logger;
46
+
47
+    /**
48
+     * @param IServerContainer $serverContainer
49
+     * @param AppManager $appManager
50
+     * @param ILogger $logger
51
+     */
52
+    public function __construct(IServerContainer $serverContainer, AppManager $appManager, ILogger $logger) {
53
+        $this->serverContainer = $serverContainer;
54
+        $this->appManager = $appManager;
55
+        $this->logger = $logger;
56
+    }
57
+
58
+    /**
59
+     * @param IUser $user
60
+     * @return IProvider[]
61
+     * @throws Exception
62
+     */
63
+    public function getProviders(IUser $user) {
64
+        $appClasses = $this->getAppProviderClasses($user);
65
+        $providerClasses = $this->getServerProviderClasses();
66
+        $allClasses = array_merge($providerClasses, $appClasses);
67
+        $providers = [];
68
+
69
+        foreach ($allClasses as $class) {
70
+            try {
71
+                $providers[] = $this->serverContainer->query($class);
72
+            } catch (QueryException $ex) {
73
+                $this->logger->logException($ex, [
74
+                    'message' => "Could not load contacts menu action provider $class",
75
+                    'app' => 'core',
76
+                ]);
77
+                throw new Exception("Could not load contacts menu action provider");
78
+            }
79
+        }
80
+
81
+        return $providers;
82
+    }
83
+
84
+    /**
85
+     * @return string[]
86
+     */
87
+    private function getServerProviderClasses() {
88
+        return [
89
+            EMailProvider::class,
90
+        ];
91
+    }
92
+
93
+    /**
94
+     * @param IUser $user
95
+     * @return string[]
96
+     */
97
+    private function getAppProviderClasses(IUser $user) {
98
+        return array_reduce($this->appManager->getEnabledAppsForUser($user), function($all, $appId) {
99
+            $info = $this->appManager->getAppInfo($appId);
100
+
101
+            if (!isset($info['contactsmenu']) || !isset($info['contactsmenu'])) {
102
+                // Nothing to add
103
+                return $all;
104
+            }
105
+
106
+            $providers = array_reduce($info['contactsmenu'], function($all, $provider) {
107
+                return array_merge($all, [$provider]);
108
+            }, []);
109
+
110
+            return array_merge($all, $providers);
111
+        }, []);
112
+    }
113 113
 
114 114
 }
Please login to merge, or discard this patch.
lib/private/Lockdown/LockdownManager.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -24,56 +24,56 @@
 block discarded – undo
24 24
 use OCP\Lockdown\ILockdownManager;
25 25
 
26 26
 class LockdownManager implements ILockdownManager {
27
-	/** @var ISession */
28
-	private $sessionCallback;
27
+    /** @var ISession */
28
+    private $sessionCallback;
29 29
 
30
-	private $enabled = false;
30
+    private $enabled = false;
31 31
 
32
-	/** @var array|null */
33
-	private $scope;
32
+    /** @var array|null */
33
+    private $scope;
34 34
 
35
-	/**
36
-	 * LockdownManager constructor.
37
-	 *
38
-	 * @param callable $sessionCallback we need to inject the session lazily to avoid dependency loops
39
-	 */
40
-	public function __construct(callable $sessionCallback) {
41
-		$this->sessionCallback = $sessionCallback;
42
-	}
35
+    /**
36
+     * LockdownManager constructor.
37
+     *
38
+     * @param callable $sessionCallback we need to inject the session lazily to avoid dependency loops
39
+     */
40
+    public function __construct(callable $sessionCallback) {
41
+        $this->sessionCallback = $sessionCallback;
42
+    }
43 43
 
44 44
 
45
-	public function enable() {
46
-		$this->enabled = true;
47
-	}
45
+    public function enable() {
46
+        $this->enabled = true;
47
+    }
48 48
 
49
-	/**
50
-	 * @return ISession
51
-	 */
52
-	private function getSession() {
53
-		$callback = $this->sessionCallback;
54
-		return $callback();
55
-	}
49
+    /**
50
+     * @return ISession
51
+     */
52
+    private function getSession() {
53
+        $callback = $this->sessionCallback;
54
+        return $callback();
55
+    }
56 56
 
57
-	private function getScopeAsArray() {
58
-		if (!$this->scope) {
59
-			$session = $this->getSession();
60
-			$sessionScope = $session->get('token_scope');
61
-			if ($sessionScope) {
62
-				$this->scope = $sessionScope;
63
-			}
64
-		}
65
-		return $this->scope;
66
-	}
57
+    private function getScopeAsArray() {
58
+        if (!$this->scope) {
59
+            $session = $this->getSession();
60
+            $sessionScope = $session->get('token_scope');
61
+            if ($sessionScope) {
62
+                $this->scope = $sessionScope;
63
+            }
64
+        }
65
+        return $this->scope;
66
+    }
67 67
 
68
-	public function setToken(IToken $token) {
69
-		$this->scope = $token->getScopeAsArray();
70
-		$session = $this->getSession();
71
-		$session->set('token_scope', $this->scope);
72
-		$this->enable();
73
-	}
68
+    public function setToken(IToken $token) {
69
+        $this->scope = $token->getScopeAsArray();
70
+        $session = $this->getSession();
71
+        $session->set('token_scope', $this->scope);
72
+        $this->enable();
73
+    }
74 74
 
75
-	public function canAccessFilesystem() {
76
-		$scope = $this->getScopeAsArray();
77
-		return !$scope || $scope['filesystem'];
78
-	}
75
+    public function canAccessFilesystem() {
76
+        $scope = $this->getScopeAsArray();
77
+        return !$scope || $scope['filesystem'];
78
+    }
79 79
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Hooks.php 1 patch
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -31,31 +31,31 @@
 block discarded – undo
31 31
 
32 32
 class Hooks {
33 33
 
34
-	public static function deleteUser($params) {
35
-		$manager = new External\Manager(
36
-			\OC::$server->getDatabaseConnection(),
37
-			\OC\Files\Filesystem::getMountManager(),
38
-			\OC\Files\Filesystem::getLoader(),
39
-			\OC::$server->getHTTPClientService(),
40
-			\OC::$server->getNotificationManager(),
41
-			\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
42
-			$params['uid']);
34
+    public static function deleteUser($params) {
35
+        $manager = new External\Manager(
36
+            \OC::$server->getDatabaseConnection(),
37
+            \OC\Files\Filesystem::getMountManager(),
38
+            \OC\Files\Filesystem::getLoader(),
39
+            \OC::$server->getHTTPClientService(),
40
+            \OC::$server->getNotificationManager(),
41
+            \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
42
+            $params['uid']);
43 43
 
44
-		$manager->removeUserShares($params['uid']);
45
-	}
44
+        $manager->removeUserShares($params['uid']);
45
+    }
46 46
 
47
-	public static function unshareChildren($params) {
48
-		$path = Filesystem::getView()->getAbsolutePath($params['path']);
49
-		$view = new \OC\Files\View('/');
47
+    public static function unshareChildren($params) {
48
+        $path = Filesystem::getView()->getAbsolutePath($params['path']);
49
+        $view = new \OC\Files\View('/');
50 50
 
51
-		// find share mount points within $path and unmount them
52
-		$mountManager = \OC\Files\Filesystem::getMountManager();
53
-		$mountedShares = $mountManager->findIn($path);
54
-		foreach ($mountedShares as $mount) {
55
-			if ($mount->getStorage()->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
56
-				$mountPoint = $mount->getMountPoint();
57
-				$view->unlink($mountPoint);
58
-			}
59
-		}
60
-	}
51
+        // find share mount points within $path and unmount them
52
+        $mountManager = \OC\Files\Filesystem::getMountManager();
53
+        $mountedShares = $mountManager->findIn($path);
54
+        foreach ($mountedShares as $mount) {
55
+            if ($mount->getStorage()->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
56
+                $mountPoint = $mount->getMountPoint();
57
+                $view->unlink($mountPoint);
58
+            }
59
+        }
60
+    }
61 61
 }
Please login to merge, or discard this patch.