Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
created
apps/files/lib/Helper.php 1 patch
Indentation   +208 added lines, -208 removed lines patch added patch discarded remove patch
@@ -40,232 +40,232 @@
 block discarded – undo
40 40
  * Helper class for manipulating file information
41 41
  */
42 42
 class Helper {
43
-	/**
44
-	 * @param string $dir
45
-	 * @return array
46
-	 * @throws \OCP\Files\NotFoundException
47
-	 */
48
-	public static function buildFileStorageStatistics($dir) {
49
-		// information about storage capacities
50
-		$storageInfo = \OC_Helper::getStorageInfo($dir);
51
-		$l = \OC::$server->getL10N('files');
52
-		$maxUploadFileSize = \OCP\Util::maxUploadFilesize($dir, $storageInfo['free']);
53
-		$maxHumanFileSize = \OCP\Util::humanFileSize($maxUploadFileSize);
54
-		$maxHumanFileSize = $l->t('Upload (max. %s)', [$maxHumanFileSize]);
43
+    /**
44
+     * @param string $dir
45
+     * @return array
46
+     * @throws \OCP\Files\NotFoundException
47
+     */
48
+    public static function buildFileStorageStatistics($dir) {
49
+        // information about storage capacities
50
+        $storageInfo = \OC_Helper::getStorageInfo($dir);
51
+        $l = \OC::$server->getL10N('files');
52
+        $maxUploadFileSize = \OCP\Util::maxUploadFilesize($dir, $storageInfo['free']);
53
+        $maxHumanFileSize = \OCP\Util::humanFileSize($maxUploadFileSize);
54
+        $maxHumanFileSize = $l->t('Upload (max. %s)', [$maxHumanFileSize]);
55 55
 
56
-		return [
57
-			'uploadMaxFilesize' => $maxUploadFileSize,
58
-			'maxHumanFilesize'  => $maxHumanFileSize,
59
-			'freeSpace' => $storageInfo['free'],
60
-			'quota' => $storageInfo['quota'],
61
-			'used' => $storageInfo['used'],
62
-			'usedSpacePercent'  => (int)$storageInfo['relative'],
63
-			'owner' => $storageInfo['owner'],
64
-			'ownerDisplayName' => $storageInfo['ownerDisplayName'],
65
-		];
66
-	}
56
+        return [
57
+            'uploadMaxFilesize' => $maxUploadFileSize,
58
+            'maxHumanFilesize'  => $maxHumanFileSize,
59
+            'freeSpace' => $storageInfo['free'],
60
+            'quota' => $storageInfo['quota'],
61
+            'used' => $storageInfo['used'],
62
+            'usedSpacePercent'  => (int)$storageInfo['relative'],
63
+            'owner' => $storageInfo['owner'],
64
+            'ownerDisplayName' => $storageInfo['ownerDisplayName'],
65
+        ];
66
+    }
67 67
 
68
-	/**
69
-	 * Determine icon for a given file
70
-	 *
71
-	 * @param \OCP\Files\FileInfo $file file info
72
-	 * @return string icon URL
73
-	 */
74
-	public static function determineIcon($file) {
75
-		if($file['type'] === 'dir') {
76
-			$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir');
77
-			// TODO: move this part to the client side, using mountType
78
-			if ($file->isShared()) {
79
-				$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-shared');
80
-			} elseif ($file->isMounted()) {
81
-				$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-external');
82
-			}
83
-		}else{
84
-			$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($file->getMimetype());
85
-		}
68
+    /**
69
+     * Determine icon for a given file
70
+     *
71
+     * @param \OCP\Files\FileInfo $file file info
72
+     * @return string icon URL
73
+     */
74
+    public static function determineIcon($file) {
75
+        if($file['type'] === 'dir') {
76
+            $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir');
77
+            // TODO: move this part to the client side, using mountType
78
+            if ($file->isShared()) {
79
+                $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-shared');
80
+            } elseif ($file->isMounted()) {
81
+                $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-external');
82
+            }
83
+        }else{
84
+            $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($file->getMimetype());
85
+        }
86 86
 
87
-		return substr($icon, 0, -3) . 'svg';
88
-	}
87
+        return substr($icon, 0, -3) . 'svg';
88
+    }
89 89
 
90
-	/**
91
-	 * Comparator function to sort files alphabetically and have
92
-	 * the directories appear first
93
-	 *
94
-	 * @param \OCP\Files\FileInfo $a file
95
-	 * @param \OCP\Files\FileInfo $b file
96
-	 * @return int -1 if $a must come before $b, 1 otherwise
97
-	 */
98
-	public static function compareFileNames(FileInfo $a, FileInfo $b) {
99
-		$aType = $a->getType();
100
-		$bType = $b->getType();
101
-		if ($aType === 'dir' and $bType !== 'dir') {
102
-			return -1;
103
-		} elseif ($aType !== 'dir' and $bType === 'dir') {
104
-			return 1;
105
-		} else {
106
-			return \OCP\Util::naturalSortCompare($a->getName(), $b->getName());
107
-		}
108
-	}
90
+    /**
91
+     * Comparator function to sort files alphabetically and have
92
+     * the directories appear first
93
+     *
94
+     * @param \OCP\Files\FileInfo $a file
95
+     * @param \OCP\Files\FileInfo $b file
96
+     * @return int -1 if $a must come before $b, 1 otherwise
97
+     */
98
+    public static function compareFileNames(FileInfo $a, FileInfo $b) {
99
+        $aType = $a->getType();
100
+        $bType = $b->getType();
101
+        if ($aType === 'dir' and $bType !== 'dir') {
102
+            return -1;
103
+        } elseif ($aType !== 'dir' and $bType === 'dir') {
104
+            return 1;
105
+        } else {
106
+            return \OCP\Util::naturalSortCompare($a->getName(), $b->getName());
107
+        }
108
+    }
109 109
 
110
-	/**
111
-	 * Comparator function to sort files by date
112
-	 *
113
-	 * @param \OCP\Files\FileInfo $a file
114
-	 * @param \OCP\Files\FileInfo $b file
115
-	 * @return int -1 if $a must come before $b, 1 otherwise
116
-	 */
117
-	public static function compareTimestamp(FileInfo $a, FileInfo $b) {
118
-		$aTime = $a->getMTime();
119
-		$bTime = $b->getMTime();
120
-		return ($aTime < $bTime) ? -1 : 1;
121
-	}
110
+    /**
111
+     * Comparator function to sort files by date
112
+     *
113
+     * @param \OCP\Files\FileInfo $a file
114
+     * @param \OCP\Files\FileInfo $b file
115
+     * @return int -1 if $a must come before $b, 1 otherwise
116
+     */
117
+    public static function compareTimestamp(FileInfo $a, FileInfo $b) {
118
+        $aTime = $a->getMTime();
119
+        $bTime = $b->getMTime();
120
+        return ($aTime < $bTime) ? -1 : 1;
121
+    }
122 122
 
123
-	/**
124
-	 * Comparator function to sort files by size
125
-	 *
126
-	 * @param \OCP\Files\FileInfo $a file
127
-	 * @param \OCP\Files\FileInfo $b file
128
-	 * @return int -1 if $a must come before $b, 1 otherwise
129
-	 */
130
-	public static function compareSize(FileInfo $a, FileInfo $b) {
131
-		$aSize = $a->getSize();
132
-		$bSize = $b->getSize();
133
-		return ($aSize < $bSize) ? -1 : 1;
134
-	}
123
+    /**
124
+     * Comparator function to sort files by size
125
+     *
126
+     * @param \OCP\Files\FileInfo $a file
127
+     * @param \OCP\Files\FileInfo $b file
128
+     * @return int -1 if $a must come before $b, 1 otherwise
129
+     */
130
+    public static function compareSize(FileInfo $a, FileInfo $b) {
131
+        $aSize = $a->getSize();
132
+        $bSize = $b->getSize();
133
+        return ($aSize < $bSize) ? -1 : 1;
134
+    }
135 135
 
136
-	/**
137
-	 * Formats the file info to be returned as JSON to the client.
138
-	 *
139
-	 * @param \OCP\Files\FileInfo $i
140
-	 * @return array formatted file info
141
-	 */
142
-	public static function formatFileInfo(FileInfo $i) {
143
-		$entry = [];
136
+    /**
137
+     * Formats the file info to be returned as JSON to the client.
138
+     *
139
+     * @param \OCP\Files\FileInfo $i
140
+     * @return array formatted file info
141
+     */
142
+    public static function formatFileInfo(FileInfo $i) {
143
+        $entry = [];
144 144
 
145
-		$entry['id'] = $i['fileid'];
146
-		$entry['parentId'] = $i['parent'];
147
-		$entry['mtime'] = $i['mtime'] * 1000;
148
-		// only pick out the needed attributes
149
-		$entry['name'] = $i->getName();
150
-		$entry['permissions'] = $i['permissions'];
151
-		$entry['mimetype'] = $i['mimetype'];
152
-		$entry['size'] = $i['size'];
153
-		$entry['type'] = $i['type'];
154
-		$entry['etag'] = $i['etag'];
155
-		if (isset($i['tags'])) {
156
-			$entry['tags'] = $i['tags'];
157
-		}
158
-		if (isset($i['displayname_owner'])) {
159
-			$entry['shareOwner'] = $i['displayname_owner'];
160
-		}
161
-		if (isset($i['is_share_mount_point'])) {
162
-			$entry['isShareMountPoint'] = $i['is_share_mount_point'];
163
-		}
164
-		$mountType = null;
165
-		$mount = $i->getMountPoint();
166
-		$mountType = $mount->getMountType();
167
-		if ($mountType !== '') {
168
-			if ($i->getInternalPath() === '') {
169
-				$mountType .= '-root';
170
-			}
171
-			$entry['mountType'] = $mountType;
172
-		}
173
-		if (isset($i['extraData'])) {
174
-			$entry['extraData'] = $i['extraData'];
175
-		}
176
-		return $entry;
177
-	}
145
+        $entry['id'] = $i['fileid'];
146
+        $entry['parentId'] = $i['parent'];
147
+        $entry['mtime'] = $i['mtime'] * 1000;
148
+        // only pick out the needed attributes
149
+        $entry['name'] = $i->getName();
150
+        $entry['permissions'] = $i['permissions'];
151
+        $entry['mimetype'] = $i['mimetype'];
152
+        $entry['size'] = $i['size'];
153
+        $entry['type'] = $i['type'];
154
+        $entry['etag'] = $i['etag'];
155
+        if (isset($i['tags'])) {
156
+            $entry['tags'] = $i['tags'];
157
+        }
158
+        if (isset($i['displayname_owner'])) {
159
+            $entry['shareOwner'] = $i['displayname_owner'];
160
+        }
161
+        if (isset($i['is_share_mount_point'])) {
162
+            $entry['isShareMountPoint'] = $i['is_share_mount_point'];
163
+        }
164
+        $mountType = null;
165
+        $mount = $i->getMountPoint();
166
+        $mountType = $mount->getMountType();
167
+        if ($mountType !== '') {
168
+            if ($i->getInternalPath() === '') {
169
+                $mountType .= '-root';
170
+            }
171
+            $entry['mountType'] = $mountType;
172
+        }
173
+        if (isset($i['extraData'])) {
174
+            $entry['extraData'] = $i['extraData'];
175
+        }
176
+        return $entry;
177
+    }
178 178
 
179
-	/**
180
-	 * Format file info for JSON
181
-	 * @param \OCP\Files\FileInfo[] $fileInfos file infos
182
-	 * @return array
183
-	 */
184
-	public static function formatFileInfos($fileInfos) {
185
-		$files = [];
186
-		foreach ($fileInfos as $i) {
187
-			$files[] = self::formatFileInfo($i);
188
-		}
179
+    /**
180
+     * Format file info for JSON
181
+     * @param \OCP\Files\FileInfo[] $fileInfos file infos
182
+     * @return array
183
+     */
184
+    public static function formatFileInfos($fileInfos) {
185
+        $files = [];
186
+        foreach ($fileInfos as $i) {
187
+            $files[] = self::formatFileInfo($i);
188
+        }
189 189
 
190
-		return $files;
191
-	}
190
+        return $files;
191
+    }
192 192
 
193
-	/**
194
-	 * Retrieves the contents of the given directory and
195
-	 * returns it as a sorted array of FileInfo.
196
-	 *
197
-	 * @param string $dir path to the directory
198
-	 * @param string $sortAttribute attribute to sort on
199
-	 * @param bool $sortDescending true for descending sort, false otherwise
200
-	 * @param string $mimetypeFilter limit returned content to this mimetype or mimepart
201
-	 * @return \OCP\Files\FileInfo[] files
202
-	 */
203
-	public static function getFiles($dir, $sortAttribute = 'name', $sortDescending = false, $mimetypeFilter = '') {
204
-		$content = \OC\Files\Filesystem::getDirectoryContent($dir, $mimetypeFilter);
193
+    /**
194
+     * Retrieves the contents of the given directory and
195
+     * returns it as a sorted array of FileInfo.
196
+     *
197
+     * @param string $dir path to the directory
198
+     * @param string $sortAttribute attribute to sort on
199
+     * @param bool $sortDescending true for descending sort, false otherwise
200
+     * @param string $mimetypeFilter limit returned content to this mimetype or mimepart
201
+     * @return \OCP\Files\FileInfo[] files
202
+     */
203
+    public static function getFiles($dir, $sortAttribute = 'name', $sortDescending = false, $mimetypeFilter = '') {
204
+        $content = \OC\Files\Filesystem::getDirectoryContent($dir, $mimetypeFilter);
205 205
 
206
-		return self::sortFiles($content, $sortAttribute, $sortDescending);
207
-	}
206
+        return self::sortFiles($content, $sortAttribute, $sortDescending);
207
+    }
208 208
 
209
-	/**
210
-	 * Populate the result set with file tags
211
-	 *
212
-	 * @param array $fileList
213
-	 * @param string $fileIdentifier identifier attribute name for values in $fileList
214
-	 * @param ITagManager $tagManager
215
-	 * @return array file list populated with tags
216
-	 */
217
-	public static function populateTags(array $fileList, $fileIdentifier = 'fileid', ITagManager $tagManager) {
218
-		$ids = [];
219
-		foreach ($fileList as $fileData) {
220
-			$ids[] = $fileData[$fileIdentifier];
221
-		}
222
-		$tagger = $tagManager->load('files');
223
-		$tags = $tagger->getTagsForObjects($ids);
209
+    /**
210
+     * Populate the result set with file tags
211
+     *
212
+     * @param array $fileList
213
+     * @param string $fileIdentifier identifier attribute name for values in $fileList
214
+     * @param ITagManager $tagManager
215
+     * @return array file list populated with tags
216
+     */
217
+    public static function populateTags(array $fileList, $fileIdentifier = 'fileid', ITagManager $tagManager) {
218
+        $ids = [];
219
+        foreach ($fileList as $fileData) {
220
+            $ids[] = $fileData[$fileIdentifier];
221
+        }
222
+        $tagger = $tagManager->load('files');
223
+        $tags = $tagger->getTagsForObjects($ids);
224 224
 
225
-		if (!is_array($tags)) {
226
-			throw new \UnexpectedValueException('$tags must be an array');
227
-		}
225
+        if (!is_array($tags)) {
226
+            throw new \UnexpectedValueException('$tags must be an array');
227
+        }
228 228
 
229
-		// Set empty tag array
230
-		foreach ($fileList as $key => $fileData) {
231
-			$fileList[$key]['tags'] = [];
232
-		}
229
+        // Set empty tag array
230
+        foreach ($fileList as $key => $fileData) {
231
+            $fileList[$key]['tags'] = [];
232
+        }
233 233
 
234
-		if (!empty($tags)) {
235
-			foreach ($tags as $fileId => $fileTags) {
234
+        if (!empty($tags)) {
235
+            foreach ($tags as $fileId => $fileTags) {
236 236
 
237
-				foreach ($fileList as $key => $fileData) {
238
-					if ($fileId !== $fileData[$fileIdentifier]) {
239
-						continue;
240
-					}
237
+                foreach ($fileList as $key => $fileData) {
238
+                    if ($fileId !== $fileData[$fileIdentifier]) {
239
+                        continue;
240
+                    }
241 241
 
242
-					$fileList[$key]['tags'] = $fileTags;
243
-				}
244
-			}
245
-		}
242
+                    $fileList[$key]['tags'] = $fileTags;
243
+                }
244
+            }
245
+        }
246 246
 
247
-		return $fileList;
248
-	}
247
+        return $fileList;
248
+    }
249 249
 
250
-	/**
251
-	 * Sort the given file info array
252
-	 *
253
-	 * @param \OCP\Files\FileInfo[] $files files to sort
254
-	 * @param string $sortAttribute attribute to sort on
255
-	 * @param bool $sortDescending true for descending sort, false otherwise
256
-	 * @return \OCP\Files\FileInfo[] sorted files
257
-	 */
258
-	public static function sortFiles($files, $sortAttribute = 'name', $sortDescending = false) {
259
-		$sortFunc = 'compareFileNames';
260
-		if ($sortAttribute === 'mtime') {
261
-			$sortFunc = 'compareTimestamp';
262
-		} else if ($sortAttribute === 'size') {
263
-			$sortFunc = 'compareSize';
264
-		}
265
-		usort($files, [Helper::class, $sortFunc]);
266
-		if ($sortDescending) {
267
-			$files = array_reverse($files);
268
-		}
269
-		return $files;
270
-	}
250
+    /**
251
+     * Sort the given file info array
252
+     *
253
+     * @param \OCP\Files\FileInfo[] $files files to sort
254
+     * @param string $sortAttribute attribute to sort on
255
+     * @param bool $sortDescending true for descending sort, false otherwise
256
+     * @return \OCP\Files\FileInfo[] sorted files
257
+     */
258
+    public static function sortFiles($files, $sortAttribute = 'name', $sortDescending = false) {
259
+        $sortFunc = 'compareFileNames';
260
+        if ($sortAttribute === 'mtime') {
261
+            $sortFunc = 'compareTimestamp';
262
+        } else if ($sortAttribute === 'size') {
263
+            $sortFunc = 'compareSize';
264
+        }
265
+        usort($files, [Helper::class, $sortFunc]);
266
+        if ($sortDescending) {
267
+            $files = array_reverse($files);
268
+        }
269
+        return $files;
270
+    }
271 271
 }
Please login to merge, or discard this patch.
apps/files/lib/AppInfo/Application.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -48,63 +48,63 @@
 block discarded – undo
48 48
 
49 49
 class Application extends App {
50 50
 
51
-	public const APP_ID = 'files';
51
+    public const APP_ID = 'files';
52 52
 
53
-	public function __construct(array $urlParams=[]) {
54
-		parent::__construct(self::APP_ID, $urlParams);
55
-		$container = $this->getContainer();
56
-		$server = $container->getServer();
53
+    public function __construct(array $urlParams=[]) {
54
+        parent::__construct(self::APP_ID, $urlParams);
55
+        $container = $this->getContainer();
56
+        $server = $container->getServer();
57 57
 
58
-		/**
59
-		 * Controllers
60
-		 */
61
-		$container->registerService('APIController', function (IContainer $c) use ($server) {
62
-			return new ApiController(
63
-				$c->query('AppName'),
64
-				$c->query('Request'),
65
-				$server->getUserSession(),
66
-				$c->query('TagService'),
67
-				$server->getPreviewManager(),
68
-				$server->getShareManager(),
69
-				$server->getConfig(),
70
-				$server->getUserFolder()
71
-			);
72
-		});
58
+        /**
59
+         * Controllers
60
+         */
61
+        $container->registerService('APIController', function (IContainer $c) use ($server) {
62
+            return new ApiController(
63
+                $c->query('AppName'),
64
+                $c->query('Request'),
65
+                $server->getUserSession(),
66
+                $c->query('TagService'),
67
+                $server->getPreviewManager(),
68
+                $server->getShareManager(),
69
+                $server->getConfig(),
70
+                $server->getUserFolder()
71
+            );
72
+        });
73 73
 
74
-		/**
75
-		 * Services
76
-		 */
77
-		$container->registerService('TagService', function(IContainer $c) use ($server) {
78
-			$homeFolder = $c->query('ServerContainer')->getUserFolder();
79
-			return new TagService(
80
-				$c->query('ServerContainer')->getUserSession(),
81
-				$c->query('ServerContainer')->getActivityManager(),
82
-				$c->query('ServerContainer')->getTagManager()->load(self::APP_ID),
83
-				$homeFolder,
84
-				$server->getEventDispatcher()
85
-			);
86
-		});
74
+        /**
75
+         * Services
76
+         */
77
+        $container->registerService('TagService', function(IContainer $c) use ($server) {
78
+            $homeFolder = $c->query('ServerContainer')->getUserFolder();
79
+            return new TagService(
80
+                $c->query('ServerContainer')->getUserSession(),
81
+                $c->query('ServerContainer')->getActivityManager(),
82
+                $c->query('ServerContainer')->getTagManager()->load(self::APP_ID),
83
+                $homeFolder,
84
+                $server->getEventDispatcher()
85
+            );
86
+        });
87 87
 
88
-		/*
88
+        /*
89 89
 		 * Register capabilities
90 90
 		 */
91
-		$container->registerCapability(Capabilities::class);
91
+        $container->registerCapability(Capabilities::class);
92 92
 
93
-		/**
94
-		 * Register Collaboration ResourceProvider
95
-		 */
96
-		/** @var IProviderManager $providerManager */
97
-		$providerManager = $container->query(IProviderManager::class);
98
-		$providerManager->registerResourceProvider(ResourceProvider::class);
99
-		Listener::register($server->getEventDispatcher());
93
+        /**
94
+         * Register Collaboration ResourceProvider
95
+         */
96
+        /** @var IProviderManager $providerManager */
97
+        $providerManager = $container->query(IProviderManager::class);
98
+        $providerManager->registerResourceProvider(ResourceProvider::class);
99
+        Listener::register($server->getEventDispatcher());
100 100
 
101
-		/** @var IEventDispatcher $dispatcher */
102
-		$dispatcher = $container->query(IEventDispatcher::class);
103
-		$dispatcher->addServiceListener(LoadAdditionalScriptsEvent::class, LegacyLoadAdditionalScriptsAdapter::class);
104
-		$dispatcher->addServiceListener(LoadSidebar::class, LoadSidebarListener::class);
101
+        /** @var IEventDispatcher $dispatcher */
102
+        $dispatcher = $container->query(IEventDispatcher::class);
103
+        $dispatcher->addServiceListener(LoadAdditionalScriptsEvent::class, LegacyLoadAdditionalScriptsAdapter::class);
104
+        $dispatcher->addServiceListener(LoadSidebar::class, LoadSidebarListener::class);
105 105
 
106
-		/** @var \OCP\Notification\IManager $notifications */
107
-		$notifications = $container->query(\OCP\Notification\IManager::class);
108
-		$notifications->registerNotifierService(Notifier::class);
109
-	}
106
+        /** @var \OCP\Notification\IManager $notifications */
107
+        $notifications = $container->query(\OCP\Notification\IManager::class);
108
+        $notifications->registerNotifierService(Notifier::class);
109
+    }
110 110
 }
Please login to merge, or discard this patch.
apps/files/lib/Controller/ViewController.php 1 patch
Indentation   +289 added lines, -289 removed lines patch added patch discarded remove patch
@@ -62,293 +62,293 @@
 block discarded – undo
62 62
  * @package OCA\Files\Controller
63 63
  */
64 64
 class ViewController extends Controller {
65
-	/** @var string */
66
-	protected $appName;
67
-	/** @var IRequest */
68
-	protected $request;
69
-	/** @var IURLGenerator */
70
-	protected $urlGenerator;
71
-	/** @var IL10N */
72
-	protected $l10n;
73
-	/** @var IConfig */
74
-	protected $config;
75
-	/** @var IEventDispatcher */
76
-	protected $eventDispatcher;
77
-	/** @var IUserSession */
78
-	protected $userSession;
79
-	/** @var IAppManager */
80
-	protected $appManager;
81
-	/** @var IRootFolder */
82
-	protected $rootFolder;
83
-	/** @var Helper */
84
-	protected $activityHelper;
85
-
86
-	public function __construct(string $appName,
87
-		IRequest $request,
88
-		IURLGenerator $urlGenerator,
89
-		IL10N $l10n,
90
-		IConfig $config,
91
-		IEventDispatcher $eventDispatcher,
92
-		IUserSession $userSession,
93
-		IAppManager $appManager,
94
-		IRootFolder $rootFolder,
95
-		Helper $activityHelper
96
-	) {
97
-		parent::__construct($appName, $request);
98
-		$this->appName         = $appName;
99
-		$this->request         = $request;
100
-		$this->urlGenerator    = $urlGenerator;
101
-		$this->l10n            = $l10n;
102
-		$this->config          = $config;
103
-		$this->eventDispatcher = $eventDispatcher;
104
-		$this->userSession     = $userSession;
105
-		$this->appManager      = $appManager;
106
-		$this->rootFolder      = $rootFolder;
107
-		$this->activityHelper  = $activityHelper;
108
-	}
109
-
110
-	/**
111
-	 * @param string $appName
112
-	 * @param string $scriptName
113
-	 * @return string
114
-	 */
115
-	protected function renderScript($appName, $scriptName) {
116
-		$content    = '';
117
-		$appPath    = \OC_App::getAppPath($appName);
118
-		$scriptPath = $appPath . '/' . $scriptName;
119
-		if (file_exists($scriptPath)) {
120
-			// TODO: sanitize path / script name ?
121
-			ob_start();
122
-			include $scriptPath;
123
-			$content = ob_get_contents();
124
-			@ob_end_clean();
125
-		}
126
-
127
-		return $content;
128
-	}
129
-
130
-	/**
131
-	 * FIXME: Replace with non static code
132
-	 *
133
-	 * @return array
134
-	 * @throws \OCP\Files\NotFoundException
135
-	 */
136
-	protected function getStorageInfo() {
137
-		$dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
138
-
139
-		return \OC_Helper::getStorageInfo('/', $dirInfo);
140
-	}
141
-
142
-	/**
143
-	 * @NoCSRFRequired
144
-	 * @NoAdminRequired
145
-	 *
146
-	 * @param string $fileid
147
-	 * @return TemplateResponse|RedirectResponse
148
-	 * @throws NotFoundException
149
-	 */
150
-	public function showFile(string $fileid = null): Response {
151
-		// This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
152
-		try {
153
-			return $this->redirectToFile($fileid);
154
-		} catch (NotFoundException $e) {
155
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
156
-		}
157
-	}
158
-
159
-	/**
160
-	 * @NoCSRFRequired
161
-	 * @NoAdminRequired
162
-	 *
163
-	 * @param string $dir
164
-	 * @param string $view
165
-	 * @param string $fileid
166
-	 * @param bool $fileNotFound
167
-	 * @return TemplateResponse|RedirectResponse
168
-	 * @throws NotFoundException
169
-	 */
170
-	public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
171
-		if ($fileid !== null) {
172
-			try {
173
-				return $this->redirectToFile($fileid);
174
-			} catch (NotFoundException $e) {
175
-				return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
176
-			}
177
-		}
178
-
179
-		$nav = new \OCP\Template('files', 'appnavigation', '');
180
-
181
-		// Load the files we need
182
-		\OCP\Util::addStyle('files', 'merged');
183
-		\OCP\Util::addScript('files', 'merged-index');
184
-
185
-		// mostly for the home storage's free space
186
-		// FIXME: Make non static
187
-		$storageInfo = $this->getStorageInfo();
188
-
189
-		$user = $this->userSession->getUser()->getUID();
190
-
191
-		// Get all the user favorites to create a submenu
192
-		try {
193
-			$favElements = $this->activityHelper->getFavoriteFilePaths($this->userSession->getUser()->getUID());
194
-		} catch (\RuntimeException $e) {
195
-			$favElements['folders'] = [];
196
-		}
197
-
198
-		$collapseClasses = '';
199
-		if (count($favElements['folders']) > 0) {
200
-			$collapseClasses = 'collapsible';
201
-		}
202
-
203
-		$favoritesSublistArray = [];
204
-
205
-		$navBarPositionPosition = 6;
206
-		$currentCount           = 0;
207
-		foreach ($favElements['folders'] as $dir) {
208
-
209
-			$link         = $this->urlGenerator->linkToRoute('files.view.index', ['dir' => $dir, 'view' => 'files']);
210
-			$sortingValue = ++$currentCount;
211
-			$element      = [
212
-				'id'                 => str_replace('/', '-', $dir),
213
-				'view'               => 'files',
214
-				'href'               => $link,
215
-				'dir'                => $dir,
216
-				'order'              => $navBarPositionPosition,
217
-				'folderPosition'     => $sortingValue,
218
-				'name'               => basename($dir),
219
-				'icon'               => 'files',
220
-				'quickaccesselement' => 'true'
221
-			];
222
-
223
-			array_push($favoritesSublistArray, $element);
224
-			$navBarPositionPosition++;
225
-		}
226
-
227
-		$navItems = \OCA\Files\App::getNavigationManager()->getAll();
228
-
229
-		// add the favorites entry in menu
230
-		$navItems['favorites']['sublist'] = $favoritesSublistArray;
231
-		$navItems['favorites']['classes'] = $collapseClasses;
232
-
233
-		// parse every menu and add the expandedState user value
234
-		foreach ($navItems as $key => $item) {
235
-			if (isset($item['expandedState'])) {
236
-				$navItems[$key]['defaultExpandedState'] = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', $item['expandedState'], '0') === '1';
237
-			}
238
-		}
239
-
240
-		$nav->assign('navigationItems', $navItems);
241
-
242
-		$nav->assign('usage', \OC_Helper::humanFileSize($storageInfo['used']));
243
-		if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
244
-			$totalSpace = $this->l10n->t('Unlimited');
245
-		} else {
246
-			$totalSpace = \OC_Helper::humanFileSize($storageInfo['total']);
247
-		}
248
-		$nav->assign('total_space', $totalSpace);
249
-		$nav->assign('quota', $storageInfo['quota']);
250
-		$nav->assign('usage_relative', $storageInfo['relative']);
251
-
252
-		$nav->assign('webdav_url', \OCP\Util::linkToRemote('dav/files/' . $user));
253
-
254
-		$contentItems = [];
255
-
256
-		// render the container content for every navigation item
257
-		foreach ($navItems as $item) {
258
-			$content = '';
259
-			if (isset($item['script'])) {
260
-				$content = $this->renderScript($item['appname'], $item['script']);
261
-			}
262
-			// parse submenus
263
-			if (isset($item['sublist'])) {
264
-				foreach ($item['sublist'] as $subitem) {
265
-					$subcontent = '';
266
-					if (isset($subitem['script'])) {
267
-						$subcontent = $this->renderScript($subitem['appname'], $subitem['script']);
268
-					}
269
-					$contentItems[$subitem['id']] = [
270
-						'id'      => $subitem['id'],
271
-						'content' => $subcontent
272
-					];
273
-				}
274
-			}
275
-			$contentItems[$item['id']] = [
276
-				'id'      => $item['id'],
277
-				'content' => $content
278
-			];
279
-		}
280
-
281
-		$event = new LoadAdditionalScriptsEvent();
282
-		$this->eventDispatcher->dispatch(LoadAdditionalScriptsEvent::class, $event);
283
-
284
-		$this->eventDispatcher->dispatch(LoadSidebar::class, new LoadSidebar());
285
-		// Load Viewer scripts
286
-		if (class_exists(LoadViewer::class)) {
287
-			$this->eventDispatcher->dispatchTyped(new LoadViewer());
288
-		}
289
-
290
-		$params                                = [];
291
-		$params['usedSpacePercent']            = (int) $storageInfo['relative'];
292
-		$params['owner']                       = $storageInfo['owner'] ?? '';
293
-		$params['ownerDisplayName']            = $storageInfo['ownerDisplayName'] ?? '';
294
-		$params['isPublic']                    = false;
295
-		$params['allowShareWithLink']          = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes');
296
-		$params['defaultFileSorting']          = $this->config->getUserValue($user, 'files', 'file_sorting', 'name');
297
-		$params['defaultFileSortingDirection'] = $this->config->getUserValue($user, 'files', 'file_sorting_direction', 'asc');
298
-		$params['showgridview']				   = $this->config->getUserValue($user, 'files', 'show_grid', false);
299
-		$params['isIE']						   = \OCP\Util::isIE();
300
-		$showHidden                            = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', false);
301
-		$params['showHiddenFiles']             = $showHidden ? 1 : 0;
302
-		$params['fileNotFound']                = $fileNotFound ? 1 : 0;
303
-		$params['appNavigation']               = $nav;
304
-		$params['appContents']                 = $contentItems;
305
-		$params['hiddenFields']                = $event->getHiddenFields();
306
-
307
-		$response = new TemplateResponse(
308
-			$this->appName,
309
-			'index',
310
-			$params
311
-		);
312
-		$policy = new ContentSecurityPolicy();
313
-		$policy->addAllowedFrameDomain('\'self\'');
314
-		$response->setContentSecurityPolicy($policy);
315
-
316
-		return $response;
317
-	}
318
-
319
-	/**
320
-	 * Redirects to the file list and highlight the given file id
321
-	 *
322
-	 * @param string $fileId file id to show
323
-	 * @return RedirectResponse redirect response or not found response
324
-	 * @throws \OCP\Files\NotFoundException
325
-	 */
326
-	private function redirectToFile($fileId) {
327
-		$uid        = $this->userSession->getUser()->getUID();
328
-		$baseFolder = $this->rootFolder->getUserFolder($uid);
329
-		$files      = $baseFolder->getById($fileId);
330
-		$params     = [];
331
-
332
-		if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
333
-			$baseFolder     = $this->rootFolder->get($uid . '/files_trashbin/files/');
334
-			$files          = $baseFolder->getById($fileId);
335
-			$params['view'] = 'trashbin';
336
-		}
337
-
338
-		if (!empty($files)) {
339
-			$file = current($files);
340
-			if ($file instanceof Folder) {
341
-				// set the full path to enter the folder
342
-				$params['dir'] = $baseFolder->getRelativePath($file->getPath());
343
-			} else {
344
-				// set parent path as dir
345
-				$params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
346
-				// and scroll to the entry
347
-				$params['scrollto'] = $file->getName();
348
-			}
349
-
350
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
351
-		}
352
-		throw new \OCP\Files\NotFoundException();
353
-	}
65
+    /** @var string */
66
+    protected $appName;
67
+    /** @var IRequest */
68
+    protected $request;
69
+    /** @var IURLGenerator */
70
+    protected $urlGenerator;
71
+    /** @var IL10N */
72
+    protected $l10n;
73
+    /** @var IConfig */
74
+    protected $config;
75
+    /** @var IEventDispatcher */
76
+    protected $eventDispatcher;
77
+    /** @var IUserSession */
78
+    protected $userSession;
79
+    /** @var IAppManager */
80
+    protected $appManager;
81
+    /** @var IRootFolder */
82
+    protected $rootFolder;
83
+    /** @var Helper */
84
+    protected $activityHelper;
85
+
86
+    public function __construct(string $appName,
87
+        IRequest $request,
88
+        IURLGenerator $urlGenerator,
89
+        IL10N $l10n,
90
+        IConfig $config,
91
+        IEventDispatcher $eventDispatcher,
92
+        IUserSession $userSession,
93
+        IAppManager $appManager,
94
+        IRootFolder $rootFolder,
95
+        Helper $activityHelper
96
+    ) {
97
+        parent::__construct($appName, $request);
98
+        $this->appName         = $appName;
99
+        $this->request         = $request;
100
+        $this->urlGenerator    = $urlGenerator;
101
+        $this->l10n            = $l10n;
102
+        $this->config          = $config;
103
+        $this->eventDispatcher = $eventDispatcher;
104
+        $this->userSession     = $userSession;
105
+        $this->appManager      = $appManager;
106
+        $this->rootFolder      = $rootFolder;
107
+        $this->activityHelper  = $activityHelper;
108
+    }
109
+
110
+    /**
111
+     * @param string $appName
112
+     * @param string $scriptName
113
+     * @return string
114
+     */
115
+    protected function renderScript($appName, $scriptName) {
116
+        $content    = '';
117
+        $appPath    = \OC_App::getAppPath($appName);
118
+        $scriptPath = $appPath . '/' . $scriptName;
119
+        if (file_exists($scriptPath)) {
120
+            // TODO: sanitize path / script name ?
121
+            ob_start();
122
+            include $scriptPath;
123
+            $content = ob_get_contents();
124
+            @ob_end_clean();
125
+        }
126
+
127
+        return $content;
128
+    }
129
+
130
+    /**
131
+     * FIXME: Replace with non static code
132
+     *
133
+     * @return array
134
+     * @throws \OCP\Files\NotFoundException
135
+     */
136
+    protected function getStorageInfo() {
137
+        $dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
138
+
139
+        return \OC_Helper::getStorageInfo('/', $dirInfo);
140
+    }
141
+
142
+    /**
143
+     * @NoCSRFRequired
144
+     * @NoAdminRequired
145
+     *
146
+     * @param string $fileid
147
+     * @return TemplateResponse|RedirectResponse
148
+     * @throws NotFoundException
149
+     */
150
+    public function showFile(string $fileid = null): Response {
151
+        // This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
152
+        try {
153
+            return $this->redirectToFile($fileid);
154
+        } catch (NotFoundException $e) {
155
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
156
+        }
157
+    }
158
+
159
+    /**
160
+     * @NoCSRFRequired
161
+     * @NoAdminRequired
162
+     *
163
+     * @param string $dir
164
+     * @param string $view
165
+     * @param string $fileid
166
+     * @param bool $fileNotFound
167
+     * @return TemplateResponse|RedirectResponse
168
+     * @throws NotFoundException
169
+     */
170
+    public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
171
+        if ($fileid !== null) {
172
+            try {
173
+                return $this->redirectToFile($fileid);
174
+            } catch (NotFoundException $e) {
175
+                return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
176
+            }
177
+        }
178
+
179
+        $nav = new \OCP\Template('files', 'appnavigation', '');
180
+
181
+        // Load the files we need
182
+        \OCP\Util::addStyle('files', 'merged');
183
+        \OCP\Util::addScript('files', 'merged-index');
184
+
185
+        // mostly for the home storage's free space
186
+        // FIXME: Make non static
187
+        $storageInfo = $this->getStorageInfo();
188
+
189
+        $user = $this->userSession->getUser()->getUID();
190
+
191
+        // Get all the user favorites to create a submenu
192
+        try {
193
+            $favElements = $this->activityHelper->getFavoriteFilePaths($this->userSession->getUser()->getUID());
194
+        } catch (\RuntimeException $e) {
195
+            $favElements['folders'] = [];
196
+        }
197
+
198
+        $collapseClasses = '';
199
+        if (count($favElements['folders']) > 0) {
200
+            $collapseClasses = 'collapsible';
201
+        }
202
+
203
+        $favoritesSublistArray = [];
204
+
205
+        $navBarPositionPosition = 6;
206
+        $currentCount           = 0;
207
+        foreach ($favElements['folders'] as $dir) {
208
+
209
+            $link         = $this->urlGenerator->linkToRoute('files.view.index', ['dir' => $dir, 'view' => 'files']);
210
+            $sortingValue = ++$currentCount;
211
+            $element      = [
212
+                'id'                 => str_replace('/', '-', $dir),
213
+                'view'               => 'files',
214
+                'href'               => $link,
215
+                'dir'                => $dir,
216
+                'order'              => $navBarPositionPosition,
217
+                'folderPosition'     => $sortingValue,
218
+                'name'               => basename($dir),
219
+                'icon'               => 'files',
220
+                'quickaccesselement' => 'true'
221
+            ];
222
+
223
+            array_push($favoritesSublistArray, $element);
224
+            $navBarPositionPosition++;
225
+        }
226
+
227
+        $navItems = \OCA\Files\App::getNavigationManager()->getAll();
228
+
229
+        // add the favorites entry in menu
230
+        $navItems['favorites']['sublist'] = $favoritesSublistArray;
231
+        $navItems['favorites']['classes'] = $collapseClasses;
232
+
233
+        // parse every menu and add the expandedState user value
234
+        foreach ($navItems as $key => $item) {
235
+            if (isset($item['expandedState'])) {
236
+                $navItems[$key]['defaultExpandedState'] = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', $item['expandedState'], '0') === '1';
237
+            }
238
+        }
239
+
240
+        $nav->assign('navigationItems', $navItems);
241
+
242
+        $nav->assign('usage', \OC_Helper::humanFileSize($storageInfo['used']));
243
+        if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
244
+            $totalSpace = $this->l10n->t('Unlimited');
245
+        } else {
246
+            $totalSpace = \OC_Helper::humanFileSize($storageInfo['total']);
247
+        }
248
+        $nav->assign('total_space', $totalSpace);
249
+        $nav->assign('quota', $storageInfo['quota']);
250
+        $nav->assign('usage_relative', $storageInfo['relative']);
251
+
252
+        $nav->assign('webdav_url', \OCP\Util::linkToRemote('dav/files/' . $user));
253
+
254
+        $contentItems = [];
255
+
256
+        // render the container content for every navigation item
257
+        foreach ($navItems as $item) {
258
+            $content = '';
259
+            if (isset($item['script'])) {
260
+                $content = $this->renderScript($item['appname'], $item['script']);
261
+            }
262
+            // parse submenus
263
+            if (isset($item['sublist'])) {
264
+                foreach ($item['sublist'] as $subitem) {
265
+                    $subcontent = '';
266
+                    if (isset($subitem['script'])) {
267
+                        $subcontent = $this->renderScript($subitem['appname'], $subitem['script']);
268
+                    }
269
+                    $contentItems[$subitem['id']] = [
270
+                        'id'      => $subitem['id'],
271
+                        'content' => $subcontent
272
+                    ];
273
+                }
274
+            }
275
+            $contentItems[$item['id']] = [
276
+                'id'      => $item['id'],
277
+                'content' => $content
278
+            ];
279
+        }
280
+
281
+        $event = new LoadAdditionalScriptsEvent();
282
+        $this->eventDispatcher->dispatch(LoadAdditionalScriptsEvent::class, $event);
283
+
284
+        $this->eventDispatcher->dispatch(LoadSidebar::class, new LoadSidebar());
285
+        // Load Viewer scripts
286
+        if (class_exists(LoadViewer::class)) {
287
+            $this->eventDispatcher->dispatchTyped(new LoadViewer());
288
+        }
289
+
290
+        $params                                = [];
291
+        $params['usedSpacePercent']            = (int) $storageInfo['relative'];
292
+        $params['owner']                       = $storageInfo['owner'] ?? '';
293
+        $params['ownerDisplayName']            = $storageInfo['ownerDisplayName'] ?? '';
294
+        $params['isPublic']                    = false;
295
+        $params['allowShareWithLink']          = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes');
296
+        $params['defaultFileSorting']          = $this->config->getUserValue($user, 'files', 'file_sorting', 'name');
297
+        $params['defaultFileSortingDirection'] = $this->config->getUserValue($user, 'files', 'file_sorting_direction', 'asc');
298
+        $params['showgridview']				   = $this->config->getUserValue($user, 'files', 'show_grid', false);
299
+        $params['isIE']						   = \OCP\Util::isIE();
300
+        $showHidden                            = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', false);
301
+        $params['showHiddenFiles']             = $showHidden ? 1 : 0;
302
+        $params['fileNotFound']                = $fileNotFound ? 1 : 0;
303
+        $params['appNavigation']               = $nav;
304
+        $params['appContents']                 = $contentItems;
305
+        $params['hiddenFields']                = $event->getHiddenFields();
306
+
307
+        $response = new TemplateResponse(
308
+            $this->appName,
309
+            'index',
310
+            $params
311
+        );
312
+        $policy = new ContentSecurityPolicy();
313
+        $policy->addAllowedFrameDomain('\'self\'');
314
+        $response->setContentSecurityPolicy($policy);
315
+
316
+        return $response;
317
+    }
318
+
319
+    /**
320
+     * Redirects to the file list and highlight the given file id
321
+     *
322
+     * @param string $fileId file id to show
323
+     * @return RedirectResponse redirect response or not found response
324
+     * @throws \OCP\Files\NotFoundException
325
+     */
326
+    private function redirectToFile($fileId) {
327
+        $uid        = $this->userSession->getUser()->getUID();
328
+        $baseFolder = $this->rootFolder->getUserFolder($uid);
329
+        $files      = $baseFolder->getById($fileId);
330
+        $params     = [];
331
+
332
+        if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
333
+            $baseFolder     = $this->rootFolder->get($uid . '/files_trashbin/files/');
334
+            $files          = $baseFolder->getById($fileId);
335
+            $params['view'] = 'trashbin';
336
+        }
337
+
338
+        if (!empty($files)) {
339
+            $file = current($files);
340
+            if ($file instanceof Folder) {
341
+                // set the full path to enter the folder
342
+                $params['dir'] = $baseFolder->getRelativePath($file->getPath());
343
+            } else {
344
+                // set parent path as dir
345
+                $params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
346
+                // and scroll to the entry
347
+                $params['scrollto'] = $file->getName();
348
+            }
349
+
350
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
351
+        }
352
+        throw new \OCP\Files\NotFoundException();
353
+    }
354 354
 }
Please login to merge, or discard this patch.
apps/files/lib/Service/TagService.php 1 patch
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -38,110 +38,110 @@
 block discarded – undo
38 38
  */
39 39
 class TagService {
40 40
 
41
-	/** @var IUserSession */
42
-	private $userSession;
43
-	/** @var IManager */
44
-	private $activityManager;
45
-	/** @var ITags */
46
-	private $tagger;
47
-	/** @var Folder */
48
-	private $homeFolder;
49
-	/** @var EventDispatcherInterface */
50
-	private $dispatcher;
41
+    /** @var IUserSession */
42
+    private $userSession;
43
+    /** @var IManager */
44
+    private $activityManager;
45
+    /** @var ITags */
46
+    private $tagger;
47
+    /** @var Folder */
48
+    private $homeFolder;
49
+    /** @var EventDispatcherInterface */
50
+    private $dispatcher;
51 51
 
52
-	/**
53
-	 * @param IUserSession $userSession
54
-	 * @param IManager $activityManager
55
-	 * @param ITags $tagger
56
-	 * @param Folder $homeFolder
57
-	 * @param EventDispatcherInterface $dispatcher
58
-	 */
59
-	public function __construct(
60
-		IUserSession $userSession,
61
-		IManager $activityManager,
62
-		ITags $tagger,
63
-		Folder $homeFolder,
64
-		EventDispatcherInterface $dispatcher
65
-	) {
66
-		$this->userSession = $userSession;
67
-		$this->activityManager = $activityManager;
68
-		$this->tagger = $tagger;
69
-		$this->homeFolder = $homeFolder;
70
-		$this->dispatcher = $dispatcher;
71
-	}
52
+    /**
53
+     * @param IUserSession $userSession
54
+     * @param IManager $activityManager
55
+     * @param ITags $tagger
56
+     * @param Folder $homeFolder
57
+     * @param EventDispatcherInterface $dispatcher
58
+     */
59
+    public function __construct(
60
+        IUserSession $userSession,
61
+        IManager $activityManager,
62
+        ITags $tagger,
63
+        Folder $homeFolder,
64
+        EventDispatcherInterface $dispatcher
65
+    ) {
66
+        $this->userSession = $userSession;
67
+        $this->activityManager = $activityManager;
68
+        $this->tagger = $tagger;
69
+        $this->homeFolder = $homeFolder;
70
+        $this->dispatcher = $dispatcher;
71
+    }
72 72
 
73
-	/**
74
-	 * Updates the tags of the specified file path.
75
-	 * The passed tags are absolute, which means they will
76
-	 * replace the actual tag selection.
77
-	 *
78
-	 * @param string $path path
79
-	 * @param array  $tags array of tags
80
-	 * @return array list of tags
81
-	 * @throws \OCP\Files\NotFoundException if the file does not exist
82
-	 */
83
-	public function updateFileTags($path, $tags) {
84
-		$fileId = $this->homeFolder->get($path)->getId();
73
+    /**
74
+     * Updates the tags of the specified file path.
75
+     * The passed tags are absolute, which means they will
76
+     * replace the actual tag selection.
77
+     *
78
+     * @param string $path path
79
+     * @param array  $tags array of tags
80
+     * @return array list of tags
81
+     * @throws \OCP\Files\NotFoundException if the file does not exist
82
+     */
83
+    public function updateFileTags($path, $tags) {
84
+        $fileId = $this->homeFolder->get($path)->getId();
85 85
 
86
-		$currentTags = $this->tagger->getTagsForObjects([$fileId]);
86
+        $currentTags = $this->tagger->getTagsForObjects([$fileId]);
87 87
 
88
-		if (!empty($currentTags)) {
89
-			$currentTags = current($currentTags);
90
-		}
88
+        if (!empty($currentTags)) {
89
+            $currentTags = current($currentTags);
90
+        }
91 91
 
92
-		$newTags = array_diff($tags, $currentTags);
93
-		foreach ($newTags as $tag) {
94
-			if ($tag === ITags::TAG_FAVORITE) {
95
-				$this->addActivity(true, $fileId, $path);
96
-			}
97
-			$this->tagger->tagAs($fileId, $tag);
98
-		}
99
-		$deletedTags = array_diff($currentTags, $tags);
100
-		foreach ($deletedTags as $tag) {
101
-			if ($tag === ITags::TAG_FAVORITE) {
102
-				$this->addActivity(false, $fileId, $path);
103
-			}
104
-			$this->tagger->unTag($fileId, $tag);
105
-		}
92
+        $newTags = array_diff($tags, $currentTags);
93
+        foreach ($newTags as $tag) {
94
+            if ($tag === ITags::TAG_FAVORITE) {
95
+                $this->addActivity(true, $fileId, $path);
96
+            }
97
+            $this->tagger->tagAs($fileId, $tag);
98
+        }
99
+        $deletedTags = array_diff($currentTags, $tags);
100
+        foreach ($deletedTags as $tag) {
101
+            if ($tag === ITags::TAG_FAVORITE) {
102
+                $this->addActivity(false, $fileId, $path);
103
+            }
104
+            $this->tagger->unTag($fileId, $tag);
105
+        }
106 106
 
107
-		// TODO: re-read from tagger to make sure the
108
-		// list is up to date, in case of concurrent changes ?
109
-		return $tags;
110
-	}
107
+        // TODO: re-read from tagger to make sure the
108
+        // list is up to date, in case of concurrent changes ?
109
+        return $tags;
110
+    }
111 111
 
112
-	/**
113
-	 * @param bool $addToFavorite
114
-	 * @param int $fileId
115
-	 * @param string $path
116
-	 */
117
-	protected function addActivity($addToFavorite, $fileId, $path) {
118
-		$user = $this->userSession->getUser();
119
-		if (!$user instanceof IUser) {
120
-			return;
121
-		}
112
+    /**
113
+     * @param bool $addToFavorite
114
+     * @param int $fileId
115
+     * @param string $path
116
+     */
117
+    protected function addActivity($addToFavorite, $fileId, $path) {
118
+        $user = $this->userSession->getUser();
119
+        if (!$user instanceof IUser) {
120
+            return;
121
+        }
122 122
 
123
-		$eventName = $addToFavorite ? 'addFavorite' : 'removeFavorite';
124
-		$this->dispatcher->dispatch(self::class . '::' . $eventName, new GenericEvent(null, [
125
-			'userId' => $user->getUID(),
126
-			'fileId' => $fileId,
127
-			'path' => $path,
128
-		]));
123
+        $eventName = $addToFavorite ? 'addFavorite' : 'removeFavorite';
124
+        $this->dispatcher->dispatch(self::class . '::' . $eventName, new GenericEvent(null, [
125
+            'userId' => $user->getUID(),
126
+            'fileId' => $fileId,
127
+            'path' => $path,
128
+        ]));
129 129
 
130
-		$event = $this->activityManager->generateEvent();
131
-		try {
132
-			$event->setApp('files')
133
-				->setObject('files', $fileId, $path)
134
-				->setType('favorite')
135
-				->setAuthor($user->getUID())
136
-				->setAffectedUser($user->getUID())
137
-				->setTimestamp(time())
138
-				->setSubject(
139
-					$addToFavorite ? FavoriteProvider::SUBJECT_ADDED : FavoriteProvider::SUBJECT_REMOVED,
140
-					['id' => $fileId, 'path' => $path]
141
-				);
142
-			$this->activityManager->publish($event);
143
-		} catch (\InvalidArgumentException $e) {
144
-		} catch (\BadMethodCallException $e) {
145
-		}
146
-	}
130
+        $event = $this->activityManager->generateEvent();
131
+        try {
132
+            $event->setApp('files')
133
+                ->setObject('files', $fileId, $path)
134
+                ->setType('favorite')
135
+                ->setAuthor($user->getUID())
136
+                ->setAffectedUser($user->getUID())
137
+                ->setTimestamp(time())
138
+                ->setSubject(
139
+                    $addToFavorite ? FavoriteProvider::SUBJECT_ADDED : FavoriteProvider::SUBJECT_REMOVED,
140
+                    ['id' => $fileId, 'path' => $path]
141
+                );
142
+            $this->activityManager->publish($event);
143
+        } catch (\InvalidArgumentException $e) {
144
+        } catch (\BadMethodCallException $e) {
145
+        }
146
+    }
147 147
 }
Please login to merge, or discard this patch.
apps/testing/lib/AppInfo/Application.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -27,18 +27,18 @@
 block discarded – undo
27 27
 use OCP\AppFramework\App;
28 28
 
29 29
 class Application extends App {
30
-	public function __construct (array $urlParams = []) {
31
-		$appName = 'testing';
32
-		parent::__construct($appName, $urlParams);
30
+    public function __construct (array $urlParams = []) {
31
+        $appName = 'testing';
32
+        parent::__construct($appName, $urlParams);
33 33
 
34
-		$c = $this->getContainer();
35
-		$config = $c->getServer()->getConfig();
36
-		if ($config->getAppValue($appName, 'enable_alt_user_backend', 'no') === 'yes') {
37
-			$userManager = $c->getServer()->getUserManager();
34
+        $c = $this->getContainer();
35
+        $config = $c->getServer()->getConfig();
36
+        if ($config->getAppValue($appName, 'enable_alt_user_backend', 'no') === 'yes') {
37
+            $userManager = $c->getServer()->getUserManager();
38 38
 
39
-			// replace all user backends with this one
40
-			$userManager->clearBackends();
41
-			$userManager->registerBackend($c->query(AlternativeHomeUserBackend::class));
42
-		}
43
-	}
39
+            // replace all user backends with this one
40
+            $userManager->clearBackends();
41
+            $userManager->registerBackend($c->query(AlternativeHomeUserBackend::class));
42
+        }
43
+    }
44 44
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/AppInfo/Application.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -33,19 +33,19 @@
 block discarded – undo
33 33
 
34 34
 class Application extends App {
35 35
 
36
-	public function __construct(array $urlParams = []) {
37
-		parent::__construct('sharebymail', $urlParams);
36
+    public function __construct(array $urlParams = []) {
37
+        parent::__construct('sharebymail', $urlParams);
38 38
 
39
-		$settingsManager = \OC::$server->query(Settings\SettingsManager::class);
40
-		$settings = new Settings($settingsManager);
39
+        $settingsManager = \OC::$server->query(Settings\SettingsManager::class);
40
+        $settings = new Settings($settingsManager);
41 41
 
42
-		/** register capabilities */
43
-		$container = $this->getContainer();
44
-		$container->registerCapability(Capabilities::class);
42
+        /** register capabilities */
43
+        $container = $this->getContainer();
44
+        $container->registerCapability(Capabilities::class);
45 45
 
46
-		/** register hooks */
47
-		Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareProvider');
48
-		Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareByMailSettings');
49
-	}
46
+        /** register hooks */
47
+        Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareProvider');
48
+        Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareByMailSettings');
49
+    }
50 50
 
51 51
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/ShareByMailProvider.php 1 patch
Indentation   +1135 added lines, -1135 removed lines patch added patch discarded remove patch
@@ -68,1152 +68,1152 @@
 block discarded – undo
68 68
  */
69 69
 class ShareByMailProvider implements IShareProvider {
70 70
 
71
-	/** @var  IDBConnection */
72
-	private $dbConnection;
73
-
74
-	/** @var ILogger */
75
-	private $logger;
76
-
77
-	/** @var ISecureRandom */
78
-	private $secureRandom;
79
-
80
-	/** @var IUserManager */
81
-	private $userManager;
82
-
83
-	/** @var IRootFolder */
84
-	private $rootFolder;
85
-
86
-	/** @var IL10N */
87
-	private $l;
88
-
89
-	/** @var IMailer */
90
-	private $mailer;
91
-
92
-	/** @var IURLGenerator */
93
-	private $urlGenerator;
94
-
95
-	/** @var IManager  */
96
-	private $activityManager;
97
-
98
-	/** @var SettingsManager */
99
-	private $settingsManager;
100
-
101
-	/** @var Defaults */
102
-	private $defaults;
103
-
104
-	/** @var IHasher */
105
-	private $hasher;
106
-
107
-	/** @var  CapabilitiesManager */
108
-	private $capabilitiesManager;
109
-
110
-	/**
111
-	 * Return the identifier of this provider.
112
-	 *
113
-	 * @return string Containing only [a-zA-Z0-9]
114
-	 */
115
-	public function identifier() {
116
-		return 'ocMailShare';
117
-	}
118
-
119
-	/**
120
-	 * DefaultShareProvider constructor.
121
-	 *
122
-	 * @param IDBConnection $connection
123
-	 * @param ISecureRandom $secureRandom
124
-	 * @param IUserManager $userManager
125
-	 * @param IRootFolder $rootFolder
126
-	 * @param IL10N $l
127
-	 * @param ILogger $logger
128
-	 * @param IMailer $mailer
129
-	 * @param IURLGenerator $urlGenerator
130
-	 * @param IManager $activityManager
131
-	 * @param SettingsManager $settingsManager
132
-	 * @param Defaults $defaults
133
-	 * @param IHasher $hasher
134
-	 * @param CapabilitiesManager $capabilitiesManager
135
-	 */
136
-	public function __construct(
137
-		IDBConnection $connection,
138
-		ISecureRandom $secureRandom,
139
-		IUserManager $userManager,
140
-		IRootFolder $rootFolder,
141
-		IL10N $l,
142
-		ILogger $logger,
143
-		IMailer $mailer,
144
-		IURLGenerator $urlGenerator,
145
-		IManager $activityManager,
146
-		SettingsManager $settingsManager,
147
-		Defaults $defaults,
148
-		IHasher $hasher,
149
-		CapabilitiesManager $capabilitiesManager
150
-	) {
151
-		$this->dbConnection = $connection;
152
-		$this->secureRandom = $secureRandom;
153
-		$this->userManager = $userManager;
154
-		$this->rootFolder = $rootFolder;
155
-		$this->l = $l;
156
-		$this->logger = $logger;
157
-		$this->mailer = $mailer;
158
-		$this->urlGenerator = $urlGenerator;
159
-		$this->activityManager = $activityManager;
160
-		$this->settingsManager = $settingsManager;
161
-		$this->defaults = $defaults;
162
-		$this->hasher = $hasher;
163
-		$this->capabilitiesManager = $capabilitiesManager;
164
-	}
165
-
166
-	/**
167
-	 * Share a path
168
-	 *
169
-	 * @param IShare $share
170
-	 * @return IShare The share object
171
-	 * @throws ShareNotFound
172
-	 * @throws \Exception
173
-	 */
174
-	public function create(IShare $share) {
175
-
176
-		$shareWith = $share->getSharedWith();
177
-		/*
71
+    /** @var  IDBConnection */
72
+    private $dbConnection;
73
+
74
+    /** @var ILogger */
75
+    private $logger;
76
+
77
+    /** @var ISecureRandom */
78
+    private $secureRandom;
79
+
80
+    /** @var IUserManager */
81
+    private $userManager;
82
+
83
+    /** @var IRootFolder */
84
+    private $rootFolder;
85
+
86
+    /** @var IL10N */
87
+    private $l;
88
+
89
+    /** @var IMailer */
90
+    private $mailer;
91
+
92
+    /** @var IURLGenerator */
93
+    private $urlGenerator;
94
+
95
+    /** @var IManager  */
96
+    private $activityManager;
97
+
98
+    /** @var SettingsManager */
99
+    private $settingsManager;
100
+
101
+    /** @var Defaults */
102
+    private $defaults;
103
+
104
+    /** @var IHasher */
105
+    private $hasher;
106
+
107
+    /** @var  CapabilitiesManager */
108
+    private $capabilitiesManager;
109
+
110
+    /**
111
+     * Return the identifier of this provider.
112
+     *
113
+     * @return string Containing only [a-zA-Z0-9]
114
+     */
115
+    public function identifier() {
116
+        return 'ocMailShare';
117
+    }
118
+
119
+    /**
120
+     * DefaultShareProvider constructor.
121
+     *
122
+     * @param IDBConnection $connection
123
+     * @param ISecureRandom $secureRandom
124
+     * @param IUserManager $userManager
125
+     * @param IRootFolder $rootFolder
126
+     * @param IL10N $l
127
+     * @param ILogger $logger
128
+     * @param IMailer $mailer
129
+     * @param IURLGenerator $urlGenerator
130
+     * @param IManager $activityManager
131
+     * @param SettingsManager $settingsManager
132
+     * @param Defaults $defaults
133
+     * @param IHasher $hasher
134
+     * @param CapabilitiesManager $capabilitiesManager
135
+     */
136
+    public function __construct(
137
+        IDBConnection $connection,
138
+        ISecureRandom $secureRandom,
139
+        IUserManager $userManager,
140
+        IRootFolder $rootFolder,
141
+        IL10N $l,
142
+        ILogger $logger,
143
+        IMailer $mailer,
144
+        IURLGenerator $urlGenerator,
145
+        IManager $activityManager,
146
+        SettingsManager $settingsManager,
147
+        Defaults $defaults,
148
+        IHasher $hasher,
149
+        CapabilitiesManager $capabilitiesManager
150
+    ) {
151
+        $this->dbConnection = $connection;
152
+        $this->secureRandom = $secureRandom;
153
+        $this->userManager = $userManager;
154
+        $this->rootFolder = $rootFolder;
155
+        $this->l = $l;
156
+        $this->logger = $logger;
157
+        $this->mailer = $mailer;
158
+        $this->urlGenerator = $urlGenerator;
159
+        $this->activityManager = $activityManager;
160
+        $this->settingsManager = $settingsManager;
161
+        $this->defaults = $defaults;
162
+        $this->hasher = $hasher;
163
+        $this->capabilitiesManager = $capabilitiesManager;
164
+    }
165
+
166
+    /**
167
+     * Share a path
168
+     *
169
+     * @param IShare $share
170
+     * @return IShare The share object
171
+     * @throws ShareNotFound
172
+     * @throws \Exception
173
+     */
174
+    public function create(IShare $share) {
175
+
176
+        $shareWith = $share->getSharedWith();
177
+        /*
178 178
 		 * Check if file is not already shared with the remote user
179 179
 		 */
180
-		$alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
181
-		if (!empty($alreadyShared)) {
182
-			$message = 'Sharing %1$s failed, this item is already shared with %2$s';
183
-			$message_t = $this->l->t('Sharing %1$s failed, this item is already shared with %2$s', [$share->getNode()->getName(), $shareWith]);
184
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
185
-			throw new \Exception($message_t);
186
-		}
187
-
188
-		// if the admin enforces a password for all mail shares we create a
189
-		// random password and send it to the recipient
190
-		$password = '';
191
-		$passwordEnforced = $this->settingsManager->enforcePasswordProtection();
192
-		if ($passwordEnforced) {
193
-			$password = $this->autoGeneratePassword($share);
194
-		}
195
-
196
-		$shareId = $this->createMailShare($share);
197
-		$send = $this->sendPassword($share, $password);
198
-		if ($passwordEnforced && $send === false) {
199
-			$this->sendPasswordToOwner($share, $password);
200
-		}
201
-
202
-		$this->createShareActivity($share);
203
-		$data = $this->getRawShare($shareId);
204
-
205
-		return $this->createShareObject($data);
206
-
207
-	}
208
-
209
-	/**
210
-	 * auto generate password in case of password enforcement on mail shares
211
-	 *
212
-	 * @param IShare $share
213
-	 * @return string
214
-	 * @throws \Exception
215
-	 */
216
-	protected function autoGeneratePassword($share) {
217
-		$initiatorUser = $this->userManager->get($share->getSharedBy());
218
-		$initiatorEMailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
219
-		$allowPasswordByMail = $this->settingsManager->sendPasswordByMail();
220
-
221
-		if ($initiatorEMailAddress === null && !$allowPasswordByMail) {
222
-			throw new \Exception(
223
-				$this->l->t("We can't send you the auto-generated password. Please set a valid email address in your personal settings and try again.")
224
-			);
225
-		}
226
-
227
-		$passwordPolicy = $this->getPasswordPolicy();
228
-		$passwordCharset = ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS;
229
-		$passwordLength = 8;
230
-		if (!empty($passwordPolicy)) {
231
-			$passwordLength = (int)$passwordPolicy['minLength'] > 0 ? (int)$passwordPolicy['minLength'] : $passwordLength;
232
-			$passwordCharset .= $passwordPolicy['enforceSpecialCharacters'] ? ISecureRandom::CHAR_SYMBOLS : '';
233
-		}
234
-
235
-		$password = $this->secureRandom->generate($passwordLength, $passwordCharset);
236
-
237
-		$share->setPassword($this->hasher->hash($password));
238
-
239
-		return $password;
240
-	}
241
-
242
-	/**
243
-	 * get password policy
244
-	 *
245
-	 * @return array
246
-	 */
247
-	protected function getPasswordPolicy() {
248
-		$capabilities = $this->capabilitiesManager->getCapabilities();
249
-		if (isset($capabilities['password_policy'])) {
250
-			return $capabilities['password_policy'];
251
-		}
252
-
253
-		return [];
254
-	}
255
-
256
-	/**
257
-	 * create activity if a file/folder was shared by mail
258
-	 *
259
-	 * @param IShare $share
260
-	 * @param string $type
261
-	 */
262
-	protected function createShareActivity(IShare $share, string $type = 'share') {
263
-
264
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
265
-
266
-		$this->publishActivity(
267
-			$type === 'share' ? Activity::SUBJECT_SHARED_EMAIL_SELF : Activity::SUBJECT_UNSHARED_EMAIL_SELF,
268
-			[$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
269
-			$share->getSharedBy(),
270
-			$share->getNode()->getId(),
271
-			(string) $userFolder->getRelativePath($share->getNode()->getPath())
272
-		);
273
-
274
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
275
-			$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
276
-			$fileId = $share->getNode()->getId();
277
-			$nodes = $ownerFolder->getById($fileId);
278
-			$ownerPath = $nodes[0]->getPath();
279
-			$this->publishActivity(
280
-				$type === 'share' ? Activity::SUBJECT_SHARED_EMAIL_BY : Activity::SUBJECT_UNSHARED_EMAIL_BY,
281
-				[$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
282
-				$share->getShareOwner(),
283
-				$fileId,
284
-				(string) $ownerFolder->getRelativePath($ownerPath)
285
-			);
286
-		}
287
-
288
-	}
289
-
290
-	/**
291
-	 * create activity if a file/folder was shared by mail
292
-	 *
293
-	 * @param IShare $share
294
-	 * @param string $sharedWith
295
-	 * @param bool $sendToSelf
296
-	 */
297
-	protected function createPasswordSendActivity(IShare $share, $sharedWith, $sendToSelf) {
298
-
299
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
300
-
301
-		if ($sendToSelf) {
302
-			$this->publishActivity(
303
-				Activity::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF,
304
-				[$userFolder->getRelativePath($share->getNode()->getPath())],
305
-				$share->getSharedBy(),
306
-				$share->getNode()->getId(),
307
-				(string) $userFolder->getRelativePath($share->getNode()->getPath())
308
-			);
309
-		} else {
310
-			$this->publishActivity(
311
-				Activity::SUBJECT_SHARED_EMAIL_PASSWORD_SEND,
312
-				[$userFolder->getRelativePath($share->getNode()->getPath()), $sharedWith],
313
-				$share->getSharedBy(),
314
-				$share->getNode()->getId(),
315
-				(string) $userFolder->getRelativePath($share->getNode()->getPath())
316
-			);
317
-		}
318
-	}
319
-
320
-
321
-	/**
322
-	 * publish activity if a file/folder was shared by mail
323
-	 *
324
-	 * @param string $subject
325
-	 * @param array $parameters
326
-	 * @param string $affectedUser
327
-	 * @param int $fileId
328
-	 * @param string $filePath
329
-	 */
330
-	protected function publishActivity(string $subject, array $parameters, string $affectedUser, int $fileId, string $filePath) {
331
-		$event = $this->activityManager->generateEvent();
332
-		$event->setApp('sharebymail')
333
-			->setType('shared')
334
-			->setSubject($subject, $parameters)
335
-			->setAffectedUser($affectedUser)
336
-			->setObject('files', $fileId, $filePath);
337
-		$this->activityManager->publish($event);
338
-
339
-	}
340
-
341
-	/**
342
-	 * @param IShare $share
343
-	 * @return int
344
-	 * @throws \Exception
345
-	 */
346
-	protected function createMailShare(IShare $share) {
347
-		$share->setToken($this->generateToken());
348
-		$shareId = $this->addShareToDB(
349
-			$share->getNodeId(),
350
-			$share->getNodeType(),
351
-			$share->getSharedWith(),
352
-			$share->getSharedBy(),
353
-			$share->getShareOwner(),
354
-			$share->getPermissions(),
355
-			$share->getToken(),
356
-			$share->getPassword(),
357
-			$share->getSendPasswordByTalk(),
358
-			$share->getHideDownload()
359
-		);
360
-
361
-		try {
362
-			$link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
363
-				['token' => $share->getToken()]);
364
-			$this->sendMailNotification(
365
-				$share->getNode()->getName(),
366
-				$link,
367
-				$share->getSharedBy(),
368
-				$share->getSharedWith(),
369
-				$share->getExpirationDate()
370
-			);
371
-		} catch (HintException $hintException) {
372
-			$this->logger->logException($hintException, [
373
-				'message' => 'Failed to send share by mail.',
374
-				'level' => ILogger::ERROR,
375
-				'app' => 'sharebymail',
376
-			]);
377
-			$this->removeShareFromTable($shareId);
378
-			throw $hintException;
379
-		} catch (\Exception $e) {
380
-			$this->logger->logException($e, [
381
-				'message' => 'Failed to send share by mail.',
382
-				'level' => ILogger::ERROR,
383
-				'app' => 'sharebymail',
384
-			]);
385
-			$this->removeShareFromTable($shareId);
386
-			throw new HintException('Failed to send share by mail',
387
-				$this->l->t('Failed to send share by email'));
388
-		}
389
-
390
-		return $shareId;
391
-
392
-	}
393
-
394
-	/**
395
-	 * @param string $filename
396
-	 * @param string $link
397
-	 * @param string $initiator
398
-	 * @param string $shareWith
399
-	 * @param \DateTime|null $expiration
400
-	 * @throws \Exception If mail couldn't be sent
401
-	 */
402
-	protected function sendMailNotification($filename,
403
-											$link,
404
-											$initiator,
405
-											$shareWith,
406
-											\DateTime $expiration = null) {
407
-		$initiatorUser = $this->userManager->get($initiator);
408
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
409
-		$message = $this->mailer->createMessage();
410
-
411
-		$emailTemplate = $this->mailer->createEMailTemplate('sharebymail.RecipientNotification', [
412
-			'filename' => $filename,
413
-			'link' => $link,
414
-			'initiator' => $initiatorDisplayName,
415
-			'expiration' => $expiration,
416
-			'shareWith' => $shareWith,
417
-		]);
418
-
419
-		$emailTemplate->setSubject($this->l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]));
420
-		$emailTemplate->addHeader();
421
-		$emailTemplate->addHeading($this->l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
422
-		$text = $this->l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
423
-
424
-		$emailTemplate->addBodyText(
425
-			htmlspecialchars($text . ' ' . $this->l->t('Click the button below to open it.')),
426
-			$text
427
-		);
428
-		$emailTemplate->addBodyButton(
429
-			$this->l->t('Open »%s«', [$filename]),
430
-			$link
431
-		);
432
-
433
-		$message->setTo([$shareWith]);
434
-
435
-		// The "From" contains the sharers name
436
-		$instanceName = $this->defaults->getName();
437
-		$senderName = $this->l->t(
438
-			'%1$s via %2$s',
439
-			[
440
-				$initiatorDisplayName,
441
-				$instanceName
442
-			]
443
-		);
444
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
445
-
446
-		// The "Reply-To" is set to the sharer if an mail address is configured
447
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
448
-		$initiatorEmail = $initiatorUser->getEMailAddress();
449
-		if($initiatorEmail !== null) {
450
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
451
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
452
-		} else {
453
-			$emailTemplate->addFooter();
454
-		}
455
-
456
-		$message->useTemplate($emailTemplate);
457
-		$this->mailer->send($message);
458
-	}
459
-
460
-	/**
461
-	 * send password to recipient of a mail share
462
-	 *
463
-	 * @param IShare $share
464
-	 * @param string $password
465
-	 * @return bool
466
-	 */
467
-	protected function sendPassword(IShare $share, $password) {
468
-
469
-		$filename = $share->getNode()->getName();
470
-		$initiator = $share->getSharedBy();
471
-		$shareWith = $share->getSharedWith();
472
-
473
-		if ($password === '' || $this->settingsManager->sendPasswordByMail() === false || $share->getSendPasswordByTalk()) {
474
-			return false;
475
-		}
476
-
477
-		$initiatorUser = $this->userManager->get($initiator);
478
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
479
-		$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
480
-
481
-		$plainBodyPart = $this->l->t("%1\$s shared »%2\$s« with you.\nYou should have already received a separate mail with a link to access it.\n", [$initiatorDisplayName, $filename]);
482
-		$htmlBodyPart = $this->l->t('%1$s shared »%2$s« with you. You should have already received a separate mail with a link to access it.', [$initiatorDisplayName, $filename]);
483
-
484
-		$message = $this->mailer->createMessage();
485
-
486
-		$emailTemplate = $this->mailer->createEMailTemplate('sharebymail.RecipientPasswordNotification', [
487
-			'filename' => $filename,
488
-			'password' => $password,
489
-			'initiator' => $initiatorDisplayName,
490
-			'initiatorEmail' => $initiatorEmailAddress,
491
-			'shareWith' => $shareWith,
492
-		]);
493
-
494
-		$emailTemplate->setSubject($this->l->t('Password to access »%1$s« shared to you by %2$s', [$filename, $initiatorDisplayName]));
495
-		$emailTemplate->addHeader();
496
-		$emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]), false);
497
-		$emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
498
-		$emailTemplate->addBodyText($this->l->t('It is protected with the following password:'));
499
-		$emailTemplate->addBodyText($password);
500
-
501
-		// The "From" contains the sharers name
502
-		$instanceName = $this->defaults->getName();
503
-		$senderName = $this->l->t(
504
-			'%1$s via %2$s',
505
-			[
506
-				$initiatorDisplayName,
507
-				$instanceName
508
-			]
509
-		);
510
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
511
-		if ($initiatorEmailAddress !== null) {
512
-			$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
513
-			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
514
-		} else {
515
-			$emailTemplate->addFooter();
516
-		}
517
-
518
-		$message->setTo([$shareWith]);
519
-		$message->useTemplate($emailTemplate);
520
-		$this->mailer->send($message);
521
-
522
-		$this->createPasswordSendActivity($share, $shareWith, false);
523
-
524
-		return true;
525
-	}
526
-
527
-	protected function sendNote(IShare $share) {
528
-
529
-		$recipient = $share->getSharedWith();
530
-
531
-
532
-		$filename = $share->getNode()->getName();
533
-		$initiator = $share->getSharedBy();
534
-		$note = $share->getNote();
535
-
536
-		$initiatorUser = $this->userManager->get($initiator);
537
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
538
-		$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
539
-
540
-		$plainHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
541
-		$htmlHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
542
-
543
-		$message = $this->mailer->createMessage();
544
-
545
-		$emailTemplate = $this->mailer->createEMailTemplate('shareByMail.sendNote');
546
-
547
-		$emailTemplate->setSubject($this->l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
548
-		$emailTemplate->addHeader();
549
-		$emailTemplate->addHeading(htmlspecialchars($htmlHeading), $plainHeading);
550
-		$emailTemplate->addBodyText(htmlspecialchars($note), $note);
551
-
552
-		$link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
553
-			['token' => $share->getToken()]);
554
-		$emailTemplate->addBodyButton(
555
-			$this->l->t('Open »%s«', [$filename]),
556
-			$link
557
-		);
558
-
559
-		// The "From" contains the sharers name
560
-		$instanceName = $this->defaults->getName();
561
-		$senderName = $this->l->t(
562
-			'%1$s via %2$s',
563
-			[
564
-				$initiatorDisplayName,
565
-				$instanceName
566
-			]
567
-		);
568
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
569
-		if ($initiatorEmailAddress !== null) {
570
-			$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
571
-			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
572
-		} else {
573
-			$emailTemplate->addFooter();
574
-		}
575
-
576
-		$message->setTo([$recipient]);
577
-		$message->useTemplate($emailTemplate);
578
-		$this->mailer->send($message);
579
-
580
-	}
581
-
582
-	/**
583
-	 * send auto generated password to the owner. This happens if the admin enforces
584
-	 * a password for mail shares and forbid to send the password by mail to the recipient
585
-	 *
586
-	 * @param IShare $share
587
-	 * @param string $password
588
-	 * @return bool
589
-	 * @throws \Exception
590
-	 */
591
-	protected function sendPasswordToOwner(IShare $share, $password) {
592
-
593
-		$filename = $share->getNode()->getName();
594
-		$initiator = $this->userManager->get($share->getSharedBy());
595
-		$initiatorEMailAddress = ($initiator instanceof IUser) ? $initiator->getEMailAddress() : null;
596
-		$initiatorDisplayName = ($initiator instanceof IUser) ? $initiator->getDisplayName() : $share->getSharedBy();
597
-		$shareWith = $share->getSharedWith();
598
-
599
-		if ($initiatorEMailAddress === null) {
600
-			throw new \Exception(
601
-				$this->l->t("We can't send you the auto-generated password. Please set a valid email address in your personal settings and try again.")
602
-			);
603
-		}
604
-
605
-		$bodyPart = $this->l->t('You just shared »%1$s« with %2$s. The share was already sent to the recipient. Due to the security policies defined by the administrator of %3$s each share needs to be protected by password and it is not allowed to send the password directly to the recipient. Therefore you need to forward the password manually to the recipient.', [$filename, $shareWith, $this->defaults->getName()]);
606
-
607
-		$message = $this->mailer->createMessage();
608
-		$emailTemplate = $this->mailer->createEMailTemplate('sharebymail.OwnerPasswordNotification', [
609
-			'filename' => $filename,
610
-			'password' => $password,
611
-			'initiator' => $initiatorDisplayName,
612
-			'initiatorEmail' => $initiatorEMailAddress,
613
-			'shareWith' => $shareWith,
614
-		]);
615
-
616
-		$emailTemplate->setSubject($this->l->t('Password to access »%1$s« shared by you with %2$s', [$filename, $shareWith]));
617
-		$emailTemplate->addHeader();
618
-		$emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]), false);
619
-		$emailTemplate->addBodyText($bodyPart);
620
-		$emailTemplate->addBodyText($this->l->t('This is the password:'));
621
-		$emailTemplate->addBodyText($password);
622
-		$emailTemplate->addBodyText($this->l->t('You can choose a different password at any time in the share dialog.'));
623
-		$emailTemplate->addFooter();
624
-
625
-		$instanceName = $this->defaults->getName();
626
-		$senderName = $this->l->t(
627
-			'%1$s via %2$s',
628
-			[
629
-				$initiatorDisplayName,
630
-				$instanceName
631
-			]
632
-		);
633
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
634
-		$message->setTo([$initiatorEMailAddress => $initiatorDisplayName]);
635
-		$message->useTemplate($emailTemplate);
636
-		$this->mailer->send($message);
637
-
638
-		$this->createPasswordSendActivity($share, $shareWith, true);
639
-
640
-		return true;
641
-	}
642
-
643
-	/**
644
-	 * generate share token
645
-	 *
646
-	 * @return string
647
-	 */
648
-	protected function generateToken($size = 15) {
649
-		$token = $this->secureRandom->generate($size, ISecureRandom::CHAR_HUMAN_READABLE);
650
-		return $token;
651
-	}
652
-
653
-	/**
654
-	 * Get all children of this share
655
-	 *
656
-	 * @param IShare $parent
657
-	 * @return IShare[]
658
-	 */
659
-	public function getChildren(IShare $parent) {
660
-		$children = [];
661
-
662
-		$qb = $this->dbConnection->getQueryBuilder();
663
-		$qb->select('*')
664
-			->from('share')
665
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
666
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
667
-			->orderBy('id');
668
-
669
-		$cursor = $qb->execute();
670
-		while($data = $cursor->fetch()) {
671
-			$children[] = $this->createShareObject($data);
672
-		}
673
-		$cursor->closeCursor();
674
-
675
-		return $children;
676
-	}
677
-
678
-	/**
679
-	 * add share to the database and return the ID
680
-	 *
681
-	 * @param int $itemSource
682
-	 * @param string $itemType
683
-	 * @param string $shareWith
684
-	 * @param string $sharedBy
685
-	 * @param string $uidOwner
686
-	 * @param int $permissions
687
-	 * @param string $token
688
-	 * @param string $password
689
-	 * @param bool $sendPasswordByTalk
690
-	 * @param bool $hideDownload
691
-	 * @return int
692
-	 */
693
-	protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token, $password, $sendPasswordByTalk, $hideDownload) {
694
-		$qb = $this->dbConnection->getQueryBuilder();
695
-		$qb->insert('share')
696
-			->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
697
-			->setValue('item_type', $qb->createNamedParameter($itemType))
698
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
699
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
700
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
701
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
702
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
703
-			->setValue('permissions', $qb->createNamedParameter($permissions))
704
-			->setValue('token', $qb->createNamedParameter($token))
705
-			->setValue('password', $qb->createNamedParameter($password))
706
-			->setValue('password_by_talk', $qb->createNamedParameter($sendPasswordByTalk, IQueryBuilder::PARAM_BOOL))
707
-			->setValue('stime', $qb->createNamedParameter(time()))
708
-			->setValue('hide_download', $qb->createNamedParameter((int)$hideDownload, IQueryBuilder::PARAM_INT));
709
-
710
-		/*
180
+        $alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
181
+        if (!empty($alreadyShared)) {
182
+            $message = 'Sharing %1$s failed, this item is already shared with %2$s';
183
+            $message_t = $this->l->t('Sharing %1$s failed, this item is already shared with %2$s', [$share->getNode()->getName(), $shareWith]);
184
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
185
+            throw new \Exception($message_t);
186
+        }
187
+
188
+        // if the admin enforces a password for all mail shares we create a
189
+        // random password and send it to the recipient
190
+        $password = '';
191
+        $passwordEnforced = $this->settingsManager->enforcePasswordProtection();
192
+        if ($passwordEnforced) {
193
+            $password = $this->autoGeneratePassword($share);
194
+        }
195
+
196
+        $shareId = $this->createMailShare($share);
197
+        $send = $this->sendPassword($share, $password);
198
+        if ($passwordEnforced && $send === false) {
199
+            $this->sendPasswordToOwner($share, $password);
200
+        }
201
+
202
+        $this->createShareActivity($share);
203
+        $data = $this->getRawShare($shareId);
204
+
205
+        return $this->createShareObject($data);
206
+
207
+    }
208
+
209
+    /**
210
+     * auto generate password in case of password enforcement on mail shares
211
+     *
212
+     * @param IShare $share
213
+     * @return string
214
+     * @throws \Exception
215
+     */
216
+    protected function autoGeneratePassword($share) {
217
+        $initiatorUser = $this->userManager->get($share->getSharedBy());
218
+        $initiatorEMailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
219
+        $allowPasswordByMail = $this->settingsManager->sendPasswordByMail();
220
+
221
+        if ($initiatorEMailAddress === null && !$allowPasswordByMail) {
222
+            throw new \Exception(
223
+                $this->l->t("We can't send you the auto-generated password. Please set a valid email address in your personal settings and try again.")
224
+            );
225
+        }
226
+
227
+        $passwordPolicy = $this->getPasswordPolicy();
228
+        $passwordCharset = ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS;
229
+        $passwordLength = 8;
230
+        if (!empty($passwordPolicy)) {
231
+            $passwordLength = (int)$passwordPolicy['minLength'] > 0 ? (int)$passwordPolicy['minLength'] : $passwordLength;
232
+            $passwordCharset .= $passwordPolicy['enforceSpecialCharacters'] ? ISecureRandom::CHAR_SYMBOLS : '';
233
+        }
234
+
235
+        $password = $this->secureRandom->generate($passwordLength, $passwordCharset);
236
+
237
+        $share->setPassword($this->hasher->hash($password));
238
+
239
+        return $password;
240
+    }
241
+
242
+    /**
243
+     * get password policy
244
+     *
245
+     * @return array
246
+     */
247
+    protected function getPasswordPolicy() {
248
+        $capabilities = $this->capabilitiesManager->getCapabilities();
249
+        if (isset($capabilities['password_policy'])) {
250
+            return $capabilities['password_policy'];
251
+        }
252
+
253
+        return [];
254
+    }
255
+
256
+    /**
257
+     * create activity if a file/folder was shared by mail
258
+     *
259
+     * @param IShare $share
260
+     * @param string $type
261
+     */
262
+    protected function createShareActivity(IShare $share, string $type = 'share') {
263
+
264
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
265
+
266
+        $this->publishActivity(
267
+            $type === 'share' ? Activity::SUBJECT_SHARED_EMAIL_SELF : Activity::SUBJECT_UNSHARED_EMAIL_SELF,
268
+            [$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
269
+            $share->getSharedBy(),
270
+            $share->getNode()->getId(),
271
+            (string) $userFolder->getRelativePath($share->getNode()->getPath())
272
+        );
273
+
274
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
275
+            $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
276
+            $fileId = $share->getNode()->getId();
277
+            $nodes = $ownerFolder->getById($fileId);
278
+            $ownerPath = $nodes[0]->getPath();
279
+            $this->publishActivity(
280
+                $type === 'share' ? Activity::SUBJECT_SHARED_EMAIL_BY : Activity::SUBJECT_UNSHARED_EMAIL_BY,
281
+                [$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
282
+                $share->getShareOwner(),
283
+                $fileId,
284
+                (string) $ownerFolder->getRelativePath($ownerPath)
285
+            );
286
+        }
287
+
288
+    }
289
+
290
+    /**
291
+     * create activity if a file/folder was shared by mail
292
+     *
293
+     * @param IShare $share
294
+     * @param string $sharedWith
295
+     * @param bool $sendToSelf
296
+     */
297
+    protected function createPasswordSendActivity(IShare $share, $sharedWith, $sendToSelf) {
298
+
299
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
300
+
301
+        if ($sendToSelf) {
302
+            $this->publishActivity(
303
+                Activity::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF,
304
+                [$userFolder->getRelativePath($share->getNode()->getPath())],
305
+                $share->getSharedBy(),
306
+                $share->getNode()->getId(),
307
+                (string) $userFolder->getRelativePath($share->getNode()->getPath())
308
+            );
309
+        } else {
310
+            $this->publishActivity(
311
+                Activity::SUBJECT_SHARED_EMAIL_PASSWORD_SEND,
312
+                [$userFolder->getRelativePath($share->getNode()->getPath()), $sharedWith],
313
+                $share->getSharedBy(),
314
+                $share->getNode()->getId(),
315
+                (string) $userFolder->getRelativePath($share->getNode()->getPath())
316
+            );
317
+        }
318
+    }
319
+
320
+
321
+    /**
322
+     * publish activity if a file/folder was shared by mail
323
+     *
324
+     * @param string $subject
325
+     * @param array $parameters
326
+     * @param string $affectedUser
327
+     * @param int $fileId
328
+     * @param string $filePath
329
+     */
330
+    protected function publishActivity(string $subject, array $parameters, string $affectedUser, int $fileId, string $filePath) {
331
+        $event = $this->activityManager->generateEvent();
332
+        $event->setApp('sharebymail')
333
+            ->setType('shared')
334
+            ->setSubject($subject, $parameters)
335
+            ->setAffectedUser($affectedUser)
336
+            ->setObject('files', $fileId, $filePath);
337
+        $this->activityManager->publish($event);
338
+
339
+    }
340
+
341
+    /**
342
+     * @param IShare $share
343
+     * @return int
344
+     * @throws \Exception
345
+     */
346
+    protected function createMailShare(IShare $share) {
347
+        $share->setToken($this->generateToken());
348
+        $shareId = $this->addShareToDB(
349
+            $share->getNodeId(),
350
+            $share->getNodeType(),
351
+            $share->getSharedWith(),
352
+            $share->getSharedBy(),
353
+            $share->getShareOwner(),
354
+            $share->getPermissions(),
355
+            $share->getToken(),
356
+            $share->getPassword(),
357
+            $share->getSendPasswordByTalk(),
358
+            $share->getHideDownload()
359
+        );
360
+
361
+        try {
362
+            $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
363
+                ['token' => $share->getToken()]);
364
+            $this->sendMailNotification(
365
+                $share->getNode()->getName(),
366
+                $link,
367
+                $share->getSharedBy(),
368
+                $share->getSharedWith(),
369
+                $share->getExpirationDate()
370
+            );
371
+        } catch (HintException $hintException) {
372
+            $this->logger->logException($hintException, [
373
+                'message' => 'Failed to send share by mail.',
374
+                'level' => ILogger::ERROR,
375
+                'app' => 'sharebymail',
376
+            ]);
377
+            $this->removeShareFromTable($shareId);
378
+            throw $hintException;
379
+        } catch (\Exception $e) {
380
+            $this->logger->logException($e, [
381
+                'message' => 'Failed to send share by mail.',
382
+                'level' => ILogger::ERROR,
383
+                'app' => 'sharebymail',
384
+            ]);
385
+            $this->removeShareFromTable($shareId);
386
+            throw new HintException('Failed to send share by mail',
387
+                $this->l->t('Failed to send share by email'));
388
+        }
389
+
390
+        return $shareId;
391
+
392
+    }
393
+
394
+    /**
395
+     * @param string $filename
396
+     * @param string $link
397
+     * @param string $initiator
398
+     * @param string $shareWith
399
+     * @param \DateTime|null $expiration
400
+     * @throws \Exception If mail couldn't be sent
401
+     */
402
+    protected function sendMailNotification($filename,
403
+                                            $link,
404
+                                            $initiator,
405
+                                            $shareWith,
406
+                                            \DateTime $expiration = null) {
407
+        $initiatorUser = $this->userManager->get($initiator);
408
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
409
+        $message = $this->mailer->createMessage();
410
+
411
+        $emailTemplate = $this->mailer->createEMailTemplate('sharebymail.RecipientNotification', [
412
+            'filename' => $filename,
413
+            'link' => $link,
414
+            'initiator' => $initiatorDisplayName,
415
+            'expiration' => $expiration,
416
+            'shareWith' => $shareWith,
417
+        ]);
418
+
419
+        $emailTemplate->setSubject($this->l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]));
420
+        $emailTemplate->addHeader();
421
+        $emailTemplate->addHeading($this->l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
422
+        $text = $this->l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
423
+
424
+        $emailTemplate->addBodyText(
425
+            htmlspecialchars($text . ' ' . $this->l->t('Click the button below to open it.')),
426
+            $text
427
+        );
428
+        $emailTemplate->addBodyButton(
429
+            $this->l->t('Open »%s«', [$filename]),
430
+            $link
431
+        );
432
+
433
+        $message->setTo([$shareWith]);
434
+
435
+        // The "From" contains the sharers name
436
+        $instanceName = $this->defaults->getName();
437
+        $senderName = $this->l->t(
438
+            '%1$s via %2$s',
439
+            [
440
+                $initiatorDisplayName,
441
+                $instanceName
442
+            ]
443
+        );
444
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
445
+
446
+        // The "Reply-To" is set to the sharer if an mail address is configured
447
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
448
+        $initiatorEmail = $initiatorUser->getEMailAddress();
449
+        if($initiatorEmail !== null) {
450
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
451
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
452
+        } else {
453
+            $emailTemplate->addFooter();
454
+        }
455
+
456
+        $message->useTemplate($emailTemplate);
457
+        $this->mailer->send($message);
458
+    }
459
+
460
+    /**
461
+     * send password to recipient of a mail share
462
+     *
463
+     * @param IShare $share
464
+     * @param string $password
465
+     * @return bool
466
+     */
467
+    protected function sendPassword(IShare $share, $password) {
468
+
469
+        $filename = $share->getNode()->getName();
470
+        $initiator = $share->getSharedBy();
471
+        $shareWith = $share->getSharedWith();
472
+
473
+        if ($password === '' || $this->settingsManager->sendPasswordByMail() === false || $share->getSendPasswordByTalk()) {
474
+            return false;
475
+        }
476
+
477
+        $initiatorUser = $this->userManager->get($initiator);
478
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
479
+        $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
480
+
481
+        $plainBodyPart = $this->l->t("%1\$s shared »%2\$s« with you.\nYou should have already received a separate mail with a link to access it.\n", [$initiatorDisplayName, $filename]);
482
+        $htmlBodyPart = $this->l->t('%1$s shared »%2$s« with you. You should have already received a separate mail with a link to access it.', [$initiatorDisplayName, $filename]);
483
+
484
+        $message = $this->mailer->createMessage();
485
+
486
+        $emailTemplate = $this->mailer->createEMailTemplate('sharebymail.RecipientPasswordNotification', [
487
+            'filename' => $filename,
488
+            'password' => $password,
489
+            'initiator' => $initiatorDisplayName,
490
+            'initiatorEmail' => $initiatorEmailAddress,
491
+            'shareWith' => $shareWith,
492
+        ]);
493
+
494
+        $emailTemplate->setSubject($this->l->t('Password to access »%1$s« shared to you by %2$s', [$filename, $initiatorDisplayName]));
495
+        $emailTemplate->addHeader();
496
+        $emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]), false);
497
+        $emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
498
+        $emailTemplate->addBodyText($this->l->t('It is protected with the following password:'));
499
+        $emailTemplate->addBodyText($password);
500
+
501
+        // The "From" contains the sharers name
502
+        $instanceName = $this->defaults->getName();
503
+        $senderName = $this->l->t(
504
+            '%1$s via %2$s',
505
+            [
506
+                $initiatorDisplayName,
507
+                $instanceName
508
+            ]
509
+        );
510
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
511
+        if ($initiatorEmailAddress !== null) {
512
+            $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
513
+            $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
514
+        } else {
515
+            $emailTemplate->addFooter();
516
+        }
517
+
518
+        $message->setTo([$shareWith]);
519
+        $message->useTemplate($emailTemplate);
520
+        $this->mailer->send($message);
521
+
522
+        $this->createPasswordSendActivity($share, $shareWith, false);
523
+
524
+        return true;
525
+    }
526
+
527
+    protected function sendNote(IShare $share) {
528
+
529
+        $recipient = $share->getSharedWith();
530
+
531
+
532
+        $filename = $share->getNode()->getName();
533
+        $initiator = $share->getSharedBy();
534
+        $note = $share->getNote();
535
+
536
+        $initiatorUser = $this->userManager->get($initiator);
537
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
538
+        $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
539
+
540
+        $plainHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
541
+        $htmlHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
542
+
543
+        $message = $this->mailer->createMessage();
544
+
545
+        $emailTemplate = $this->mailer->createEMailTemplate('shareByMail.sendNote');
546
+
547
+        $emailTemplate->setSubject($this->l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
548
+        $emailTemplate->addHeader();
549
+        $emailTemplate->addHeading(htmlspecialchars($htmlHeading), $plainHeading);
550
+        $emailTemplate->addBodyText(htmlspecialchars($note), $note);
551
+
552
+        $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
553
+            ['token' => $share->getToken()]);
554
+        $emailTemplate->addBodyButton(
555
+            $this->l->t('Open »%s«', [$filename]),
556
+            $link
557
+        );
558
+
559
+        // The "From" contains the sharers name
560
+        $instanceName = $this->defaults->getName();
561
+        $senderName = $this->l->t(
562
+            '%1$s via %2$s',
563
+            [
564
+                $initiatorDisplayName,
565
+                $instanceName
566
+            ]
567
+        );
568
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
569
+        if ($initiatorEmailAddress !== null) {
570
+            $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
571
+            $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
572
+        } else {
573
+            $emailTemplate->addFooter();
574
+        }
575
+
576
+        $message->setTo([$recipient]);
577
+        $message->useTemplate($emailTemplate);
578
+        $this->mailer->send($message);
579
+
580
+    }
581
+
582
+    /**
583
+     * send auto generated password to the owner. This happens if the admin enforces
584
+     * a password for mail shares and forbid to send the password by mail to the recipient
585
+     *
586
+     * @param IShare $share
587
+     * @param string $password
588
+     * @return bool
589
+     * @throws \Exception
590
+     */
591
+    protected function sendPasswordToOwner(IShare $share, $password) {
592
+
593
+        $filename = $share->getNode()->getName();
594
+        $initiator = $this->userManager->get($share->getSharedBy());
595
+        $initiatorEMailAddress = ($initiator instanceof IUser) ? $initiator->getEMailAddress() : null;
596
+        $initiatorDisplayName = ($initiator instanceof IUser) ? $initiator->getDisplayName() : $share->getSharedBy();
597
+        $shareWith = $share->getSharedWith();
598
+
599
+        if ($initiatorEMailAddress === null) {
600
+            throw new \Exception(
601
+                $this->l->t("We can't send you the auto-generated password. Please set a valid email address in your personal settings and try again.")
602
+            );
603
+        }
604
+
605
+        $bodyPart = $this->l->t('You just shared »%1$s« with %2$s. The share was already sent to the recipient. Due to the security policies defined by the administrator of %3$s each share needs to be protected by password and it is not allowed to send the password directly to the recipient. Therefore you need to forward the password manually to the recipient.', [$filename, $shareWith, $this->defaults->getName()]);
606
+
607
+        $message = $this->mailer->createMessage();
608
+        $emailTemplate = $this->mailer->createEMailTemplate('sharebymail.OwnerPasswordNotification', [
609
+            'filename' => $filename,
610
+            'password' => $password,
611
+            'initiator' => $initiatorDisplayName,
612
+            'initiatorEmail' => $initiatorEMailAddress,
613
+            'shareWith' => $shareWith,
614
+        ]);
615
+
616
+        $emailTemplate->setSubject($this->l->t('Password to access »%1$s« shared by you with %2$s', [$filename, $shareWith]));
617
+        $emailTemplate->addHeader();
618
+        $emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]), false);
619
+        $emailTemplate->addBodyText($bodyPart);
620
+        $emailTemplate->addBodyText($this->l->t('This is the password:'));
621
+        $emailTemplate->addBodyText($password);
622
+        $emailTemplate->addBodyText($this->l->t('You can choose a different password at any time in the share dialog.'));
623
+        $emailTemplate->addFooter();
624
+
625
+        $instanceName = $this->defaults->getName();
626
+        $senderName = $this->l->t(
627
+            '%1$s via %2$s',
628
+            [
629
+                $initiatorDisplayName,
630
+                $instanceName
631
+            ]
632
+        );
633
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
634
+        $message->setTo([$initiatorEMailAddress => $initiatorDisplayName]);
635
+        $message->useTemplate($emailTemplate);
636
+        $this->mailer->send($message);
637
+
638
+        $this->createPasswordSendActivity($share, $shareWith, true);
639
+
640
+        return true;
641
+    }
642
+
643
+    /**
644
+     * generate share token
645
+     *
646
+     * @return string
647
+     */
648
+    protected function generateToken($size = 15) {
649
+        $token = $this->secureRandom->generate($size, ISecureRandom::CHAR_HUMAN_READABLE);
650
+        return $token;
651
+    }
652
+
653
+    /**
654
+     * Get all children of this share
655
+     *
656
+     * @param IShare $parent
657
+     * @return IShare[]
658
+     */
659
+    public function getChildren(IShare $parent) {
660
+        $children = [];
661
+
662
+        $qb = $this->dbConnection->getQueryBuilder();
663
+        $qb->select('*')
664
+            ->from('share')
665
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
666
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
667
+            ->orderBy('id');
668
+
669
+        $cursor = $qb->execute();
670
+        while($data = $cursor->fetch()) {
671
+            $children[] = $this->createShareObject($data);
672
+        }
673
+        $cursor->closeCursor();
674
+
675
+        return $children;
676
+    }
677
+
678
+    /**
679
+     * add share to the database and return the ID
680
+     *
681
+     * @param int $itemSource
682
+     * @param string $itemType
683
+     * @param string $shareWith
684
+     * @param string $sharedBy
685
+     * @param string $uidOwner
686
+     * @param int $permissions
687
+     * @param string $token
688
+     * @param string $password
689
+     * @param bool $sendPasswordByTalk
690
+     * @param bool $hideDownload
691
+     * @return int
692
+     */
693
+    protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token, $password, $sendPasswordByTalk, $hideDownload) {
694
+        $qb = $this->dbConnection->getQueryBuilder();
695
+        $qb->insert('share')
696
+            ->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
697
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
698
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
699
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
700
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
701
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
702
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
703
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
704
+            ->setValue('token', $qb->createNamedParameter($token))
705
+            ->setValue('password', $qb->createNamedParameter($password))
706
+            ->setValue('password_by_talk', $qb->createNamedParameter($sendPasswordByTalk, IQueryBuilder::PARAM_BOOL))
707
+            ->setValue('stime', $qb->createNamedParameter(time()))
708
+            ->setValue('hide_download', $qb->createNamedParameter((int)$hideDownload, IQueryBuilder::PARAM_INT));
709
+
710
+        /*
711 711
 		 * Added to fix https://github.com/owncloud/core/issues/22215
712 712
 		 * Can be removed once we get rid of ajax/share.php
713 713
 		 */
714
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
714
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
715 715
 
716
-		$qb->execute();
717
-		$id = $qb->getLastInsertId();
716
+        $qb->execute();
717
+        $id = $qb->getLastInsertId();
718 718
 
719
-		return (int)$id;
720
-	}
719
+        return (int)$id;
720
+    }
721 721
 
722
-	/**
723
-	 * Update a share
724
-	 *
725
-	 * @param IShare $share
726
-	 * @param string|null $plainTextPassword
727
-	 * @return IShare The share object
728
-	 */
729
-	public function update(IShare $share, $plainTextPassword = null) {
722
+    /**
723
+     * Update a share
724
+     *
725
+     * @param IShare $share
726
+     * @param string|null $plainTextPassword
727
+     * @return IShare The share object
728
+     */
729
+    public function update(IShare $share, $plainTextPassword = null) {
730 730
 
731
-		$originalShare = $this->getShareById($share->getId());
731
+        $originalShare = $this->getShareById($share->getId());
732 732
 
733
-		// a real password was given
734
-		$validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
733
+        // a real password was given
734
+        $validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
735 735
 
736
-		if($validPassword && ($originalShare->getPassword() !== $share->getPassword() ||
737
-								($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()))) {
738
-			$this->sendPassword($share, $plainTextPassword);
739
-		}
740
-		/*
736
+        if($validPassword && ($originalShare->getPassword() !== $share->getPassword() ||
737
+                                ($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()))) {
738
+            $this->sendPassword($share, $plainTextPassword);
739
+        }
740
+        /*
741 741
 		 * We allow updating the permissions and password of mail shares
742 742
 		 */
743
-		$qb = $this->dbConnection->getQueryBuilder();
744
-		$qb->update('share')
745
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
746
-			->set('permissions', $qb->createNamedParameter($share->getPermissions()))
747
-			->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
748
-			->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
749
-			->set('password', $qb->createNamedParameter($share->getPassword()))
750
-			->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
751
-			->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
752
-			->set('note', $qb->createNamedParameter($share->getNote()))
753
-			->set('hide_download', $qb->createNamedParameter((int)$share->getHideDownload(), IQueryBuilder::PARAM_INT))
754
-			->execute();
755
-
756
-		if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
757
-			$this->sendNote($share);
758
-		}
759
-
760
-		return $share;
761
-	}
762
-
763
-	/**
764
-	 * @inheritdoc
765
-	 */
766
-	public function move(IShare $share, $recipient) {
767
-		/**
768
-		 * nothing to do here, mail shares are only outgoing shares
769
-		 */
770
-		return $share;
771
-	}
772
-
773
-	/**
774
-	 * Delete a share (owner unShares the file)
775
-	 *
776
-	 * @param IShare $share
777
-	 */
778
-	public function delete(IShare $share) {
779
-		try {
780
-			$this->createShareActivity($share, 'unshare');
781
-		} catch (\Exception $e) {
782
-		}
783
-
784
-		$this->removeShareFromTable($share->getId());
785
-	}
786
-
787
-	/**
788
-	 * @inheritdoc
789
-	 */
790
-	public function deleteFromSelf(IShare $share, $recipient) {
791
-		// nothing to do here, mail shares are only outgoing shares
792
-	}
793
-
794
-	public function restore(IShare $share, string $recipient): IShare {
795
-		throw new GenericShareException('not implemented');
796
-	}
797
-
798
-	/**
799
-	 * @inheritdoc
800
-	 */
801
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
802
-		$qb = $this->dbConnection->getQueryBuilder();
803
-		$qb->select('*')
804
-			->from('share');
805
-
806
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
807
-
808
-		/**
809
-		 * Reshares for this user are shares where they are the owner.
810
-		 */
811
-		if ($reshares === false) {
812
-			//Special case for old shares created via the web UI
813
-			$or1 = $qb->expr()->andX(
814
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
815
-				$qb->expr()->isNull('uid_initiator')
816
-			);
817
-
818
-			$qb->andWhere(
819
-				$qb->expr()->orX(
820
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
821
-					$or1
822
-				)
823
-			);
824
-		} else {
825
-			$qb->andWhere(
826
-				$qb->expr()->orX(
827
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
828
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
829
-				)
830
-			);
831
-		}
832
-
833
-		if ($node !== null) {
834
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
835
-		}
836
-
837
-		if ($limit !== -1) {
838
-			$qb->setMaxResults($limit);
839
-		}
840
-
841
-		$qb->setFirstResult($offset);
842
-		$qb->orderBy('id');
843
-
844
-		$cursor = $qb->execute();
845
-		$shares = [];
846
-		while($data = $cursor->fetch()) {
847
-			$shares[] = $this->createShareObject($data);
848
-		}
849
-		$cursor->closeCursor();
850
-
851
-		return $shares;
852
-	}
853
-
854
-	/**
855
-	 * @inheritdoc
856
-	 */
857
-	public function getShareById($id, $recipientId = null) {
858
-		$qb = $this->dbConnection->getQueryBuilder();
859
-
860
-		$qb->select('*')
861
-			->from('share')
862
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
863
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
864
-
865
-		$cursor = $qb->execute();
866
-		$data = $cursor->fetch();
867
-		$cursor->closeCursor();
868
-
869
-		if ($data === false) {
870
-			throw new ShareNotFound();
871
-		}
872
-
873
-		try {
874
-			$share = $this->createShareObject($data);
875
-		} catch (InvalidShare $e) {
876
-			throw new ShareNotFound();
877
-		}
878
-
879
-		return $share;
880
-	}
881
-
882
-	/**
883
-	 * Get shares for a given path
884
-	 *
885
-	 * @param \OCP\Files\Node $path
886
-	 * @return IShare[]
887
-	 */
888
-	public function getSharesByPath(Node $path) {
889
-		$qb = $this->dbConnection->getQueryBuilder();
890
-
891
-		$cursor = $qb->select('*')
892
-			->from('share')
893
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
894
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
895
-			->execute();
896
-
897
-		$shares = [];
898
-		while($data = $cursor->fetch()) {
899
-			$shares[] = $this->createShareObject($data);
900
-		}
901
-		$cursor->closeCursor();
902
-
903
-		return $shares;
904
-	}
905
-
906
-	/**
907
-	 * @inheritdoc
908
-	 */
909
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
910
-		/** @var IShare[] $shares */
911
-		$shares = [];
912
-
913
-		//Get shares directly with this user
914
-		$qb = $this->dbConnection->getQueryBuilder();
915
-		$qb->select('*')
916
-			->from('share');
917
-
918
-		// Order by id
919
-		$qb->orderBy('id');
920
-
921
-		// Set limit and offset
922
-		if ($limit !== -1) {
923
-			$qb->setMaxResults($limit);
924
-		}
925
-		$qb->setFirstResult($offset);
926
-
927
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
928
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
929
-
930
-		// Filter by node if provided
931
-		if ($node !== null) {
932
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
933
-		}
934
-
935
-		$cursor = $qb->execute();
936
-
937
-		while($data = $cursor->fetch()) {
938
-			$shares[] = $this->createShareObject($data);
939
-		}
940
-		$cursor->closeCursor();
941
-
942
-
943
-		return $shares;
944
-	}
945
-
946
-	/**
947
-	 * Get a share by token
948
-	 *
949
-	 * @param string $token
950
-	 * @return IShare
951
-	 * @throws ShareNotFound
952
-	 */
953
-	public function getShareByToken($token) {
954
-		$qb = $this->dbConnection->getQueryBuilder();
955
-
956
-		$cursor = $qb->select('*')
957
-			->from('share')
958
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
959
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
960
-			->execute();
961
-
962
-		$data = $cursor->fetch();
963
-
964
-		if ($data === false) {
965
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
966
-		}
967
-
968
-		try {
969
-			$share = $this->createShareObject($data);
970
-		} catch (InvalidShare $e) {
971
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
972
-		}
973
-
974
-		return $share;
975
-	}
976
-
977
-	/**
978
-	 * remove share from table
979
-	 *
980
-	 * @param string $shareId
981
-	 */
982
-	protected function removeShareFromTable($shareId) {
983
-		$qb = $this->dbConnection->getQueryBuilder();
984
-		$qb->delete('share')
985
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
986
-		$qb->execute();
987
-	}
988
-
989
-	/**
990
-	 * Create a share object from an database row
991
-	 *
992
-	 * @param array $data
993
-	 * @return IShare
994
-	 * @throws InvalidShare
995
-	 * @throws ShareNotFound
996
-	 */
997
-	protected function createShareObject($data) {
998
-
999
-		$share = new Share($this->rootFolder, $this->userManager);
1000
-		$share->setId((int)$data['id'])
1001
-			->setShareType((int)$data['share_type'])
1002
-			->setPermissions((int)$data['permissions'])
1003
-			->setTarget($data['file_target'])
1004
-			->setMailSend((bool)$data['mail_send'])
1005
-			->setNote($data['note'])
1006
-			->setToken($data['token']);
1007
-
1008
-		$shareTime = new \DateTime();
1009
-		$shareTime->setTimestamp((int)$data['stime']);
1010
-		$share->setShareTime($shareTime);
1011
-		$share->setSharedWith($data['share_with']);
1012
-		$share->setPassword($data['password']);
1013
-		$share->setSendPasswordByTalk((bool)$data['password_by_talk']);
1014
-		$share->setHideDownload((bool)$data['hide_download']);
1015
-
1016
-		if ($data['uid_initiator'] !== null) {
1017
-			$share->setShareOwner($data['uid_owner']);
1018
-			$share->setSharedBy($data['uid_initiator']);
1019
-		} else {
1020
-			//OLD SHARE
1021
-			$share->setSharedBy($data['uid_owner']);
1022
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
1023
-
1024
-			$owner = $path->getOwner();
1025
-			$share->setShareOwner($owner->getUID());
1026
-		}
1027
-
1028
-		if ($data['expiration'] !== null) {
1029
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
1030
-			if ($expiration !== false) {
1031
-				$share->setExpirationDate($expiration);
1032
-			}
1033
-		}
1034
-
1035
-		$share->setNodeId((int)$data['file_source']);
1036
-		$share->setNodeType($data['item_type']);
1037
-
1038
-		$share->setProviderId($this->identifier());
1039
-
1040
-		return $share;
1041
-	}
1042
-
1043
-	/**
1044
-	 * Get the node with file $id for $user
1045
-	 *
1046
-	 * @param string $userId
1047
-	 * @param int $id
1048
-	 * @return \OCP\Files\File|\OCP\Files\Folder
1049
-	 * @throws InvalidShare
1050
-	 */
1051
-	private function getNode($userId, $id) {
1052
-		try {
1053
-			$userFolder = $this->rootFolder->getUserFolder($userId);
1054
-		} catch (NoUserException $e) {
1055
-			throw new InvalidShare();
1056
-		}
1057
-
1058
-		$nodes = $userFolder->getById($id);
1059
-
1060
-		if (empty($nodes)) {
1061
-			throw new InvalidShare();
1062
-		}
1063
-
1064
-		return $nodes[0];
1065
-	}
1066
-
1067
-	/**
1068
-	 * A user is deleted from the system
1069
-	 * So clean up the relevant shares.
1070
-	 *
1071
-	 * @param string $uid
1072
-	 * @param int $shareType
1073
-	 */
1074
-	public function userDeleted($uid, $shareType) {
1075
-		$qb = $this->dbConnection->getQueryBuilder();
1076
-
1077
-		$qb->delete('share')
1078
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
1079
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
1080
-			->execute();
1081
-	}
1082
-
1083
-	/**
1084
-	 * This provider does not support group shares
1085
-	 *
1086
-	 * @param string $gid
1087
-	 */
1088
-	public function groupDeleted($gid) {
1089
-	}
1090
-
1091
-	/**
1092
-	 * This provider does not support group shares
1093
-	 *
1094
-	 * @param string $uid
1095
-	 * @param string $gid
1096
-	 */
1097
-	public function userDeletedFromGroup($uid, $gid) {
1098
-	}
1099
-
1100
-	/**
1101
-	 * get database row of a give share
1102
-	 *
1103
-	 * @param $id
1104
-	 * @return array
1105
-	 * @throws ShareNotFound
1106
-	 */
1107
-	protected function getRawShare($id) {
1108
-
1109
-		// Now fetch the inserted share and create a complete share object
1110
-		$qb = $this->dbConnection->getQueryBuilder();
1111
-		$qb->select('*')
1112
-			->from('share')
1113
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
1114
-
1115
-		$cursor = $qb->execute();
1116
-		$data = $cursor->fetch();
1117
-		$cursor->closeCursor();
1118
-
1119
-		if ($data === false) {
1120
-			throw new ShareNotFound;
1121
-		}
1122
-
1123
-		return $data;
1124
-	}
1125
-
1126
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
1127
-		$qb = $this->dbConnection->getQueryBuilder();
1128
-		$qb->select('*')
1129
-			->from('share', 's')
1130
-			->andWhere($qb->expr()->orX(
1131
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1132
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1133
-			))
1134
-			->andWhere(
1135
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
1136
-			);
1137
-
1138
-		/**
1139
-		 * Reshares for this user are shares where they are the owner.
1140
-		 */
1141
-		if ($reshares === false) {
1142
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
1143
-		} else {
1144
-			$qb->andWhere(
1145
-				$qb->expr()->orX(
1146
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
1147
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
1148
-				)
1149
-			);
1150
-		}
1151
-
1152
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
1153
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
1154
-
1155
-		$qb->orderBy('id');
1156
-
1157
-		$cursor = $qb->execute();
1158
-		$shares = [];
1159
-		while ($data = $cursor->fetch()) {
1160
-			$shares[$data['fileid']][] = $this->createShareObject($data);
1161
-		}
1162
-		$cursor->closeCursor();
1163
-
1164
-		return $shares;
1165
-	}
1166
-
1167
-	/**
1168
-	 * @inheritdoc
1169
-	 */
1170
-	public function getAccessList($nodes, $currentAccess) {
1171
-		$ids = [];
1172
-		foreach ($nodes as $node) {
1173
-			$ids[] = $node->getId();
1174
-		}
1175
-
1176
-		$qb = $this->dbConnection->getQueryBuilder();
1177
-		$qb->select('share_with')
1178
-			->from('share')
1179
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
1180
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1181
-			->andWhere($qb->expr()->orX(
1182
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1183
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1184
-			))
1185
-			->setMaxResults(1);
1186
-		$cursor = $qb->execute();
1187
-
1188
-		$mail = $cursor->fetch() !== false;
1189
-		$cursor->closeCursor();
1190
-
1191
-		return ['public' => $mail];
1192
-	}
1193
-
1194
-	public function getAllShares(): iterable {
1195
-		$qb = $this->dbConnection->getQueryBuilder();
1196
-
1197
-		$qb->select('*')
1198
-			->from('share')
1199
-			->where(
1200
-				$qb->expr()->orX(
1201
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_EMAIL))
1202
-				)
1203
-			);
1204
-
1205
-		$cursor = $qb->execute();
1206
-		while($data = $cursor->fetch()) {
1207
-			try {
1208
-				$share = $this->createShareObject($data);
1209
-			} catch (InvalidShare $e) {
1210
-				continue;
1211
-			} catch (ShareNotFound $e) {
1212
-				continue;
1213
-			}
1214
-
1215
-			yield $share;
1216
-		}
1217
-		$cursor->closeCursor();
1218
-	}
743
+        $qb = $this->dbConnection->getQueryBuilder();
744
+        $qb->update('share')
745
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
746
+            ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
747
+            ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
748
+            ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
749
+            ->set('password', $qb->createNamedParameter($share->getPassword()))
750
+            ->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
751
+            ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
752
+            ->set('note', $qb->createNamedParameter($share->getNote()))
753
+            ->set('hide_download', $qb->createNamedParameter((int)$share->getHideDownload(), IQueryBuilder::PARAM_INT))
754
+            ->execute();
755
+
756
+        if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
757
+            $this->sendNote($share);
758
+        }
759
+
760
+        return $share;
761
+    }
762
+
763
+    /**
764
+     * @inheritdoc
765
+     */
766
+    public function move(IShare $share, $recipient) {
767
+        /**
768
+         * nothing to do here, mail shares are only outgoing shares
769
+         */
770
+        return $share;
771
+    }
772
+
773
+    /**
774
+     * Delete a share (owner unShares the file)
775
+     *
776
+     * @param IShare $share
777
+     */
778
+    public function delete(IShare $share) {
779
+        try {
780
+            $this->createShareActivity($share, 'unshare');
781
+        } catch (\Exception $e) {
782
+        }
783
+
784
+        $this->removeShareFromTable($share->getId());
785
+    }
786
+
787
+    /**
788
+     * @inheritdoc
789
+     */
790
+    public function deleteFromSelf(IShare $share, $recipient) {
791
+        // nothing to do here, mail shares are only outgoing shares
792
+    }
793
+
794
+    public function restore(IShare $share, string $recipient): IShare {
795
+        throw new GenericShareException('not implemented');
796
+    }
797
+
798
+    /**
799
+     * @inheritdoc
800
+     */
801
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
802
+        $qb = $this->dbConnection->getQueryBuilder();
803
+        $qb->select('*')
804
+            ->from('share');
805
+
806
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
807
+
808
+        /**
809
+         * Reshares for this user are shares where they are the owner.
810
+         */
811
+        if ($reshares === false) {
812
+            //Special case for old shares created via the web UI
813
+            $or1 = $qb->expr()->andX(
814
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
815
+                $qb->expr()->isNull('uid_initiator')
816
+            );
817
+
818
+            $qb->andWhere(
819
+                $qb->expr()->orX(
820
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
821
+                    $or1
822
+                )
823
+            );
824
+        } else {
825
+            $qb->andWhere(
826
+                $qb->expr()->orX(
827
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
828
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
829
+                )
830
+            );
831
+        }
832
+
833
+        if ($node !== null) {
834
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
835
+        }
836
+
837
+        if ($limit !== -1) {
838
+            $qb->setMaxResults($limit);
839
+        }
840
+
841
+        $qb->setFirstResult($offset);
842
+        $qb->orderBy('id');
843
+
844
+        $cursor = $qb->execute();
845
+        $shares = [];
846
+        while($data = $cursor->fetch()) {
847
+            $shares[] = $this->createShareObject($data);
848
+        }
849
+        $cursor->closeCursor();
850
+
851
+        return $shares;
852
+    }
853
+
854
+    /**
855
+     * @inheritdoc
856
+     */
857
+    public function getShareById($id, $recipientId = null) {
858
+        $qb = $this->dbConnection->getQueryBuilder();
859
+
860
+        $qb->select('*')
861
+            ->from('share')
862
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
863
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
864
+
865
+        $cursor = $qb->execute();
866
+        $data = $cursor->fetch();
867
+        $cursor->closeCursor();
868
+
869
+        if ($data === false) {
870
+            throw new ShareNotFound();
871
+        }
872
+
873
+        try {
874
+            $share = $this->createShareObject($data);
875
+        } catch (InvalidShare $e) {
876
+            throw new ShareNotFound();
877
+        }
878
+
879
+        return $share;
880
+    }
881
+
882
+    /**
883
+     * Get shares for a given path
884
+     *
885
+     * @param \OCP\Files\Node $path
886
+     * @return IShare[]
887
+     */
888
+    public function getSharesByPath(Node $path) {
889
+        $qb = $this->dbConnection->getQueryBuilder();
890
+
891
+        $cursor = $qb->select('*')
892
+            ->from('share')
893
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
894
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
895
+            ->execute();
896
+
897
+        $shares = [];
898
+        while($data = $cursor->fetch()) {
899
+            $shares[] = $this->createShareObject($data);
900
+        }
901
+        $cursor->closeCursor();
902
+
903
+        return $shares;
904
+    }
905
+
906
+    /**
907
+     * @inheritdoc
908
+     */
909
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
910
+        /** @var IShare[] $shares */
911
+        $shares = [];
912
+
913
+        //Get shares directly with this user
914
+        $qb = $this->dbConnection->getQueryBuilder();
915
+        $qb->select('*')
916
+            ->from('share');
917
+
918
+        // Order by id
919
+        $qb->orderBy('id');
920
+
921
+        // Set limit and offset
922
+        if ($limit !== -1) {
923
+            $qb->setMaxResults($limit);
924
+        }
925
+        $qb->setFirstResult($offset);
926
+
927
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
928
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
929
+
930
+        // Filter by node if provided
931
+        if ($node !== null) {
932
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
933
+        }
934
+
935
+        $cursor = $qb->execute();
936
+
937
+        while($data = $cursor->fetch()) {
938
+            $shares[] = $this->createShareObject($data);
939
+        }
940
+        $cursor->closeCursor();
941
+
942
+
943
+        return $shares;
944
+    }
945
+
946
+    /**
947
+     * Get a share by token
948
+     *
949
+     * @param string $token
950
+     * @return IShare
951
+     * @throws ShareNotFound
952
+     */
953
+    public function getShareByToken($token) {
954
+        $qb = $this->dbConnection->getQueryBuilder();
955
+
956
+        $cursor = $qb->select('*')
957
+            ->from('share')
958
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
959
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
960
+            ->execute();
961
+
962
+        $data = $cursor->fetch();
963
+
964
+        if ($data === false) {
965
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
966
+        }
967
+
968
+        try {
969
+            $share = $this->createShareObject($data);
970
+        } catch (InvalidShare $e) {
971
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
972
+        }
973
+
974
+        return $share;
975
+    }
976
+
977
+    /**
978
+     * remove share from table
979
+     *
980
+     * @param string $shareId
981
+     */
982
+    protected function removeShareFromTable($shareId) {
983
+        $qb = $this->dbConnection->getQueryBuilder();
984
+        $qb->delete('share')
985
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
986
+        $qb->execute();
987
+    }
988
+
989
+    /**
990
+     * Create a share object from an database row
991
+     *
992
+     * @param array $data
993
+     * @return IShare
994
+     * @throws InvalidShare
995
+     * @throws ShareNotFound
996
+     */
997
+    protected function createShareObject($data) {
998
+
999
+        $share = new Share($this->rootFolder, $this->userManager);
1000
+        $share->setId((int)$data['id'])
1001
+            ->setShareType((int)$data['share_type'])
1002
+            ->setPermissions((int)$data['permissions'])
1003
+            ->setTarget($data['file_target'])
1004
+            ->setMailSend((bool)$data['mail_send'])
1005
+            ->setNote($data['note'])
1006
+            ->setToken($data['token']);
1007
+
1008
+        $shareTime = new \DateTime();
1009
+        $shareTime->setTimestamp((int)$data['stime']);
1010
+        $share->setShareTime($shareTime);
1011
+        $share->setSharedWith($data['share_with']);
1012
+        $share->setPassword($data['password']);
1013
+        $share->setSendPasswordByTalk((bool)$data['password_by_talk']);
1014
+        $share->setHideDownload((bool)$data['hide_download']);
1015
+
1016
+        if ($data['uid_initiator'] !== null) {
1017
+            $share->setShareOwner($data['uid_owner']);
1018
+            $share->setSharedBy($data['uid_initiator']);
1019
+        } else {
1020
+            //OLD SHARE
1021
+            $share->setSharedBy($data['uid_owner']);
1022
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
1023
+
1024
+            $owner = $path->getOwner();
1025
+            $share->setShareOwner($owner->getUID());
1026
+        }
1027
+
1028
+        if ($data['expiration'] !== null) {
1029
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
1030
+            if ($expiration !== false) {
1031
+                $share->setExpirationDate($expiration);
1032
+            }
1033
+        }
1034
+
1035
+        $share->setNodeId((int)$data['file_source']);
1036
+        $share->setNodeType($data['item_type']);
1037
+
1038
+        $share->setProviderId($this->identifier());
1039
+
1040
+        return $share;
1041
+    }
1042
+
1043
+    /**
1044
+     * Get the node with file $id for $user
1045
+     *
1046
+     * @param string $userId
1047
+     * @param int $id
1048
+     * @return \OCP\Files\File|\OCP\Files\Folder
1049
+     * @throws InvalidShare
1050
+     */
1051
+    private function getNode($userId, $id) {
1052
+        try {
1053
+            $userFolder = $this->rootFolder->getUserFolder($userId);
1054
+        } catch (NoUserException $e) {
1055
+            throw new InvalidShare();
1056
+        }
1057
+
1058
+        $nodes = $userFolder->getById($id);
1059
+
1060
+        if (empty($nodes)) {
1061
+            throw new InvalidShare();
1062
+        }
1063
+
1064
+        return $nodes[0];
1065
+    }
1066
+
1067
+    /**
1068
+     * A user is deleted from the system
1069
+     * So clean up the relevant shares.
1070
+     *
1071
+     * @param string $uid
1072
+     * @param int $shareType
1073
+     */
1074
+    public function userDeleted($uid, $shareType) {
1075
+        $qb = $this->dbConnection->getQueryBuilder();
1076
+
1077
+        $qb->delete('share')
1078
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
1079
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
1080
+            ->execute();
1081
+    }
1082
+
1083
+    /**
1084
+     * This provider does not support group shares
1085
+     *
1086
+     * @param string $gid
1087
+     */
1088
+    public function groupDeleted($gid) {
1089
+    }
1090
+
1091
+    /**
1092
+     * This provider does not support group shares
1093
+     *
1094
+     * @param string $uid
1095
+     * @param string $gid
1096
+     */
1097
+    public function userDeletedFromGroup($uid, $gid) {
1098
+    }
1099
+
1100
+    /**
1101
+     * get database row of a give share
1102
+     *
1103
+     * @param $id
1104
+     * @return array
1105
+     * @throws ShareNotFound
1106
+     */
1107
+    protected function getRawShare($id) {
1108
+
1109
+        // Now fetch the inserted share and create a complete share object
1110
+        $qb = $this->dbConnection->getQueryBuilder();
1111
+        $qb->select('*')
1112
+            ->from('share')
1113
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
1114
+
1115
+        $cursor = $qb->execute();
1116
+        $data = $cursor->fetch();
1117
+        $cursor->closeCursor();
1118
+
1119
+        if ($data === false) {
1120
+            throw new ShareNotFound;
1121
+        }
1122
+
1123
+        return $data;
1124
+    }
1125
+
1126
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
1127
+        $qb = $this->dbConnection->getQueryBuilder();
1128
+        $qb->select('*')
1129
+            ->from('share', 's')
1130
+            ->andWhere($qb->expr()->orX(
1131
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1132
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1133
+            ))
1134
+            ->andWhere(
1135
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
1136
+            );
1137
+
1138
+        /**
1139
+         * Reshares for this user are shares where they are the owner.
1140
+         */
1141
+        if ($reshares === false) {
1142
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
1143
+        } else {
1144
+            $qb->andWhere(
1145
+                $qb->expr()->orX(
1146
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
1147
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
1148
+                )
1149
+            );
1150
+        }
1151
+
1152
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
1153
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
1154
+
1155
+        $qb->orderBy('id');
1156
+
1157
+        $cursor = $qb->execute();
1158
+        $shares = [];
1159
+        while ($data = $cursor->fetch()) {
1160
+            $shares[$data['fileid']][] = $this->createShareObject($data);
1161
+        }
1162
+        $cursor->closeCursor();
1163
+
1164
+        return $shares;
1165
+    }
1166
+
1167
+    /**
1168
+     * @inheritdoc
1169
+     */
1170
+    public function getAccessList($nodes, $currentAccess) {
1171
+        $ids = [];
1172
+        foreach ($nodes as $node) {
1173
+            $ids[] = $node->getId();
1174
+        }
1175
+
1176
+        $qb = $this->dbConnection->getQueryBuilder();
1177
+        $qb->select('share_with')
1178
+            ->from('share')
1179
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
1180
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1181
+            ->andWhere($qb->expr()->orX(
1182
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1183
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1184
+            ))
1185
+            ->setMaxResults(1);
1186
+        $cursor = $qb->execute();
1187
+
1188
+        $mail = $cursor->fetch() !== false;
1189
+        $cursor->closeCursor();
1190
+
1191
+        return ['public' => $mail];
1192
+    }
1193
+
1194
+    public function getAllShares(): iterable {
1195
+        $qb = $this->dbConnection->getQueryBuilder();
1196
+
1197
+        $qb->select('*')
1198
+            ->from('share')
1199
+            ->where(
1200
+                $qb->expr()->orX(
1201
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_EMAIL))
1202
+                )
1203
+            );
1204
+
1205
+        $cursor = $qb->execute();
1206
+        while($data = $cursor->fetch()) {
1207
+            try {
1208
+                $share = $this->createShareObject($data);
1209
+            } catch (InvalidShare $e) {
1210
+                continue;
1211
+            } catch (ShareNotFound $e) {
1212
+                continue;
1213
+            }
1214
+
1215
+            yield $share;
1216
+        }
1217
+        $cursor->closeCursor();
1218
+    }
1219 1219
 }
Please login to merge, or discard this patch.
apps/provisioning_api/lib/AppInfo/Application.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -36,35 +36,35 @@
 block discarded – undo
36 36
 use OCP\Util;
37 37
 
38 38
 class Application extends App {
39
-	public function __construct(array $urlParams = []) {
40
-		parent::__construct('provisioning_api', $urlParams);
39
+    public function __construct(array $urlParams = []) {
40
+        parent::__construct('provisioning_api', $urlParams);
41 41
 
42
-		$container = $this->getContainer();
43
-		$server = $container->getServer();
42
+        $container = $this->getContainer();
43
+        $server = $container->getServer();
44 44
 
45
-		$container->registerService(NewUserMailHelper::class, function(SimpleContainer $c) use ($server) {
46
-			return new NewUserMailHelper(
47
-				$server->query(Defaults::class),
48
-				$server->getURLGenerator(),
49
-				$server->getL10NFactory(),
50
-				$server->getMailer(),
51
-				$server->getSecureRandom(),
52
-				new TimeFactory(),
53
-				$server->getConfig(),
54
-				$server->getCrypto(),
55
-				Util::getDefaultEmailAddress('no-reply')
56
-			);
57
-		});
58
-		$container->registerService('ProvisioningApiMiddleware', function(SimpleContainer $c) use ($server) {
59
-			$user = $server->getUserManager()->get($c['UserId']);
60
-			$isAdmin = $user !== null ? $server->getGroupManager()->isAdmin($user->getUID()) : false;
61
-			$isSubAdmin = $user !== null ? $server->getGroupManager()->getSubAdmin()->isSubAdmin($user) : false;
62
-			return new ProvisioningApiMiddleware(
63
-				$c->query(IControllerMethodReflector::class),
64
-				$isAdmin,
65
-				$isSubAdmin
66
-			);
67
-		});
68
-		$container->registerMiddleWare('ProvisioningApiMiddleware');
69
-	}
45
+        $container->registerService(NewUserMailHelper::class, function(SimpleContainer $c) use ($server) {
46
+            return new NewUserMailHelper(
47
+                $server->query(Defaults::class),
48
+                $server->getURLGenerator(),
49
+                $server->getL10NFactory(),
50
+                $server->getMailer(),
51
+                $server->getSecureRandom(),
52
+                new TimeFactory(),
53
+                $server->getConfig(),
54
+                $server->getCrypto(),
55
+                Util::getDefaultEmailAddress('no-reply')
56
+            );
57
+        });
58
+        $container->registerService('ProvisioningApiMiddleware', function(SimpleContainer $c) use ($server) {
59
+            $user = $server->getUserManager()->get($c['UserId']);
60
+            $isAdmin = $user !== null ? $server->getGroupManager()->isAdmin($user->getUID()) : false;
61
+            $isSubAdmin = $user !== null ? $server->getGroupManager()->getSubAdmin()->isSubAdmin($user) : false;
62
+            return new ProvisioningApiMiddleware(
63
+                $c->query(IControllerMethodReflector::class),
64
+                $isAdmin,
65
+                $isSubAdmin
66
+            );
67
+        });
68
+        $container->registerMiddleWare('ProvisioningApiMiddleware');
69
+    }
70 70
 }
Please login to merge, or discard this patch.
apps/files_external/ajax/applicable.php 1 patch
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -32,23 +32,23 @@
 block discarded – undo
32 32
 $limit = null;
33 33
 $offset = null;
34 34
 if (isset($_GET['pattern'])) {
35
-	$pattern = (string)$_GET['pattern'];
35
+    $pattern = (string)$_GET['pattern'];
36 36
 }
37 37
 if (isset($_GET['limit'])) {
38
-	$limit = (int)$_GET['limit'];
38
+    $limit = (int)$_GET['limit'];
39 39
 }
40 40
 if (isset($_GET['offset'])) {
41
-	$offset = (int)$_GET['offset'];
41
+    $offset = (int)$_GET['offset'];
42 42
 }
43 43
 
44 44
 $groups = [];
45 45
 foreach (\OC::$server->getGroupManager()->search($pattern, $limit, $offset) as $group) {
46
-	$groups[$group->getGID()] = $group->getDisplayName();
46
+    $groups[$group->getGID()] = $group->getDisplayName();
47 47
 }
48 48
 
49 49
 $users = [];
50 50
 foreach (\OC::$server->getUserManager()->searchDisplayName($pattern, $limit, $offset) as $user) {
51
-	$users[$user->getUID()] = $user->getDisplayName();
51
+    $users[$user->getUID()] = $user->getDisplayName();
52 52
 }
53 53
 
54 54
 $results = ['groups' => $groups, 'users' => $users];
Please login to merge, or discard this patch.