Completed
Pull Request — master (#6779)
by Blizzz
12:08
created
core/routes.php 1 patch
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -35,41 +35,41 @@  discard block
 block discarded – undo
35 35
 
36 36
 $application = new Application();
37 37
 $application->registerRoutes($this, [
38
-	'routes' => [
39
-		['name' => 'lost#email', 'url' => '/lostpassword/email', 'verb' => 'POST'],
40
-		['name' => 'lost#resetform', 'url' => '/lostpassword/reset/form/{token}/{userId}', 'verb' => 'GET'],
41
-		['name' => 'lost#setPassword', 'url' => '/lostpassword/set/{token}/{userId}', 'verb' => 'POST'],
42
-		['name' => 'user#getDisplayNames', 'url' => '/displaynames', 'verb' => 'POST'],
43
-		['name' => 'avatar#getAvatar', 'url' => '/avatar/{userId}/{size}', 'verb' => 'GET'],
44
-		['name' => 'avatar#deleteAvatar', 'url' => '/avatar/', 'verb' => 'DELETE'],
45
-		['name' => 'avatar#postCroppedAvatar', 'url' => '/avatar/cropped', 'verb' => 'POST'],
46
-		['name' => 'avatar#getTmpAvatar', 'url' => '/avatar/tmp', 'verb' => 'GET'],
47
-		['name' => 'avatar#postAvatar', 'url' => '/avatar/', 'verb' => 'POST'],
48
-		['name' => 'login#tryLogin', 'url' => '/login', 'verb' => 'POST'],
49
-		['name' => 'login#confirmPassword', 'url' => '/login/confirm', 'verb' => 'POST'],
50
-		['name' => 'login#showLoginForm', 'url' => '/login', 'verb' => 'GET'],
51
-		['name' => 'login#logout', 'url' => '/logout', 'verb' => 'GET'],
52
-		['name' => 'ClientFlowLogin#showAuthPickerPage', 'url' => '/login/flow', 'verb' => 'GET'],
53
-		['name' => 'ClientFlowLogin#redirectPage', 'url' => '/login/flow/redirect', 'verb' => 'GET'],
54
-		['name' => 'ClientFlowLogin#generateAppPassword', 'url' => '/login/flow', 'verb' => 'POST'],
55
-		['name' => 'TwoFactorChallenge#selectChallenge', 'url' => '/login/selectchallenge', 'verb' => 'GET'],
56
-		['name' => 'TwoFactorChallenge#showChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'GET'],
57
-		['name' => 'TwoFactorChallenge#solveChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'POST'],
58
-		['name' => 'OCJS#getConfig', 'url' => '/core/js/oc.js', 'verb' => 'GET'],
59
-		['name' => 'Preview#getPreview', 'url' => '/core/preview', 'verb' => 'GET'],
60
-		['name' => 'Preview#getPreview', 'url' => '/core/preview.png', 'verb' => 'GET'],
61
-		['name' => 'Css#getCss', 'url' => '/css/{appName}/{fileName}', 'verb' => 'GET'],
62
-		['name' => 'Js#getJs', 'url' => '/js/{appName}/{fileName}', 'verb' => 'GET'],
63
-		['name' => 'contactsMenu#index', 'url' => '/contactsmenu/contacts', 'verb' => 'POST'],
64
-		['name' => 'contactsMenu#findOne', 'url' => '/contactsmenu/findOne', 'verb' => 'POST'],
65
-		['name' => 'AutoComplete#get', 'url' => 'autocomplete/get', 'verb' => 'GET']
66
-	],
67
-	'ocs' => [
68
-		['root' => '/cloud', 'name' => 'OCS#getCapabilities', 'url' => '/capabilities', 'verb' => 'GET'],
69
-		['root' => '', 'name' => 'OCS#getConfig', 'url' => '/config', 'verb' => 'GET'],
70
-		['root' => '/person', 'name' => 'OCS#personCheck', 'url' => '/check', 'verb' => 'POST'],
71
-		['root' => '/identityproof', 'name' => 'OCS#getIdentityProof', 'url' => '/key/{cloudId}', 'verb' => 'GET'],
72
-	],
38
+    'routes' => [
39
+        ['name' => 'lost#email', 'url' => '/lostpassword/email', 'verb' => 'POST'],
40
+        ['name' => 'lost#resetform', 'url' => '/lostpassword/reset/form/{token}/{userId}', 'verb' => 'GET'],
41
+        ['name' => 'lost#setPassword', 'url' => '/lostpassword/set/{token}/{userId}', 'verb' => 'POST'],
42
+        ['name' => 'user#getDisplayNames', 'url' => '/displaynames', 'verb' => 'POST'],
43
+        ['name' => 'avatar#getAvatar', 'url' => '/avatar/{userId}/{size}', 'verb' => 'GET'],
44
+        ['name' => 'avatar#deleteAvatar', 'url' => '/avatar/', 'verb' => 'DELETE'],
45
+        ['name' => 'avatar#postCroppedAvatar', 'url' => '/avatar/cropped', 'verb' => 'POST'],
46
+        ['name' => 'avatar#getTmpAvatar', 'url' => '/avatar/tmp', 'verb' => 'GET'],
47
+        ['name' => 'avatar#postAvatar', 'url' => '/avatar/', 'verb' => 'POST'],
48
+        ['name' => 'login#tryLogin', 'url' => '/login', 'verb' => 'POST'],
49
+        ['name' => 'login#confirmPassword', 'url' => '/login/confirm', 'verb' => 'POST'],
50
+        ['name' => 'login#showLoginForm', 'url' => '/login', 'verb' => 'GET'],
51
+        ['name' => 'login#logout', 'url' => '/logout', 'verb' => 'GET'],
52
+        ['name' => 'ClientFlowLogin#showAuthPickerPage', 'url' => '/login/flow', 'verb' => 'GET'],
53
+        ['name' => 'ClientFlowLogin#redirectPage', 'url' => '/login/flow/redirect', 'verb' => 'GET'],
54
+        ['name' => 'ClientFlowLogin#generateAppPassword', 'url' => '/login/flow', 'verb' => 'POST'],
55
+        ['name' => 'TwoFactorChallenge#selectChallenge', 'url' => '/login/selectchallenge', 'verb' => 'GET'],
56
+        ['name' => 'TwoFactorChallenge#showChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'GET'],
57
+        ['name' => 'TwoFactorChallenge#solveChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'POST'],
58
+        ['name' => 'OCJS#getConfig', 'url' => '/core/js/oc.js', 'verb' => 'GET'],
59
+        ['name' => 'Preview#getPreview', 'url' => '/core/preview', 'verb' => 'GET'],
60
+        ['name' => 'Preview#getPreview', 'url' => '/core/preview.png', 'verb' => 'GET'],
61
+        ['name' => 'Css#getCss', 'url' => '/css/{appName}/{fileName}', 'verb' => 'GET'],
62
+        ['name' => 'Js#getJs', 'url' => '/js/{appName}/{fileName}', 'verb' => 'GET'],
63
+        ['name' => 'contactsMenu#index', 'url' => '/contactsmenu/contacts', 'verb' => 'POST'],
64
+        ['name' => 'contactsMenu#findOne', 'url' => '/contactsmenu/findOne', 'verb' => 'POST'],
65
+        ['name' => 'AutoComplete#get', 'url' => 'autocomplete/get', 'verb' => 'GET']
66
+    ],
67
+    'ocs' => [
68
+        ['root' => '/cloud', 'name' => 'OCS#getCapabilities', 'url' => '/capabilities', 'verb' => 'GET'],
69
+        ['root' => '', 'name' => 'OCS#getConfig', 'url' => '/config', 'verb' => 'GET'],
70
+        ['root' => '/person', 'name' => 'OCS#personCheck', 'url' => '/check', 'verb' => 'POST'],
71
+        ['root' => '/identityproof', 'name' => 'OCS#getIdentityProof', 'url' => '/key/{cloudId}', 'verb' => 'GET'],
72
+    ],
73 73
 ]);
74 74
 
75 75
 // Post installation check
@@ -78,15 +78,15 @@  discard block
 block discarded – undo
78 78
 // Core ajax actions
79 79
 // Search
80 80
 $this->create('search_ajax_search', '/core/search')
81
-	->actionInclude('core/search/ajax/search.php');
81
+    ->actionInclude('core/search/ajax/search.php');
82 82
 // Routing
83 83
 $this->create('core_ajax_update', '/core/ajax/update.php')
84
-	->actionInclude('core/ajax/update.php');
84
+    ->actionInclude('core/ajax/update.php');
85 85
 
86 86
 // File routes
87 87
 $this->create('files.viewcontroller.showFile', '/f/{fileid}')->action(function($urlParams) {
88
-	$app = new \OCA\Files\AppInfo\Application($urlParams);
89
-	$app->dispatch('ViewController', 'index');
88
+    $app = new \OCA\Files\AppInfo\Application($urlParams);
89
+    $app->dispatch('ViewController', 'index');
90 90
 });
91 91
 
92 92
 // Call routes
@@ -95,57 +95,57 @@  discard block
 block discarded – undo
95 95
  * @suppress PhanUndeclaredClassMethod
96 96
  */
97 97
 $this->create('spreed.pagecontroller.showCall', '/call/{token}')->action(function($urlParams) {
98
-	if (class_exists(\OCA\Spreed\AppInfo\Application::class, false)) {
99
-		$app = new \OCA\Spreed\AppInfo\Application($urlParams);
100
-		$app->dispatch('PageController', 'index');
101
-	} else {
102
-		throw new \OC\HintException('App spreed is not enabled');
103
-	}
98
+    if (class_exists(\OCA\Spreed\AppInfo\Application::class, false)) {
99
+        $app = new \OCA\Spreed\AppInfo\Application($urlParams);
100
+        $app->dispatch('PageController', 'index');
101
+    } else {
102
+        throw new \OC\HintException('App spreed is not enabled');
103
+    }
104 104
 });
105 105
 
106 106
 // Sharing routes
107 107
 $this->create('files_sharing.sharecontroller.showShare', '/s/{token}')->action(function($urlParams) {
108
-	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
109
-		$app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
110
-		$app->dispatch('ShareController', 'showShare');
111
-	} else {
112
-		throw new \OC\HintException('App file sharing is not enabled');
113
-	}
108
+    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
109
+        $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
110
+        $app->dispatch('ShareController', 'showShare');
111
+    } else {
112
+        throw new \OC\HintException('App file sharing is not enabled');
113
+    }
114 114
 });
115 115
 $this->create('files_sharing.sharecontroller.authenticate', '/s/{token}/authenticate')->post()->action(function($urlParams) {
116
-	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
117
-		$app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
118
-		$app->dispatch('ShareController', 'authenticate');
119
-	} else {
120
-		throw new \OC\HintException('App file sharing is not enabled');
121
-	}
116
+    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
117
+        $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
118
+        $app->dispatch('ShareController', 'authenticate');
119
+    } else {
120
+        throw new \OC\HintException('App file sharing is not enabled');
121
+    }
122 122
 });
123 123
 $this->create('files_sharing.sharecontroller.showAuthenticate', '/s/{token}/authenticate')->get()->action(function($urlParams) {
124
-	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
125
-		$app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
126
-		$app->dispatch('ShareController', 'showAuthenticate');
127
-	} else {
128
-		throw new \OC\HintException('App file sharing is not enabled');
129
-	}
124
+    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
125
+        $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
126
+        $app->dispatch('ShareController', 'showAuthenticate');
127
+    } else {
128
+        throw new \OC\HintException('App file sharing is not enabled');
129
+    }
130 130
 });
131 131
 $this->create('files_sharing.sharecontroller.downloadShare', '/s/{token}/download')->get()->action(function($urlParams) {
132
-	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
133
-		$app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
134
-		$app->dispatch('ShareController', 'downloadShare');
135
-	} else {
136
-		throw new \OC\HintException('App file sharing is not enabled');
137
-	}
132
+    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
133
+        $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
134
+        $app->dispatch('ShareController', 'downloadShare');
135
+    } else {
136
+        throw new \OC\HintException('App file sharing is not enabled');
137
+    }
138 138
 });
139 139
 $this->create('files_sharing.publicpreview.directLink', '/s/{token}/preview')->get()->action(function($urlParams) {
140
-	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
141
-		$app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
142
-		$app->dispatch('PublicPreviewController', 'directLink');
143
-	} else {
144
-		throw new \OC\HintException('App file sharing is not enabled');
145
-	}
140
+    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
141
+        $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
142
+        $app->dispatch('PublicPreviewController', 'directLink');
143
+    } else {
144
+        throw new \OC\HintException('App file sharing is not enabled');
145
+    }
146 146
 });
147 147
 
148 148
 // used for heartbeat
149 149
 $this->create('heartbeat', '/heartbeat')->action(function(){
150
-	// do nothing
150
+    // do nothing
151 151
 });
Please login to merge, or discard this patch.
lib/public/Comments/ICommentsManager.php 1 patch
Indentation   +254 added lines, -254 removed lines patch added patch discarded remove patch
@@ -35,277 +35,277 @@
 block discarded – undo
35 35
  */
36 36
 interface ICommentsManager {
37 37
 
38
-	/**
39
-	 * @const DELETED_USER type and id for a user that has been deleted
40
-	 * @see deleteReferencesOfActor
41
-	 * @since 9.0.0
42
-	 *
43
-	 * To be used as replacement for user type actors in deleteReferencesOfActor().
44
-	 *
45
-	 * User interfaces shall show "Deleted user" as display name, if needed.
46
-	 */
47
-	const DELETED_USER = 'deleted_users';
38
+    /**
39
+     * @const DELETED_USER type and id for a user that has been deleted
40
+     * @see deleteReferencesOfActor
41
+     * @since 9.0.0
42
+     *
43
+     * To be used as replacement for user type actors in deleteReferencesOfActor().
44
+     *
45
+     * User interfaces shall show "Deleted user" as display name, if needed.
46
+     */
47
+    const DELETED_USER = 'deleted_users';
48 48
 
49
-	/**
50
-	 * returns a comment instance
51
-	 *
52
-	 * @param string $id the ID of the comment
53
-	 * @return IComment
54
-	 * @throws NotFoundException
55
-	 * @since 9.0.0
56
-	 */
57
-	public function get($id);
49
+    /**
50
+     * returns a comment instance
51
+     *
52
+     * @param string $id the ID of the comment
53
+     * @return IComment
54
+     * @throws NotFoundException
55
+     * @since 9.0.0
56
+     */
57
+    public function get($id);
58 58
 
59
-	/**
60
-	 * returns the comment specified by the id and all it's child comments
61
-	 *
62
-	 * @param string $id
63
-	 * @param int $limit max number of entries to return, 0 returns all
64
-	 * @param int $offset the start entry
65
-	 * @return array
66
-	 * @since 9.0.0
67
-	 *
68
-	 * The return array looks like this
69
-	 * [
70
-	 * 	 'comment' => IComment, // root comment
71
-	 *   'replies' =>
72
-	 *   [
73
-	 *     0 =>
74
-	 *     [
75
-	 *       'comment' => IComment,
76
-	 *       'replies' =>
77
-	 *       [
78
-	 *         0 =>
79
-	 *         [
80
-	 *           'comment' => IComment,
81
-	 *           'replies' => [ … ]
82
-	 *         ],
83
-	 *         …
84
-	 *       ]
85
-	 *     ]
86
-	 *     1 =>
87
-	 *     [
88
-	 *       'comment' => IComment,
89
-	 *       'replies'=> [ … ]
90
-	 *     ],
91
-	 *     …
92
-	 *   ]
93
-	 * ]
94
-	 */
95
-	public function getTree($id, $limit = 0, $offset = 0);
59
+    /**
60
+     * returns the comment specified by the id and all it's child comments
61
+     *
62
+     * @param string $id
63
+     * @param int $limit max number of entries to return, 0 returns all
64
+     * @param int $offset the start entry
65
+     * @return array
66
+     * @since 9.0.0
67
+     *
68
+     * The return array looks like this
69
+     * [
70
+     * 	 'comment' => IComment, // root comment
71
+     *   'replies' =>
72
+     *   [
73
+     *     0 =>
74
+     *     [
75
+     *       'comment' => IComment,
76
+     *       'replies' =>
77
+     *       [
78
+     *         0 =>
79
+     *         [
80
+     *           'comment' => IComment,
81
+     *           'replies' => [ … ]
82
+     *         ],
83
+     *         …
84
+     *       ]
85
+     *     ]
86
+     *     1 =>
87
+     *     [
88
+     *       'comment' => IComment,
89
+     *       'replies'=> [ … ]
90
+     *     ],
91
+     *     …
92
+     *   ]
93
+     * ]
94
+     */
95
+    public function getTree($id, $limit = 0, $offset = 0);
96 96
 
97
-	/**
98
-	 * returns comments for a specific object (e.g. a file).
99
-	 *
100
-	 * The sort order is always newest to oldest.
101
-	 *
102
-	 * @param string $objectType the object type, e.g. 'files'
103
-	 * @param string $objectId the id of the object
104
-	 * @param int $limit optional, number of maximum comments to be returned. if
105
-	 * not specified, all comments are returned.
106
-	 * @param int $offset optional, starting point
107
-	 * @param \DateTime|null $notOlderThan optional, timestamp of the oldest comments
108
-	 * that may be returned
109
-	 * @return IComment[]
110
-	 * @since 9.0.0
111
-	 */
112
-	public function getForObject(
113
-			$objectType,
114
-			$objectId,
115
-			$limit = 0,
116
-			$offset = 0,
117
-			\DateTime $notOlderThan = null
118
-	);
97
+    /**
98
+     * returns comments for a specific object (e.g. a file).
99
+     *
100
+     * The sort order is always newest to oldest.
101
+     *
102
+     * @param string $objectType the object type, e.g. 'files'
103
+     * @param string $objectId the id of the object
104
+     * @param int $limit optional, number of maximum comments to be returned. if
105
+     * not specified, all comments are returned.
106
+     * @param int $offset optional, starting point
107
+     * @param \DateTime|null $notOlderThan optional, timestamp of the oldest comments
108
+     * that may be returned
109
+     * @return IComment[]
110
+     * @since 9.0.0
111
+     */
112
+    public function getForObject(
113
+            $objectType,
114
+            $objectId,
115
+            $limit = 0,
116
+            $offset = 0,
117
+            \DateTime $notOlderThan = null
118
+    );
119 119
 
120
-	/**
121
-	 * @param $objectType string the object type, e.g. 'files'
122
-	 * @param $objectId string the id of the object
123
-	 * @param \DateTime|null $notOlderThan optional, timestamp of the oldest comments
124
-	 * that may be returned
125
-	 * @return Int
126
-	 * @since 9.0.0
127
-	 */
128
-	public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null);
120
+    /**
121
+     * @param $objectType string the object type, e.g. 'files'
122
+     * @param $objectId string the id of the object
123
+     * @param \DateTime|null $notOlderThan optional, timestamp of the oldest comments
124
+     * that may be returned
125
+     * @return Int
126
+     * @since 9.0.0
127
+     */
128
+    public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null);
129 129
 
130
-	/**
131
-	 * Get the number of unread comments for all files in a folder
132
-	 *
133
-	 * @param int $folderId
134
-	 * @param IUser $user
135
-	 * @return array [$fileId => $unreadCount]
136
-	 * @since 12.0.0
137
-	 */
138
-	public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user);
130
+    /**
131
+     * Get the number of unread comments for all files in a folder
132
+     *
133
+     * @param int $folderId
134
+     * @param IUser $user
135
+     * @return array [$fileId => $unreadCount]
136
+     * @since 12.0.0
137
+     */
138
+    public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user);
139 139
 
140
-	/**
141
-	 * Get the actor types and ID that commented in the tree specified by the ID
142
-	 *
143
-	 * @param string $id
144
-	 * @return array
145
-	 * @since 13.0.0
146
-	 *
147
-	 * The return array looks like this:
148
-	 *
149
-	 * [
150
-	 *   'users' => [
151
-	 *     'alice',
152
-	 *     'bob',
153
-	 *   ],
154
-	 *   'robots' => [
155
-	 *     'r2-d2',
156
-	 *     'c-3po',
157
-	 *   ]
158
-	 * ]
159
-	 */
160
-	public function getActorsInTree($id);
140
+    /**
141
+     * Get the actor types and ID that commented in the tree specified by the ID
142
+     *
143
+     * @param string $id
144
+     * @return array
145
+     * @since 13.0.0
146
+     *
147
+     * The return array looks like this:
148
+     *
149
+     * [
150
+     *   'users' => [
151
+     *     'alice',
152
+     *     'bob',
153
+     *   ],
154
+     *   'robots' => [
155
+     *     'r2-d2',
156
+     *     'c-3po',
157
+     *   ]
158
+     * ]
159
+     */
160
+    public function getActorsInTree($id);
161 161
 
162
-	/**
163
-	 * creates a new comment and returns it. At this point of time, it is not
164
-	 * saved in the used data storage. Use save() after setting other fields
165
-	 * of the comment (e.g. message or verb).
166
-	 *
167
-	 * @param string $actorType the actor type (e.g. 'users')
168
-	 * @param string $actorId a user id
169
-	 * @param string $objectType the object type the comment is attached to
170
-	 * @param string $objectId the object id the comment is attached to
171
-	 * @return IComment
172
-	 * @since 9.0.0
173
-	 */
174
-	public function create($actorType, $actorId, $objectType, $objectId);
162
+    /**
163
+     * creates a new comment and returns it. At this point of time, it is not
164
+     * saved in the used data storage. Use save() after setting other fields
165
+     * of the comment (e.g. message or verb).
166
+     *
167
+     * @param string $actorType the actor type (e.g. 'users')
168
+     * @param string $actorId a user id
169
+     * @param string $objectType the object type the comment is attached to
170
+     * @param string $objectId the object id the comment is attached to
171
+     * @return IComment
172
+     * @since 9.0.0
173
+     */
174
+    public function create($actorType, $actorId, $objectType, $objectId);
175 175
 
176
-	/**
177
-	 * permanently deletes the comment specified by the ID
178
-	 *
179
-	 * When the comment has child comments, their parent ID will be changed to
180
-	 * the parent ID of the item that is to be deleted.
181
-	 *
182
-	 * @param string $id
183
-	 * @return bool
184
-	 * @since 9.0.0
185
-	 */
186
-	public function delete($id);
176
+    /**
177
+     * permanently deletes the comment specified by the ID
178
+     *
179
+     * When the comment has child comments, their parent ID will be changed to
180
+     * the parent ID of the item that is to be deleted.
181
+     *
182
+     * @param string $id
183
+     * @return bool
184
+     * @since 9.0.0
185
+     */
186
+    public function delete($id);
187 187
 
188
-	/**
189
-	 * saves the comment permanently
190
-	 *
191
-	 * if the supplied comment has an empty ID, a new entry comment will be
192
-	 * saved and the instance updated with the new ID.
193
-	 *
194
-	 * Otherwise, an existing comment will be updated.
195
-	 *
196
-	 * Throws NotFoundException when a comment that is to be updated does not
197
-	 * exist anymore at this point of time.
198
-	 *
199
-	 * @param IComment $comment
200
-	 * @return bool
201
-	 * @throws NotFoundException
202
-	 * @since 9.0.0
203
-	 */
204
-	public function save(IComment $comment);
188
+    /**
189
+     * saves the comment permanently
190
+     *
191
+     * if the supplied comment has an empty ID, a new entry comment will be
192
+     * saved and the instance updated with the new ID.
193
+     *
194
+     * Otherwise, an existing comment will be updated.
195
+     *
196
+     * Throws NotFoundException when a comment that is to be updated does not
197
+     * exist anymore at this point of time.
198
+     *
199
+     * @param IComment $comment
200
+     * @return bool
201
+     * @throws NotFoundException
202
+     * @since 9.0.0
203
+     */
204
+    public function save(IComment $comment);
205 205
 
206
-	/**
207
-	 * removes references to specific actor (e.g. on user delete) of a comment.
208
-	 * The comment itself must not get lost/deleted.
209
-	 *
210
-	 * A 'users' type actor (type and id) should get replaced by the
211
-	 * value of the DELETED_USER constant of this interface.
212
-	 *
213
-	 * @param string $actorType the actor type (e.g. 'users')
214
-	 * @param string $actorId a user id
215
-	 * @return boolean
216
-	 * @since 9.0.0
217
-	 */
218
-	public function deleteReferencesOfActor($actorType, $actorId);
206
+    /**
207
+     * removes references to specific actor (e.g. on user delete) of a comment.
208
+     * The comment itself must not get lost/deleted.
209
+     *
210
+     * A 'users' type actor (type and id) should get replaced by the
211
+     * value of the DELETED_USER constant of this interface.
212
+     *
213
+     * @param string $actorType the actor type (e.g. 'users')
214
+     * @param string $actorId a user id
215
+     * @return boolean
216
+     * @since 9.0.0
217
+     */
218
+    public function deleteReferencesOfActor($actorType, $actorId);
219 219
 
220
-	/**
221
-	 * deletes all comments made of a specific object (e.g. on file delete)
222
-	 *
223
-	 * @param string $objectType the object type (e.g. 'files')
224
-	 * @param string $objectId e.g. the file id
225
-	 * @return boolean
226
-	 * @since 9.0.0
227
-	 */
228
-	public function deleteCommentsAtObject($objectType, $objectId);
220
+    /**
221
+     * deletes all comments made of a specific object (e.g. on file delete)
222
+     *
223
+     * @param string $objectType the object type (e.g. 'files')
224
+     * @param string $objectId e.g. the file id
225
+     * @return boolean
226
+     * @since 9.0.0
227
+     */
228
+    public function deleteCommentsAtObject($objectType, $objectId);
229 229
 
230
-	/**
231
-	 * sets the read marker for a given file to the specified date for the
232
-	 * provided user
233
-	 *
234
-	 * @param string $objectType
235
-	 * @param string $objectId
236
-	 * @param \DateTime $dateTime
237
-	 * @param \OCP\IUser $user
238
-	 * @since 9.0.0
239
-	 */
240
-	public function setReadMark($objectType, $objectId, \DateTime $dateTime, \OCP\IUser $user);
230
+    /**
231
+     * sets the read marker for a given file to the specified date for the
232
+     * provided user
233
+     *
234
+     * @param string $objectType
235
+     * @param string $objectId
236
+     * @param \DateTime $dateTime
237
+     * @param \OCP\IUser $user
238
+     * @since 9.0.0
239
+     */
240
+    public function setReadMark($objectType, $objectId, \DateTime $dateTime, \OCP\IUser $user);
241 241
 
242
-	/**
243
-	 * returns the read marker for a given file to the specified date for the
244
-	 * provided user. It returns null, when the marker is not present, i.e.
245
-	 * no comments were marked as read.
246
-	 *
247
-	 * @param string $objectType
248
-	 * @param string $objectId
249
-	 * @param \OCP\IUser $user
250
-	 * @return \DateTime|null
251
-	 * @since 9.0.0
252
-	 */
253
-	public function getReadMark($objectType, $objectId, \OCP\IUser $user);
242
+    /**
243
+     * returns the read marker for a given file to the specified date for the
244
+     * provided user. It returns null, when the marker is not present, i.e.
245
+     * no comments were marked as read.
246
+     *
247
+     * @param string $objectType
248
+     * @param string $objectId
249
+     * @param \OCP\IUser $user
250
+     * @return \DateTime|null
251
+     * @since 9.0.0
252
+     */
253
+    public function getReadMark($objectType, $objectId, \OCP\IUser $user);
254 254
 
255
-	/**
256
-	 * deletes the read markers for the specified user
257
-	 *
258
-	 * @param \OCP\IUser $user
259
-	 * @return bool
260
-	 * @since 9.0.0
261
-	 */
262
-	public function deleteReadMarksFromUser(\OCP\IUser $user);
255
+    /**
256
+     * deletes the read markers for the specified user
257
+     *
258
+     * @param \OCP\IUser $user
259
+     * @return bool
260
+     * @since 9.0.0
261
+     */
262
+    public function deleteReadMarksFromUser(\OCP\IUser $user);
263 263
 
264
-	/**
265
-	 * deletes the read markers on the specified object
266
-	 *
267
-	 * @param string $objectType
268
-	 * @param string $objectId
269
-	 * @return bool
270
-	 * @since 9.0.0
271
-	 */
272
-	public function deleteReadMarksOnObject($objectType, $objectId);
264
+    /**
265
+     * deletes the read markers on the specified object
266
+     *
267
+     * @param string $objectType
268
+     * @param string $objectId
269
+     * @return bool
270
+     * @since 9.0.0
271
+     */
272
+    public function deleteReadMarksOnObject($objectType, $objectId);
273 273
 
274
-	/**
275
-	 * registers an Entity to the manager, so event notifications can be send
276
-	 * to consumers of the comments infrastructure
277
-	 *
278
-	 * @param \Closure $closure
279
-	 * @since 11.0.0
280
-	 */
281
-	public function registerEventHandler(\Closure $closure);
274
+    /**
275
+     * registers an Entity to the manager, so event notifications can be send
276
+     * to consumers of the comments infrastructure
277
+     *
278
+     * @param \Closure $closure
279
+     * @since 11.0.0
280
+     */
281
+    public function registerEventHandler(\Closure $closure);
282 282
 
283
-	/**
284
-	 * registers a method that resolves an ID to a display name for a given type
285
-	 *
286
-	 * @param string $type
287
-	 * @param \Closure $closure
288
-	 * @throws \OutOfBoundsException
289
-	 * @since 11.0.0
290
-	 *
291
-	 * Only one resolver shall be registered per type. Otherwise a
292
-	 * \OutOfBoundsException has to thrown.
293
-	 */
294
-	public function registerDisplayNameResolver($type, \Closure $closure);
283
+    /**
284
+     * registers a method that resolves an ID to a display name for a given type
285
+     *
286
+     * @param string $type
287
+     * @param \Closure $closure
288
+     * @throws \OutOfBoundsException
289
+     * @since 11.0.0
290
+     *
291
+     * Only one resolver shall be registered per type. Otherwise a
292
+     * \OutOfBoundsException has to thrown.
293
+     */
294
+    public function registerDisplayNameResolver($type, \Closure $closure);
295 295
 
296
-	/**
297
-	 * resolves a given ID of a given Type to a display name.
298
-	 *
299
-	 * @param string $type
300
-	 * @param string $id
301
-	 * @return string
302
-	 * @throws \OutOfBoundsException
303
-	 * @since 11.0.0
304
-	 *
305
-	 * If a provided type was not registered, an \OutOfBoundsException shall
306
-	 * be thrown. It is upon the resolver discretion what to return of the
307
-	 * provided ID is unknown. It must be ensured that a string is returned.
308
-	 */
309
-	public function resolveDisplayName($type, $id);
296
+    /**
297
+     * resolves a given ID of a given Type to a display name.
298
+     *
299
+     * @param string $type
300
+     * @param string $id
301
+     * @return string
302
+     * @throws \OutOfBoundsException
303
+     * @since 11.0.0
304
+     *
305
+     * If a provided type was not registered, an \OutOfBoundsException shall
306
+     * be thrown. It is upon the resolver discretion what to return of the
307
+     * provided ID is unknown. It must be ensured that a string is returned.
308
+     */
309
+    public function resolveDisplayName($type, $id);
310 310
 
311 311
 }
Please login to merge, or discard this patch.
lib/public/Collaboration/AutoComplete/IManager.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -30,17 +30,17 @@
 block discarded – undo
30 30
  * @since 13.0.0
31 31
  */
32 32
 interface IManager {
33
-	/**
34
-	 * @param string $className – class name of the ISorter implementation
35
-	 * @since 13.0.0
36
-	 */
37
-	public function registerSorter($className);
33
+    /**
34
+     * @param string $className – class name of the ISorter implementation
35
+     * @since 13.0.0
36
+     */
37
+    public function registerSorter($className);
38 38
 
39
-	/**
40
-	 * @param array $sorters	list of sorter IDs, seperated by "|"
41
-	 * @param array $sortArray	array representation of OCP\Collaboration\Collaborators\ISearchResult
42
-	 * @param array $context	context info of the search, keys: itemType, itemId
43
-	 * @since 13.0.0
44
-	 */
45
-	public function runSorters(array $sorters, array &$sortArray, array $context);
39
+    /**
40
+     * @param array $sorters	list of sorter IDs, seperated by "|"
41
+     * @param array $sortArray	array representation of OCP\Collaboration\Collaborators\ISearchResult
42
+     * @param array $context	context info of the search, keys: itemType, itemId
43
+     * @since 13.0.0
44
+     */
45
+    public function runSorters(array $sorters, array &$sortArray, array $context);
46 46
 }
Please login to merge, or discard this patch.
lib/private/Collaboration/AutoComplete/Manager.php 2 patches
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -28,54 +28,54 @@
 block discarded – undo
28 28
 use OCP\IServerContainer;
29 29
 
30 30
 class Manager implements IManager {
31
-	/** @var string[] */
32
-	protected $sorters =[];
31
+    /** @var string[] */
32
+    protected $sorters =[];
33 33
 
34
-	/** @var ISorter[]  */
35
-	protected $sorterInstances = [];
36
-	/** @var IServerContainer */
37
-	private $c;
34
+    /** @var ISorter[]  */
35
+    protected $sorterInstances = [];
36
+    /** @var IServerContainer */
37
+    private $c;
38 38
 
39
-	public function __construct(IServerContainer $container) {
40
-		$this->c = $container;
41
-	}
39
+    public function __construct(IServerContainer $container) {
40
+        $this->c = $container;
41
+    }
42 42
 
43
-	public function runSorters(array $sorters, array &$sortArray, array $context) {
44
-		$sorterInstances = $this->getSorters();
45
-		while($sorter = array_shift($sorters)) {
46
-			if(isset($sorterInstances[$sorter])) {
47
-				$sorterInstances[$sorter]->sort($sortArray, $context);
48
-			} else {
49
-				$this->c->getLogger()->warning('No sorter for ID "{id}", skipping', [
50
-					'app' => 'core', 'id' => $sorter
51
-				]);
52
-			}
53
-		}
54
-	}
43
+    public function runSorters(array $sorters, array &$sortArray, array $context) {
44
+        $sorterInstances = $this->getSorters();
45
+        while($sorter = array_shift($sorters)) {
46
+            if(isset($sorterInstances[$sorter])) {
47
+                $sorterInstances[$sorter]->sort($sortArray, $context);
48
+            } else {
49
+                $this->c->getLogger()->warning('No sorter for ID "{id}", skipping', [
50
+                    'app' => 'core', 'id' => $sorter
51
+                ]);
52
+            }
53
+        }
54
+    }
55 55
 
56
-	public function registerSorter($className) {
57
-		$sorters[] = $className;
58
-	}
56
+    public function registerSorter($className) {
57
+        $sorters[] = $className;
58
+    }
59 59
 
60
-	protected function getSorters() {
61
-		if(count($this->sorterInstances) === 0) {
62
-			foreach ($this->sorters as $sorter) {
63
-				/** @var ISorter $instance */
64
-				$instance = $this->c->resolve($sorter);
65
-				if(!$instance instanceof ISorter) {
66
-					$this->c->getLogger()->notice('Skipping sorter which is not an instance of ISorter. Class name: {class}',
67
-						['app' => 'core', 'class' => $sorter]);
68
-					continue;
69
-				}
70
-				$sorterId = trim($instance->getId());
71
-				if(trim($sorterId) === '') {
72
-					$this->c->getLogger()->notice('Skipping sorter with empty ID. Class name: {class}',
73
-						['app' => 'core', 'class' => $sorter]);
74
-					continue;
75
-				}
76
-				$this->sorterInstances[$sorterId] = $instance;
77
-			}
78
-		}
79
-		return $this->sorterInstances;
80
-	}
60
+    protected function getSorters() {
61
+        if(count($this->sorterInstances) === 0) {
62
+            foreach ($this->sorters as $sorter) {
63
+                /** @var ISorter $instance */
64
+                $instance = $this->c->resolve($sorter);
65
+                if(!$instance instanceof ISorter) {
66
+                    $this->c->getLogger()->notice('Skipping sorter which is not an instance of ISorter. Class name: {class}',
67
+                        ['app' => 'core', 'class' => $sorter]);
68
+                    continue;
69
+                }
70
+                $sorterId = trim($instance->getId());
71
+                if(trim($sorterId) === '') {
72
+                    $this->c->getLogger()->notice('Skipping sorter with empty ID. Class name: {class}',
73
+                        ['app' => 'core', 'class' => $sorter]);
74
+                    continue;
75
+                }
76
+                $this->sorterInstances[$sorterId] = $instance;
77
+            }
78
+        }
79
+        return $this->sorterInstances;
80
+    }
81 81
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
 
30 30
 class Manager implements IManager {
31 31
 	/** @var string[] */
32
-	protected $sorters =[];
32
+	protected $sorters = [];
33 33
 
34 34
 	/** @var ISorter[]  */
35 35
 	protected $sorterInstances = [];
@@ -42,8 +42,8 @@  discard block
 block discarded – undo
42 42
 
43 43
 	public function runSorters(array $sorters, array &$sortArray, array $context) {
44 44
 		$sorterInstances = $this->getSorters();
45
-		while($sorter = array_shift($sorters)) {
46
-			if(isset($sorterInstances[$sorter])) {
45
+		while ($sorter = array_shift($sorters)) {
46
+			if (isset($sorterInstances[$sorter])) {
47 47
 				$sorterInstances[$sorter]->sort($sortArray, $context);
48 48
 			} else {
49 49
 				$this->c->getLogger()->warning('No sorter for ID "{id}", skipping', [
@@ -58,17 +58,17 @@  discard block
 block discarded – undo
58 58
 	}
59 59
 
60 60
 	protected function getSorters() {
61
-		if(count($this->sorterInstances) === 0) {
61
+		if (count($this->sorterInstances) === 0) {
62 62
 			foreach ($this->sorters as $sorter) {
63 63
 				/** @var ISorter $instance */
64 64
 				$instance = $this->c->resolve($sorter);
65
-				if(!$instance instanceof ISorter) {
65
+				if (!$instance instanceof ISorter) {
66 66
 					$this->c->getLogger()->notice('Skipping sorter which is not an instance of ISorter. Class name: {class}',
67 67
 						['app' => 'core', 'class' => $sorter]);
68 68
 					continue;
69 69
 				}
70 70
 				$sorterId = trim($instance->getId());
71
-				if(trim($sorterId) === '') {
71
+				if (trim($sorterId) === '') {
72 72
 					$this->c->getLogger()->notice('Skipping sorter with empty ID. Class name: {class}',
73 73
 						['app' => 'core', 'class' => $sorter]);
74 74
 					continue;
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 1 patch
Indentation   +1461 added lines, -1461 removed lines patch added patch discarded remove patch
@@ -60,1489 +60,1489 @@
 block discarded – undo
60 60
  */
61 61
 class Manager implements IManager {
62 62
 
63
-	/** @var IProviderFactory */
64
-	private $factory;
65
-	/** @var ILogger */
66
-	private $logger;
67
-	/** @var IConfig */
68
-	private $config;
69
-	/** @var ISecureRandom */
70
-	private $secureRandom;
71
-	/** @var IHasher */
72
-	private $hasher;
73
-	/** @var IMountManager */
74
-	private $mountManager;
75
-	/** @var IGroupManager */
76
-	private $groupManager;
77
-	/** @var IL10N */
78
-	private $l;
79
-	/** @var IFactory */
80
-	private $l10nFactory;
81
-	/** @var IUserManager */
82
-	private $userManager;
83
-	/** @var IRootFolder */
84
-	private $rootFolder;
85
-	/** @var CappedMemoryCache */
86
-	private $sharingDisabledForUsersCache;
87
-	/** @var EventDispatcher */
88
-	private $eventDispatcher;
89
-	/** @var LegacyHooks */
90
-	private $legacyHooks;
91
-	/** @var IMailer */
92
-	private $mailer;
93
-	/** @var IURLGenerator */
94
-	private $urlGenerator;
95
-	/** @var \OC_Defaults */
96
-	private $defaults;
97
-
98
-
99
-	/**
100
-	 * Manager constructor.
101
-	 *
102
-	 * @param ILogger $logger
103
-	 * @param IConfig $config
104
-	 * @param ISecureRandom $secureRandom
105
-	 * @param IHasher $hasher
106
-	 * @param IMountManager $mountManager
107
-	 * @param IGroupManager $groupManager
108
-	 * @param IL10N $l
109
-	 * @param IFactory $l10nFactory
110
-	 * @param IProviderFactory $factory
111
-	 * @param IUserManager $userManager
112
-	 * @param IRootFolder $rootFolder
113
-	 * @param EventDispatcher $eventDispatcher
114
-	 * @param IMailer $mailer
115
-	 * @param IURLGenerator $urlGenerator
116
-	 * @param \OC_Defaults $defaults
117
-	 */
118
-	public function __construct(
119
-			ILogger $logger,
120
-			IConfig $config,
121
-			ISecureRandom $secureRandom,
122
-			IHasher $hasher,
123
-			IMountManager $mountManager,
124
-			IGroupManager $groupManager,
125
-			IL10N $l,
126
-			IFactory $l10nFactory,
127
-			IProviderFactory $factory,
128
-			IUserManager $userManager,
129
-			IRootFolder $rootFolder,
130
-			EventDispatcher $eventDispatcher,
131
-			IMailer $mailer,
132
-			IURLGenerator $urlGenerator,
133
-			\OC_Defaults $defaults
134
-	) {
135
-		$this->logger = $logger;
136
-		$this->config = $config;
137
-		$this->secureRandom = $secureRandom;
138
-		$this->hasher = $hasher;
139
-		$this->mountManager = $mountManager;
140
-		$this->groupManager = $groupManager;
141
-		$this->l = $l;
142
-		$this->l10nFactory = $l10nFactory;
143
-		$this->factory = $factory;
144
-		$this->userManager = $userManager;
145
-		$this->rootFolder = $rootFolder;
146
-		$this->eventDispatcher = $eventDispatcher;
147
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
148
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
149
-		$this->mailer = $mailer;
150
-		$this->urlGenerator = $urlGenerator;
151
-		$this->defaults = $defaults;
152
-	}
153
-
154
-	/**
155
-	 * Convert from a full share id to a tuple (providerId, shareId)
156
-	 *
157
-	 * @param string $id
158
-	 * @return string[]
159
-	 */
160
-	private function splitFullId($id) {
161
-		return explode(':', $id, 2);
162
-	}
163
-
164
-	/**
165
-	 * Verify if a password meets all requirements
166
-	 *
167
-	 * @param string $password
168
-	 * @throws \Exception
169
-	 */
170
-	protected function verifyPassword($password) {
171
-		if ($password === null) {
172
-			// No password is set, check if this is allowed.
173
-			if ($this->shareApiLinkEnforcePassword()) {
174
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
175
-			}
176
-
177
-			return;
178
-		}
179
-
180
-		// Let others verify the password
181
-		try {
182
-			$event = new GenericEvent($password);
183
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
184
-		} catch (HintException $e) {
185
-			throw new \Exception($e->getHint());
186
-		}
187
-	}
188
-
189
-	/**
190
-	 * Check for generic requirements before creating a share
191
-	 *
192
-	 * @param \OCP\Share\IShare $share
193
-	 * @throws \InvalidArgumentException
194
-	 * @throws GenericShareException
195
-	 *
196
-	 * @suppress PhanUndeclaredClassMethod
197
-	 */
198
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
199
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
200
-			// We expect a valid user as sharedWith for user shares
201
-			if (!$this->userManager->userExists($share->getSharedWith())) {
202
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
203
-			}
204
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
205
-			// We expect a valid group as sharedWith for group shares
206
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
207
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
208
-			}
209
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
210
-			if ($share->getSharedWith() !== null) {
211
-				throw new \InvalidArgumentException('SharedWith should be empty');
212
-			}
213
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
214
-			if ($share->getSharedWith() === null) {
215
-				throw new \InvalidArgumentException('SharedWith should not be empty');
216
-			}
217
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
218
-			if ($share->getSharedWith() === null) {
219
-				throw new \InvalidArgumentException('SharedWith should not be empty');
220
-			}
221
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
222
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
223
-			if ($circle === null) {
224
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
225
-			}
226
-		} else {
227
-			// We can't handle other types yet
228
-			throw new \InvalidArgumentException('unknown share type');
229
-		}
230
-
231
-		// Verify the initiator of the share is set
232
-		if ($share->getSharedBy() === null) {
233
-			throw new \InvalidArgumentException('SharedBy should be set');
234
-		}
235
-
236
-		// Cannot share with yourself
237
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
238
-			$share->getSharedWith() === $share->getSharedBy()) {
239
-			throw new \InvalidArgumentException('Can’t share with yourself');
240
-		}
241
-
242
-		// The path should be set
243
-		if ($share->getNode() === null) {
244
-			throw new \InvalidArgumentException('Path should be set');
245
-		}
246
-
247
-		// And it should be a file or a folder
248
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
249
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
250
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
251
-		}
252
-
253
-		// And you can't share your rootfolder
254
-		if ($this->userManager->userExists($share->getSharedBy())) {
255
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
256
-		} else {
257
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
258
-		}
259
-		if ($sharedPath === $share->getNode()->getPath()) {
260
-			throw new \InvalidArgumentException('You can’t share your root folder');
261
-		}
262
-
263
-		// Check if we actually have share permissions
264
-		if (!$share->getNode()->isShareable()) {
265
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
266
-			throw new GenericShareException($message_t, $message_t, 404);
267
-		}
268
-
269
-		// Permissions should be set
270
-		if ($share->getPermissions() === null) {
271
-			throw new \InvalidArgumentException('A share requires permissions');
272
-		}
273
-
274
-		/*
63
+    /** @var IProviderFactory */
64
+    private $factory;
65
+    /** @var ILogger */
66
+    private $logger;
67
+    /** @var IConfig */
68
+    private $config;
69
+    /** @var ISecureRandom */
70
+    private $secureRandom;
71
+    /** @var IHasher */
72
+    private $hasher;
73
+    /** @var IMountManager */
74
+    private $mountManager;
75
+    /** @var IGroupManager */
76
+    private $groupManager;
77
+    /** @var IL10N */
78
+    private $l;
79
+    /** @var IFactory */
80
+    private $l10nFactory;
81
+    /** @var IUserManager */
82
+    private $userManager;
83
+    /** @var IRootFolder */
84
+    private $rootFolder;
85
+    /** @var CappedMemoryCache */
86
+    private $sharingDisabledForUsersCache;
87
+    /** @var EventDispatcher */
88
+    private $eventDispatcher;
89
+    /** @var LegacyHooks */
90
+    private $legacyHooks;
91
+    /** @var IMailer */
92
+    private $mailer;
93
+    /** @var IURLGenerator */
94
+    private $urlGenerator;
95
+    /** @var \OC_Defaults */
96
+    private $defaults;
97
+
98
+
99
+    /**
100
+     * Manager constructor.
101
+     *
102
+     * @param ILogger $logger
103
+     * @param IConfig $config
104
+     * @param ISecureRandom $secureRandom
105
+     * @param IHasher $hasher
106
+     * @param IMountManager $mountManager
107
+     * @param IGroupManager $groupManager
108
+     * @param IL10N $l
109
+     * @param IFactory $l10nFactory
110
+     * @param IProviderFactory $factory
111
+     * @param IUserManager $userManager
112
+     * @param IRootFolder $rootFolder
113
+     * @param EventDispatcher $eventDispatcher
114
+     * @param IMailer $mailer
115
+     * @param IURLGenerator $urlGenerator
116
+     * @param \OC_Defaults $defaults
117
+     */
118
+    public function __construct(
119
+            ILogger $logger,
120
+            IConfig $config,
121
+            ISecureRandom $secureRandom,
122
+            IHasher $hasher,
123
+            IMountManager $mountManager,
124
+            IGroupManager $groupManager,
125
+            IL10N $l,
126
+            IFactory $l10nFactory,
127
+            IProviderFactory $factory,
128
+            IUserManager $userManager,
129
+            IRootFolder $rootFolder,
130
+            EventDispatcher $eventDispatcher,
131
+            IMailer $mailer,
132
+            IURLGenerator $urlGenerator,
133
+            \OC_Defaults $defaults
134
+    ) {
135
+        $this->logger = $logger;
136
+        $this->config = $config;
137
+        $this->secureRandom = $secureRandom;
138
+        $this->hasher = $hasher;
139
+        $this->mountManager = $mountManager;
140
+        $this->groupManager = $groupManager;
141
+        $this->l = $l;
142
+        $this->l10nFactory = $l10nFactory;
143
+        $this->factory = $factory;
144
+        $this->userManager = $userManager;
145
+        $this->rootFolder = $rootFolder;
146
+        $this->eventDispatcher = $eventDispatcher;
147
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
148
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
149
+        $this->mailer = $mailer;
150
+        $this->urlGenerator = $urlGenerator;
151
+        $this->defaults = $defaults;
152
+    }
153
+
154
+    /**
155
+     * Convert from a full share id to a tuple (providerId, shareId)
156
+     *
157
+     * @param string $id
158
+     * @return string[]
159
+     */
160
+    private function splitFullId($id) {
161
+        return explode(':', $id, 2);
162
+    }
163
+
164
+    /**
165
+     * Verify if a password meets all requirements
166
+     *
167
+     * @param string $password
168
+     * @throws \Exception
169
+     */
170
+    protected function verifyPassword($password) {
171
+        if ($password === null) {
172
+            // No password is set, check if this is allowed.
173
+            if ($this->shareApiLinkEnforcePassword()) {
174
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
175
+            }
176
+
177
+            return;
178
+        }
179
+
180
+        // Let others verify the password
181
+        try {
182
+            $event = new GenericEvent($password);
183
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
184
+        } catch (HintException $e) {
185
+            throw new \Exception($e->getHint());
186
+        }
187
+    }
188
+
189
+    /**
190
+     * Check for generic requirements before creating a share
191
+     *
192
+     * @param \OCP\Share\IShare $share
193
+     * @throws \InvalidArgumentException
194
+     * @throws GenericShareException
195
+     *
196
+     * @suppress PhanUndeclaredClassMethod
197
+     */
198
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
199
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
200
+            // We expect a valid user as sharedWith for user shares
201
+            if (!$this->userManager->userExists($share->getSharedWith())) {
202
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
203
+            }
204
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
205
+            // We expect a valid group as sharedWith for group shares
206
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
207
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
208
+            }
209
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
210
+            if ($share->getSharedWith() !== null) {
211
+                throw new \InvalidArgumentException('SharedWith should be empty');
212
+            }
213
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
214
+            if ($share->getSharedWith() === null) {
215
+                throw new \InvalidArgumentException('SharedWith should not be empty');
216
+            }
217
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
218
+            if ($share->getSharedWith() === null) {
219
+                throw new \InvalidArgumentException('SharedWith should not be empty');
220
+            }
221
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
222
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
223
+            if ($circle === null) {
224
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
225
+            }
226
+        } else {
227
+            // We can't handle other types yet
228
+            throw new \InvalidArgumentException('unknown share type');
229
+        }
230
+
231
+        // Verify the initiator of the share is set
232
+        if ($share->getSharedBy() === null) {
233
+            throw new \InvalidArgumentException('SharedBy should be set');
234
+        }
235
+
236
+        // Cannot share with yourself
237
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
238
+            $share->getSharedWith() === $share->getSharedBy()) {
239
+            throw new \InvalidArgumentException('Can’t share with yourself');
240
+        }
241
+
242
+        // The path should be set
243
+        if ($share->getNode() === null) {
244
+            throw new \InvalidArgumentException('Path should be set');
245
+        }
246
+
247
+        // And it should be a file or a folder
248
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
249
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
250
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
251
+        }
252
+
253
+        // And you can't share your rootfolder
254
+        if ($this->userManager->userExists($share->getSharedBy())) {
255
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
256
+        } else {
257
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
258
+        }
259
+        if ($sharedPath === $share->getNode()->getPath()) {
260
+            throw new \InvalidArgumentException('You can’t share your root folder');
261
+        }
262
+
263
+        // Check if we actually have share permissions
264
+        if (!$share->getNode()->isShareable()) {
265
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
266
+            throw new GenericShareException($message_t, $message_t, 404);
267
+        }
268
+
269
+        // Permissions should be set
270
+        if ($share->getPermissions() === null) {
271
+            throw new \InvalidArgumentException('A share requires permissions');
272
+        }
273
+
274
+        /*
275 275
 		 * Quick fix for #23536
276 276
 		 * Non moveable mount points do not have update and delete permissions
277 277
 		 * while we 'most likely' do have that on the storage.
278 278
 		 */
279
-		$permissions = $share->getNode()->getPermissions();
280
-		$mount = $share->getNode()->getMountPoint();
281
-		if (!($mount instanceof MoveableMount)) {
282
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
283
-		}
284
-
285
-		// Check that we do not share with more permissions than we have
286
-		if ($share->getPermissions() & ~$permissions) {
287
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
288
-			throw new GenericShareException($message_t, $message_t, 404);
289
-		}
290
-
291
-
292
-		// Check that read permissions are always set
293
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
294
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
295
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
296
-		if (!$noReadPermissionRequired &&
297
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
298
-			throw new \InvalidArgumentException('Shares need at least read permissions');
299
-		}
300
-
301
-		if ($share->getNode() instanceof \OCP\Files\File) {
302
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
303
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
304
-				throw new GenericShareException($message_t);
305
-			}
306
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
307
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
308
-				throw new GenericShareException($message_t);
309
-			}
310
-		}
311
-	}
312
-
313
-	/**
314
-	 * Validate if the expiration date fits the system settings
315
-	 *
316
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
317
-	 * @return \OCP\Share\IShare The modified share object
318
-	 * @throws GenericShareException
319
-	 * @throws \InvalidArgumentException
320
-	 * @throws \Exception
321
-	 */
322
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
323
-
324
-		$expirationDate = $share->getExpirationDate();
325
-
326
-		if ($expirationDate !== null) {
327
-			//Make sure the expiration date is a date
328
-			$expirationDate->setTime(0, 0, 0);
329
-
330
-			$date = new \DateTime();
331
-			$date->setTime(0, 0, 0);
332
-			if ($date >= $expirationDate) {
333
-				$message = $this->l->t('Expiration date is in the past');
334
-				throw new GenericShareException($message, $message, 404);
335
-			}
336
-		}
337
-
338
-		// If expiredate is empty set a default one if there is a default
339
-		$fullId = null;
340
-		try {
341
-			$fullId = $share->getFullId();
342
-		} catch (\UnexpectedValueException $e) {
343
-			// This is a new share
344
-		}
345
-
346
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
347
-			$expirationDate = new \DateTime();
348
-			$expirationDate->setTime(0,0,0);
349
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
350
-		}
351
-
352
-		// If we enforce the expiration date check that is does not exceed
353
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
354
-			if ($expirationDate === null) {
355
-				throw new \InvalidArgumentException('Expiration date is enforced');
356
-			}
357
-
358
-			$date = new \DateTime();
359
-			$date->setTime(0, 0, 0);
360
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
361
-			if ($date < $expirationDate) {
362
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
363
-				throw new GenericShareException($message, $message, 404);
364
-			}
365
-		}
366
-
367
-		$accepted = true;
368
-		$message = '';
369
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
370
-			'expirationDate' => &$expirationDate,
371
-			'accepted' => &$accepted,
372
-			'message' => &$message,
373
-			'passwordSet' => $share->getPassword() !== null,
374
-		]);
375
-
376
-		if (!$accepted) {
377
-			throw new \Exception($message);
378
-		}
379
-
380
-		$share->setExpirationDate($expirationDate);
381
-
382
-		return $share;
383
-	}
384
-
385
-	/**
386
-	 * Check for pre share requirements for user shares
387
-	 *
388
-	 * @param \OCP\Share\IShare $share
389
-	 * @throws \Exception
390
-	 */
391
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
392
-		// Check if we can share with group members only
393
-		if ($this->shareWithGroupMembersOnly()) {
394
-			$sharedBy = $this->userManager->get($share->getSharedBy());
395
-			$sharedWith = $this->userManager->get($share->getSharedWith());
396
-			// Verify we can share with this user
397
-			$groups = array_intersect(
398
-					$this->groupManager->getUserGroupIds($sharedBy),
399
-					$this->groupManager->getUserGroupIds($sharedWith)
400
-			);
401
-			if (empty($groups)) {
402
-				throw new \Exception('Sharing is only allowed with group members');
403
-			}
404
-		}
405
-
406
-		/*
279
+        $permissions = $share->getNode()->getPermissions();
280
+        $mount = $share->getNode()->getMountPoint();
281
+        if (!($mount instanceof MoveableMount)) {
282
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
283
+        }
284
+
285
+        // Check that we do not share with more permissions than we have
286
+        if ($share->getPermissions() & ~$permissions) {
287
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
288
+            throw new GenericShareException($message_t, $message_t, 404);
289
+        }
290
+
291
+
292
+        // Check that read permissions are always set
293
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
294
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
295
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
296
+        if (!$noReadPermissionRequired &&
297
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
298
+            throw new \InvalidArgumentException('Shares need at least read permissions');
299
+        }
300
+
301
+        if ($share->getNode() instanceof \OCP\Files\File) {
302
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
303
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
304
+                throw new GenericShareException($message_t);
305
+            }
306
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
307
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
308
+                throw new GenericShareException($message_t);
309
+            }
310
+        }
311
+    }
312
+
313
+    /**
314
+     * Validate if the expiration date fits the system settings
315
+     *
316
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
317
+     * @return \OCP\Share\IShare The modified share object
318
+     * @throws GenericShareException
319
+     * @throws \InvalidArgumentException
320
+     * @throws \Exception
321
+     */
322
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
323
+
324
+        $expirationDate = $share->getExpirationDate();
325
+
326
+        if ($expirationDate !== null) {
327
+            //Make sure the expiration date is a date
328
+            $expirationDate->setTime(0, 0, 0);
329
+
330
+            $date = new \DateTime();
331
+            $date->setTime(0, 0, 0);
332
+            if ($date >= $expirationDate) {
333
+                $message = $this->l->t('Expiration date is in the past');
334
+                throw new GenericShareException($message, $message, 404);
335
+            }
336
+        }
337
+
338
+        // If expiredate is empty set a default one if there is a default
339
+        $fullId = null;
340
+        try {
341
+            $fullId = $share->getFullId();
342
+        } catch (\UnexpectedValueException $e) {
343
+            // This is a new share
344
+        }
345
+
346
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
347
+            $expirationDate = new \DateTime();
348
+            $expirationDate->setTime(0,0,0);
349
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
350
+        }
351
+
352
+        // If we enforce the expiration date check that is does not exceed
353
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
354
+            if ($expirationDate === null) {
355
+                throw new \InvalidArgumentException('Expiration date is enforced');
356
+            }
357
+
358
+            $date = new \DateTime();
359
+            $date->setTime(0, 0, 0);
360
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
361
+            if ($date < $expirationDate) {
362
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
363
+                throw new GenericShareException($message, $message, 404);
364
+            }
365
+        }
366
+
367
+        $accepted = true;
368
+        $message = '';
369
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
370
+            'expirationDate' => &$expirationDate,
371
+            'accepted' => &$accepted,
372
+            'message' => &$message,
373
+            'passwordSet' => $share->getPassword() !== null,
374
+        ]);
375
+
376
+        if (!$accepted) {
377
+            throw new \Exception($message);
378
+        }
379
+
380
+        $share->setExpirationDate($expirationDate);
381
+
382
+        return $share;
383
+    }
384
+
385
+    /**
386
+     * Check for pre share requirements for user shares
387
+     *
388
+     * @param \OCP\Share\IShare $share
389
+     * @throws \Exception
390
+     */
391
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
392
+        // Check if we can share with group members only
393
+        if ($this->shareWithGroupMembersOnly()) {
394
+            $sharedBy = $this->userManager->get($share->getSharedBy());
395
+            $sharedWith = $this->userManager->get($share->getSharedWith());
396
+            // Verify we can share with this user
397
+            $groups = array_intersect(
398
+                    $this->groupManager->getUserGroupIds($sharedBy),
399
+                    $this->groupManager->getUserGroupIds($sharedWith)
400
+            );
401
+            if (empty($groups)) {
402
+                throw new \Exception('Sharing is only allowed with group members');
403
+            }
404
+        }
405
+
406
+        /*
407 407
 		 * TODO: Could be costly, fix
408 408
 		 *
409 409
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
410 410
 		 */
411
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
412
-		$existingShares = $provider->getSharesByPath($share->getNode());
413
-		foreach($existingShares as $existingShare) {
414
-			// Ignore if it is the same share
415
-			try {
416
-				if ($existingShare->getFullId() === $share->getFullId()) {
417
-					continue;
418
-				}
419
-			} catch (\UnexpectedValueException $e) {
420
-				//Shares are not identical
421
-			}
422
-
423
-			// Identical share already existst
424
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
425
-				throw new \Exception('Path is already shared with this user');
426
-			}
427
-
428
-			// The share is already shared with this user via a group share
429
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
430
-				$group = $this->groupManager->get($existingShare->getSharedWith());
431
-				if (!is_null($group)) {
432
-					$user = $this->userManager->get($share->getSharedWith());
433
-
434
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
435
-						throw new \Exception('Path is already shared with this user');
436
-					}
437
-				}
438
-			}
439
-		}
440
-	}
441
-
442
-	/**
443
-	 * Check for pre share requirements for group shares
444
-	 *
445
-	 * @param \OCP\Share\IShare $share
446
-	 * @throws \Exception
447
-	 */
448
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
449
-		// Verify group shares are allowed
450
-		if (!$this->allowGroupSharing()) {
451
-			throw new \Exception('Group sharing is now allowed');
452
-		}
453
-
454
-		// Verify if the user can share with this group
455
-		if ($this->shareWithGroupMembersOnly()) {
456
-			$sharedBy = $this->userManager->get($share->getSharedBy());
457
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
458
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
459
-				throw new \Exception('Sharing is only allowed within your own groups');
460
-			}
461
-		}
462
-
463
-		/*
411
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
412
+        $existingShares = $provider->getSharesByPath($share->getNode());
413
+        foreach($existingShares as $existingShare) {
414
+            // Ignore if it is the same share
415
+            try {
416
+                if ($existingShare->getFullId() === $share->getFullId()) {
417
+                    continue;
418
+                }
419
+            } catch (\UnexpectedValueException $e) {
420
+                //Shares are not identical
421
+            }
422
+
423
+            // Identical share already existst
424
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
425
+                throw new \Exception('Path is already shared with this user');
426
+            }
427
+
428
+            // The share is already shared with this user via a group share
429
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
430
+                $group = $this->groupManager->get($existingShare->getSharedWith());
431
+                if (!is_null($group)) {
432
+                    $user = $this->userManager->get($share->getSharedWith());
433
+
434
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
435
+                        throw new \Exception('Path is already shared with this user');
436
+                    }
437
+                }
438
+            }
439
+        }
440
+    }
441
+
442
+    /**
443
+     * Check for pre share requirements for group shares
444
+     *
445
+     * @param \OCP\Share\IShare $share
446
+     * @throws \Exception
447
+     */
448
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
449
+        // Verify group shares are allowed
450
+        if (!$this->allowGroupSharing()) {
451
+            throw new \Exception('Group sharing is now allowed');
452
+        }
453
+
454
+        // Verify if the user can share with this group
455
+        if ($this->shareWithGroupMembersOnly()) {
456
+            $sharedBy = $this->userManager->get($share->getSharedBy());
457
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
458
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
459
+                throw new \Exception('Sharing is only allowed within your own groups');
460
+            }
461
+        }
462
+
463
+        /*
464 464
 		 * TODO: Could be costly, fix
465 465
 		 *
466 466
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
467 467
 		 */
468
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
469
-		$existingShares = $provider->getSharesByPath($share->getNode());
470
-		foreach($existingShares as $existingShare) {
471
-			try {
472
-				if ($existingShare->getFullId() === $share->getFullId()) {
473
-					continue;
474
-				}
475
-			} catch (\UnexpectedValueException $e) {
476
-				//It is a new share so just continue
477
-			}
478
-
479
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
480
-				throw new \Exception('Path is already shared with this group');
481
-			}
482
-		}
483
-	}
484
-
485
-	/**
486
-	 * Check for pre share requirements for link shares
487
-	 *
488
-	 * @param \OCP\Share\IShare $share
489
-	 * @throws \Exception
490
-	 */
491
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
492
-		// Are link shares allowed?
493
-		if (!$this->shareApiAllowLinks()) {
494
-			throw new \Exception('Link sharing is not allowed');
495
-		}
496
-
497
-		// Link shares by definition can't have share permissions
498
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
499
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
500
-		}
501
-
502
-		// Check if public upload is allowed
503
-		if (!$this->shareApiLinkAllowPublicUpload() &&
504
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
505
-			throw new \InvalidArgumentException('Public upload is not allowed');
506
-		}
507
-	}
508
-
509
-	/**
510
-	 * To make sure we don't get invisible link shares we set the parent
511
-	 * of a link if it is a reshare. This is a quick word around
512
-	 * until we can properly display multiple link shares in the UI
513
-	 *
514
-	 * See: https://github.com/owncloud/core/issues/22295
515
-	 *
516
-	 * FIXME: Remove once multiple link shares can be properly displayed
517
-	 *
518
-	 * @param \OCP\Share\IShare $share
519
-	 */
520
-	protected function setLinkParent(\OCP\Share\IShare $share) {
521
-
522
-		// No sense in checking if the method is not there.
523
-		if (method_exists($share, 'setParent')) {
524
-			$storage = $share->getNode()->getStorage();
525
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
526
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
527
-				$share->setParent($storage->getShareId());
528
-			}
529
-		};
530
-	}
531
-
532
-	/**
533
-	 * @param File|Folder $path
534
-	 */
535
-	protected function pathCreateChecks($path) {
536
-		// Make sure that we do not share a path that contains a shared mountpoint
537
-		if ($path instanceof \OCP\Files\Folder) {
538
-			$mounts = $this->mountManager->findIn($path->getPath());
539
-			foreach($mounts as $mount) {
540
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
541
-					throw new \InvalidArgumentException('Path contains files shared with you');
542
-				}
543
-			}
544
-		}
545
-	}
546
-
547
-	/**
548
-	 * Check if the user that is sharing can actually share
549
-	 *
550
-	 * @param \OCP\Share\IShare $share
551
-	 * @throws \Exception
552
-	 */
553
-	protected function canShare(\OCP\Share\IShare $share) {
554
-		if (!$this->shareApiEnabled()) {
555
-			throw new \Exception('Sharing is disabled');
556
-		}
557
-
558
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
559
-			throw new \Exception('Sharing is disabled for you');
560
-		}
561
-	}
562
-
563
-	/**
564
-	 * Share a path
565
-	 *
566
-	 * @param \OCP\Share\IShare $share
567
-	 * @return Share The share object
568
-	 * @throws \Exception
569
-	 *
570
-	 * TODO: handle link share permissions or check them
571
-	 */
572
-	public function createShare(\OCP\Share\IShare $share) {
573
-		$this->canShare($share);
574
-
575
-		$this->generalCreateChecks($share);
576
-
577
-		// Verify if there are any issues with the path
578
-		$this->pathCreateChecks($share->getNode());
579
-
580
-		/*
468
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
469
+        $existingShares = $provider->getSharesByPath($share->getNode());
470
+        foreach($existingShares as $existingShare) {
471
+            try {
472
+                if ($existingShare->getFullId() === $share->getFullId()) {
473
+                    continue;
474
+                }
475
+            } catch (\UnexpectedValueException $e) {
476
+                //It is a new share so just continue
477
+            }
478
+
479
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
480
+                throw new \Exception('Path is already shared with this group');
481
+            }
482
+        }
483
+    }
484
+
485
+    /**
486
+     * Check for pre share requirements for link shares
487
+     *
488
+     * @param \OCP\Share\IShare $share
489
+     * @throws \Exception
490
+     */
491
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
492
+        // Are link shares allowed?
493
+        if (!$this->shareApiAllowLinks()) {
494
+            throw new \Exception('Link sharing is not allowed');
495
+        }
496
+
497
+        // Link shares by definition can't have share permissions
498
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
499
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
500
+        }
501
+
502
+        // Check if public upload is allowed
503
+        if (!$this->shareApiLinkAllowPublicUpload() &&
504
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
505
+            throw new \InvalidArgumentException('Public upload is not allowed');
506
+        }
507
+    }
508
+
509
+    /**
510
+     * To make sure we don't get invisible link shares we set the parent
511
+     * of a link if it is a reshare. This is a quick word around
512
+     * until we can properly display multiple link shares in the UI
513
+     *
514
+     * See: https://github.com/owncloud/core/issues/22295
515
+     *
516
+     * FIXME: Remove once multiple link shares can be properly displayed
517
+     *
518
+     * @param \OCP\Share\IShare $share
519
+     */
520
+    protected function setLinkParent(\OCP\Share\IShare $share) {
521
+
522
+        // No sense in checking if the method is not there.
523
+        if (method_exists($share, 'setParent')) {
524
+            $storage = $share->getNode()->getStorage();
525
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
526
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
527
+                $share->setParent($storage->getShareId());
528
+            }
529
+        };
530
+    }
531
+
532
+    /**
533
+     * @param File|Folder $path
534
+     */
535
+    protected function pathCreateChecks($path) {
536
+        // Make sure that we do not share a path that contains a shared mountpoint
537
+        if ($path instanceof \OCP\Files\Folder) {
538
+            $mounts = $this->mountManager->findIn($path->getPath());
539
+            foreach($mounts as $mount) {
540
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
541
+                    throw new \InvalidArgumentException('Path contains files shared with you');
542
+                }
543
+            }
544
+        }
545
+    }
546
+
547
+    /**
548
+     * Check if the user that is sharing can actually share
549
+     *
550
+     * @param \OCP\Share\IShare $share
551
+     * @throws \Exception
552
+     */
553
+    protected function canShare(\OCP\Share\IShare $share) {
554
+        if (!$this->shareApiEnabled()) {
555
+            throw new \Exception('Sharing is disabled');
556
+        }
557
+
558
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
559
+            throw new \Exception('Sharing is disabled for you');
560
+        }
561
+    }
562
+
563
+    /**
564
+     * Share a path
565
+     *
566
+     * @param \OCP\Share\IShare $share
567
+     * @return Share The share object
568
+     * @throws \Exception
569
+     *
570
+     * TODO: handle link share permissions or check them
571
+     */
572
+    public function createShare(\OCP\Share\IShare $share) {
573
+        $this->canShare($share);
574
+
575
+        $this->generalCreateChecks($share);
576
+
577
+        // Verify if there are any issues with the path
578
+        $this->pathCreateChecks($share->getNode());
579
+
580
+        /*
581 581
 		 * On creation of a share the owner is always the owner of the path
582 582
 		 * Except for mounted federated shares.
583 583
 		 */
584
-		$storage = $share->getNode()->getStorage();
585
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
586
-			$parent = $share->getNode()->getParent();
587
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
588
-				$parent = $parent->getParent();
589
-			}
590
-			$share->setShareOwner($parent->getOwner()->getUID());
591
-		} else {
592
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
593
-		}
594
-
595
-		//Verify share type
596
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
597
-			$this->userCreateChecks($share);
598
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
599
-			$this->groupCreateChecks($share);
600
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
601
-			$this->linkCreateChecks($share);
602
-			$this->setLinkParent($share);
603
-
604
-			/*
584
+        $storage = $share->getNode()->getStorage();
585
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
586
+            $parent = $share->getNode()->getParent();
587
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
588
+                $parent = $parent->getParent();
589
+            }
590
+            $share->setShareOwner($parent->getOwner()->getUID());
591
+        } else {
592
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
593
+        }
594
+
595
+        //Verify share type
596
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
597
+            $this->userCreateChecks($share);
598
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
599
+            $this->groupCreateChecks($share);
600
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
601
+            $this->linkCreateChecks($share);
602
+            $this->setLinkParent($share);
603
+
604
+            /*
605 605
 			 * For now ignore a set token.
606 606
 			 */
607
-			$share->setToken(
608
-				$this->secureRandom->generate(
609
-					\OC\Share\Constants::TOKEN_LENGTH,
610
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
611
-				)
612
-			);
613
-
614
-			//Verify the expiration date
615
-			$this->validateExpirationDate($share);
616
-
617
-			//Verify the password
618
-			$this->verifyPassword($share->getPassword());
619
-
620
-			// If a password is set. Hash it!
621
-			if ($share->getPassword() !== null) {
622
-				$share->setPassword($this->hasher->hash($share->getPassword()));
623
-			}
624
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
625
-			$share->setToken(
626
-				$this->secureRandom->generate(
627
-					\OC\Share\Constants::TOKEN_LENGTH,
628
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
629
-				)
630
-			);
631
-		}
632
-
633
-		// Cannot share with the owner
634
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
635
-			$share->getSharedWith() === $share->getShareOwner()) {
636
-			throw new \InvalidArgumentException('Can’t share with the share owner');
637
-		}
638
-
639
-		// Generate the target
640
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
641
-		$target = \OC\Files\Filesystem::normalizePath($target);
642
-		$share->setTarget($target);
643
-
644
-		// Pre share event
645
-		$event = new GenericEvent($share);
646
-		$a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
647
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
648
-			throw new \Exception($event->getArgument('error'));
649
-		}
650
-
651
-		$oldShare = $share;
652
-		$provider = $this->factory->getProviderForType($share->getShareType());
653
-		$share = $provider->create($share);
654
-		//reuse the node we already have
655
-		$share->setNode($oldShare->getNode());
656
-
657
-		// Post share event
658
-		$event = new GenericEvent($share);
659
-		$this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
660
-
661
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
662
-			$user = $this->userManager->get($share->getSharedWith());
663
-			if ($user !== null) {
664
-				$emailAddress = $user->getEMailAddress();
665
-				if ($emailAddress !== null && $emailAddress !== '') {
666
-					$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
667
-					$l = $this->l10nFactory->get('lib', $userLang);
668
-					$this->sendMailNotification(
669
-						$l,
670
-						$share->getNode()->getName(),
671
-						$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
672
-						$share->getSharedBy(),
673
-						$emailAddress,
674
-						$share->getExpirationDate()
675
-					);
676
-					$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
677
-				} else {
678
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
679
-				}
680
-			} else {
681
-				$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
682
-			}
683
-		}
684
-
685
-		return $share;
686
-	}
687
-
688
-	/**
689
-	 * @param IL10N $l Language of the recipient
690
-	 * @param string $filename file/folder name
691
-	 * @param string $link link to the file/folder
692
-	 * @param string $initiator user ID of share sender
693
-	 * @param string $shareWith email address of share receiver
694
-	 * @param \DateTime|null $expiration
695
-	 * @throws \Exception If mail couldn't be sent
696
-	 */
697
-	protected function sendMailNotification(IL10N $l,
698
-											$filename,
699
-											$link,
700
-											$initiator,
701
-											$shareWith,
702
-											\DateTime $expiration = null) {
703
-		$initiatorUser = $this->userManager->get($initiator);
704
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
705
-		$subject = $l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename));
706
-
707
-		$message = $this->mailer->createMessage();
708
-
709
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
710
-			'filename' => $filename,
711
-			'link' => $link,
712
-			'initiator' => $initiatorDisplayName,
713
-			'expiration' => $expiration,
714
-			'shareWith' => $shareWith,
715
-		]);
716
-
717
-		$emailTemplate->addHeader();
718
-		$emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
719
-		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
720
-
721
-		$emailTemplate->addBodyText(
722
-			$text . ' ' . $l->t('Click the button below to open it.'),
723
-			$text
724
-		);
725
-		$emailTemplate->addBodyButton(
726
-			$l->t('Open »%s«', [$filename]),
727
-			$link
728
-		);
729
-
730
-		$message->setTo([$shareWith]);
731
-
732
-		// The "From" contains the sharers name
733
-		$instanceName = $this->defaults->getName();
734
-		$senderName = $l->t(
735
-			'%s via %s',
736
-			[
737
-				$initiatorDisplayName,
738
-				$instanceName
739
-			]
740
-		);
741
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
742
-
743
-		// The "Reply-To" is set to the sharer if an mail address is configured
744
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
745
-		$initiatorEmail = $initiatorUser->getEMailAddress();
746
-		if($initiatorEmail !== null) {
747
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
748
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
749
-		} else {
750
-			$emailTemplate->addFooter();
751
-		}
752
-
753
-		$message->setSubject($subject);
754
-		$message->setPlainBody($emailTemplate->renderText());
755
-		$message->setHtmlBody($emailTemplate->renderHtml());
756
-		$this->mailer->send($message);
757
-	}
758
-
759
-	/**
760
-	 * Update a share
761
-	 *
762
-	 * @param \OCP\Share\IShare $share
763
-	 * @return \OCP\Share\IShare The share object
764
-	 * @throws \InvalidArgumentException
765
-	 */
766
-	public function updateShare(\OCP\Share\IShare $share) {
767
-		$expirationDateUpdated = false;
768
-
769
-		$this->canShare($share);
770
-
771
-		try {
772
-			$originalShare = $this->getShareById($share->getFullId());
773
-		} catch (\UnexpectedValueException $e) {
774
-			throw new \InvalidArgumentException('Share does not have a full id');
775
-		}
776
-
777
-		// We can't change the share type!
778
-		if ($share->getShareType() !== $originalShare->getShareType()) {
779
-			throw new \InvalidArgumentException('Can’t change share type');
780
-		}
781
-
782
-		// We can only change the recipient on user shares
783
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
784
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
785
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
786
-		}
787
-
788
-		// Cannot share with the owner
789
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
790
-			$share->getSharedWith() === $share->getShareOwner()) {
791
-			throw new \InvalidArgumentException('Can’t share with the share owner');
792
-		}
793
-
794
-		$this->generalCreateChecks($share);
795
-
796
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
797
-			$this->userCreateChecks($share);
798
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
799
-			$this->groupCreateChecks($share);
800
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
801
-			$this->linkCreateChecks($share);
802
-
803
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
804
-
805
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
806
-				//Verify the expiration date
807
-				$this->validateExpirationDate($share);
808
-				$expirationDateUpdated = true;
809
-			}
810
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
811
-			$plainTextPassword = $share->getPassword();
812
-			if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
813
-				$plainTextPassword = null;
814
-			}
815
-		}
816
-
817
-		$this->pathCreateChecks($share->getNode());
818
-
819
-		// Now update the share!
820
-		$provider = $this->factory->getProviderForType($share->getShareType());
821
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
822
-			$share = $provider->update($share, $plainTextPassword);
823
-		} else {
824
-			$share = $provider->update($share);
825
-		}
826
-
827
-		if ($expirationDateUpdated === true) {
828
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
829
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
830
-				'itemSource' => $share->getNode()->getId(),
831
-				'date' => $share->getExpirationDate(),
832
-				'uidOwner' => $share->getSharedBy(),
833
-			]);
834
-		}
835
-
836
-		if ($share->getPassword() !== $originalShare->getPassword()) {
837
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
838
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
839
-				'itemSource' => $share->getNode()->getId(),
840
-				'uidOwner' => $share->getSharedBy(),
841
-				'token' => $share->getToken(),
842
-				'disabled' => is_null($share->getPassword()),
843
-			]);
844
-		}
845
-
846
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
847
-			if ($this->userManager->userExists($share->getShareOwner())) {
848
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
849
-			} else {
850
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
851
-			}
852
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
853
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
854
-				'itemSource' => $share->getNode()->getId(),
855
-				'shareType' => $share->getShareType(),
856
-				'shareWith' => $share->getSharedWith(),
857
-				'uidOwner' => $share->getSharedBy(),
858
-				'permissions' => $share->getPermissions(),
859
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
860
-			));
861
-		}
862
-
863
-		return $share;
864
-	}
865
-
866
-	/**
867
-	 * Updates the password of the given share if it is not the same as the
868
-	 * password of the original share.
869
-	 *
870
-	 * @param \OCP\Share\IShare $share the share to update its password.
871
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
872
-	 *        password with.
873
-	 * @return boolean whether the password was updated or not.
874
-	 */
875
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
876
-		// Password updated.
877
-		if ($share->getPassword() !== $originalShare->getPassword()) {
878
-			//Verify the password
879
-			$this->verifyPassword($share->getPassword());
880
-
881
-			// If a password is set. Hash it!
882
-			if ($share->getPassword() !== null) {
883
-				$share->setPassword($this->hasher->hash($share->getPassword()));
884
-
885
-				return true;
886
-			}
887
-		}
888
-
889
-		return false;
890
-	}
891
-
892
-	/**
893
-	 * Delete all the children of this share
894
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
895
-	 *
896
-	 * @param \OCP\Share\IShare $share
897
-	 * @return \OCP\Share\IShare[] List of deleted shares
898
-	 */
899
-	protected function deleteChildren(\OCP\Share\IShare $share) {
900
-		$deletedShares = [];
901
-
902
-		$provider = $this->factory->getProviderForType($share->getShareType());
903
-
904
-		foreach ($provider->getChildren($share) as $child) {
905
-			$deletedChildren = $this->deleteChildren($child);
906
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
907
-
908
-			$provider->delete($child);
909
-			$deletedShares[] = $child;
910
-		}
911
-
912
-		return $deletedShares;
913
-	}
914
-
915
-	/**
916
-	 * Delete a share
917
-	 *
918
-	 * @param \OCP\Share\IShare $share
919
-	 * @throws ShareNotFound
920
-	 * @throws \InvalidArgumentException
921
-	 */
922
-	public function deleteShare(\OCP\Share\IShare $share) {
923
-
924
-		try {
925
-			$share->getFullId();
926
-		} catch (\UnexpectedValueException $e) {
927
-			throw new \InvalidArgumentException('Share does not have a full id');
928
-		}
929
-
930
-		$event = new GenericEvent($share);
931
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
932
-
933
-		// Get all children and delete them as well
934
-		$deletedShares = $this->deleteChildren($share);
935
-
936
-		// Do the actual delete
937
-		$provider = $this->factory->getProviderForType($share->getShareType());
938
-		$provider->delete($share);
939
-
940
-		// All the deleted shares caused by this delete
941
-		$deletedShares[] = $share;
942
-
943
-		// Emit post hook
944
-		$event->setArgument('deletedShares', $deletedShares);
945
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
946
-	}
947
-
948
-
949
-	/**
950
-	 * Unshare a file as the recipient.
951
-	 * This can be different from a regular delete for example when one of
952
-	 * the users in a groups deletes that share. But the provider should
953
-	 * handle this.
954
-	 *
955
-	 * @param \OCP\Share\IShare $share
956
-	 * @param string $recipientId
957
-	 */
958
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
959
-		list($providerId, ) = $this->splitFullId($share->getFullId());
960
-		$provider = $this->factory->getProvider($providerId);
961
-
962
-		$provider->deleteFromSelf($share, $recipientId);
963
-		$event = new GenericEvent($share);
964
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
965
-	}
966
-
967
-	/**
968
-	 * @inheritdoc
969
-	 */
970
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
971
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
972
-			throw new \InvalidArgumentException('Can’t change target of link share');
973
-		}
974
-
975
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
976
-			throw new \InvalidArgumentException('Invalid recipient');
977
-		}
978
-
979
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
980
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
981
-			if (is_null($sharedWith)) {
982
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
983
-			}
984
-			$recipient = $this->userManager->get($recipientId);
985
-			if (!$sharedWith->inGroup($recipient)) {
986
-				throw new \InvalidArgumentException('Invalid recipient');
987
-			}
988
-		}
989
-
990
-		list($providerId, ) = $this->splitFullId($share->getFullId());
991
-		$provider = $this->factory->getProvider($providerId);
992
-
993
-		$provider->move($share, $recipientId);
994
-	}
995
-
996
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
997
-		$providers = $this->factory->getAllProviders();
998
-
999
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1000
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1001
-			foreach ($newShares as $fid => $data) {
1002
-				if (!isset($shares[$fid])) {
1003
-					$shares[$fid] = [];
1004
-				}
1005
-
1006
-				$shares[$fid] = array_merge($shares[$fid], $data);
1007
-			}
1008
-			return $shares;
1009
-		}, []);
1010
-	}
1011
-
1012
-	/**
1013
-	 * @inheritdoc
1014
-	 */
1015
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1016
-		if ($path !== null &&
1017
-				!($path instanceof \OCP\Files\File) &&
1018
-				!($path instanceof \OCP\Files\Folder)) {
1019
-			throw new \InvalidArgumentException('invalid path');
1020
-		}
1021
-
1022
-		try {
1023
-			$provider = $this->factory->getProviderForType($shareType);
1024
-		} catch (ProviderException $e) {
1025
-			return [];
1026
-		}
1027
-
1028
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1029
-
1030
-		/*
607
+            $share->setToken(
608
+                $this->secureRandom->generate(
609
+                    \OC\Share\Constants::TOKEN_LENGTH,
610
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
611
+                )
612
+            );
613
+
614
+            //Verify the expiration date
615
+            $this->validateExpirationDate($share);
616
+
617
+            //Verify the password
618
+            $this->verifyPassword($share->getPassword());
619
+
620
+            // If a password is set. Hash it!
621
+            if ($share->getPassword() !== null) {
622
+                $share->setPassword($this->hasher->hash($share->getPassword()));
623
+            }
624
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
625
+            $share->setToken(
626
+                $this->secureRandom->generate(
627
+                    \OC\Share\Constants::TOKEN_LENGTH,
628
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
629
+                )
630
+            );
631
+        }
632
+
633
+        // Cannot share with the owner
634
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
635
+            $share->getSharedWith() === $share->getShareOwner()) {
636
+            throw new \InvalidArgumentException('Can’t share with the share owner');
637
+        }
638
+
639
+        // Generate the target
640
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
641
+        $target = \OC\Files\Filesystem::normalizePath($target);
642
+        $share->setTarget($target);
643
+
644
+        // Pre share event
645
+        $event = new GenericEvent($share);
646
+        $a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
647
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
648
+            throw new \Exception($event->getArgument('error'));
649
+        }
650
+
651
+        $oldShare = $share;
652
+        $provider = $this->factory->getProviderForType($share->getShareType());
653
+        $share = $provider->create($share);
654
+        //reuse the node we already have
655
+        $share->setNode($oldShare->getNode());
656
+
657
+        // Post share event
658
+        $event = new GenericEvent($share);
659
+        $this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
660
+
661
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
662
+            $user = $this->userManager->get($share->getSharedWith());
663
+            if ($user !== null) {
664
+                $emailAddress = $user->getEMailAddress();
665
+                if ($emailAddress !== null && $emailAddress !== '') {
666
+                    $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
667
+                    $l = $this->l10nFactory->get('lib', $userLang);
668
+                    $this->sendMailNotification(
669
+                        $l,
670
+                        $share->getNode()->getName(),
671
+                        $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
672
+                        $share->getSharedBy(),
673
+                        $emailAddress,
674
+                        $share->getExpirationDate()
675
+                    );
676
+                    $this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
677
+                } else {
678
+                    $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
679
+                }
680
+            } else {
681
+                $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
682
+            }
683
+        }
684
+
685
+        return $share;
686
+    }
687
+
688
+    /**
689
+     * @param IL10N $l Language of the recipient
690
+     * @param string $filename file/folder name
691
+     * @param string $link link to the file/folder
692
+     * @param string $initiator user ID of share sender
693
+     * @param string $shareWith email address of share receiver
694
+     * @param \DateTime|null $expiration
695
+     * @throws \Exception If mail couldn't be sent
696
+     */
697
+    protected function sendMailNotification(IL10N $l,
698
+                                            $filename,
699
+                                            $link,
700
+                                            $initiator,
701
+                                            $shareWith,
702
+                                            \DateTime $expiration = null) {
703
+        $initiatorUser = $this->userManager->get($initiator);
704
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
705
+        $subject = $l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename));
706
+
707
+        $message = $this->mailer->createMessage();
708
+
709
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
710
+            'filename' => $filename,
711
+            'link' => $link,
712
+            'initiator' => $initiatorDisplayName,
713
+            'expiration' => $expiration,
714
+            'shareWith' => $shareWith,
715
+        ]);
716
+
717
+        $emailTemplate->addHeader();
718
+        $emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
719
+        $text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
720
+
721
+        $emailTemplate->addBodyText(
722
+            $text . ' ' . $l->t('Click the button below to open it.'),
723
+            $text
724
+        );
725
+        $emailTemplate->addBodyButton(
726
+            $l->t('Open »%s«', [$filename]),
727
+            $link
728
+        );
729
+
730
+        $message->setTo([$shareWith]);
731
+
732
+        // The "From" contains the sharers name
733
+        $instanceName = $this->defaults->getName();
734
+        $senderName = $l->t(
735
+            '%s via %s',
736
+            [
737
+                $initiatorDisplayName,
738
+                $instanceName
739
+            ]
740
+        );
741
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
742
+
743
+        // The "Reply-To" is set to the sharer if an mail address is configured
744
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
745
+        $initiatorEmail = $initiatorUser->getEMailAddress();
746
+        if($initiatorEmail !== null) {
747
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
748
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
749
+        } else {
750
+            $emailTemplate->addFooter();
751
+        }
752
+
753
+        $message->setSubject($subject);
754
+        $message->setPlainBody($emailTemplate->renderText());
755
+        $message->setHtmlBody($emailTemplate->renderHtml());
756
+        $this->mailer->send($message);
757
+    }
758
+
759
+    /**
760
+     * Update a share
761
+     *
762
+     * @param \OCP\Share\IShare $share
763
+     * @return \OCP\Share\IShare The share object
764
+     * @throws \InvalidArgumentException
765
+     */
766
+    public function updateShare(\OCP\Share\IShare $share) {
767
+        $expirationDateUpdated = false;
768
+
769
+        $this->canShare($share);
770
+
771
+        try {
772
+            $originalShare = $this->getShareById($share->getFullId());
773
+        } catch (\UnexpectedValueException $e) {
774
+            throw new \InvalidArgumentException('Share does not have a full id');
775
+        }
776
+
777
+        // We can't change the share type!
778
+        if ($share->getShareType() !== $originalShare->getShareType()) {
779
+            throw new \InvalidArgumentException('Can’t change share type');
780
+        }
781
+
782
+        // We can only change the recipient on user shares
783
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
784
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
785
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
786
+        }
787
+
788
+        // Cannot share with the owner
789
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
790
+            $share->getSharedWith() === $share->getShareOwner()) {
791
+            throw new \InvalidArgumentException('Can’t share with the share owner');
792
+        }
793
+
794
+        $this->generalCreateChecks($share);
795
+
796
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
797
+            $this->userCreateChecks($share);
798
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
799
+            $this->groupCreateChecks($share);
800
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
801
+            $this->linkCreateChecks($share);
802
+
803
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
804
+
805
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
806
+                //Verify the expiration date
807
+                $this->validateExpirationDate($share);
808
+                $expirationDateUpdated = true;
809
+            }
810
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
811
+            $plainTextPassword = $share->getPassword();
812
+            if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
813
+                $plainTextPassword = null;
814
+            }
815
+        }
816
+
817
+        $this->pathCreateChecks($share->getNode());
818
+
819
+        // Now update the share!
820
+        $provider = $this->factory->getProviderForType($share->getShareType());
821
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
822
+            $share = $provider->update($share, $plainTextPassword);
823
+        } else {
824
+            $share = $provider->update($share);
825
+        }
826
+
827
+        if ($expirationDateUpdated === true) {
828
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
829
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
830
+                'itemSource' => $share->getNode()->getId(),
831
+                'date' => $share->getExpirationDate(),
832
+                'uidOwner' => $share->getSharedBy(),
833
+            ]);
834
+        }
835
+
836
+        if ($share->getPassword() !== $originalShare->getPassword()) {
837
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
838
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
839
+                'itemSource' => $share->getNode()->getId(),
840
+                'uidOwner' => $share->getSharedBy(),
841
+                'token' => $share->getToken(),
842
+                'disabled' => is_null($share->getPassword()),
843
+            ]);
844
+        }
845
+
846
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
847
+            if ($this->userManager->userExists($share->getShareOwner())) {
848
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
849
+            } else {
850
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
851
+            }
852
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
853
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
854
+                'itemSource' => $share->getNode()->getId(),
855
+                'shareType' => $share->getShareType(),
856
+                'shareWith' => $share->getSharedWith(),
857
+                'uidOwner' => $share->getSharedBy(),
858
+                'permissions' => $share->getPermissions(),
859
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
860
+            ));
861
+        }
862
+
863
+        return $share;
864
+    }
865
+
866
+    /**
867
+     * Updates the password of the given share if it is not the same as the
868
+     * password of the original share.
869
+     *
870
+     * @param \OCP\Share\IShare $share the share to update its password.
871
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
872
+     *        password with.
873
+     * @return boolean whether the password was updated or not.
874
+     */
875
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
876
+        // Password updated.
877
+        if ($share->getPassword() !== $originalShare->getPassword()) {
878
+            //Verify the password
879
+            $this->verifyPassword($share->getPassword());
880
+
881
+            // If a password is set. Hash it!
882
+            if ($share->getPassword() !== null) {
883
+                $share->setPassword($this->hasher->hash($share->getPassword()));
884
+
885
+                return true;
886
+            }
887
+        }
888
+
889
+        return false;
890
+    }
891
+
892
+    /**
893
+     * Delete all the children of this share
894
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
895
+     *
896
+     * @param \OCP\Share\IShare $share
897
+     * @return \OCP\Share\IShare[] List of deleted shares
898
+     */
899
+    protected function deleteChildren(\OCP\Share\IShare $share) {
900
+        $deletedShares = [];
901
+
902
+        $provider = $this->factory->getProviderForType($share->getShareType());
903
+
904
+        foreach ($provider->getChildren($share) as $child) {
905
+            $deletedChildren = $this->deleteChildren($child);
906
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
907
+
908
+            $provider->delete($child);
909
+            $deletedShares[] = $child;
910
+        }
911
+
912
+        return $deletedShares;
913
+    }
914
+
915
+    /**
916
+     * Delete a share
917
+     *
918
+     * @param \OCP\Share\IShare $share
919
+     * @throws ShareNotFound
920
+     * @throws \InvalidArgumentException
921
+     */
922
+    public function deleteShare(\OCP\Share\IShare $share) {
923
+
924
+        try {
925
+            $share->getFullId();
926
+        } catch (\UnexpectedValueException $e) {
927
+            throw new \InvalidArgumentException('Share does not have a full id');
928
+        }
929
+
930
+        $event = new GenericEvent($share);
931
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
932
+
933
+        // Get all children and delete them as well
934
+        $deletedShares = $this->deleteChildren($share);
935
+
936
+        // Do the actual delete
937
+        $provider = $this->factory->getProviderForType($share->getShareType());
938
+        $provider->delete($share);
939
+
940
+        // All the deleted shares caused by this delete
941
+        $deletedShares[] = $share;
942
+
943
+        // Emit post hook
944
+        $event->setArgument('deletedShares', $deletedShares);
945
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
946
+    }
947
+
948
+
949
+    /**
950
+     * Unshare a file as the recipient.
951
+     * This can be different from a regular delete for example when one of
952
+     * the users in a groups deletes that share. But the provider should
953
+     * handle this.
954
+     *
955
+     * @param \OCP\Share\IShare $share
956
+     * @param string $recipientId
957
+     */
958
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
959
+        list($providerId, ) = $this->splitFullId($share->getFullId());
960
+        $provider = $this->factory->getProvider($providerId);
961
+
962
+        $provider->deleteFromSelf($share, $recipientId);
963
+        $event = new GenericEvent($share);
964
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
965
+    }
966
+
967
+    /**
968
+     * @inheritdoc
969
+     */
970
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
971
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
972
+            throw new \InvalidArgumentException('Can’t change target of link share');
973
+        }
974
+
975
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
976
+            throw new \InvalidArgumentException('Invalid recipient');
977
+        }
978
+
979
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
980
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
981
+            if (is_null($sharedWith)) {
982
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
983
+            }
984
+            $recipient = $this->userManager->get($recipientId);
985
+            if (!$sharedWith->inGroup($recipient)) {
986
+                throw new \InvalidArgumentException('Invalid recipient');
987
+            }
988
+        }
989
+
990
+        list($providerId, ) = $this->splitFullId($share->getFullId());
991
+        $provider = $this->factory->getProvider($providerId);
992
+
993
+        $provider->move($share, $recipientId);
994
+    }
995
+
996
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
997
+        $providers = $this->factory->getAllProviders();
998
+
999
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1000
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1001
+            foreach ($newShares as $fid => $data) {
1002
+                if (!isset($shares[$fid])) {
1003
+                    $shares[$fid] = [];
1004
+                }
1005
+
1006
+                $shares[$fid] = array_merge($shares[$fid], $data);
1007
+            }
1008
+            return $shares;
1009
+        }, []);
1010
+    }
1011
+
1012
+    /**
1013
+     * @inheritdoc
1014
+     */
1015
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1016
+        if ($path !== null &&
1017
+                !($path instanceof \OCP\Files\File) &&
1018
+                !($path instanceof \OCP\Files\Folder)) {
1019
+            throw new \InvalidArgumentException('invalid path');
1020
+        }
1021
+
1022
+        try {
1023
+            $provider = $this->factory->getProviderForType($shareType);
1024
+        } catch (ProviderException $e) {
1025
+            return [];
1026
+        }
1027
+
1028
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1029
+
1030
+        /*
1031 1031
 		 * Work around so we don't return expired shares but still follow
1032 1032
 		 * proper pagination.
1033 1033
 		 */
1034 1034
 
1035
-		$shares2 = [];
1036
-
1037
-		while(true) {
1038
-			$added = 0;
1039
-			foreach ($shares as $share) {
1040
-
1041
-				try {
1042
-					$this->checkExpireDate($share);
1043
-				} catch (ShareNotFound $e) {
1044
-					//Ignore since this basically means the share is deleted
1045
-					continue;
1046
-				}
1047
-
1048
-				$added++;
1049
-				$shares2[] = $share;
1050
-
1051
-				if (count($shares2) === $limit) {
1052
-					break;
1053
-				}
1054
-			}
1055
-
1056
-			// If we did not fetch more shares than the limit then there are no more shares
1057
-			if (count($shares) < $limit) {
1058
-				break;
1059
-			}
1060
-
1061
-			if (count($shares2) === $limit) {
1062
-				break;
1063
-			}
1064
-
1065
-			// If there was no limit on the select we are done
1066
-			if ($limit === -1) {
1067
-				break;
1068
-			}
1069
-
1070
-			$offset += $added;
1071
-
1072
-			// Fetch again $limit shares
1073
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1074
-
1075
-			// No more shares means we are done
1076
-			if (empty($shares)) {
1077
-				break;
1078
-			}
1079
-		}
1080
-
1081
-		$shares = $shares2;
1082
-
1083
-		return $shares;
1084
-	}
1085
-
1086
-	/**
1087
-	 * @inheritdoc
1088
-	 */
1089
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1090
-		try {
1091
-			$provider = $this->factory->getProviderForType($shareType);
1092
-		} catch (ProviderException $e) {
1093
-			return [];
1094
-		}
1095
-
1096
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1097
-
1098
-		// remove all shares which are already expired
1099
-		foreach ($shares as $key => $share) {
1100
-			try {
1101
-				$this->checkExpireDate($share);
1102
-			} catch (ShareNotFound $e) {
1103
-				unset($shares[$key]);
1104
-			}
1105
-		}
1106
-
1107
-		return $shares;
1108
-	}
1109
-
1110
-	/**
1111
-	 * @inheritdoc
1112
-	 */
1113
-	public function getShareById($id, $recipient = null) {
1114
-		if ($id === null) {
1115
-			throw new ShareNotFound();
1116
-		}
1117
-
1118
-		list($providerId, $id) = $this->splitFullId($id);
1119
-
1120
-		try {
1121
-			$provider = $this->factory->getProvider($providerId);
1122
-		} catch (ProviderException $e) {
1123
-			throw new ShareNotFound();
1124
-		}
1125
-
1126
-		$share = $provider->getShareById($id, $recipient);
1127
-
1128
-		$this->checkExpireDate($share);
1129
-
1130
-		return $share;
1131
-	}
1132
-
1133
-	/**
1134
-	 * Get all the shares for a given path
1135
-	 *
1136
-	 * @param \OCP\Files\Node $path
1137
-	 * @param int $page
1138
-	 * @param int $perPage
1139
-	 *
1140
-	 * @return Share[]
1141
-	 */
1142
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1143
-		return [];
1144
-	}
1145
-
1146
-	/**
1147
-	 * Get the share by token possible with password
1148
-	 *
1149
-	 * @param string $token
1150
-	 * @return Share
1151
-	 *
1152
-	 * @throws ShareNotFound
1153
-	 */
1154
-	public function getShareByToken($token) {
1155
-		$share = null;
1156
-		try {
1157
-			if($this->shareApiAllowLinks()) {
1158
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1159
-				$share = $provider->getShareByToken($token);
1160
-			}
1161
-		} catch (ProviderException $e) {
1162
-		} catch (ShareNotFound $e) {
1163
-		}
1164
-
1165
-
1166
-		// If it is not a link share try to fetch a federated share by token
1167
-		if ($share === null) {
1168
-			try {
1169
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1170
-				$share = $provider->getShareByToken($token);
1171
-			} catch (ProviderException $e) {
1172
-			} catch (ShareNotFound $e) {
1173
-			}
1174
-		}
1175
-
1176
-		// If it is not a link share try to fetch a mail share by token
1177
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1178
-			try {
1179
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1180
-				$share = $provider->getShareByToken($token);
1181
-			} catch (ProviderException $e) {
1182
-			} catch (ShareNotFound $e) {
1183
-			}
1184
-		}
1185
-
1186
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1187
-			try {
1188
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1189
-				$share = $provider->getShareByToken($token);
1190
-			} catch (ProviderException $e) {
1191
-			} catch (ShareNotFound $e) {
1192
-			}
1193
-		}
1194
-
1195
-		if ($share === null) {
1196
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1197
-		}
1198
-
1199
-		$this->checkExpireDate($share);
1200
-
1201
-		/*
1035
+        $shares2 = [];
1036
+
1037
+        while(true) {
1038
+            $added = 0;
1039
+            foreach ($shares as $share) {
1040
+
1041
+                try {
1042
+                    $this->checkExpireDate($share);
1043
+                } catch (ShareNotFound $e) {
1044
+                    //Ignore since this basically means the share is deleted
1045
+                    continue;
1046
+                }
1047
+
1048
+                $added++;
1049
+                $shares2[] = $share;
1050
+
1051
+                if (count($shares2) === $limit) {
1052
+                    break;
1053
+                }
1054
+            }
1055
+
1056
+            // If we did not fetch more shares than the limit then there are no more shares
1057
+            if (count($shares) < $limit) {
1058
+                break;
1059
+            }
1060
+
1061
+            if (count($shares2) === $limit) {
1062
+                break;
1063
+            }
1064
+
1065
+            // If there was no limit on the select we are done
1066
+            if ($limit === -1) {
1067
+                break;
1068
+            }
1069
+
1070
+            $offset += $added;
1071
+
1072
+            // Fetch again $limit shares
1073
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1074
+
1075
+            // No more shares means we are done
1076
+            if (empty($shares)) {
1077
+                break;
1078
+            }
1079
+        }
1080
+
1081
+        $shares = $shares2;
1082
+
1083
+        return $shares;
1084
+    }
1085
+
1086
+    /**
1087
+     * @inheritdoc
1088
+     */
1089
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1090
+        try {
1091
+            $provider = $this->factory->getProviderForType($shareType);
1092
+        } catch (ProviderException $e) {
1093
+            return [];
1094
+        }
1095
+
1096
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1097
+
1098
+        // remove all shares which are already expired
1099
+        foreach ($shares as $key => $share) {
1100
+            try {
1101
+                $this->checkExpireDate($share);
1102
+            } catch (ShareNotFound $e) {
1103
+                unset($shares[$key]);
1104
+            }
1105
+        }
1106
+
1107
+        return $shares;
1108
+    }
1109
+
1110
+    /**
1111
+     * @inheritdoc
1112
+     */
1113
+    public function getShareById($id, $recipient = null) {
1114
+        if ($id === null) {
1115
+            throw new ShareNotFound();
1116
+        }
1117
+
1118
+        list($providerId, $id) = $this->splitFullId($id);
1119
+
1120
+        try {
1121
+            $provider = $this->factory->getProvider($providerId);
1122
+        } catch (ProviderException $e) {
1123
+            throw new ShareNotFound();
1124
+        }
1125
+
1126
+        $share = $provider->getShareById($id, $recipient);
1127
+
1128
+        $this->checkExpireDate($share);
1129
+
1130
+        return $share;
1131
+    }
1132
+
1133
+    /**
1134
+     * Get all the shares for a given path
1135
+     *
1136
+     * @param \OCP\Files\Node $path
1137
+     * @param int $page
1138
+     * @param int $perPage
1139
+     *
1140
+     * @return Share[]
1141
+     */
1142
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1143
+        return [];
1144
+    }
1145
+
1146
+    /**
1147
+     * Get the share by token possible with password
1148
+     *
1149
+     * @param string $token
1150
+     * @return Share
1151
+     *
1152
+     * @throws ShareNotFound
1153
+     */
1154
+    public function getShareByToken($token) {
1155
+        $share = null;
1156
+        try {
1157
+            if($this->shareApiAllowLinks()) {
1158
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1159
+                $share = $provider->getShareByToken($token);
1160
+            }
1161
+        } catch (ProviderException $e) {
1162
+        } catch (ShareNotFound $e) {
1163
+        }
1164
+
1165
+
1166
+        // If it is not a link share try to fetch a federated share by token
1167
+        if ($share === null) {
1168
+            try {
1169
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1170
+                $share = $provider->getShareByToken($token);
1171
+            } catch (ProviderException $e) {
1172
+            } catch (ShareNotFound $e) {
1173
+            }
1174
+        }
1175
+
1176
+        // If it is not a link share try to fetch a mail share by token
1177
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1178
+            try {
1179
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1180
+                $share = $provider->getShareByToken($token);
1181
+            } catch (ProviderException $e) {
1182
+            } catch (ShareNotFound $e) {
1183
+            }
1184
+        }
1185
+
1186
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1187
+            try {
1188
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1189
+                $share = $provider->getShareByToken($token);
1190
+            } catch (ProviderException $e) {
1191
+            } catch (ShareNotFound $e) {
1192
+            }
1193
+        }
1194
+
1195
+        if ($share === null) {
1196
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1197
+        }
1198
+
1199
+        $this->checkExpireDate($share);
1200
+
1201
+        /*
1202 1202
 		 * Reduce the permissions for link shares if public upload is not enabled
1203 1203
 		 */
1204
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1205
-			!$this->shareApiLinkAllowPublicUpload()) {
1206
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1207
-		}
1208
-
1209
-		return $share;
1210
-	}
1211
-
1212
-	protected function checkExpireDate($share) {
1213
-		if ($share->getExpirationDate() !== null &&
1214
-			$share->getExpirationDate() <= new \DateTime()) {
1215
-			$this->deleteShare($share);
1216
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1217
-		}
1218
-
1219
-	}
1220
-
1221
-	/**
1222
-	 * Verify the password of a public share
1223
-	 *
1224
-	 * @param \OCP\Share\IShare $share
1225
-	 * @param string $password
1226
-	 * @return bool
1227
-	 */
1228
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1229
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1230
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1231
-		if (!$passwordProtected) {
1232
-			//TODO maybe exception?
1233
-			return false;
1234
-		}
1235
-
1236
-		if ($password === null || $share->getPassword() === null) {
1237
-			return false;
1238
-		}
1239
-
1240
-		$newHash = '';
1241
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1242
-			return false;
1243
-		}
1244
-
1245
-		if (!empty($newHash)) {
1246
-			$share->setPassword($newHash);
1247
-			$provider = $this->factory->getProviderForType($share->getShareType());
1248
-			$provider->update($share);
1249
-		}
1250
-
1251
-		return true;
1252
-	}
1253
-
1254
-	/**
1255
-	 * @inheritdoc
1256
-	 */
1257
-	public function userDeleted($uid) {
1258
-		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1259
-
1260
-		foreach ($types as $type) {
1261
-			try {
1262
-				$provider = $this->factory->getProviderForType($type);
1263
-			} catch (ProviderException $e) {
1264
-				continue;
1265
-			}
1266
-			$provider->userDeleted($uid, $type);
1267
-		}
1268
-	}
1269
-
1270
-	/**
1271
-	 * @inheritdoc
1272
-	 */
1273
-	public function groupDeleted($gid) {
1274
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1275
-		$provider->groupDeleted($gid);
1276
-	}
1277
-
1278
-	/**
1279
-	 * @inheritdoc
1280
-	 */
1281
-	public function userDeletedFromGroup($uid, $gid) {
1282
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1283
-		$provider->userDeletedFromGroup($uid, $gid);
1284
-	}
1285
-
1286
-	/**
1287
-	 * Get access list to a path. This means
1288
-	 * all the users that can access a given path.
1289
-	 *
1290
-	 * Consider:
1291
-	 * -root
1292
-	 * |-folder1 (23)
1293
-	 *  |-folder2 (32)
1294
-	 *   |-fileA (42)
1295
-	 *
1296
-	 * fileA is shared with user1 and user1@server1
1297
-	 * folder2 is shared with group2 (user4 is a member of group2)
1298
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1299
-	 *
1300
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1301
-	 * [
1302
-	 *  users  => [
1303
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1304
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1305
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1306
-	 *  ],
1307
-	 *  remote => [
1308
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1309
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1310
-	 *  ],
1311
-	 *  public => bool
1312
-	 *  mail => bool
1313
-	 * ]
1314
-	 *
1315
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1316
-	 * [
1317
-	 *  users  => ['user1', 'user2', 'user4'],
1318
-	 *  remote => bool,
1319
-	 *  public => bool
1320
-	 *  mail => bool
1321
-	 * ]
1322
-	 *
1323
-	 * This is required for encryption/activity
1324
-	 *
1325
-	 * @param \OCP\Files\Node $path
1326
-	 * @param bool $recursive Should we check all parent folders as well
1327
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1328
-	 * @return array
1329
-	 */
1330
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1331
-		$owner = $path->getOwner()->getUID();
1332
-
1333
-		if ($currentAccess) {
1334
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1335
-		} else {
1336
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1337
-		}
1338
-		if (!$this->userManager->userExists($owner)) {
1339
-			return $al;
1340
-		}
1341
-
1342
-		//Get node for the owner
1343
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1344
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1345
-			$path = $userFolder->getById($path->getId())[0];
1346
-		}
1347
-
1348
-		$providers = $this->factory->getAllProviders();
1349
-
1350
-		/** @var Node[] $nodes */
1351
-		$nodes = [];
1352
-
1353
-
1354
-		if ($currentAccess) {
1355
-			$ownerPath = $path->getPath();
1356
-			$ownerPath = explode('/', $ownerPath, 4);
1357
-			if (count($ownerPath) < 4) {
1358
-				$ownerPath = '';
1359
-			} else {
1360
-				$ownerPath = $ownerPath[3];
1361
-			}
1362
-			$al['users'][$owner] = [
1363
-				'node_id' => $path->getId(),
1364
-				'node_path' => '/' . $ownerPath,
1365
-			];
1366
-		} else {
1367
-			$al['users'][] = $owner;
1368
-		}
1369
-
1370
-		// Collect all the shares
1371
-		while ($path->getPath() !== $userFolder->getPath()) {
1372
-			$nodes[] = $path;
1373
-			if (!$recursive) {
1374
-				break;
1375
-			}
1376
-			$path = $path->getParent();
1377
-		}
1378
-
1379
-		foreach ($providers as $provider) {
1380
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1381
-
1382
-			foreach ($tmp as $k => $v) {
1383
-				if (isset($al[$k])) {
1384
-					if (is_array($al[$k])) {
1385
-						$al[$k] = array_merge($al[$k], $v);
1386
-					} else {
1387
-						$al[$k] = $al[$k] || $v;
1388
-					}
1389
-				} else {
1390
-					$al[$k] = $v;
1391
-				}
1392
-			}
1393
-		}
1394
-
1395
-		return $al;
1396
-	}
1397
-
1398
-	/**
1399
-	 * Create a new share
1400
-	 * @return \OCP\Share\IShare;
1401
-	 */
1402
-	public function newShare() {
1403
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1404
-	}
1405
-
1406
-	/**
1407
-	 * Is the share API enabled
1408
-	 *
1409
-	 * @return bool
1410
-	 */
1411
-	public function shareApiEnabled() {
1412
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1413
-	}
1414
-
1415
-	/**
1416
-	 * Is public link sharing enabled
1417
-	 *
1418
-	 * @return bool
1419
-	 */
1420
-	public function shareApiAllowLinks() {
1421
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1422
-	}
1423
-
1424
-	/**
1425
-	 * Is password on public link requires
1426
-	 *
1427
-	 * @return bool
1428
-	 */
1429
-	public function shareApiLinkEnforcePassword() {
1430
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1431
-	}
1432
-
1433
-	/**
1434
-	 * Is default expire date enabled
1435
-	 *
1436
-	 * @return bool
1437
-	 */
1438
-	public function shareApiLinkDefaultExpireDate() {
1439
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1440
-	}
1441
-
1442
-	/**
1443
-	 * Is default expire date enforced
1444
-	 *`
1445
-	 * @return bool
1446
-	 */
1447
-	public function shareApiLinkDefaultExpireDateEnforced() {
1448
-		return $this->shareApiLinkDefaultExpireDate() &&
1449
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1450
-	}
1451
-
1452
-	/**
1453
-	 * Number of default expire days
1454
-	 *shareApiLinkAllowPublicUpload
1455
-	 * @return int
1456
-	 */
1457
-	public function shareApiLinkDefaultExpireDays() {
1458
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1459
-	}
1460
-
1461
-	/**
1462
-	 * Allow public upload on link shares
1463
-	 *
1464
-	 * @return bool
1465
-	 */
1466
-	public function shareApiLinkAllowPublicUpload() {
1467
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1468
-	}
1469
-
1470
-	/**
1471
-	 * check if user can only share with group members
1472
-	 * @return bool
1473
-	 */
1474
-	public function shareWithGroupMembersOnly() {
1475
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1476
-	}
1477
-
1478
-	/**
1479
-	 * Check if users can share with groups
1480
-	 * @return bool
1481
-	 */
1482
-	public function allowGroupSharing() {
1483
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1484
-	}
1485
-
1486
-	/**
1487
-	 * Copied from \OC_Util::isSharingDisabledForUser
1488
-	 *
1489
-	 * TODO: Deprecate fuction from OC_Util
1490
-	 *
1491
-	 * @param string $userId
1492
-	 * @return bool
1493
-	 */
1494
-	public function sharingDisabledForUser($userId) {
1495
-		if ($userId === null) {
1496
-			return false;
1497
-		}
1498
-
1499
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1500
-			return $this->sharingDisabledForUsersCache[$userId];
1501
-		}
1502
-
1503
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1504
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1505
-			$excludedGroups = json_decode($groupsList);
1506
-			if (is_null($excludedGroups)) {
1507
-				$excludedGroups = explode(',', $groupsList);
1508
-				$newValue = json_encode($excludedGroups);
1509
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1510
-			}
1511
-			$user = $this->userManager->get($userId);
1512
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1513
-			if (!empty($usersGroups)) {
1514
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1515
-				// if the user is only in groups which are disabled for sharing then
1516
-				// sharing is also disabled for the user
1517
-				if (empty($remainingGroups)) {
1518
-					$this->sharingDisabledForUsersCache[$userId] = true;
1519
-					return true;
1520
-				}
1521
-			}
1522
-		}
1523
-
1524
-		$this->sharingDisabledForUsersCache[$userId] = false;
1525
-		return false;
1526
-	}
1527
-
1528
-	/**
1529
-	 * @inheritdoc
1530
-	 */
1531
-	public function outgoingServer2ServerSharesAllowed() {
1532
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1533
-	}
1534
-
1535
-	/**
1536
-	 * @inheritdoc
1537
-	 */
1538
-	public function shareProviderExists($shareType) {
1539
-		try {
1540
-			$this->factory->getProviderForType($shareType);
1541
-		} catch (ProviderException $e) {
1542
-			return false;
1543
-		}
1544
-
1545
-		return true;
1546
-	}
1204
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1205
+            !$this->shareApiLinkAllowPublicUpload()) {
1206
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1207
+        }
1208
+
1209
+        return $share;
1210
+    }
1211
+
1212
+    protected function checkExpireDate($share) {
1213
+        if ($share->getExpirationDate() !== null &&
1214
+            $share->getExpirationDate() <= new \DateTime()) {
1215
+            $this->deleteShare($share);
1216
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1217
+        }
1218
+
1219
+    }
1220
+
1221
+    /**
1222
+     * Verify the password of a public share
1223
+     *
1224
+     * @param \OCP\Share\IShare $share
1225
+     * @param string $password
1226
+     * @return bool
1227
+     */
1228
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1229
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1230
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1231
+        if (!$passwordProtected) {
1232
+            //TODO maybe exception?
1233
+            return false;
1234
+        }
1235
+
1236
+        if ($password === null || $share->getPassword() === null) {
1237
+            return false;
1238
+        }
1239
+
1240
+        $newHash = '';
1241
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1242
+            return false;
1243
+        }
1244
+
1245
+        if (!empty($newHash)) {
1246
+            $share->setPassword($newHash);
1247
+            $provider = $this->factory->getProviderForType($share->getShareType());
1248
+            $provider->update($share);
1249
+        }
1250
+
1251
+        return true;
1252
+    }
1253
+
1254
+    /**
1255
+     * @inheritdoc
1256
+     */
1257
+    public function userDeleted($uid) {
1258
+        $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1259
+
1260
+        foreach ($types as $type) {
1261
+            try {
1262
+                $provider = $this->factory->getProviderForType($type);
1263
+            } catch (ProviderException $e) {
1264
+                continue;
1265
+            }
1266
+            $provider->userDeleted($uid, $type);
1267
+        }
1268
+    }
1269
+
1270
+    /**
1271
+     * @inheritdoc
1272
+     */
1273
+    public function groupDeleted($gid) {
1274
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1275
+        $provider->groupDeleted($gid);
1276
+    }
1277
+
1278
+    /**
1279
+     * @inheritdoc
1280
+     */
1281
+    public function userDeletedFromGroup($uid, $gid) {
1282
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1283
+        $provider->userDeletedFromGroup($uid, $gid);
1284
+    }
1285
+
1286
+    /**
1287
+     * Get access list to a path. This means
1288
+     * all the users that can access a given path.
1289
+     *
1290
+     * Consider:
1291
+     * -root
1292
+     * |-folder1 (23)
1293
+     *  |-folder2 (32)
1294
+     *   |-fileA (42)
1295
+     *
1296
+     * fileA is shared with user1 and user1@server1
1297
+     * folder2 is shared with group2 (user4 is a member of group2)
1298
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1299
+     *
1300
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1301
+     * [
1302
+     *  users  => [
1303
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1304
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1305
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1306
+     *  ],
1307
+     *  remote => [
1308
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1309
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1310
+     *  ],
1311
+     *  public => bool
1312
+     *  mail => bool
1313
+     * ]
1314
+     *
1315
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1316
+     * [
1317
+     *  users  => ['user1', 'user2', 'user4'],
1318
+     *  remote => bool,
1319
+     *  public => bool
1320
+     *  mail => bool
1321
+     * ]
1322
+     *
1323
+     * This is required for encryption/activity
1324
+     *
1325
+     * @param \OCP\Files\Node $path
1326
+     * @param bool $recursive Should we check all parent folders as well
1327
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1328
+     * @return array
1329
+     */
1330
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1331
+        $owner = $path->getOwner()->getUID();
1332
+
1333
+        if ($currentAccess) {
1334
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1335
+        } else {
1336
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1337
+        }
1338
+        if (!$this->userManager->userExists($owner)) {
1339
+            return $al;
1340
+        }
1341
+
1342
+        //Get node for the owner
1343
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1344
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1345
+            $path = $userFolder->getById($path->getId())[0];
1346
+        }
1347
+
1348
+        $providers = $this->factory->getAllProviders();
1349
+
1350
+        /** @var Node[] $nodes */
1351
+        $nodes = [];
1352
+
1353
+
1354
+        if ($currentAccess) {
1355
+            $ownerPath = $path->getPath();
1356
+            $ownerPath = explode('/', $ownerPath, 4);
1357
+            if (count($ownerPath) < 4) {
1358
+                $ownerPath = '';
1359
+            } else {
1360
+                $ownerPath = $ownerPath[3];
1361
+            }
1362
+            $al['users'][$owner] = [
1363
+                'node_id' => $path->getId(),
1364
+                'node_path' => '/' . $ownerPath,
1365
+            ];
1366
+        } else {
1367
+            $al['users'][] = $owner;
1368
+        }
1369
+
1370
+        // Collect all the shares
1371
+        while ($path->getPath() !== $userFolder->getPath()) {
1372
+            $nodes[] = $path;
1373
+            if (!$recursive) {
1374
+                break;
1375
+            }
1376
+            $path = $path->getParent();
1377
+        }
1378
+
1379
+        foreach ($providers as $provider) {
1380
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1381
+
1382
+            foreach ($tmp as $k => $v) {
1383
+                if (isset($al[$k])) {
1384
+                    if (is_array($al[$k])) {
1385
+                        $al[$k] = array_merge($al[$k], $v);
1386
+                    } else {
1387
+                        $al[$k] = $al[$k] || $v;
1388
+                    }
1389
+                } else {
1390
+                    $al[$k] = $v;
1391
+                }
1392
+            }
1393
+        }
1394
+
1395
+        return $al;
1396
+    }
1397
+
1398
+    /**
1399
+     * Create a new share
1400
+     * @return \OCP\Share\IShare;
1401
+     */
1402
+    public function newShare() {
1403
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1404
+    }
1405
+
1406
+    /**
1407
+     * Is the share API enabled
1408
+     *
1409
+     * @return bool
1410
+     */
1411
+    public function shareApiEnabled() {
1412
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1413
+    }
1414
+
1415
+    /**
1416
+     * Is public link sharing enabled
1417
+     *
1418
+     * @return bool
1419
+     */
1420
+    public function shareApiAllowLinks() {
1421
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1422
+    }
1423
+
1424
+    /**
1425
+     * Is password on public link requires
1426
+     *
1427
+     * @return bool
1428
+     */
1429
+    public function shareApiLinkEnforcePassword() {
1430
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1431
+    }
1432
+
1433
+    /**
1434
+     * Is default expire date enabled
1435
+     *
1436
+     * @return bool
1437
+     */
1438
+    public function shareApiLinkDefaultExpireDate() {
1439
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1440
+    }
1441
+
1442
+    /**
1443
+     * Is default expire date enforced
1444
+     *`
1445
+     * @return bool
1446
+     */
1447
+    public function shareApiLinkDefaultExpireDateEnforced() {
1448
+        return $this->shareApiLinkDefaultExpireDate() &&
1449
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1450
+    }
1451
+
1452
+    /**
1453
+     * Number of default expire days
1454
+     *shareApiLinkAllowPublicUpload
1455
+     * @return int
1456
+     */
1457
+    public function shareApiLinkDefaultExpireDays() {
1458
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1459
+    }
1460
+
1461
+    /**
1462
+     * Allow public upload on link shares
1463
+     *
1464
+     * @return bool
1465
+     */
1466
+    public function shareApiLinkAllowPublicUpload() {
1467
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1468
+    }
1469
+
1470
+    /**
1471
+     * check if user can only share with group members
1472
+     * @return bool
1473
+     */
1474
+    public function shareWithGroupMembersOnly() {
1475
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1476
+    }
1477
+
1478
+    /**
1479
+     * Check if users can share with groups
1480
+     * @return bool
1481
+     */
1482
+    public function allowGroupSharing() {
1483
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1484
+    }
1485
+
1486
+    /**
1487
+     * Copied from \OC_Util::isSharingDisabledForUser
1488
+     *
1489
+     * TODO: Deprecate fuction from OC_Util
1490
+     *
1491
+     * @param string $userId
1492
+     * @return bool
1493
+     */
1494
+    public function sharingDisabledForUser($userId) {
1495
+        if ($userId === null) {
1496
+            return false;
1497
+        }
1498
+
1499
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1500
+            return $this->sharingDisabledForUsersCache[$userId];
1501
+        }
1502
+
1503
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1504
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1505
+            $excludedGroups = json_decode($groupsList);
1506
+            if (is_null($excludedGroups)) {
1507
+                $excludedGroups = explode(',', $groupsList);
1508
+                $newValue = json_encode($excludedGroups);
1509
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1510
+            }
1511
+            $user = $this->userManager->get($userId);
1512
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1513
+            if (!empty($usersGroups)) {
1514
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1515
+                // if the user is only in groups which are disabled for sharing then
1516
+                // sharing is also disabled for the user
1517
+                if (empty($remainingGroups)) {
1518
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1519
+                    return true;
1520
+                }
1521
+            }
1522
+        }
1523
+
1524
+        $this->sharingDisabledForUsersCache[$userId] = false;
1525
+        return false;
1526
+    }
1527
+
1528
+    /**
1529
+     * @inheritdoc
1530
+     */
1531
+    public function outgoingServer2ServerSharesAllowed() {
1532
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1533
+    }
1534
+
1535
+    /**
1536
+     * @inheritdoc
1537
+     */
1538
+    public function shareProviderExists($shareType) {
1539
+        try {
1540
+            $this->factory->getProviderForType($shareType);
1541
+        } catch (ProviderException $e) {
1542
+            return false;
1543
+        }
1544
+
1545
+        return true;
1546
+    }
1547 1547
 
1548 1548
 }
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +1714 added lines, -1714 removed lines patch added patch discarded remove patch
@@ -132,1723 +132,1723 @@
 block discarded – undo
132 132
  * TODO: hookup all manager classes
133 133
  */
134 134
 class Server extends ServerContainer implements IServerContainer {
135
-	/** @var string */
136
-	private $webRoot;
137
-
138
-	/**
139
-	 * @param string $webRoot
140
-	 * @param \OC\Config $config
141
-	 */
142
-	public function __construct($webRoot, \OC\Config $config) {
143
-		parent::__construct();
144
-		$this->webRoot = $webRoot;
145
-
146
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
147
-			return $c;
148
-		});
149
-
150
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
151
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
152
-
153
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
154
-
155
-
156
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
157
-			return new PreviewManager(
158
-				$c->getConfig(),
159
-				$c->getRootFolder(),
160
-				$c->getAppDataDir('preview'),
161
-				$c->getEventDispatcher(),
162
-				$c->getSession()->get('user_id')
163
-			);
164
-		});
165
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
166
-
167
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
168
-			return new \OC\Preview\Watcher(
169
-				$c->getAppDataDir('preview')
170
-			);
171
-		});
172
-
173
-		$this->registerService('EncryptionManager', function (Server $c) {
174
-			$view = new View();
175
-			$util = new Encryption\Util(
176
-				$view,
177
-				$c->getUserManager(),
178
-				$c->getGroupManager(),
179
-				$c->getConfig()
180
-			);
181
-			return new Encryption\Manager(
182
-				$c->getConfig(),
183
-				$c->getLogger(),
184
-				$c->getL10N('core'),
185
-				new View(),
186
-				$util,
187
-				new ArrayCache()
188
-			);
189
-		});
190
-
191
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
192
-			$util = new Encryption\Util(
193
-				new View(),
194
-				$c->getUserManager(),
195
-				$c->getGroupManager(),
196
-				$c->getConfig()
197
-			);
198
-			return new Encryption\File(
199
-				$util,
200
-				$c->getRootFolder(),
201
-				$c->getShareManager()
202
-			);
203
-		});
204
-
205
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
206
-			$view = new View();
207
-			$util = new Encryption\Util(
208
-				$view,
209
-				$c->getUserManager(),
210
-				$c->getGroupManager(),
211
-				$c->getConfig()
212
-			);
213
-
214
-			return new Encryption\Keys\Storage($view, $util);
215
-		});
216
-		$this->registerService('TagMapper', function (Server $c) {
217
-			return new TagMapper($c->getDatabaseConnection());
218
-		});
219
-
220
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
221
-			$tagMapper = $c->query('TagMapper');
222
-			return new TagManager($tagMapper, $c->getUserSession());
223
-		});
224
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
225
-
226
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
227
-			$config = $c->getConfig();
228
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
229
-			/** @var \OC\SystemTag\ManagerFactory $factory */
230
-			$factory = new $factoryClass($this);
231
-			return $factory;
232
-		});
233
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
234
-			return $c->query('SystemTagManagerFactory')->getManager();
235
-		});
236
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
237
-
238
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
239
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
240
-		});
241
-		$this->registerService('RootFolder', function (Server $c) {
242
-			$manager = \OC\Files\Filesystem::getMountManager(null);
243
-			$view = new View();
244
-			$root = new Root(
245
-				$manager,
246
-				$view,
247
-				null,
248
-				$c->getUserMountCache(),
249
-				$this->getLogger(),
250
-				$this->getUserManager()
251
-			);
252
-			$connector = new HookConnector($root, $view);
253
-			$connector->viewToNode();
254
-
255
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
256
-			$previewConnector->connectWatcher();
257
-
258
-			return $root;
259
-		});
260
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
261
-
262
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
263
-			return new LazyRoot(function () use ($c) {
264
-				return $c->query('RootFolder');
265
-			});
266
-		});
267
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
268
-
269
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
270
-			$config = $c->getConfig();
271
-			return new \OC\User\Manager($config);
272
-		});
273
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
274
-
275
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
276
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
277
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
278
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
279
-			});
280
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
281
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
282
-			});
283
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
284
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
285
-			});
286
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
287
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
288
-			});
289
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
290
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
291
-			});
292
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
293
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
294
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
295
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
296
-			});
297
-			return $groupManager;
298
-		});
299
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
300
-
301
-		$this->registerService(Store::class, function (Server $c) {
302
-			$session = $c->getSession();
303
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
304
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
305
-			} else {
306
-				$tokenProvider = null;
307
-			}
308
-			$logger = $c->getLogger();
309
-			return new Store($session, $logger, $tokenProvider);
310
-		});
311
-		$this->registerAlias(IStore::class, Store::class);
312
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
313
-			$dbConnection = $c->getDatabaseConnection();
314
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
315
-		});
316
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
317
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
318
-			$crypto = $c->getCrypto();
319
-			$config = $c->getConfig();
320
-			$logger = $c->getLogger();
321
-			$timeFactory = new TimeFactory();
322
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
323
-		});
324
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
325
-
326
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
327
-			$manager = $c->getUserManager();
328
-			$session = new \OC\Session\Memory('');
329
-			$timeFactory = new TimeFactory();
330
-			// Token providers might require a working database. This code
331
-			// might however be called when ownCloud is not yet setup.
332
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
333
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
334
-			} else {
335
-				$defaultTokenProvider = null;
336
-			}
337
-
338
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
339
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
340
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
341
-			});
342
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
343
-				/** @var $user \OC\User\User */
344
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
345
-			});
346
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
347
-				/** @var $user \OC\User\User */
348
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
349
-			});
350
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
351
-				/** @var $user \OC\User\User */
352
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
353
-			});
354
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
355
-				/** @var $user \OC\User\User */
356
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
357
-			});
358
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
359
-				/** @var $user \OC\User\User */
360
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
361
-			});
362
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
363
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
364
-			});
365
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
366
-				/** @var $user \OC\User\User */
367
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
368
-			});
369
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
370
-				/** @var $user \OC\User\User */
371
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
372
-			});
373
-			$userSession->listen('\OC\User', 'logout', function () {
374
-				\OC_Hook::emit('OC_User', 'logout', array());
375
-			});
376
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
377
-				/** @var $user \OC\User\User */
378
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
379
-			});
380
-			return $userSession;
381
-		});
382
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
383
-
384
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
385
-			return new \OC\Authentication\TwoFactorAuth\Manager(
386
-				$c->getAppManager(),
387
-				$c->getSession(),
388
-				$c->getConfig(),
389
-				$c->getActivityManager(),
390
-				$c->getLogger(),
391
-				$c->query(\OC\Authentication\Token\IProvider::class),
392
-				$c->query(ITimeFactory::class)
393
-			);
394
-		});
395
-
396
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
397
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
398
-
399
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
400
-			return new \OC\AllConfig(
401
-				$c->getSystemConfig()
402
-			);
403
-		});
404
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
405
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
406
-
407
-		$this->registerService('SystemConfig', function ($c) use ($config) {
408
-			return new \OC\SystemConfig($config);
409
-		});
410
-
411
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
412
-			return new \OC\AppConfig($c->getDatabaseConnection());
413
-		});
414
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
415
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
416
-
417
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
418
-			return new \OC\L10N\Factory(
419
-				$c->getConfig(),
420
-				$c->getRequest(),
421
-				$c->getUserSession(),
422
-				\OC::$SERVERROOT
423
-			);
424
-		});
425
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
426
-
427
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
428
-			$config = $c->getConfig();
429
-			$cacheFactory = $c->getMemCacheFactory();
430
-			$request = $c->getRequest();
431
-			return new \OC\URLGenerator(
432
-				$config,
433
-				$cacheFactory,
434
-				$request
435
-			);
436
-		});
437
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
438
-
439
-		$this->registerService('AppHelper', function ($c) {
440
-			return new \OC\AppHelper();
441
-		});
442
-		$this->registerAlias('AppFetcher', AppFetcher::class);
443
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
444
-
445
-		$this->registerService(\OCP\ICache::class, function ($c) {
446
-			return new Cache\File();
447
-		});
448
-		$this->registerAlias('UserCache', \OCP\ICache::class);
449
-
450
-		$this->registerService(Factory::class, function (Server $c) {
451
-
452
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
453
-				'\\OC\\Memcache\\ArrayCache',
454
-				'\\OC\\Memcache\\ArrayCache',
455
-				'\\OC\\Memcache\\ArrayCache'
456
-			);
457
-			$config = $c->getConfig();
458
-			$request = $c->getRequest();
459
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
460
-
461
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
462
-				$v = \OC_App::getAppVersions();
463
-				$v['core'] = implode(',', \OC_Util::getVersion());
464
-				$version = implode(',', $v);
465
-				$instanceId = \OC_Util::getInstanceId();
466
-				$path = \OC::$SERVERROOT;
467
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
468
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
469
-					$config->getSystemValue('memcache.local', null),
470
-					$config->getSystemValue('memcache.distributed', null),
471
-					$config->getSystemValue('memcache.locking', null)
472
-				);
473
-			}
474
-			return $arrayCacheFactory;
475
-
476
-		});
477
-		$this->registerAlias('MemCacheFactory', Factory::class);
478
-		$this->registerAlias(ICacheFactory::class, Factory::class);
479
-
480
-		$this->registerService('RedisFactory', function (Server $c) {
481
-			$systemConfig = $c->getSystemConfig();
482
-			return new RedisFactory($systemConfig);
483
-		});
484
-
485
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
486
-			return new \OC\Activity\Manager(
487
-				$c->getRequest(),
488
-				$c->getUserSession(),
489
-				$c->getConfig(),
490
-				$c->query(IValidator::class)
491
-			);
492
-		});
493
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
494
-
495
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
496
-			return new \OC\Activity\EventMerger(
497
-				$c->getL10N('lib')
498
-			);
499
-		});
500
-		$this->registerAlias(IValidator::class, Validator::class);
501
-
502
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
503
-			return new AvatarManager(
504
-				$c->getUserManager(),
505
-				$c->getAppDataDir('avatar'),
506
-				$c->getL10N('lib'),
507
-				$c->getLogger(),
508
-				$c->getConfig()
509
-			);
510
-		});
511
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
512
-
513
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
514
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
515
-			$logger = Log::getLogClass($logType);
516
-			call_user_func(array($logger, 'init'));
517
-
518
-			return new Log($logger);
519
-		});
520
-		$this->registerAlias('Logger', \OCP\ILogger::class);
521
-
522
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
523
-			$config = $c->getConfig();
524
-			return new \OC\BackgroundJob\JobList(
525
-				$c->getDatabaseConnection(),
526
-				$config,
527
-				new TimeFactory()
528
-			);
529
-		});
530
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
531
-
532
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
533
-			$cacheFactory = $c->getMemCacheFactory();
534
-			$logger = $c->getLogger();
535
-			if ($cacheFactory->isAvailable()) {
536
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
537
-			} else {
538
-				$router = new \OC\Route\Router($logger);
539
-			}
540
-			return $router;
541
-		});
542
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
543
-
544
-		$this->registerService(\OCP\ISearch::class, function ($c) {
545
-			return new Search();
546
-		});
547
-		$this->registerAlias('Search', \OCP\ISearch::class);
548
-
549
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
550
-			return new \OC\Security\RateLimiting\Limiter(
551
-				$this->getUserSession(),
552
-				$this->getRequest(),
553
-				new \OC\AppFramework\Utility\TimeFactory(),
554
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
555
-			);
556
-		});
557
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
558
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
559
-				$this->getMemCacheFactory(),
560
-				new \OC\AppFramework\Utility\TimeFactory()
561
-			);
562
-		});
563
-
564
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
565
-			return new SecureRandom();
566
-		});
567
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
568
-
569
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
570
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
571
-		});
572
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
573
-
574
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
575
-			return new Hasher($c->getConfig());
576
-		});
577
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
578
-
579
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
580
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
581
-		});
582
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
583
-
584
-		$this->registerService(IDBConnection::class, function (Server $c) {
585
-			$systemConfig = $c->getSystemConfig();
586
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
587
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
588
-			if (!$factory->isValidType($type)) {
589
-				throw new \OC\DatabaseException('Invalid database type');
590
-			}
591
-			$connectionParams = $factory->createConnectionParams();
592
-			$connection = $factory->getConnection($type, $connectionParams);
593
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
594
-			return $connection;
595
-		});
596
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
597
-
598
-		$this->registerService('HTTPHelper', function (Server $c) {
599
-			$config = $c->getConfig();
600
-			return new HTTPHelper(
601
-				$config,
602
-				$c->getHTTPClientService()
603
-			);
604
-		});
605
-
606
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
607
-			$user = \OC_User::getUser();
608
-			$uid = $user ? $user : null;
609
-			return new ClientService(
610
-				$c->getConfig(),
611
-				new \OC\Security\CertificateManager(
612
-					$uid,
613
-					new View(),
614
-					$c->getConfig(),
615
-					$c->getLogger(),
616
-					$c->getSecureRandom()
617
-				)
618
-			);
619
-		});
620
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
621
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
622
-			$eventLogger = new EventLogger();
623
-			if ($c->getSystemConfig()->getValue('debug', false)) {
624
-				// In debug mode, module is being activated by default
625
-				$eventLogger->activate();
626
-			}
627
-			return $eventLogger;
628
-		});
629
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
630
-
631
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
632
-			$queryLogger = new QueryLogger();
633
-			if ($c->getSystemConfig()->getValue('debug', false)) {
634
-				// In debug mode, module is being activated by default
635
-				$queryLogger->activate();
636
-			}
637
-			return $queryLogger;
638
-		});
639
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
640
-
641
-		$this->registerService(TempManager::class, function (Server $c) {
642
-			return new TempManager(
643
-				$c->getLogger(),
644
-				$c->getConfig()
645
-			);
646
-		});
647
-		$this->registerAlias('TempManager', TempManager::class);
648
-		$this->registerAlias(ITempManager::class, TempManager::class);
649
-
650
-		$this->registerService(AppManager::class, function (Server $c) {
651
-			return new \OC\App\AppManager(
652
-				$c->getUserSession(),
653
-				$c->getAppConfig(),
654
-				$c->getGroupManager(),
655
-				$c->getMemCacheFactory(),
656
-				$c->getEventDispatcher()
657
-			);
658
-		});
659
-		$this->registerAlias('AppManager', AppManager::class);
660
-		$this->registerAlias(IAppManager::class, AppManager::class);
661
-
662
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
663
-			return new DateTimeZone(
664
-				$c->getConfig(),
665
-				$c->getSession()
666
-			);
667
-		});
668
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
669
-
670
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
671
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
672
-
673
-			return new DateTimeFormatter(
674
-				$c->getDateTimeZone()->getTimeZone(),
675
-				$c->getL10N('lib', $language)
676
-			);
677
-		});
678
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
679
-
680
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
681
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
682
-			$listener = new UserMountCacheListener($mountCache);
683
-			$listener->listen($c->getUserManager());
684
-			return $mountCache;
685
-		});
686
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
687
-
688
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
689
-			$loader = \OC\Files\Filesystem::getLoader();
690
-			$mountCache = $c->query('UserMountCache');
691
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
692
-
693
-			// builtin providers
694
-
695
-			$config = $c->getConfig();
696
-			$manager->registerProvider(new CacheMountProvider($config));
697
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
698
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
699
-
700
-			return $manager;
701
-		});
702
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
703
-
704
-		$this->registerService('IniWrapper', function ($c) {
705
-			return new IniGetWrapper();
706
-		});
707
-		$this->registerService('AsyncCommandBus', function (Server $c) {
708
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
709
-			if ($busClass) {
710
-				list($app, $class) = explode('::', $busClass, 2);
711
-				if ($c->getAppManager()->isInstalled($app)) {
712
-					\OC_App::loadApp($app);
713
-					return $c->query($class);
714
-				} else {
715
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
716
-				}
717
-			} else {
718
-				$jobList = $c->getJobList();
719
-				return new CronBus($jobList);
720
-			}
721
-		});
722
-		$this->registerService('TrustedDomainHelper', function ($c) {
723
-			return new TrustedDomainHelper($this->getConfig());
724
-		});
725
-		$this->registerService('Throttler', function (Server $c) {
726
-			return new Throttler(
727
-				$c->getDatabaseConnection(),
728
-				new TimeFactory(),
729
-				$c->getLogger(),
730
-				$c->getConfig()
731
-			);
732
-		});
733
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
734
-			// IConfig and IAppManager requires a working database. This code
735
-			// might however be called when ownCloud is not yet setup.
736
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
737
-				$config = $c->getConfig();
738
-				$appManager = $c->getAppManager();
739
-			} else {
740
-				$config = null;
741
-				$appManager = null;
742
-			}
743
-
744
-			return new Checker(
745
-				new EnvironmentHelper(),
746
-				new FileAccessHelper(),
747
-				new AppLocator(),
748
-				$config,
749
-				$c->getMemCacheFactory(),
750
-				$appManager,
751
-				$c->getTempManager()
752
-			);
753
-		});
754
-		$this->registerService(\OCP\IRequest::class, function ($c) {
755
-			if (isset($this['urlParams'])) {
756
-				$urlParams = $this['urlParams'];
757
-			} else {
758
-				$urlParams = [];
759
-			}
760
-
761
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
762
-				&& in_array('fakeinput', stream_get_wrappers())
763
-			) {
764
-				$stream = 'fakeinput://data';
765
-			} else {
766
-				$stream = 'php://input';
767
-			}
768
-
769
-			return new Request(
770
-				[
771
-					'get' => $_GET,
772
-					'post' => $_POST,
773
-					'files' => $_FILES,
774
-					'server' => $_SERVER,
775
-					'env' => $_ENV,
776
-					'cookies' => $_COOKIE,
777
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
778
-						? $_SERVER['REQUEST_METHOD']
779
-						: null,
780
-					'urlParams' => $urlParams,
781
-				],
782
-				$this->getSecureRandom(),
783
-				$this->getConfig(),
784
-				$this->getCsrfTokenManager(),
785
-				$stream
786
-			);
787
-		});
788
-		$this->registerAlias('Request', \OCP\IRequest::class);
789
-
790
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
791
-			return new Mailer(
792
-				$c->getConfig(),
793
-				$c->getLogger(),
794
-				$c->query(Defaults::class),
795
-				$c->getURLGenerator(),
796
-				$c->getL10N('lib')
797
-			);
798
-		});
799
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
800
-
801
-		$this->registerService('LDAPProvider', function (Server $c) {
802
-			$config = $c->getConfig();
803
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
804
-			if (is_null($factoryClass)) {
805
-				throw new \Exception('ldapProviderFactory not set');
806
-			}
807
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
808
-			$factory = new $factoryClass($this);
809
-			return $factory->getLDAPProvider();
810
-		});
811
-		$this->registerService(ILockingProvider::class, function (Server $c) {
812
-			$ini = $c->getIniWrapper();
813
-			$config = $c->getConfig();
814
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
815
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
816
-				/** @var \OC\Memcache\Factory $memcacheFactory */
817
-				$memcacheFactory = $c->getMemCacheFactory();
818
-				$memcache = $memcacheFactory->createLocking('lock');
819
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
820
-					return new MemcacheLockingProvider($memcache, $ttl);
821
-				}
822
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
823
-			}
824
-			return new NoopLockingProvider();
825
-		});
826
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
827
-
828
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
829
-			return new \OC\Files\Mount\Manager();
830
-		});
831
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
832
-
833
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
834
-			return new \OC\Files\Type\Detection(
835
-				$c->getURLGenerator(),
836
-				\OC::$configDir,
837
-				\OC::$SERVERROOT . '/resources/config/'
838
-			);
839
-		});
840
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
841
-
842
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
843
-			return new \OC\Files\Type\Loader(
844
-				$c->getDatabaseConnection()
845
-			);
846
-		});
847
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
848
-		$this->registerService(BundleFetcher::class, function () {
849
-			return new BundleFetcher($this->getL10N('lib'));
850
-		});
851
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
852
-			return new Manager(
853
-				$c->query(IValidator::class)
854
-			);
855
-		});
856
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
857
-
858
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
859
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
860
-			$manager->registerCapability(function () use ($c) {
861
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
862
-			});
863
-			$manager->registerCapability(function () use ($c) {
864
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
865
-			});
866
-			return $manager;
867
-		});
868
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
869
-
870
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
871
-			$config = $c->getConfig();
872
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
873
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
874
-			$factory = new $factoryClass($this);
875
-			return $factory->getManager();
876
-		});
877
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
878
-
879
-		$this->registerService('ThemingDefaults', function (Server $c) {
880
-			/*
135
+    /** @var string */
136
+    private $webRoot;
137
+
138
+    /**
139
+     * @param string $webRoot
140
+     * @param \OC\Config $config
141
+     */
142
+    public function __construct($webRoot, \OC\Config $config) {
143
+        parent::__construct();
144
+        $this->webRoot = $webRoot;
145
+
146
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
147
+            return $c;
148
+        });
149
+
150
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
151
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
152
+
153
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
154
+
155
+
156
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
157
+            return new PreviewManager(
158
+                $c->getConfig(),
159
+                $c->getRootFolder(),
160
+                $c->getAppDataDir('preview'),
161
+                $c->getEventDispatcher(),
162
+                $c->getSession()->get('user_id')
163
+            );
164
+        });
165
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
166
+
167
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
168
+            return new \OC\Preview\Watcher(
169
+                $c->getAppDataDir('preview')
170
+            );
171
+        });
172
+
173
+        $this->registerService('EncryptionManager', function (Server $c) {
174
+            $view = new View();
175
+            $util = new Encryption\Util(
176
+                $view,
177
+                $c->getUserManager(),
178
+                $c->getGroupManager(),
179
+                $c->getConfig()
180
+            );
181
+            return new Encryption\Manager(
182
+                $c->getConfig(),
183
+                $c->getLogger(),
184
+                $c->getL10N('core'),
185
+                new View(),
186
+                $util,
187
+                new ArrayCache()
188
+            );
189
+        });
190
+
191
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
192
+            $util = new Encryption\Util(
193
+                new View(),
194
+                $c->getUserManager(),
195
+                $c->getGroupManager(),
196
+                $c->getConfig()
197
+            );
198
+            return new Encryption\File(
199
+                $util,
200
+                $c->getRootFolder(),
201
+                $c->getShareManager()
202
+            );
203
+        });
204
+
205
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
206
+            $view = new View();
207
+            $util = new Encryption\Util(
208
+                $view,
209
+                $c->getUserManager(),
210
+                $c->getGroupManager(),
211
+                $c->getConfig()
212
+            );
213
+
214
+            return new Encryption\Keys\Storage($view, $util);
215
+        });
216
+        $this->registerService('TagMapper', function (Server $c) {
217
+            return new TagMapper($c->getDatabaseConnection());
218
+        });
219
+
220
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
221
+            $tagMapper = $c->query('TagMapper');
222
+            return new TagManager($tagMapper, $c->getUserSession());
223
+        });
224
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
225
+
226
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
227
+            $config = $c->getConfig();
228
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
229
+            /** @var \OC\SystemTag\ManagerFactory $factory */
230
+            $factory = new $factoryClass($this);
231
+            return $factory;
232
+        });
233
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
234
+            return $c->query('SystemTagManagerFactory')->getManager();
235
+        });
236
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
237
+
238
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
239
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
240
+        });
241
+        $this->registerService('RootFolder', function (Server $c) {
242
+            $manager = \OC\Files\Filesystem::getMountManager(null);
243
+            $view = new View();
244
+            $root = new Root(
245
+                $manager,
246
+                $view,
247
+                null,
248
+                $c->getUserMountCache(),
249
+                $this->getLogger(),
250
+                $this->getUserManager()
251
+            );
252
+            $connector = new HookConnector($root, $view);
253
+            $connector->viewToNode();
254
+
255
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
256
+            $previewConnector->connectWatcher();
257
+
258
+            return $root;
259
+        });
260
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
261
+
262
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
263
+            return new LazyRoot(function () use ($c) {
264
+                return $c->query('RootFolder');
265
+            });
266
+        });
267
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
268
+
269
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
270
+            $config = $c->getConfig();
271
+            return new \OC\User\Manager($config);
272
+        });
273
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
274
+
275
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
276
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
277
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
278
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
279
+            });
280
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
281
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
282
+            });
283
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
284
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
285
+            });
286
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
287
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
288
+            });
289
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
290
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
291
+            });
292
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
293
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
294
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
295
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
296
+            });
297
+            return $groupManager;
298
+        });
299
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
300
+
301
+        $this->registerService(Store::class, function (Server $c) {
302
+            $session = $c->getSession();
303
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
304
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
305
+            } else {
306
+                $tokenProvider = null;
307
+            }
308
+            $logger = $c->getLogger();
309
+            return new Store($session, $logger, $tokenProvider);
310
+        });
311
+        $this->registerAlias(IStore::class, Store::class);
312
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
313
+            $dbConnection = $c->getDatabaseConnection();
314
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
315
+        });
316
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
317
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
318
+            $crypto = $c->getCrypto();
319
+            $config = $c->getConfig();
320
+            $logger = $c->getLogger();
321
+            $timeFactory = new TimeFactory();
322
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
323
+        });
324
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
325
+
326
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
327
+            $manager = $c->getUserManager();
328
+            $session = new \OC\Session\Memory('');
329
+            $timeFactory = new TimeFactory();
330
+            // Token providers might require a working database. This code
331
+            // might however be called when ownCloud is not yet setup.
332
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
333
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
334
+            } else {
335
+                $defaultTokenProvider = null;
336
+            }
337
+
338
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
339
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
340
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
341
+            });
342
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
343
+                /** @var $user \OC\User\User */
344
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
345
+            });
346
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
347
+                /** @var $user \OC\User\User */
348
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
349
+            });
350
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
351
+                /** @var $user \OC\User\User */
352
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
353
+            });
354
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
355
+                /** @var $user \OC\User\User */
356
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
357
+            });
358
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
359
+                /** @var $user \OC\User\User */
360
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
361
+            });
362
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
363
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
364
+            });
365
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
366
+                /** @var $user \OC\User\User */
367
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
368
+            });
369
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
370
+                /** @var $user \OC\User\User */
371
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
372
+            });
373
+            $userSession->listen('\OC\User', 'logout', function () {
374
+                \OC_Hook::emit('OC_User', 'logout', array());
375
+            });
376
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
377
+                /** @var $user \OC\User\User */
378
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
379
+            });
380
+            return $userSession;
381
+        });
382
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
383
+
384
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
385
+            return new \OC\Authentication\TwoFactorAuth\Manager(
386
+                $c->getAppManager(),
387
+                $c->getSession(),
388
+                $c->getConfig(),
389
+                $c->getActivityManager(),
390
+                $c->getLogger(),
391
+                $c->query(\OC\Authentication\Token\IProvider::class),
392
+                $c->query(ITimeFactory::class)
393
+            );
394
+        });
395
+
396
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
397
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
398
+
399
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
400
+            return new \OC\AllConfig(
401
+                $c->getSystemConfig()
402
+            );
403
+        });
404
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
405
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
406
+
407
+        $this->registerService('SystemConfig', function ($c) use ($config) {
408
+            return new \OC\SystemConfig($config);
409
+        });
410
+
411
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
412
+            return new \OC\AppConfig($c->getDatabaseConnection());
413
+        });
414
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
415
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
416
+
417
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
418
+            return new \OC\L10N\Factory(
419
+                $c->getConfig(),
420
+                $c->getRequest(),
421
+                $c->getUserSession(),
422
+                \OC::$SERVERROOT
423
+            );
424
+        });
425
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
426
+
427
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
428
+            $config = $c->getConfig();
429
+            $cacheFactory = $c->getMemCacheFactory();
430
+            $request = $c->getRequest();
431
+            return new \OC\URLGenerator(
432
+                $config,
433
+                $cacheFactory,
434
+                $request
435
+            );
436
+        });
437
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
438
+
439
+        $this->registerService('AppHelper', function ($c) {
440
+            return new \OC\AppHelper();
441
+        });
442
+        $this->registerAlias('AppFetcher', AppFetcher::class);
443
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
444
+
445
+        $this->registerService(\OCP\ICache::class, function ($c) {
446
+            return new Cache\File();
447
+        });
448
+        $this->registerAlias('UserCache', \OCP\ICache::class);
449
+
450
+        $this->registerService(Factory::class, function (Server $c) {
451
+
452
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
453
+                '\\OC\\Memcache\\ArrayCache',
454
+                '\\OC\\Memcache\\ArrayCache',
455
+                '\\OC\\Memcache\\ArrayCache'
456
+            );
457
+            $config = $c->getConfig();
458
+            $request = $c->getRequest();
459
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
460
+
461
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
462
+                $v = \OC_App::getAppVersions();
463
+                $v['core'] = implode(',', \OC_Util::getVersion());
464
+                $version = implode(',', $v);
465
+                $instanceId = \OC_Util::getInstanceId();
466
+                $path = \OC::$SERVERROOT;
467
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
468
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
469
+                    $config->getSystemValue('memcache.local', null),
470
+                    $config->getSystemValue('memcache.distributed', null),
471
+                    $config->getSystemValue('memcache.locking', null)
472
+                );
473
+            }
474
+            return $arrayCacheFactory;
475
+
476
+        });
477
+        $this->registerAlias('MemCacheFactory', Factory::class);
478
+        $this->registerAlias(ICacheFactory::class, Factory::class);
479
+
480
+        $this->registerService('RedisFactory', function (Server $c) {
481
+            $systemConfig = $c->getSystemConfig();
482
+            return new RedisFactory($systemConfig);
483
+        });
484
+
485
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
486
+            return new \OC\Activity\Manager(
487
+                $c->getRequest(),
488
+                $c->getUserSession(),
489
+                $c->getConfig(),
490
+                $c->query(IValidator::class)
491
+            );
492
+        });
493
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
494
+
495
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
496
+            return new \OC\Activity\EventMerger(
497
+                $c->getL10N('lib')
498
+            );
499
+        });
500
+        $this->registerAlias(IValidator::class, Validator::class);
501
+
502
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
503
+            return new AvatarManager(
504
+                $c->getUserManager(),
505
+                $c->getAppDataDir('avatar'),
506
+                $c->getL10N('lib'),
507
+                $c->getLogger(),
508
+                $c->getConfig()
509
+            );
510
+        });
511
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
512
+
513
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
514
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
515
+            $logger = Log::getLogClass($logType);
516
+            call_user_func(array($logger, 'init'));
517
+
518
+            return new Log($logger);
519
+        });
520
+        $this->registerAlias('Logger', \OCP\ILogger::class);
521
+
522
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
523
+            $config = $c->getConfig();
524
+            return new \OC\BackgroundJob\JobList(
525
+                $c->getDatabaseConnection(),
526
+                $config,
527
+                new TimeFactory()
528
+            );
529
+        });
530
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
531
+
532
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
533
+            $cacheFactory = $c->getMemCacheFactory();
534
+            $logger = $c->getLogger();
535
+            if ($cacheFactory->isAvailable()) {
536
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
537
+            } else {
538
+                $router = new \OC\Route\Router($logger);
539
+            }
540
+            return $router;
541
+        });
542
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
543
+
544
+        $this->registerService(\OCP\ISearch::class, function ($c) {
545
+            return new Search();
546
+        });
547
+        $this->registerAlias('Search', \OCP\ISearch::class);
548
+
549
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
550
+            return new \OC\Security\RateLimiting\Limiter(
551
+                $this->getUserSession(),
552
+                $this->getRequest(),
553
+                new \OC\AppFramework\Utility\TimeFactory(),
554
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
555
+            );
556
+        });
557
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
558
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
559
+                $this->getMemCacheFactory(),
560
+                new \OC\AppFramework\Utility\TimeFactory()
561
+            );
562
+        });
563
+
564
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
565
+            return new SecureRandom();
566
+        });
567
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
568
+
569
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
570
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
571
+        });
572
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
573
+
574
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
575
+            return new Hasher($c->getConfig());
576
+        });
577
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
578
+
579
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
580
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
581
+        });
582
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
583
+
584
+        $this->registerService(IDBConnection::class, function (Server $c) {
585
+            $systemConfig = $c->getSystemConfig();
586
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
587
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
588
+            if (!$factory->isValidType($type)) {
589
+                throw new \OC\DatabaseException('Invalid database type');
590
+            }
591
+            $connectionParams = $factory->createConnectionParams();
592
+            $connection = $factory->getConnection($type, $connectionParams);
593
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
594
+            return $connection;
595
+        });
596
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
597
+
598
+        $this->registerService('HTTPHelper', function (Server $c) {
599
+            $config = $c->getConfig();
600
+            return new HTTPHelper(
601
+                $config,
602
+                $c->getHTTPClientService()
603
+            );
604
+        });
605
+
606
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
607
+            $user = \OC_User::getUser();
608
+            $uid = $user ? $user : null;
609
+            return new ClientService(
610
+                $c->getConfig(),
611
+                new \OC\Security\CertificateManager(
612
+                    $uid,
613
+                    new View(),
614
+                    $c->getConfig(),
615
+                    $c->getLogger(),
616
+                    $c->getSecureRandom()
617
+                )
618
+            );
619
+        });
620
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
621
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
622
+            $eventLogger = new EventLogger();
623
+            if ($c->getSystemConfig()->getValue('debug', false)) {
624
+                // In debug mode, module is being activated by default
625
+                $eventLogger->activate();
626
+            }
627
+            return $eventLogger;
628
+        });
629
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
630
+
631
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
632
+            $queryLogger = new QueryLogger();
633
+            if ($c->getSystemConfig()->getValue('debug', false)) {
634
+                // In debug mode, module is being activated by default
635
+                $queryLogger->activate();
636
+            }
637
+            return $queryLogger;
638
+        });
639
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
640
+
641
+        $this->registerService(TempManager::class, function (Server $c) {
642
+            return new TempManager(
643
+                $c->getLogger(),
644
+                $c->getConfig()
645
+            );
646
+        });
647
+        $this->registerAlias('TempManager', TempManager::class);
648
+        $this->registerAlias(ITempManager::class, TempManager::class);
649
+
650
+        $this->registerService(AppManager::class, function (Server $c) {
651
+            return new \OC\App\AppManager(
652
+                $c->getUserSession(),
653
+                $c->getAppConfig(),
654
+                $c->getGroupManager(),
655
+                $c->getMemCacheFactory(),
656
+                $c->getEventDispatcher()
657
+            );
658
+        });
659
+        $this->registerAlias('AppManager', AppManager::class);
660
+        $this->registerAlias(IAppManager::class, AppManager::class);
661
+
662
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
663
+            return new DateTimeZone(
664
+                $c->getConfig(),
665
+                $c->getSession()
666
+            );
667
+        });
668
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
669
+
670
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
671
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
672
+
673
+            return new DateTimeFormatter(
674
+                $c->getDateTimeZone()->getTimeZone(),
675
+                $c->getL10N('lib', $language)
676
+            );
677
+        });
678
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
679
+
680
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
681
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
682
+            $listener = new UserMountCacheListener($mountCache);
683
+            $listener->listen($c->getUserManager());
684
+            return $mountCache;
685
+        });
686
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
687
+
688
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
689
+            $loader = \OC\Files\Filesystem::getLoader();
690
+            $mountCache = $c->query('UserMountCache');
691
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
692
+
693
+            // builtin providers
694
+
695
+            $config = $c->getConfig();
696
+            $manager->registerProvider(new CacheMountProvider($config));
697
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
698
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
699
+
700
+            return $manager;
701
+        });
702
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
703
+
704
+        $this->registerService('IniWrapper', function ($c) {
705
+            return new IniGetWrapper();
706
+        });
707
+        $this->registerService('AsyncCommandBus', function (Server $c) {
708
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
709
+            if ($busClass) {
710
+                list($app, $class) = explode('::', $busClass, 2);
711
+                if ($c->getAppManager()->isInstalled($app)) {
712
+                    \OC_App::loadApp($app);
713
+                    return $c->query($class);
714
+                } else {
715
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
716
+                }
717
+            } else {
718
+                $jobList = $c->getJobList();
719
+                return new CronBus($jobList);
720
+            }
721
+        });
722
+        $this->registerService('TrustedDomainHelper', function ($c) {
723
+            return new TrustedDomainHelper($this->getConfig());
724
+        });
725
+        $this->registerService('Throttler', function (Server $c) {
726
+            return new Throttler(
727
+                $c->getDatabaseConnection(),
728
+                new TimeFactory(),
729
+                $c->getLogger(),
730
+                $c->getConfig()
731
+            );
732
+        });
733
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
734
+            // IConfig and IAppManager requires a working database. This code
735
+            // might however be called when ownCloud is not yet setup.
736
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
737
+                $config = $c->getConfig();
738
+                $appManager = $c->getAppManager();
739
+            } else {
740
+                $config = null;
741
+                $appManager = null;
742
+            }
743
+
744
+            return new Checker(
745
+                new EnvironmentHelper(),
746
+                new FileAccessHelper(),
747
+                new AppLocator(),
748
+                $config,
749
+                $c->getMemCacheFactory(),
750
+                $appManager,
751
+                $c->getTempManager()
752
+            );
753
+        });
754
+        $this->registerService(\OCP\IRequest::class, function ($c) {
755
+            if (isset($this['urlParams'])) {
756
+                $urlParams = $this['urlParams'];
757
+            } else {
758
+                $urlParams = [];
759
+            }
760
+
761
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
762
+                && in_array('fakeinput', stream_get_wrappers())
763
+            ) {
764
+                $stream = 'fakeinput://data';
765
+            } else {
766
+                $stream = 'php://input';
767
+            }
768
+
769
+            return new Request(
770
+                [
771
+                    'get' => $_GET,
772
+                    'post' => $_POST,
773
+                    'files' => $_FILES,
774
+                    'server' => $_SERVER,
775
+                    'env' => $_ENV,
776
+                    'cookies' => $_COOKIE,
777
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
778
+                        ? $_SERVER['REQUEST_METHOD']
779
+                        : null,
780
+                    'urlParams' => $urlParams,
781
+                ],
782
+                $this->getSecureRandom(),
783
+                $this->getConfig(),
784
+                $this->getCsrfTokenManager(),
785
+                $stream
786
+            );
787
+        });
788
+        $this->registerAlias('Request', \OCP\IRequest::class);
789
+
790
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
791
+            return new Mailer(
792
+                $c->getConfig(),
793
+                $c->getLogger(),
794
+                $c->query(Defaults::class),
795
+                $c->getURLGenerator(),
796
+                $c->getL10N('lib')
797
+            );
798
+        });
799
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
800
+
801
+        $this->registerService('LDAPProvider', function (Server $c) {
802
+            $config = $c->getConfig();
803
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
804
+            if (is_null($factoryClass)) {
805
+                throw new \Exception('ldapProviderFactory not set');
806
+            }
807
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
808
+            $factory = new $factoryClass($this);
809
+            return $factory->getLDAPProvider();
810
+        });
811
+        $this->registerService(ILockingProvider::class, function (Server $c) {
812
+            $ini = $c->getIniWrapper();
813
+            $config = $c->getConfig();
814
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
815
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
816
+                /** @var \OC\Memcache\Factory $memcacheFactory */
817
+                $memcacheFactory = $c->getMemCacheFactory();
818
+                $memcache = $memcacheFactory->createLocking('lock');
819
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
820
+                    return new MemcacheLockingProvider($memcache, $ttl);
821
+                }
822
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
823
+            }
824
+            return new NoopLockingProvider();
825
+        });
826
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
827
+
828
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
829
+            return new \OC\Files\Mount\Manager();
830
+        });
831
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
832
+
833
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
834
+            return new \OC\Files\Type\Detection(
835
+                $c->getURLGenerator(),
836
+                \OC::$configDir,
837
+                \OC::$SERVERROOT . '/resources/config/'
838
+            );
839
+        });
840
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
841
+
842
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
843
+            return new \OC\Files\Type\Loader(
844
+                $c->getDatabaseConnection()
845
+            );
846
+        });
847
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
848
+        $this->registerService(BundleFetcher::class, function () {
849
+            return new BundleFetcher($this->getL10N('lib'));
850
+        });
851
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
852
+            return new Manager(
853
+                $c->query(IValidator::class)
854
+            );
855
+        });
856
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
857
+
858
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
859
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
860
+            $manager->registerCapability(function () use ($c) {
861
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
862
+            });
863
+            $manager->registerCapability(function () use ($c) {
864
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
865
+            });
866
+            return $manager;
867
+        });
868
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
869
+
870
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
871
+            $config = $c->getConfig();
872
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
873
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
874
+            $factory = new $factoryClass($this);
875
+            return $factory->getManager();
876
+        });
877
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
878
+
879
+        $this->registerService('ThemingDefaults', function (Server $c) {
880
+            /*
881 881
 			 * Dark magic for autoloader.
882 882
 			 * If we do a class_exists it will try to load the class which will
883 883
 			 * make composer cache the result. Resulting in errors when enabling
884 884
 			 * the theming app.
885 885
 			 */
886
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
887
-			if (isset($prefixes['OCA\\Theming\\'])) {
888
-				$classExists = true;
889
-			} else {
890
-				$classExists = false;
891
-			}
892
-
893
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
894
-				return new ThemingDefaults(
895
-					$c->getConfig(),
896
-					$c->getL10N('theming'),
897
-					$c->getURLGenerator(),
898
-					$c->getAppDataDir('theming'),
899
-					$c->getMemCacheFactory(),
900
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
901
-					$this->getAppManager()
902
-				);
903
-			}
904
-			return new \OC_Defaults();
905
-		});
906
-		$this->registerService(SCSSCacher::class, function (Server $c) {
907
-			/** @var Factory $cacheFactory */
908
-			$cacheFactory = $c->query(Factory::class);
909
-			return new SCSSCacher(
910
-				$c->getLogger(),
911
-				$c->query(\OC\Files\AppData\Factory::class),
912
-				$c->getURLGenerator(),
913
-				$c->getConfig(),
914
-				$c->getThemingDefaults(),
915
-				\OC::$SERVERROOT,
916
-				$cacheFactory->create('SCSS')
917
-			);
918
-		});
919
-		$this->registerService(EventDispatcher::class, function () {
920
-			return new EventDispatcher();
921
-		});
922
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
923
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
924
-
925
-		$this->registerService('CryptoWrapper', function (Server $c) {
926
-			// FIXME: Instantiiated here due to cyclic dependency
927
-			$request = new Request(
928
-				[
929
-					'get' => $_GET,
930
-					'post' => $_POST,
931
-					'files' => $_FILES,
932
-					'server' => $_SERVER,
933
-					'env' => $_ENV,
934
-					'cookies' => $_COOKIE,
935
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
936
-						? $_SERVER['REQUEST_METHOD']
937
-						: null,
938
-				],
939
-				$c->getSecureRandom(),
940
-				$c->getConfig()
941
-			);
942
-
943
-			return new CryptoWrapper(
944
-				$c->getConfig(),
945
-				$c->getCrypto(),
946
-				$c->getSecureRandom(),
947
-				$request
948
-			);
949
-		});
950
-		$this->registerService('CsrfTokenManager', function (Server $c) {
951
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
952
-
953
-			return new CsrfTokenManager(
954
-				$tokenGenerator,
955
-				$c->query(SessionStorage::class)
956
-			);
957
-		});
958
-		$this->registerService(SessionStorage::class, function (Server $c) {
959
-			return new SessionStorage($c->getSession());
960
-		});
961
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
962
-			return new ContentSecurityPolicyManager();
963
-		});
964
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
965
-
966
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
967
-			return new ContentSecurityPolicyNonceManager(
968
-				$c->getCsrfTokenManager(),
969
-				$c->getRequest()
970
-			);
971
-		});
972
-
973
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
974
-			$config = $c->getConfig();
975
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
976
-			/** @var \OCP\Share\IProviderFactory $factory */
977
-			$factory = new $factoryClass($this);
978
-
979
-			$manager = new \OC\Share20\Manager(
980
-				$c->getLogger(),
981
-				$c->getConfig(),
982
-				$c->getSecureRandom(),
983
-				$c->getHasher(),
984
-				$c->getMountManager(),
985
-				$c->getGroupManager(),
986
-				$c->getL10N('lib'),
987
-				$c->getL10NFactory(),
988
-				$factory,
989
-				$c->getUserManager(),
990
-				$c->getLazyRootFolder(),
991
-				$c->getEventDispatcher(),
992
-				$c->getMailer(),
993
-				$c->getURLGenerator(),
994
-				$c->getThemingDefaults()
995
-			);
996
-
997
-			return $manager;
998
-		});
999
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1000
-
1001
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1002
-			$instance = new Collaboration\Collaborators\Search($c);
1003
-
1004
-			// register default plugins
1005
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1006
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1007
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1008
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1009
-
1010
-			return $instance;
1011
-		});
1012
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1013
-
1014
-		$this->registerService(\OCP\Collaboration\AutoComplete\IManager::class, function (Server $c) {
1015
-			return new Collaboration\AutoComplete\Manager($c);
1016
-		});
1017
-		$this->registerAlias('AutoCompleteManager', \OCP\Collaboration\AutoComplete\IManager::class);
1018
-
1019
-		$this->registerService('SettingsManager', function (Server $c) {
1020
-			$manager = new \OC\Settings\Manager(
1021
-				$c->getLogger(),
1022
-				$c->getDatabaseConnection(),
1023
-				$c->getL10N('lib'),
1024
-				$c->getConfig(),
1025
-				$c->getEncryptionManager(),
1026
-				$c->getUserManager(),
1027
-				$c->getLockingProvider(),
1028
-				$c->getRequest(),
1029
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
1030
-				$c->getURLGenerator(),
1031
-				$c->query(AccountManager::class),
1032
-				$c->getGroupManager(),
1033
-				$c->getL10NFactory(),
1034
-				$c->getThemingDefaults(),
1035
-				$c->getAppManager()
1036
-			);
1037
-			return $manager;
1038
-		});
1039
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1040
-			return new \OC\Files\AppData\Factory(
1041
-				$c->getRootFolder(),
1042
-				$c->getSystemConfig()
1043
-			);
1044
-		});
1045
-
1046
-		$this->registerService('LockdownManager', function (Server $c) {
1047
-			return new LockdownManager(function () use ($c) {
1048
-				return $c->getSession();
1049
-			});
1050
-		});
1051
-
1052
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1053
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1054
-		});
1055
-
1056
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1057
-			return new CloudIdManager();
1058
-		});
1059
-
1060
-		/* To trick DI since we don't extend the DIContainer here */
1061
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1062
-			return new CleanPreviewsBackgroundJob(
1063
-				$c->getRootFolder(),
1064
-				$c->getLogger(),
1065
-				$c->getJobList(),
1066
-				new TimeFactory()
1067
-			);
1068
-		});
1069
-
1070
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1071
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1072
-
1073
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1074
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1075
-
1076
-		$this->registerService(Defaults::class, function (Server $c) {
1077
-			return new Defaults(
1078
-				$c->getThemingDefaults()
1079
-			);
1080
-		});
1081
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1082
-
1083
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1084
-			return $c->query(\OCP\IUserSession::class)->getSession();
1085
-		});
1086
-
1087
-		$this->registerService(IShareHelper::class, function (Server $c) {
1088
-			return new ShareHelper(
1089
-				$c->query(\OCP\Share\IManager::class)
1090
-			);
1091
-		});
1092
-	}
1093
-
1094
-	/**
1095
-	 * @return \OCP\Contacts\IManager
1096
-	 */
1097
-	public function getContactsManager() {
1098
-		return $this->query('ContactsManager');
1099
-	}
1100
-
1101
-	/**
1102
-	 * @return \OC\Encryption\Manager
1103
-	 */
1104
-	public function getEncryptionManager() {
1105
-		return $this->query('EncryptionManager');
1106
-	}
1107
-
1108
-	/**
1109
-	 * @return \OC\Encryption\File
1110
-	 */
1111
-	public function getEncryptionFilesHelper() {
1112
-		return $this->query('EncryptionFileHelper');
1113
-	}
1114
-
1115
-	/**
1116
-	 * @return \OCP\Encryption\Keys\IStorage
1117
-	 */
1118
-	public function getEncryptionKeyStorage() {
1119
-		return $this->query('EncryptionKeyStorage');
1120
-	}
1121
-
1122
-	/**
1123
-	 * The current request object holding all information about the request
1124
-	 * currently being processed is returned from this method.
1125
-	 * In case the current execution was not initiated by a web request null is returned
1126
-	 *
1127
-	 * @return \OCP\IRequest
1128
-	 */
1129
-	public function getRequest() {
1130
-		return $this->query('Request');
1131
-	}
1132
-
1133
-	/**
1134
-	 * Returns the preview manager which can create preview images for a given file
1135
-	 *
1136
-	 * @return \OCP\IPreview
1137
-	 */
1138
-	public function getPreviewManager() {
1139
-		return $this->query('PreviewManager');
1140
-	}
1141
-
1142
-	/**
1143
-	 * Returns the tag manager which can get and set tags for different object types
1144
-	 *
1145
-	 * @see \OCP\ITagManager::load()
1146
-	 * @return \OCP\ITagManager
1147
-	 */
1148
-	public function getTagManager() {
1149
-		return $this->query('TagManager');
1150
-	}
1151
-
1152
-	/**
1153
-	 * Returns the system-tag manager
1154
-	 *
1155
-	 * @return \OCP\SystemTag\ISystemTagManager
1156
-	 *
1157
-	 * @since 9.0.0
1158
-	 */
1159
-	public function getSystemTagManager() {
1160
-		return $this->query('SystemTagManager');
1161
-	}
1162
-
1163
-	/**
1164
-	 * Returns the system-tag object mapper
1165
-	 *
1166
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1167
-	 *
1168
-	 * @since 9.0.0
1169
-	 */
1170
-	public function getSystemTagObjectMapper() {
1171
-		return $this->query('SystemTagObjectMapper');
1172
-	}
1173
-
1174
-	/**
1175
-	 * Returns the avatar manager, used for avatar functionality
1176
-	 *
1177
-	 * @return \OCP\IAvatarManager
1178
-	 */
1179
-	public function getAvatarManager() {
1180
-		return $this->query('AvatarManager');
1181
-	}
1182
-
1183
-	/**
1184
-	 * Returns the root folder of ownCloud's data directory
1185
-	 *
1186
-	 * @return \OCP\Files\IRootFolder
1187
-	 */
1188
-	public function getRootFolder() {
1189
-		return $this->query('LazyRootFolder');
1190
-	}
1191
-
1192
-	/**
1193
-	 * Returns the root folder of ownCloud's data directory
1194
-	 * This is the lazy variant so this gets only initialized once it
1195
-	 * is actually used.
1196
-	 *
1197
-	 * @return \OCP\Files\IRootFolder
1198
-	 */
1199
-	public function getLazyRootFolder() {
1200
-		return $this->query('LazyRootFolder');
1201
-	}
1202
-
1203
-	/**
1204
-	 * Returns a view to ownCloud's files folder
1205
-	 *
1206
-	 * @param string $userId user ID
1207
-	 * @return \OCP\Files\Folder|null
1208
-	 */
1209
-	public function getUserFolder($userId = null) {
1210
-		if ($userId === null) {
1211
-			$user = $this->getUserSession()->getUser();
1212
-			if (!$user) {
1213
-				return null;
1214
-			}
1215
-			$userId = $user->getUID();
1216
-		}
1217
-		$root = $this->getRootFolder();
1218
-		return $root->getUserFolder($userId);
1219
-	}
1220
-
1221
-	/**
1222
-	 * Returns an app-specific view in ownClouds data directory
1223
-	 *
1224
-	 * @return \OCP\Files\Folder
1225
-	 * @deprecated since 9.2.0 use IAppData
1226
-	 */
1227
-	public function getAppFolder() {
1228
-		$dir = '/' . \OC_App::getCurrentApp();
1229
-		$root = $this->getRootFolder();
1230
-		if (!$root->nodeExists($dir)) {
1231
-			$folder = $root->newFolder($dir);
1232
-		} else {
1233
-			$folder = $root->get($dir);
1234
-		}
1235
-		return $folder;
1236
-	}
1237
-
1238
-	/**
1239
-	 * @return \OC\User\Manager
1240
-	 */
1241
-	public function getUserManager() {
1242
-		return $this->query('UserManager');
1243
-	}
1244
-
1245
-	/**
1246
-	 * @return \OC\Group\Manager
1247
-	 */
1248
-	public function getGroupManager() {
1249
-		return $this->query('GroupManager');
1250
-	}
1251
-
1252
-	/**
1253
-	 * @return \OC\User\Session
1254
-	 */
1255
-	public function getUserSession() {
1256
-		return $this->query('UserSession');
1257
-	}
1258
-
1259
-	/**
1260
-	 * @return \OCP\ISession
1261
-	 */
1262
-	public function getSession() {
1263
-		return $this->query('UserSession')->getSession();
1264
-	}
1265
-
1266
-	/**
1267
-	 * @param \OCP\ISession $session
1268
-	 */
1269
-	public function setSession(\OCP\ISession $session) {
1270
-		$this->query(SessionStorage::class)->setSession($session);
1271
-		$this->query('UserSession')->setSession($session);
1272
-		$this->query(Store::class)->setSession($session);
1273
-	}
1274
-
1275
-	/**
1276
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1277
-	 */
1278
-	public function getTwoFactorAuthManager() {
1279
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1280
-	}
1281
-
1282
-	/**
1283
-	 * @return \OC\NavigationManager
1284
-	 */
1285
-	public function getNavigationManager() {
1286
-		return $this->query('NavigationManager');
1287
-	}
1288
-
1289
-	/**
1290
-	 * @return \OCP\IConfig
1291
-	 */
1292
-	public function getConfig() {
1293
-		return $this->query('AllConfig');
1294
-	}
1295
-
1296
-	/**
1297
-	 * @return \OC\SystemConfig
1298
-	 */
1299
-	public function getSystemConfig() {
1300
-		return $this->query('SystemConfig');
1301
-	}
1302
-
1303
-	/**
1304
-	 * Returns the app config manager
1305
-	 *
1306
-	 * @return \OCP\IAppConfig
1307
-	 */
1308
-	public function getAppConfig() {
1309
-		return $this->query('AppConfig');
1310
-	}
1311
-
1312
-	/**
1313
-	 * @return \OCP\L10N\IFactory
1314
-	 */
1315
-	public function getL10NFactory() {
1316
-		return $this->query('L10NFactory');
1317
-	}
1318
-
1319
-	/**
1320
-	 * get an L10N instance
1321
-	 *
1322
-	 * @param string $app appid
1323
-	 * @param string $lang
1324
-	 * @return IL10N
1325
-	 */
1326
-	public function getL10N($app, $lang = null) {
1327
-		return $this->getL10NFactory()->get($app, $lang);
1328
-	}
1329
-
1330
-	/**
1331
-	 * @return \OCP\IURLGenerator
1332
-	 */
1333
-	public function getURLGenerator() {
1334
-		return $this->query('URLGenerator');
1335
-	}
1336
-
1337
-	/**
1338
-	 * @return \OCP\IHelper
1339
-	 */
1340
-	public function getHelper() {
1341
-		return $this->query('AppHelper');
1342
-	}
1343
-
1344
-	/**
1345
-	 * @return AppFetcher
1346
-	 */
1347
-	public function getAppFetcher() {
1348
-		return $this->query(AppFetcher::class);
1349
-	}
1350
-
1351
-	/**
1352
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1353
-	 * getMemCacheFactory() instead.
1354
-	 *
1355
-	 * @return \OCP\ICache
1356
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1357
-	 */
1358
-	public function getCache() {
1359
-		return $this->query('UserCache');
1360
-	}
1361
-
1362
-	/**
1363
-	 * Returns an \OCP\CacheFactory instance
1364
-	 *
1365
-	 * @return \OCP\ICacheFactory
1366
-	 */
1367
-	public function getMemCacheFactory() {
1368
-		return $this->query('MemCacheFactory');
1369
-	}
1370
-
1371
-	/**
1372
-	 * Returns an \OC\RedisFactory instance
1373
-	 *
1374
-	 * @return \OC\RedisFactory
1375
-	 */
1376
-	public function getGetRedisFactory() {
1377
-		return $this->query('RedisFactory');
1378
-	}
1379
-
1380
-
1381
-	/**
1382
-	 * Returns the current session
1383
-	 *
1384
-	 * @return \OCP\IDBConnection
1385
-	 */
1386
-	public function getDatabaseConnection() {
1387
-		return $this->query('DatabaseConnection');
1388
-	}
1389
-
1390
-	/**
1391
-	 * Returns the activity manager
1392
-	 *
1393
-	 * @return \OCP\Activity\IManager
1394
-	 */
1395
-	public function getActivityManager() {
1396
-		return $this->query('ActivityManager');
1397
-	}
1398
-
1399
-	/**
1400
-	 * Returns an job list for controlling background jobs
1401
-	 *
1402
-	 * @return \OCP\BackgroundJob\IJobList
1403
-	 */
1404
-	public function getJobList() {
1405
-		return $this->query('JobList');
1406
-	}
1407
-
1408
-	/**
1409
-	 * Returns a logger instance
1410
-	 *
1411
-	 * @return \OCP\ILogger
1412
-	 */
1413
-	public function getLogger() {
1414
-		return $this->query('Logger');
1415
-	}
1416
-
1417
-	/**
1418
-	 * Returns a router for generating and matching urls
1419
-	 *
1420
-	 * @return \OCP\Route\IRouter
1421
-	 */
1422
-	public function getRouter() {
1423
-		return $this->query('Router');
1424
-	}
1425
-
1426
-	/**
1427
-	 * Returns a search instance
1428
-	 *
1429
-	 * @return \OCP\ISearch
1430
-	 */
1431
-	public function getSearch() {
1432
-		return $this->query('Search');
1433
-	}
1434
-
1435
-	/**
1436
-	 * Returns a SecureRandom instance
1437
-	 *
1438
-	 * @return \OCP\Security\ISecureRandom
1439
-	 */
1440
-	public function getSecureRandom() {
1441
-		return $this->query('SecureRandom');
1442
-	}
1443
-
1444
-	/**
1445
-	 * Returns a Crypto instance
1446
-	 *
1447
-	 * @return \OCP\Security\ICrypto
1448
-	 */
1449
-	public function getCrypto() {
1450
-		return $this->query('Crypto');
1451
-	}
1452
-
1453
-	/**
1454
-	 * Returns a Hasher instance
1455
-	 *
1456
-	 * @return \OCP\Security\IHasher
1457
-	 */
1458
-	public function getHasher() {
1459
-		return $this->query('Hasher');
1460
-	}
1461
-
1462
-	/**
1463
-	 * Returns a CredentialsManager instance
1464
-	 *
1465
-	 * @return \OCP\Security\ICredentialsManager
1466
-	 */
1467
-	public function getCredentialsManager() {
1468
-		return $this->query('CredentialsManager');
1469
-	}
1470
-
1471
-	/**
1472
-	 * Returns an instance of the HTTP helper class
1473
-	 *
1474
-	 * @deprecated Use getHTTPClientService()
1475
-	 * @return \OC\HTTPHelper
1476
-	 */
1477
-	public function getHTTPHelper() {
1478
-		return $this->query('HTTPHelper');
1479
-	}
1480
-
1481
-	/**
1482
-	 * Get the certificate manager for the user
1483
-	 *
1484
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1485
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1486
-	 */
1487
-	public function getCertificateManager($userId = '') {
1488
-		if ($userId === '') {
1489
-			$userSession = $this->getUserSession();
1490
-			$user = $userSession->getUser();
1491
-			if (is_null($user)) {
1492
-				return null;
1493
-			}
1494
-			$userId = $user->getUID();
1495
-		}
1496
-		return new CertificateManager(
1497
-			$userId,
1498
-			new View(),
1499
-			$this->getConfig(),
1500
-			$this->getLogger(),
1501
-			$this->getSecureRandom()
1502
-		);
1503
-	}
1504
-
1505
-	/**
1506
-	 * Returns an instance of the HTTP client service
1507
-	 *
1508
-	 * @return \OCP\Http\Client\IClientService
1509
-	 */
1510
-	public function getHTTPClientService() {
1511
-		return $this->query('HttpClientService');
1512
-	}
1513
-
1514
-	/**
1515
-	 * Create a new event source
1516
-	 *
1517
-	 * @return \OCP\IEventSource
1518
-	 */
1519
-	public function createEventSource() {
1520
-		return new \OC_EventSource();
1521
-	}
1522
-
1523
-	/**
1524
-	 * Get the active event logger
1525
-	 *
1526
-	 * The returned logger only logs data when debug mode is enabled
1527
-	 *
1528
-	 * @return \OCP\Diagnostics\IEventLogger
1529
-	 */
1530
-	public function getEventLogger() {
1531
-		return $this->query('EventLogger');
1532
-	}
1533
-
1534
-	/**
1535
-	 * Get the active query logger
1536
-	 *
1537
-	 * The returned logger only logs data when debug mode is enabled
1538
-	 *
1539
-	 * @return \OCP\Diagnostics\IQueryLogger
1540
-	 */
1541
-	public function getQueryLogger() {
1542
-		return $this->query('QueryLogger');
1543
-	}
1544
-
1545
-	/**
1546
-	 * Get the manager for temporary files and folders
1547
-	 *
1548
-	 * @return \OCP\ITempManager
1549
-	 */
1550
-	public function getTempManager() {
1551
-		return $this->query('TempManager');
1552
-	}
1553
-
1554
-	/**
1555
-	 * Get the app manager
1556
-	 *
1557
-	 * @return \OCP\App\IAppManager
1558
-	 */
1559
-	public function getAppManager() {
1560
-		return $this->query('AppManager');
1561
-	}
1562
-
1563
-	/**
1564
-	 * Creates a new mailer
1565
-	 *
1566
-	 * @return \OCP\Mail\IMailer
1567
-	 */
1568
-	public function getMailer() {
1569
-		return $this->query('Mailer');
1570
-	}
1571
-
1572
-	/**
1573
-	 * Get the webroot
1574
-	 *
1575
-	 * @return string
1576
-	 */
1577
-	public function getWebRoot() {
1578
-		return $this->webRoot;
1579
-	}
1580
-
1581
-	/**
1582
-	 * @return \OC\OCSClient
1583
-	 */
1584
-	public function getOcsClient() {
1585
-		return $this->query('OcsClient');
1586
-	}
1587
-
1588
-	/**
1589
-	 * @return \OCP\IDateTimeZone
1590
-	 */
1591
-	public function getDateTimeZone() {
1592
-		return $this->query('DateTimeZone');
1593
-	}
1594
-
1595
-	/**
1596
-	 * @return \OCP\IDateTimeFormatter
1597
-	 */
1598
-	public function getDateTimeFormatter() {
1599
-		return $this->query('DateTimeFormatter');
1600
-	}
1601
-
1602
-	/**
1603
-	 * @return \OCP\Files\Config\IMountProviderCollection
1604
-	 */
1605
-	public function getMountProviderCollection() {
1606
-		return $this->query('MountConfigManager');
1607
-	}
1608
-
1609
-	/**
1610
-	 * Get the IniWrapper
1611
-	 *
1612
-	 * @return IniGetWrapper
1613
-	 */
1614
-	public function getIniWrapper() {
1615
-		return $this->query('IniWrapper');
1616
-	}
1617
-
1618
-	/**
1619
-	 * @return \OCP\Command\IBus
1620
-	 */
1621
-	public function getCommandBus() {
1622
-		return $this->query('AsyncCommandBus');
1623
-	}
1624
-
1625
-	/**
1626
-	 * Get the trusted domain helper
1627
-	 *
1628
-	 * @return TrustedDomainHelper
1629
-	 */
1630
-	public function getTrustedDomainHelper() {
1631
-		return $this->query('TrustedDomainHelper');
1632
-	}
1633
-
1634
-	/**
1635
-	 * Get the locking provider
1636
-	 *
1637
-	 * @return \OCP\Lock\ILockingProvider
1638
-	 * @since 8.1.0
1639
-	 */
1640
-	public function getLockingProvider() {
1641
-		return $this->query('LockingProvider');
1642
-	}
1643
-
1644
-	/**
1645
-	 * @return \OCP\Files\Mount\IMountManager
1646
-	 **/
1647
-	function getMountManager() {
1648
-		return $this->query('MountManager');
1649
-	}
1650
-
1651
-	/** @return \OCP\Files\Config\IUserMountCache */
1652
-	function getUserMountCache() {
1653
-		return $this->query('UserMountCache');
1654
-	}
1655
-
1656
-	/**
1657
-	 * Get the MimeTypeDetector
1658
-	 *
1659
-	 * @return \OCP\Files\IMimeTypeDetector
1660
-	 */
1661
-	public function getMimeTypeDetector() {
1662
-		return $this->query('MimeTypeDetector');
1663
-	}
1664
-
1665
-	/**
1666
-	 * Get the MimeTypeLoader
1667
-	 *
1668
-	 * @return \OCP\Files\IMimeTypeLoader
1669
-	 */
1670
-	public function getMimeTypeLoader() {
1671
-		return $this->query('MimeTypeLoader');
1672
-	}
1673
-
1674
-	/**
1675
-	 * Get the manager of all the capabilities
1676
-	 *
1677
-	 * @return \OC\CapabilitiesManager
1678
-	 */
1679
-	public function getCapabilitiesManager() {
1680
-		return $this->query('CapabilitiesManager');
1681
-	}
1682
-
1683
-	/**
1684
-	 * Get the EventDispatcher
1685
-	 *
1686
-	 * @return EventDispatcherInterface
1687
-	 * @since 8.2.0
1688
-	 */
1689
-	public function getEventDispatcher() {
1690
-		return $this->query('EventDispatcher');
1691
-	}
1692
-
1693
-	/**
1694
-	 * Get the Notification Manager
1695
-	 *
1696
-	 * @return \OCP\Notification\IManager
1697
-	 * @since 8.2.0
1698
-	 */
1699
-	public function getNotificationManager() {
1700
-		return $this->query('NotificationManager');
1701
-	}
1702
-
1703
-	/**
1704
-	 * @return \OCP\Comments\ICommentsManager
1705
-	 */
1706
-	public function getCommentsManager() {
1707
-		return $this->query('CommentsManager');
1708
-	}
1709
-
1710
-	/**
1711
-	 * @return \OCA\Theming\ThemingDefaults
1712
-	 */
1713
-	public function getThemingDefaults() {
1714
-		return $this->query('ThemingDefaults');
1715
-	}
1716
-
1717
-	/**
1718
-	 * @return \OC\IntegrityCheck\Checker
1719
-	 */
1720
-	public function getIntegrityCodeChecker() {
1721
-		return $this->query('IntegrityCodeChecker');
1722
-	}
1723
-
1724
-	/**
1725
-	 * @return \OC\Session\CryptoWrapper
1726
-	 */
1727
-	public function getSessionCryptoWrapper() {
1728
-		return $this->query('CryptoWrapper');
1729
-	}
1730
-
1731
-	/**
1732
-	 * @return CsrfTokenManager
1733
-	 */
1734
-	public function getCsrfTokenManager() {
1735
-		return $this->query('CsrfTokenManager');
1736
-	}
1737
-
1738
-	/**
1739
-	 * @return Throttler
1740
-	 */
1741
-	public function getBruteForceThrottler() {
1742
-		return $this->query('Throttler');
1743
-	}
1744
-
1745
-	/**
1746
-	 * @return IContentSecurityPolicyManager
1747
-	 */
1748
-	public function getContentSecurityPolicyManager() {
1749
-		return $this->query('ContentSecurityPolicyManager');
1750
-	}
1751
-
1752
-	/**
1753
-	 * @return ContentSecurityPolicyNonceManager
1754
-	 */
1755
-	public function getContentSecurityPolicyNonceManager() {
1756
-		return $this->query('ContentSecurityPolicyNonceManager');
1757
-	}
1758
-
1759
-	/**
1760
-	 * Not a public API as of 8.2, wait for 9.0
1761
-	 *
1762
-	 * @return \OCA\Files_External\Service\BackendService
1763
-	 */
1764
-	public function getStoragesBackendService() {
1765
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1766
-	}
1767
-
1768
-	/**
1769
-	 * Not a public API as of 8.2, wait for 9.0
1770
-	 *
1771
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1772
-	 */
1773
-	public function getGlobalStoragesService() {
1774
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1775
-	}
1776
-
1777
-	/**
1778
-	 * Not a public API as of 8.2, wait for 9.0
1779
-	 *
1780
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1781
-	 */
1782
-	public function getUserGlobalStoragesService() {
1783
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1784
-	}
1785
-
1786
-	/**
1787
-	 * Not a public API as of 8.2, wait for 9.0
1788
-	 *
1789
-	 * @return \OCA\Files_External\Service\UserStoragesService
1790
-	 */
1791
-	public function getUserStoragesService() {
1792
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1793
-	}
1794
-
1795
-	/**
1796
-	 * @return \OCP\Share\IManager
1797
-	 */
1798
-	public function getShareManager() {
1799
-		return $this->query('ShareManager');
1800
-	}
1801
-
1802
-	/**
1803
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1804
-	 */
1805
-	public function getCollaboratorSearch() {
1806
-		return $this->query('CollaboratorSearch');
1807
-	}
1808
-
1809
-	/**
1810
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1811
-	 */
1812
-	public function getAutoCompleteManager(){
1813
-		return $this->query('AutoCompleteManager');
1814
-	}
1815
-
1816
-	/**
1817
-	 * Returns the LDAP Provider
1818
-	 *
1819
-	 * @return \OCP\LDAP\ILDAPProvider
1820
-	 */
1821
-	public function getLDAPProvider() {
1822
-		return $this->query('LDAPProvider');
1823
-	}
1824
-
1825
-	/**
1826
-	 * @return \OCP\Settings\IManager
1827
-	 */
1828
-	public function getSettingsManager() {
1829
-		return $this->query('SettingsManager');
1830
-	}
1831
-
1832
-	/**
1833
-	 * @return \OCP\Files\IAppData
1834
-	 */
1835
-	public function getAppDataDir($app) {
1836
-		/** @var \OC\Files\AppData\Factory $factory */
1837
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1838
-		return $factory->get($app);
1839
-	}
1840
-
1841
-	/**
1842
-	 * @return \OCP\Lockdown\ILockdownManager
1843
-	 */
1844
-	public function getLockdownManager() {
1845
-		return $this->query('LockdownManager');
1846
-	}
1847
-
1848
-	/**
1849
-	 * @return \OCP\Federation\ICloudIdManager
1850
-	 */
1851
-	public function getCloudIdManager() {
1852
-		return $this->query(ICloudIdManager::class);
1853
-	}
886
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
887
+            if (isset($prefixes['OCA\\Theming\\'])) {
888
+                $classExists = true;
889
+            } else {
890
+                $classExists = false;
891
+            }
892
+
893
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
894
+                return new ThemingDefaults(
895
+                    $c->getConfig(),
896
+                    $c->getL10N('theming'),
897
+                    $c->getURLGenerator(),
898
+                    $c->getAppDataDir('theming'),
899
+                    $c->getMemCacheFactory(),
900
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
901
+                    $this->getAppManager()
902
+                );
903
+            }
904
+            return new \OC_Defaults();
905
+        });
906
+        $this->registerService(SCSSCacher::class, function (Server $c) {
907
+            /** @var Factory $cacheFactory */
908
+            $cacheFactory = $c->query(Factory::class);
909
+            return new SCSSCacher(
910
+                $c->getLogger(),
911
+                $c->query(\OC\Files\AppData\Factory::class),
912
+                $c->getURLGenerator(),
913
+                $c->getConfig(),
914
+                $c->getThemingDefaults(),
915
+                \OC::$SERVERROOT,
916
+                $cacheFactory->create('SCSS')
917
+            );
918
+        });
919
+        $this->registerService(EventDispatcher::class, function () {
920
+            return new EventDispatcher();
921
+        });
922
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
923
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
924
+
925
+        $this->registerService('CryptoWrapper', function (Server $c) {
926
+            // FIXME: Instantiiated here due to cyclic dependency
927
+            $request = new Request(
928
+                [
929
+                    'get' => $_GET,
930
+                    'post' => $_POST,
931
+                    'files' => $_FILES,
932
+                    'server' => $_SERVER,
933
+                    'env' => $_ENV,
934
+                    'cookies' => $_COOKIE,
935
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
936
+                        ? $_SERVER['REQUEST_METHOD']
937
+                        : null,
938
+                ],
939
+                $c->getSecureRandom(),
940
+                $c->getConfig()
941
+            );
942
+
943
+            return new CryptoWrapper(
944
+                $c->getConfig(),
945
+                $c->getCrypto(),
946
+                $c->getSecureRandom(),
947
+                $request
948
+            );
949
+        });
950
+        $this->registerService('CsrfTokenManager', function (Server $c) {
951
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
952
+
953
+            return new CsrfTokenManager(
954
+                $tokenGenerator,
955
+                $c->query(SessionStorage::class)
956
+            );
957
+        });
958
+        $this->registerService(SessionStorage::class, function (Server $c) {
959
+            return new SessionStorage($c->getSession());
960
+        });
961
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
962
+            return new ContentSecurityPolicyManager();
963
+        });
964
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
965
+
966
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
967
+            return new ContentSecurityPolicyNonceManager(
968
+                $c->getCsrfTokenManager(),
969
+                $c->getRequest()
970
+            );
971
+        });
972
+
973
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
974
+            $config = $c->getConfig();
975
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
976
+            /** @var \OCP\Share\IProviderFactory $factory */
977
+            $factory = new $factoryClass($this);
978
+
979
+            $manager = new \OC\Share20\Manager(
980
+                $c->getLogger(),
981
+                $c->getConfig(),
982
+                $c->getSecureRandom(),
983
+                $c->getHasher(),
984
+                $c->getMountManager(),
985
+                $c->getGroupManager(),
986
+                $c->getL10N('lib'),
987
+                $c->getL10NFactory(),
988
+                $factory,
989
+                $c->getUserManager(),
990
+                $c->getLazyRootFolder(),
991
+                $c->getEventDispatcher(),
992
+                $c->getMailer(),
993
+                $c->getURLGenerator(),
994
+                $c->getThemingDefaults()
995
+            );
996
+
997
+            return $manager;
998
+        });
999
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1000
+
1001
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1002
+            $instance = new Collaboration\Collaborators\Search($c);
1003
+
1004
+            // register default plugins
1005
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1006
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1007
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1008
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1009
+
1010
+            return $instance;
1011
+        });
1012
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1013
+
1014
+        $this->registerService(\OCP\Collaboration\AutoComplete\IManager::class, function (Server $c) {
1015
+            return new Collaboration\AutoComplete\Manager($c);
1016
+        });
1017
+        $this->registerAlias('AutoCompleteManager', \OCP\Collaboration\AutoComplete\IManager::class);
1018
+
1019
+        $this->registerService('SettingsManager', function (Server $c) {
1020
+            $manager = new \OC\Settings\Manager(
1021
+                $c->getLogger(),
1022
+                $c->getDatabaseConnection(),
1023
+                $c->getL10N('lib'),
1024
+                $c->getConfig(),
1025
+                $c->getEncryptionManager(),
1026
+                $c->getUserManager(),
1027
+                $c->getLockingProvider(),
1028
+                $c->getRequest(),
1029
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
1030
+                $c->getURLGenerator(),
1031
+                $c->query(AccountManager::class),
1032
+                $c->getGroupManager(),
1033
+                $c->getL10NFactory(),
1034
+                $c->getThemingDefaults(),
1035
+                $c->getAppManager()
1036
+            );
1037
+            return $manager;
1038
+        });
1039
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1040
+            return new \OC\Files\AppData\Factory(
1041
+                $c->getRootFolder(),
1042
+                $c->getSystemConfig()
1043
+            );
1044
+        });
1045
+
1046
+        $this->registerService('LockdownManager', function (Server $c) {
1047
+            return new LockdownManager(function () use ($c) {
1048
+                return $c->getSession();
1049
+            });
1050
+        });
1051
+
1052
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1053
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1054
+        });
1055
+
1056
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1057
+            return new CloudIdManager();
1058
+        });
1059
+
1060
+        /* To trick DI since we don't extend the DIContainer here */
1061
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1062
+            return new CleanPreviewsBackgroundJob(
1063
+                $c->getRootFolder(),
1064
+                $c->getLogger(),
1065
+                $c->getJobList(),
1066
+                new TimeFactory()
1067
+            );
1068
+        });
1069
+
1070
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1071
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1072
+
1073
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1074
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1075
+
1076
+        $this->registerService(Defaults::class, function (Server $c) {
1077
+            return new Defaults(
1078
+                $c->getThemingDefaults()
1079
+            );
1080
+        });
1081
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1082
+
1083
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1084
+            return $c->query(\OCP\IUserSession::class)->getSession();
1085
+        });
1086
+
1087
+        $this->registerService(IShareHelper::class, function (Server $c) {
1088
+            return new ShareHelper(
1089
+                $c->query(\OCP\Share\IManager::class)
1090
+            );
1091
+        });
1092
+    }
1093
+
1094
+    /**
1095
+     * @return \OCP\Contacts\IManager
1096
+     */
1097
+    public function getContactsManager() {
1098
+        return $this->query('ContactsManager');
1099
+    }
1100
+
1101
+    /**
1102
+     * @return \OC\Encryption\Manager
1103
+     */
1104
+    public function getEncryptionManager() {
1105
+        return $this->query('EncryptionManager');
1106
+    }
1107
+
1108
+    /**
1109
+     * @return \OC\Encryption\File
1110
+     */
1111
+    public function getEncryptionFilesHelper() {
1112
+        return $this->query('EncryptionFileHelper');
1113
+    }
1114
+
1115
+    /**
1116
+     * @return \OCP\Encryption\Keys\IStorage
1117
+     */
1118
+    public function getEncryptionKeyStorage() {
1119
+        return $this->query('EncryptionKeyStorage');
1120
+    }
1121
+
1122
+    /**
1123
+     * The current request object holding all information about the request
1124
+     * currently being processed is returned from this method.
1125
+     * In case the current execution was not initiated by a web request null is returned
1126
+     *
1127
+     * @return \OCP\IRequest
1128
+     */
1129
+    public function getRequest() {
1130
+        return $this->query('Request');
1131
+    }
1132
+
1133
+    /**
1134
+     * Returns the preview manager which can create preview images for a given file
1135
+     *
1136
+     * @return \OCP\IPreview
1137
+     */
1138
+    public function getPreviewManager() {
1139
+        return $this->query('PreviewManager');
1140
+    }
1141
+
1142
+    /**
1143
+     * Returns the tag manager which can get and set tags for different object types
1144
+     *
1145
+     * @see \OCP\ITagManager::load()
1146
+     * @return \OCP\ITagManager
1147
+     */
1148
+    public function getTagManager() {
1149
+        return $this->query('TagManager');
1150
+    }
1151
+
1152
+    /**
1153
+     * Returns the system-tag manager
1154
+     *
1155
+     * @return \OCP\SystemTag\ISystemTagManager
1156
+     *
1157
+     * @since 9.0.0
1158
+     */
1159
+    public function getSystemTagManager() {
1160
+        return $this->query('SystemTagManager');
1161
+    }
1162
+
1163
+    /**
1164
+     * Returns the system-tag object mapper
1165
+     *
1166
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1167
+     *
1168
+     * @since 9.0.0
1169
+     */
1170
+    public function getSystemTagObjectMapper() {
1171
+        return $this->query('SystemTagObjectMapper');
1172
+    }
1173
+
1174
+    /**
1175
+     * Returns the avatar manager, used for avatar functionality
1176
+     *
1177
+     * @return \OCP\IAvatarManager
1178
+     */
1179
+    public function getAvatarManager() {
1180
+        return $this->query('AvatarManager');
1181
+    }
1182
+
1183
+    /**
1184
+     * Returns the root folder of ownCloud's data directory
1185
+     *
1186
+     * @return \OCP\Files\IRootFolder
1187
+     */
1188
+    public function getRootFolder() {
1189
+        return $this->query('LazyRootFolder');
1190
+    }
1191
+
1192
+    /**
1193
+     * Returns the root folder of ownCloud's data directory
1194
+     * This is the lazy variant so this gets only initialized once it
1195
+     * is actually used.
1196
+     *
1197
+     * @return \OCP\Files\IRootFolder
1198
+     */
1199
+    public function getLazyRootFolder() {
1200
+        return $this->query('LazyRootFolder');
1201
+    }
1202
+
1203
+    /**
1204
+     * Returns a view to ownCloud's files folder
1205
+     *
1206
+     * @param string $userId user ID
1207
+     * @return \OCP\Files\Folder|null
1208
+     */
1209
+    public function getUserFolder($userId = null) {
1210
+        if ($userId === null) {
1211
+            $user = $this->getUserSession()->getUser();
1212
+            if (!$user) {
1213
+                return null;
1214
+            }
1215
+            $userId = $user->getUID();
1216
+        }
1217
+        $root = $this->getRootFolder();
1218
+        return $root->getUserFolder($userId);
1219
+    }
1220
+
1221
+    /**
1222
+     * Returns an app-specific view in ownClouds data directory
1223
+     *
1224
+     * @return \OCP\Files\Folder
1225
+     * @deprecated since 9.2.0 use IAppData
1226
+     */
1227
+    public function getAppFolder() {
1228
+        $dir = '/' . \OC_App::getCurrentApp();
1229
+        $root = $this->getRootFolder();
1230
+        if (!$root->nodeExists($dir)) {
1231
+            $folder = $root->newFolder($dir);
1232
+        } else {
1233
+            $folder = $root->get($dir);
1234
+        }
1235
+        return $folder;
1236
+    }
1237
+
1238
+    /**
1239
+     * @return \OC\User\Manager
1240
+     */
1241
+    public function getUserManager() {
1242
+        return $this->query('UserManager');
1243
+    }
1244
+
1245
+    /**
1246
+     * @return \OC\Group\Manager
1247
+     */
1248
+    public function getGroupManager() {
1249
+        return $this->query('GroupManager');
1250
+    }
1251
+
1252
+    /**
1253
+     * @return \OC\User\Session
1254
+     */
1255
+    public function getUserSession() {
1256
+        return $this->query('UserSession');
1257
+    }
1258
+
1259
+    /**
1260
+     * @return \OCP\ISession
1261
+     */
1262
+    public function getSession() {
1263
+        return $this->query('UserSession')->getSession();
1264
+    }
1265
+
1266
+    /**
1267
+     * @param \OCP\ISession $session
1268
+     */
1269
+    public function setSession(\OCP\ISession $session) {
1270
+        $this->query(SessionStorage::class)->setSession($session);
1271
+        $this->query('UserSession')->setSession($session);
1272
+        $this->query(Store::class)->setSession($session);
1273
+    }
1274
+
1275
+    /**
1276
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1277
+     */
1278
+    public function getTwoFactorAuthManager() {
1279
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1280
+    }
1281
+
1282
+    /**
1283
+     * @return \OC\NavigationManager
1284
+     */
1285
+    public function getNavigationManager() {
1286
+        return $this->query('NavigationManager');
1287
+    }
1288
+
1289
+    /**
1290
+     * @return \OCP\IConfig
1291
+     */
1292
+    public function getConfig() {
1293
+        return $this->query('AllConfig');
1294
+    }
1295
+
1296
+    /**
1297
+     * @return \OC\SystemConfig
1298
+     */
1299
+    public function getSystemConfig() {
1300
+        return $this->query('SystemConfig');
1301
+    }
1302
+
1303
+    /**
1304
+     * Returns the app config manager
1305
+     *
1306
+     * @return \OCP\IAppConfig
1307
+     */
1308
+    public function getAppConfig() {
1309
+        return $this->query('AppConfig');
1310
+    }
1311
+
1312
+    /**
1313
+     * @return \OCP\L10N\IFactory
1314
+     */
1315
+    public function getL10NFactory() {
1316
+        return $this->query('L10NFactory');
1317
+    }
1318
+
1319
+    /**
1320
+     * get an L10N instance
1321
+     *
1322
+     * @param string $app appid
1323
+     * @param string $lang
1324
+     * @return IL10N
1325
+     */
1326
+    public function getL10N($app, $lang = null) {
1327
+        return $this->getL10NFactory()->get($app, $lang);
1328
+    }
1329
+
1330
+    /**
1331
+     * @return \OCP\IURLGenerator
1332
+     */
1333
+    public function getURLGenerator() {
1334
+        return $this->query('URLGenerator');
1335
+    }
1336
+
1337
+    /**
1338
+     * @return \OCP\IHelper
1339
+     */
1340
+    public function getHelper() {
1341
+        return $this->query('AppHelper');
1342
+    }
1343
+
1344
+    /**
1345
+     * @return AppFetcher
1346
+     */
1347
+    public function getAppFetcher() {
1348
+        return $this->query(AppFetcher::class);
1349
+    }
1350
+
1351
+    /**
1352
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1353
+     * getMemCacheFactory() instead.
1354
+     *
1355
+     * @return \OCP\ICache
1356
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1357
+     */
1358
+    public function getCache() {
1359
+        return $this->query('UserCache');
1360
+    }
1361
+
1362
+    /**
1363
+     * Returns an \OCP\CacheFactory instance
1364
+     *
1365
+     * @return \OCP\ICacheFactory
1366
+     */
1367
+    public function getMemCacheFactory() {
1368
+        return $this->query('MemCacheFactory');
1369
+    }
1370
+
1371
+    /**
1372
+     * Returns an \OC\RedisFactory instance
1373
+     *
1374
+     * @return \OC\RedisFactory
1375
+     */
1376
+    public function getGetRedisFactory() {
1377
+        return $this->query('RedisFactory');
1378
+    }
1379
+
1380
+
1381
+    /**
1382
+     * Returns the current session
1383
+     *
1384
+     * @return \OCP\IDBConnection
1385
+     */
1386
+    public function getDatabaseConnection() {
1387
+        return $this->query('DatabaseConnection');
1388
+    }
1389
+
1390
+    /**
1391
+     * Returns the activity manager
1392
+     *
1393
+     * @return \OCP\Activity\IManager
1394
+     */
1395
+    public function getActivityManager() {
1396
+        return $this->query('ActivityManager');
1397
+    }
1398
+
1399
+    /**
1400
+     * Returns an job list for controlling background jobs
1401
+     *
1402
+     * @return \OCP\BackgroundJob\IJobList
1403
+     */
1404
+    public function getJobList() {
1405
+        return $this->query('JobList');
1406
+    }
1407
+
1408
+    /**
1409
+     * Returns a logger instance
1410
+     *
1411
+     * @return \OCP\ILogger
1412
+     */
1413
+    public function getLogger() {
1414
+        return $this->query('Logger');
1415
+    }
1416
+
1417
+    /**
1418
+     * Returns a router for generating and matching urls
1419
+     *
1420
+     * @return \OCP\Route\IRouter
1421
+     */
1422
+    public function getRouter() {
1423
+        return $this->query('Router');
1424
+    }
1425
+
1426
+    /**
1427
+     * Returns a search instance
1428
+     *
1429
+     * @return \OCP\ISearch
1430
+     */
1431
+    public function getSearch() {
1432
+        return $this->query('Search');
1433
+    }
1434
+
1435
+    /**
1436
+     * Returns a SecureRandom instance
1437
+     *
1438
+     * @return \OCP\Security\ISecureRandom
1439
+     */
1440
+    public function getSecureRandom() {
1441
+        return $this->query('SecureRandom');
1442
+    }
1443
+
1444
+    /**
1445
+     * Returns a Crypto instance
1446
+     *
1447
+     * @return \OCP\Security\ICrypto
1448
+     */
1449
+    public function getCrypto() {
1450
+        return $this->query('Crypto');
1451
+    }
1452
+
1453
+    /**
1454
+     * Returns a Hasher instance
1455
+     *
1456
+     * @return \OCP\Security\IHasher
1457
+     */
1458
+    public function getHasher() {
1459
+        return $this->query('Hasher');
1460
+    }
1461
+
1462
+    /**
1463
+     * Returns a CredentialsManager instance
1464
+     *
1465
+     * @return \OCP\Security\ICredentialsManager
1466
+     */
1467
+    public function getCredentialsManager() {
1468
+        return $this->query('CredentialsManager');
1469
+    }
1470
+
1471
+    /**
1472
+     * Returns an instance of the HTTP helper class
1473
+     *
1474
+     * @deprecated Use getHTTPClientService()
1475
+     * @return \OC\HTTPHelper
1476
+     */
1477
+    public function getHTTPHelper() {
1478
+        return $this->query('HTTPHelper');
1479
+    }
1480
+
1481
+    /**
1482
+     * Get the certificate manager for the user
1483
+     *
1484
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1485
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1486
+     */
1487
+    public function getCertificateManager($userId = '') {
1488
+        if ($userId === '') {
1489
+            $userSession = $this->getUserSession();
1490
+            $user = $userSession->getUser();
1491
+            if (is_null($user)) {
1492
+                return null;
1493
+            }
1494
+            $userId = $user->getUID();
1495
+        }
1496
+        return new CertificateManager(
1497
+            $userId,
1498
+            new View(),
1499
+            $this->getConfig(),
1500
+            $this->getLogger(),
1501
+            $this->getSecureRandom()
1502
+        );
1503
+    }
1504
+
1505
+    /**
1506
+     * Returns an instance of the HTTP client service
1507
+     *
1508
+     * @return \OCP\Http\Client\IClientService
1509
+     */
1510
+    public function getHTTPClientService() {
1511
+        return $this->query('HttpClientService');
1512
+    }
1513
+
1514
+    /**
1515
+     * Create a new event source
1516
+     *
1517
+     * @return \OCP\IEventSource
1518
+     */
1519
+    public function createEventSource() {
1520
+        return new \OC_EventSource();
1521
+    }
1522
+
1523
+    /**
1524
+     * Get the active event logger
1525
+     *
1526
+     * The returned logger only logs data when debug mode is enabled
1527
+     *
1528
+     * @return \OCP\Diagnostics\IEventLogger
1529
+     */
1530
+    public function getEventLogger() {
1531
+        return $this->query('EventLogger');
1532
+    }
1533
+
1534
+    /**
1535
+     * Get the active query logger
1536
+     *
1537
+     * The returned logger only logs data when debug mode is enabled
1538
+     *
1539
+     * @return \OCP\Diagnostics\IQueryLogger
1540
+     */
1541
+    public function getQueryLogger() {
1542
+        return $this->query('QueryLogger');
1543
+    }
1544
+
1545
+    /**
1546
+     * Get the manager for temporary files and folders
1547
+     *
1548
+     * @return \OCP\ITempManager
1549
+     */
1550
+    public function getTempManager() {
1551
+        return $this->query('TempManager');
1552
+    }
1553
+
1554
+    /**
1555
+     * Get the app manager
1556
+     *
1557
+     * @return \OCP\App\IAppManager
1558
+     */
1559
+    public function getAppManager() {
1560
+        return $this->query('AppManager');
1561
+    }
1562
+
1563
+    /**
1564
+     * Creates a new mailer
1565
+     *
1566
+     * @return \OCP\Mail\IMailer
1567
+     */
1568
+    public function getMailer() {
1569
+        return $this->query('Mailer');
1570
+    }
1571
+
1572
+    /**
1573
+     * Get the webroot
1574
+     *
1575
+     * @return string
1576
+     */
1577
+    public function getWebRoot() {
1578
+        return $this->webRoot;
1579
+    }
1580
+
1581
+    /**
1582
+     * @return \OC\OCSClient
1583
+     */
1584
+    public function getOcsClient() {
1585
+        return $this->query('OcsClient');
1586
+    }
1587
+
1588
+    /**
1589
+     * @return \OCP\IDateTimeZone
1590
+     */
1591
+    public function getDateTimeZone() {
1592
+        return $this->query('DateTimeZone');
1593
+    }
1594
+
1595
+    /**
1596
+     * @return \OCP\IDateTimeFormatter
1597
+     */
1598
+    public function getDateTimeFormatter() {
1599
+        return $this->query('DateTimeFormatter');
1600
+    }
1601
+
1602
+    /**
1603
+     * @return \OCP\Files\Config\IMountProviderCollection
1604
+     */
1605
+    public function getMountProviderCollection() {
1606
+        return $this->query('MountConfigManager');
1607
+    }
1608
+
1609
+    /**
1610
+     * Get the IniWrapper
1611
+     *
1612
+     * @return IniGetWrapper
1613
+     */
1614
+    public function getIniWrapper() {
1615
+        return $this->query('IniWrapper');
1616
+    }
1617
+
1618
+    /**
1619
+     * @return \OCP\Command\IBus
1620
+     */
1621
+    public function getCommandBus() {
1622
+        return $this->query('AsyncCommandBus');
1623
+    }
1624
+
1625
+    /**
1626
+     * Get the trusted domain helper
1627
+     *
1628
+     * @return TrustedDomainHelper
1629
+     */
1630
+    public function getTrustedDomainHelper() {
1631
+        return $this->query('TrustedDomainHelper');
1632
+    }
1633
+
1634
+    /**
1635
+     * Get the locking provider
1636
+     *
1637
+     * @return \OCP\Lock\ILockingProvider
1638
+     * @since 8.1.0
1639
+     */
1640
+    public function getLockingProvider() {
1641
+        return $this->query('LockingProvider');
1642
+    }
1643
+
1644
+    /**
1645
+     * @return \OCP\Files\Mount\IMountManager
1646
+     **/
1647
+    function getMountManager() {
1648
+        return $this->query('MountManager');
1649
+    }
1650
+
1651
+    /** @return \OCP\Files\Config\IUserMountCache */
1652
+    function getUserMountCache() {
1653
+        return $this->query('UserMountCache');
1654
+    }
1655
+
1656
+    /**
1657
+     * Get the MimeTypeDetector
1658
+     *
1659
+     * @return \OCP\Files\IMimeTypeDetector
1660
+     */
1661
+    public function getMimeTypeDetector() {
1662
+        return $this->query('MimeTypeDetector');
1663
+    }
1664
+
1665
+    /**
1666
+     * Get the MimeTypeLoader
1667
+     *
1668
+     * @return \OCP\Files\IMimeTypeLoader
1669
+     */
1670
+    public function getMimeTypeLoader() {
1671
+        return $this->query('MimeTypeLoader');
1672
+    }
1673
+
1674
+    /**
1675
+     * Get the manager of all the capabilities
1676
+     *
1677
+     * @return \OC\CapabilitiesManager
1678
+     */
1679
+    public function getCapabilitiesManager() {
1680
+        return $this->query('CapabilitiesManager');
1681
+    }
1682
+
1683
+    /**
1684
+     * Get the EventDispatcher
1685
+     *
1686
+     * @return EventDispatcherInterface
1687
+     * @since 8.2.0
1688
+     */
1689
+    public function getEventDispatcher() {
1690
+        return $this->query('EventDispatcher');
1691
+    }
1692
+
1693
+    /**
1694
+     * Get the Notification Manager
1695
+     *
1696
+     * @return \OCP\Notification\IManager
1697
+     * @since 8.2.0
1698
+     */
1699
+    public function getNotificationManager() {
1700
+        return $this->query('NotificationManager');
1701
+    }
1702
+
1703
+    /**
1704
+     * @return \OCP\Comments\ICommentsManager
1705
+     */
1706
+    public function getCommentsManager() {
1707
+        return $this->query('CommentsManager');
1708
+    }
1709
+
1710
+    /**
1711
+     * @return \OCA\Theming\ThemingDefaults
1712
+     */
1713
+    public function getThemingDefaults() {
1714
+        return $this->query('ThemingDefaults');
1715
+    }
1716
+
1717
+    /**
1718
+     * @return \OC\IntegrityCheck\Checker
1719
+     */
1720
+    public function getIntegrityCodeChecker() {
1721
+        return $this->query('IntegrityCodeChecker');
1722
+    }
1723
+
1724
+    /**
1725
+     * @return \OC\Session\CryptoWrapper
1726
+     */
1727
+    public function getSessionCryptoWrapper() {
1728
+        return $this->query('CryptoWrapper');
1729
+    }
1730
+
1731
+    /**
1732
+     * @return CsrfTokenManager
1733
+     */
1734
+    public function getCsrfTokenManager() {
1735
+        return $this->query('CsrfTokenManager');
1736
+    }
1737
+
1738
+    /**
1739
+     * @return Throttler
1740
+     */
1741
+    public function getBruteForceThrottler() {
1742
+        return $this->query('Throttler');
1743
+    }
1744
+
1745
+    /**
1746
+     * @return IContentSecurityPolicyManager
1747
+     */
1748
+    public function getContentSecurityPolicyManager() {
1749
+        return $this->query('ContentSecurityPolicyManager');
1750
+    }
1751
+
1752
+    /**
1753
+     * @return ContentSecurityPolicyNonceManager
1754
+     */
1755
+    public function getContentSecurityPolicyNonceManager() {
1756
+        return $this->query('ContentSecurityPolicyNonceManager');
1757
+    }
1758
+
1759
+    /**
1760
+     * Not a public API as of 8.2, wait for 9.0
1761
+     *
1762
+     * @return \OCA\Files_External\Service\BackendService
1763
+     */
1764
+    public function getStoragesBackendService() {
1765
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1766
+    }
1767
+
1768
+    /**
1769
+     * Not a public API as of 8.2, wait for 9.0
1770
+     *
1771
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1772
+     */
1773
+    public function getGlobalStoragesService() {
1774
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1775
+    }
1776
+
1777
+    /**
1778
+     * Not a public API as of 8.2, wait for 9.0
1779
+     *
1780
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1781
+     */
1782
+    public function getUserGlobalStoragesService() {
1783
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1784
+    }
1785
+
1786
+    /**
1787
+     * Not a public API as of 8.2, wait for 9.0
1788
+     *
1789
+     * @return \OCA\Files_External\Service\UserStoragesService
1790
+     */
1791
+    public function getUserStoragesService() {
1792
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1793
+    }
1794
+
1795
+    /**
1796
+     * @return \OCP\Share\IManager
1797
+     */
1798
+    public function getShareManager() {
1799
+        return $this->query('ShareManager');
1800
+    }
1801
+
1802
+    /**
1803
+     * @return \OCP\Collaboration\Collaborators\ISearch
1804
+     */
1805
+    public function getCollaboratorSearch() {
1806
+        return $this->query('CollaboratorSearch');
1807
+    }
1808
+
1809
+    /**
1810
+     * @return \OCP\Collaboration\AutoComplete\IManager
1811
+     */
1812
+    public function getAutoCompleteManager(){
1813
+        return $this->query('AutoCompleteManager');
1814
+    }
1815
+
1816
+    /**
1817
+     * Returns the LDAP Provider
1818
+     *
1819
+     * @return \OCP\LDAP\ILDAPProvider
1820
+     */
1821
+    public function getLDAPProvider() {
1822
+        return $this->query('LDAPProvider');
1823
+    }
1824
+
1825
+    /**
1826
+     * @return \OCP\Settings\IManager
1827
+     */
1828
+    public function getSettingsManager() {
1829
+        return $this->query('SettingsManager');
1830
+    }
1831
+
1832
+    /**
1833
+     * @return \OCP\Files\IAppData
1834
+     */
1835
+    public function getAppDataDir($app) {
1836
+        /** @var \OC\Files\AppData\Factory $factory */
1837
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1838
+        return $factory->get($app);
1839
+    }
1840
+
1841
+    /**
1842
+     * @return \OCP\Lockdown\ILockdownManager
1843
+     */
1844
+    public function getLockdownManager() {
1845
+        return $this->query('LockdownManager');
1846
+    }
1847
+
1848
+    /**
1849
+     * @return \OCP\Federation\ICloudIdManager
1850
+     */
1851
+    public function getCloudIdManager() {
1852
+        return $this->query(ICloudIdManager::class);
1853
+    }
1854 1854
 }
Please login to merge, or discard this patch.
Spacing   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 		parent::__construct();
144 144
 		$this->webRoot = $webRoot;
145 145
 
146
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
146
+		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
147 147
 			return $c;
148 148
 		});
149 149
 
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
154 154
 
155 155
 
156
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
156
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
157 157
 			return new PreviewManager(
158 158
 				$c->getConfig(),
159 159
 				$c->getRootFolder(),
@@ -164,13 +164,13 @@  discard block
 block discarded – undo
164 164
 		});
165 165
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
166 166
 
167
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
167
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
168 168
 			return new \OC\Preview\Watcher(
169 169
 				$c->getAppDataDir('preview')
170 170
 			);
171 171
 		});
172 172
 
173
-		$this->registerService('EncryptionManager', function (Server $c) {
173
+		$this->registerService('EncryptionManager', function(Server $c) {
174 174
 			$view = new View();
175 175
 			$util = new Encryption\Util(
176 176
 				$view,
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 			);
189 189
 		});
190 190
 
191
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
191
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
192 192
 			$util = new Encryption\Util(
193 193
 				new View(),
194 194
 				$c->getUserManager(),
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 			);
203 203
 		});
204 204
 
205
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
205
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
206 206
 			$view = new View();
207 207
 			$util = new Encryption\Util(
208 208
 				$view,
@@ -213,32 +213,32 @@  discard block
 block discarded – undo
213 213
 
214 214
 			return new Encryption\Keys\Storage($view, $util);
215 215
 		});
216
-		$this->registerService('TagMapper', function (Server $c) {
216
+		$this->registerService('TagMapper', function(Server $c) {
217 217
 			return new TagMapper($c->getDatabaseConnection());
218 218
 		});
219 219
 
220
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
220
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
221 221
 			$tagMapper = $c->query('TagMapper');
222 222
 			return new TagManager($tagMapper, $c->getUserSession());
223 223
 		});
224 224
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
225 225
 
226
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
226
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
227 227
 			$config = $c->getConfig();
228 228
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
229 229
 			/** @var \OC\SystemTag\ManagerFactory $factory */
230 230
 			$factory = new $factoryClass($this);
231 231
 			return $factory;
232 232
 		});
233
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
233
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
234 234
 			return $c->query('SystemTagManagerFactory')->getManager();
235 235
 		});
236 236
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
237 237
 
238
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
238
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
239 239
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
240 240
 		});
241
-		$this->registerService('RootFolder', function (Server $c) {
241
+		$this->registerService('RootFolder', function(Server $c) {
242 242
 			$manager = \OC\Files\Filesystem::getMountManager(null);
243 243
 			$view = new View();
244 244
 			$root = new Root(
@@ -259,37 +259,37 @@  discard block
 block discarded – undo
259 259
 		});
260 260
 		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
261 261
 
262
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
263
-			return new LazyRoot(function () use ($c) {
262
+		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
263
+			return new LazyRoot(function() use ($c) {
264 264
 				return $c->query('RootFolder');
265 265
 			});
266 266
 		});
267 267
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
268 268
 
269
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
269
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
270 270
 			$config = $c->getConfig();
271 271
 			return new \OC\User\Manager($config);
272 272
 		});
273 273
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
274 274
 
275
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
275
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
276 276
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
277
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
277
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
278 278
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
279 279
 			});
280
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
280
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
281 281
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
282 282
 			});
283
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
283
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
284 284
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
285 285
 			});
286
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
286
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
287 287
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
288 288
 			});
289
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
289
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
290 290
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
291 291
 			});
292
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
292
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
293 293
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
294 294
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
295 295
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
 		});
299 299
 		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
300 300
 
301
-		$this->registerService(Store::class, function (Server $c) {
301
+		$this->registerService(Store::class, function(Server $c) {
302 302
 			$session = $c->getSession();
303 303
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
304 304
 				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
@@ -309,11 +309,11 @@  discard block
 block discarded – undo
309 309
 			return new Store($session, $logger, $tokenProvider);
310 310
 		});
311 311
 		$this->registerAlias(IStore::class, Store::class);
312
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
312
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
313 313
 			$dbConnection = $c->getDatabaseConnection();
314 314
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
315 315
 		});
316
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
316
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
317 317
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
318 318
 			$crypto = $c->getCrypto();
319 319
 			$config = $c->getConfig();
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
 		});
324 324
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
325 325
 
326
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
326
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
327 327
 			$manager = $c->getUserManager();
328 328
 			$session = new \OC\Session\Memory('');
329 329
 			$timeFactory = new TimeFactory();
@@ -336,44 +336,44 @@  discard block
 block discarded – undo
336 336
 			}
337 337
 
338 338
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
339
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
339
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
340 340
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
341 341
 			});
342
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
342
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
343 343
 				/** @var $user \OC\User\User */
344 344
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
345 345
 			});
346
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
346
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
347 347
 				/** @var $user \OC\User\User */
348 348
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
349 349
 			});
350
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
350
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
351 351
 				/** @var $user \OC\User\User */
352 352
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
353 353
 			});
354
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
354
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
355 355
 				/** @var $user \OC\User\User */
356 356
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
357 357
 			});
358
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
358
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
359 359
 				/** @var $user \OC\User\User */
360 360
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
361 361
 			});
362
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
362
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
363 363
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
364 364
 			});
365
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
365
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
366 366
 				/** @var $user \OC\User\User */
367 367
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
368 368
 			});
369
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
369
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
370 370
 				/** @var $user \OC\User\User */
371 371
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
372 372
 			});
373
-			$userSession->listen('\OC\User', 'logout', function () {
373
+			$userSession->listen('\OC\User', 'logout', function() {
374 374
 				\OC_Hook::emit('OC_User', 'logout', array());
375 375
 			});
376
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
376
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) {
377 377
 				/** @var $user \OC\User\User */
378 378
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
379 379
 			});
@@ -381,7 +381,7 @@  discard block
 block discarded – undo
381 381
 		});
382 382
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
383 383
 
384
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
384
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
385 385
 			return new \OC\Authentication\TwoFactorAuth\Manager(
386 386
 				$c->getAppManager(),
387 387
 				$c->getSession(),
@@ -396,7 +396,7 @@  discard block
 block discarded – undo
396 396
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
397 397
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
398 398
 
399
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
399
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
400 400
 			return new \OC\AllConfig(
401 401
 				$c->getSystemConfig()
402 402
 			);
@@ -404,17 +404,17 @@  discard block
 block discarded – undo
404 404
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
405 405
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
406 406
 
407
-		$this->registerService('SystemConfig', function ($c) use ($config) {
407
+		$this->registerService('SystemConfig', function($c) use ($config) {
408 408
 			return new \OC\SystemConfig($config);
409 409
 		});
410 410
 
411
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
411
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
412 412
 			return new \OC\AppConfig($c->getDatabaseConnection());
413 413
 		});
414 414
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
415 415
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
416 416
 
417
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
417
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
418 418
 			return new \OC\L10N\Factory(
419 419
 				$c->getConfig(),
420 420
 				$c->getRequest(),
@@ -424,7 +424,7 @@  discard block
 block discarded – undo
424 424
 		});
425 425
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
426 426
 
427
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
427
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
428 428
 			$config = $c->getConfig();
429 429
 			$cacheFactory = $c->getMemCacheFactory();
430 430
 			$request = $c->getRequest();
@@ -436,18 +436,18 @@  discard block
 block discarded – undo
436 436
 		});
437 437
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
438 438
 
439
-		$this->registerService('AppHelper', function ($c) {
439
+		$this->registerService('AppHelper', function($c) {
440 440
 			return new \OC\AppHelper();
441 441
 		});
442 442
 		$this->registerAlias('AppFetcher', AppFetcher::class);
443 443
 		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
444 444
 
445
-		$this->registerService(\OCP\ICache::class, function ($c) {
445
+		$this->registerService(\OCP\ICache::class, function($c) {
446 446
 			return new Cache\File();
447 447
 		});
448 448
 		$this->registerAlias('UserCache', \OCP\ICache::class);
449 449
 
450
-		$this->registerService(Factory::class, function (Server $c) {
450
+		$this->registerService(Factory::class, function(Server $c) {
451 451
 
452 452
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
453 453
 				'\\OC\\Memcache\\ArrayCache',
@@ -464,7 +464,7 @@  discard block
 block discarded – undo
464 464
 				$version = implode(',', $v);
465 465
 				$instanceId = \OC_Util::getInstanceId();
466 466
 				$path = \OC::$SERVERROOT;
467
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
467
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.$urlGenerator->getBaseUrl());
468 468
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
469 469
 					$config->getSystemValue('memcache.local', null),
470 470
 					$config->getSystemValue('memcache.distributed', null),
@@ -477,12 +477,12 @@  discard block
 block discarded – undo
477 477
 		$this->registerAlias('MemCacheFactory', Factory::class);
478 478
 		$this->registerAlias(ICacheFactory::class, Factory::class);
479 479
 
480
-		$this->registerService('RedisFactory', function (Server $c) {
480
+		$this->registerService('RedisFactory', function(Server $c) {
481 481
 			$systemConfig = $c->getSystemConfig();
482 482
 			return new RedisFactory($systemConfig);
483 483
 		});
484 484
 
485
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
485
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
486 486
 			return new \OC\Activity\Manager(
487 487
 				$c->getRequest(),
488 488
 				$c->getUserSession(),
@@ -492,14 +492,14 @@  discard block
 block discarded – undo
492 492
 		});
493 493
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
494 494
 
495
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
495
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
496 496
 			return new \OC\Activity\EventMerger(
497 497
 				$c->getL10N('lib')
498 498
 			);
499 499
 		});
500 500
 		$this->registerAlias(IValidator::class, Validator::class);
501 501
 
502
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
502
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
503 503
 			return new AvatarManager(
504 504
 				$c->getUserManager(),
505 505
 				$c->getAppDataDir('avatar'),
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
 		});
511 511
 		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
512 512
 
513
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
513
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
514 514
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
515 515
 			$logger = Log::getLogClass($logType);
516 516
 			call_user_func(array($logger, 'init'));
@@ -519,7 +519,7 @@  discard block
 block discarded – undo
519 519
 		});
520 520
 		$this->registerAlias('Logger', \OCP\ILogger::class);
521 521
 
522
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
522
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
523 523
 			$config = $c->getConfig();
524 524
 			return new \OC\BackgroundJob\JobList(
525 525
 				$c->getDatabaseConnection(),
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
 		});
530 530
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
531 531
 
532
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
532
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
533 533
 			$cacheFactory = $c->getMemCacheFactory();
534 534
 			$logger = $c->getLogger();
535 535
 			if ($cacheFactory->isAvailable()) {
@@ -541,12 +541,12 @@  discard block
 block discarded – undo
541 541
 		});
542 542
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
543 543
 
544
-		$this->registerService(\OCP\ISearch::class, function ($c) {
544
+		$this->registerService(\OCP\ISearch::class, function($c) {
545 545
 			return new Search();
546 546
 		});
547 547
 		$this->registerAlias('Search', \OCP\ISearch::class);
548 548
 
549
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
549
+		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
550 550
 			return new \OC\Security\RateLimiting\Limiter(
551 551
 				$this->getUserSession(),
552 552
 				$this->getRequest(),
@@ -554,34 +554,34 @@  discard block
 block discarded – undo
554 554
 				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
555 555
 			);
556 556
 		});
557
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
557
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
558 558
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
559 559
 				$this->getMemCacheFactory(),
560 560
 				new \OC\AppFramework\Utility\TimeFactory()
561 561
 			);
562 562
 		});
563 563
 
564
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
564
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
565 565
 			return new SecureRandom();
566 566
 		});
567 567
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
568 568
 
569
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
569
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
570 570
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
571 571
 		});
572 572
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
573 573
 
574
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
574
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
575 575
 			return new Hasher($c->getConfig());
576 576
 		});
577 577
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
578 578
 
579
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
579
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
580 580
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
581 581
 		});
582 582
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
583 583
 
584
-		$this->registerService(IDBConnection::class, function (Server $c) {
584
+		$this->registerService(IDBConnection::class, function(Server $c) {
585 585
 			$systemConfig = $c->getSystemConfig();
586 586
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
587 587
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 		});
596 596
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
597 597
 
598
-		$this->registerService('HTTPHelper', function (Server $c) {
598
+		$this->registerService('HTTPHelper', function(Server $c) {
599 599
 			$config = $c->getConfig();
600 600
 			return new HTTPHelper(
601 601
 				$config,
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
 			);
604 604
 		});
605 605
 
606
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
606
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
607 607
 			$user = \OC_User::getUser();
608 608
 			$uid = $user ? $user : null;
609 609
 			return new ClientService(
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
 			);
619 619
 		});
620 620
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
621
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
621
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
622 622
 			$eventLogger = new EventLogger();
623 623
 			if ($c->getSystemConfig()->getValue('debug', false)) {
624 624
 				// In debug mode, module is being activated by default
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 		});
629 629
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
630 630
 
631
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
631
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
632 632
 			$queryLogger = new QueryLogger();
633 633
 			if ($c->getSystemConfig()->getValue('debug', false)) {
634 634
 				// In debug mode, module is being activated by default
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 		});
639 639
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
640 640
 
641
-		$this->registerService(TempManager::class, function (Server $c) {
641
+		$this->registerService(TempManager::class, function(Server $c) {
642 642
 			return new TempManager(
643 643
 				$c->getLogger(),
644 644
 				$c->getConfig()
@@ -647,7 +647,7 @@  discard block
 block discarded – undo
647 647
 		$this->registerAlias('TempManager', TempManager::class);
648 648
 		$this->registerAlias(ITempManager::class, TempManager::class);
649 649
 
650
-		$this->registerService(AppManager::class, function (Server $c) {
650
+		$this->registerService(AppManager::class, function(Server $c) {
651 651
 			return new \OC\App\AppManager(
652 652
 				$c->getUserSession(),
653 653
 				$c->getAppConfig(),
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 		$this->registerAlias('AppManager', AppManager::class);
660 660
 		$this->registerAlias(IAppManager::class, AppManager::class);
661 661
 
662
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
662
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
663 663
 			return new DateTimeZone(
664 664
 				$c->getConfig(),
665 665
 				$c->getSession()
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
 		});
668 668
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
669 669
 
670
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
670
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
671 671
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
672 672
 
673 673
 			return new DateTimeFormatter(
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
 		});
678 678
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
679 679
 
680
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
680
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
681 681
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
682 682
 			$listener = new UserMountCacheListener($mountCache);
683 683
 			$listener->listen($c->getUserManager());
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
 		});
686 686
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
687 687
 
688
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
688
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
689 689
 			$loader = \OC\Files\Filesystem::getLoader();
690 690
 			$mountCache = $c->query('UserMountCache');
691 691
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -701,10 +701,10 @@  discard block
 block discarded – undo
701 701
 		});
702 702
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
703 703
 
704
-		$this->registerService('IniWrapper', function ($c) {
704
+		$this->registerService('IniWrapper', function($c) {
705 705
 			return new IniGetWrapper();
706 706
 		});
707
-		$this->registerService('AsyncCommandBus', function (Server $c) {
707
+		$this->registerService('AsyncCommandBus', function(Server $c) {
708 708
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
709 709
 			if ($busClass) {
710 710
 				list($app, $class) = explode('::', $busClass, 2);
@@ -719,10 +719,10 @@  discard block
 block discarded – undo
719 719
 				return new CronBus($jobList);
720 720
 			}
721 721
 		});
722
-		$this->registerService('TrustedDomainHelper', function ($c) {
722
+		$this->registerService('TrustedDomainHelper', function($c) {
723 723
 			return new TrustedDomainHelper($this->getConfig());
724 724
 		});
725
-		$this->registerService('Throttler', function (Server $c) {
725
+		$this->registerService('Throttler', function(Server $c) {
726 726
 			return new Throttler(
727 727
 				$c->getDatabaseConnection(),
728 728
 				new TimeFactory(),
@@ -730,7 +730,7 @@  discard block
 block discarded – undo
730 730
 				$c->getConfig()
731 731
 			);
732 732
 		});
733
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
733
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
734 734
 			// IConfig and IAppManager requires a working database. This code
735 735
 			// might however be called when ownCloud is not yet setup.
736 736
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -751,7 +751,7 @@  discard block
 block discarded – undo
751 751
 				$c->getTempManager()
752 752
 			);
753 753
 		});
754
-		$this->registerService(\OCP\IRequest::class, function ($c) {
754
+		$this->registerService(\OCP\IRequest::class, function($c) {
755 755
 			if (isset($this['urlParams'])) {
756 756
 				$urlParams = $this['urlParams'];
757 757
 			} else {
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
 		});
788 788
 		$this->registerAlias('Request', \OCP\IRequest::class);
789 789
 
790
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
790
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
791 791
 			return new Mailer(
792 792
 				$c->getConfig(),
793 793
 				$c->getLogger(),
@@ -798,7 +798,7 @@  discard block
 block discarded – undo
798 798
 		});
799 799
 		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
800 800
 
801
-		$this->registerService('LDAPProvider', function (Server $c) {
801
+		$this->registerService('LDAPProvider', function(Server $c) {
802 802
 			$config = $c->getConfig();
803 803
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
804 804
 			if (is_null($factoryClass)) {
@@ -808,7 +808,7 @@  discard block
 block discarded – undo
808 808
 			$factory = new $factoryClass($this);
809 809
 			return $factory->getLDAPProvider();
810 810
 		});
811
-		$this->registerService(ILockingProvider::class, function (Server $c) {
811
+		$this->registerService(ILockingProvider::class, function(Server $c) {
812 812
 			$ini = $c->getIniWrapper();
813 813
 			$config = $c->getConfig();
814 814
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -825,49 +825,49 @@  discard block
 block discarded – undo
825 825
 		});
826 826
 		$this->registerAlias('LockingProvider', ILockingProvider::class);
827 827
 
828
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
828
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
829 829
 			return new \OC\Files\Mount\Manager();
830 830
 		});
831 831
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
832 832
 
833
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
833
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
834 834
 			return new \OC\Files\Type\Detection(
835 835
 				$c->getURLGenerator(),
836 836
 				\OC::$configDir,
837
-				\OC::$SERVERROOT . '/resources/config/'
837
+				\OC::$SERVERROOT.'/resources/config/'
838 838
 			);
839 839
 		});
840 840
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
841 841
 
842
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
842
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
843 843
 			return new \OC\Files\Type\Loader(
844 844
 				$c->getDatabaseConnection()
845 845
 			);
846 846
 		});
847 847
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
848
-		$this->registerService(BundleFetcher::class, function () {
848
+		$this->registerService(BundleFetcher::class, function() {
849 849
 			return new BundleFetcher($this->getL10N('lib'));
850 850
 		});
851
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
851
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
852 852
 			return new Manager(
853 853
 				$c->query(IValidator::class)
854 854
 			);
855 855
 		});
856 856
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
857 857
 
858
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
858
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
859 859
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
860
-			$manager->registerCapability(function () use ($c) {
860
+			$manager->registerCapability(function() use ($c) {
861 861
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
862 862
 			});
863
-			$manager->registerCapability(function () use ($c) {
863
+			$manager->registerCapability(function() use ($c) {
864 864
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
865 865
 			});
866 866
 			return $manager;
867 867
 		});
868 868
 		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
869 869
 
870
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
870
+		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
871 871
 			$config = $c->getConfig();
872 872
 			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
873 873
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
 		});
877 877
 		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
878 878
 
879
-		$this->registerService('ThemingDefaults', function (Server $c) {
879
+		$this->registerService('ThemingDefaults', function(Server $c) {
880 880
 			/*
881 881
 			 * Dark magic for autoloader.
882 882
 			 * If we do a class_exists it will try to load the class which will
@@ -903,7 +903,7 @@  discard block
 block discarded – undo
903 903
 			}
904 904
 			return new \OC_Defaults();
905 905
 		});
906
-		$this->registerService(SCSSCacher::class, function (Server $c) {
906
+		$this->registerService(SCSSCacher::class, function(Server $c) {
907 907
 			/** @var Factory $cacheFactory */
908 908
 			$cacheFactory = $c->query(Factory::class);
909 909
 			return new SCSSCacher(
@@ -916,13 +916,13 @@  discard block
 block discarded – undo
916 916
 				$cacheFactory->create('SCSS')
917 917
 			);
918 918
 		});
919
-		$this->registerService(EventDispatcher::class, function () {
919
+		$this->registerService(EventDispatcher::class, function() {
920 920
 			return new EventDispatcher();
921 921
 		});
922 922
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
923 923
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
924 924
 
925
-		$this->registerService('CryptoWrapper', function (Server $c) {
925
+		$this->registerService('CryptoWrapper', function(Server $c) {
926 926
 			// FIXME: Instantiiated here due to cyclic dependency
927 927
 			$request = new Request(
928 928
 				[
@@ -947,7 +947,7 @@  discard block
 block discarded – undo
947 947
 				$request
948 948
 			);
949 949
 		});
950
-		$this->registerService('CsrfTokenManager', function (Server $c) {
950
+		$this->registerService('CsrfTokenManager', function(Server $c) {
951 951
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
952 952
 
953 953
 			return new CsrfTokenManager(
@@ -955,22 +955,22 @@  discard block
 block discarded – undo
955 955
 				$c->query(SessionStorage::class)
956 956
 			);
957 957
 		});
958
-		$this->registerService(SessionStorage::class, function (Server $c) {
958
+		$this->registerService(SessionStorage::class, function(Server $c) {
959 959
 			return new SessionStorage($c->getSession());
960 960
 		});
961
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
961
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
962 962
 			return new ContentSecurityPolicyManager();
963 963
 		});
964 964
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
965 965
 
966
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
966
+		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
967 967
 			return new ContentSecurityPolicyNonceManager(
968 968
 				$c->getCsrfTokenManager(),
969 969
 				$c->getRequest()
970 970
 			);
971 971
 		});
972 972
 
973
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
973
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
974 974
 			$config = $c->getConfig();
975 975
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
976 976
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1011,12 +1011,12 @@  discard block
 block discarded – undo
1011 1011
 		});
1012 1012
 		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1013 1013
 
1014
-		$this->registerService(\OCP\Collaboration\AutoComplete\IManager::class, function (Server $c) {
1014
+		$this->registerService(\OCP\Collaboration\AutoComplete\IManager::class, function(Server $c) {
1015 1015
 			return new Collaboration\AutoComplete\Manager($c);
1016 1016
 		});
1017 1017
 		$this->registerAlias('AutoCompleteManager', \OCP\Collaboration\AutoComplete\IManager::class);
1018 1018
 
1019
-		$this->registerService('SettingsManager', function (Server $c) {
1019
+		$this->registerService('SettingsManager', function(Server $c) {
1020 1020
 			$manager = new \OC\Settings\Manager(
1021 1021
 				$c->getLogger(),
1022 1022
 				$c->getDatabaseConnection(),
@@ -1036,29 +1036,29 @@  discard block
 block discarded – undo
1036 1036
 			);
1037 1037
 			return $manager;
1038 1038
 		});
1039
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1039
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1040 1040
 			return new \OC\Files\AppData\Factory(
1041 1041
 				$c->getRootFolder(),
1042 1042
 				$c->getSystemConfig()
1043 1043
 			);
1044 1044
 		});
1045 1045
 
1046
-		$this->registerService('LockdownManager', function (Server $c) {
1047
-			return new LockdownManager(function () use ($c) {
1046
+		$this->registerService('LockdownManager', function(Server $c) {
1047
+			return new LockdownManager(function() use ($c) {
1048 1048
 				return $c->getSession();
1049 1049
 			});
1050 1050
 		});
1051 1051
 
1052
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1052
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1053 1053
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1054 1054
 		});
1055 1055
 
1056
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1056
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1057 1057
 			return new CloudIdManager();
1058 1058
 		});
1059 1059
 
1060 1060
 		/* To trick DI since we don't extend the DIContainer here */
1061
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1061
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
1062 1062
 			return new CleanPreviewsBackgroundJob(
1063 1063
 				$c->getRootFolder(),
1064 1064
 				$c->getLogger(),
@@ -1073,18 +1073,18 @@  discard block
 block discarded – undo
1073 1073
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1074 1074
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1075 1075
 
1076
-		$this->registerService(Defaults::class, function (Server $c) {
1076
+		$this->registerService(Defaults::class, function(Server $c) {
1077 1077
 			return new Defaults(
1078 1078
 				$c->getThemingDefaults()
1079 1079
 			);
1080 1080
 		});
1081 1081
 		$this->registerAlias('Defaults', \OCP\Defaults::class);
1082 1082
 
1083
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1083
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1084 1084
 			return $c->query(\OCP\IUserSession::class)->getSession();
1085 1085
 		});
1086 1086
 
1087
-		$this->registerService(IShareHelper::class, function (Server $c) {
1087
+		$this->registerService(IShareHelper::class, function(Server $c) {
1088 1088
 			return new ShareHelper(
1089 1089
 				$c->query(\OCP\Share\IManager::class)
1090 1090
 			);
@@ -1225,7 +1225,7 @@  discard block
 block discarded – undo
1225 1225
 	 * @deprecated since 9.2.0 use IAppData
1226 1226
 	 */
1227 1227
 	public function getAppFolder() {
1228
-		$dir = '/' . \OC_App::getCurrentApp();
1228
+		$dir = '/'.\OC_App::getCurrentApp();
1229 1229
 		$root = $this->getRootFolder();
1230 1230
 		if (!$root->nodeExists($dir)) {
1231 1231
 			$folder = $root->newFolder($dir);
@@ -1809,7 +1809,7 @@  discard block
 block discarded – undo
1809 1809
 	/**
1810 1810
 	 * @return \OCP\Collaboration\AutoComplete\IManager
1811 1811
 	 */
1812
-	public function getAutoCompleteManager(){
1812
+	public function getAutoCompleteManager() {
1813 1813
 		return $this->query('AutoCompleteManager');
1814 1814
 	}
1815 1815
 
Please login to merge, or discard this patch.
lib/private/legacy/app.php 1 patch
Indentation   +1198 added lines, -1198 removed lines patch added patch discarded remove patch
@@ -61,1202 +61,1202 @@
 block discarded – undo
61 61
  * upgrading and removing apps.
62 62
  */
63 63
 class OC_App {
64
-	static private $appVersion = [];
65
-	static private $adminForms = array();
66
-	static private $personalForms = array();
67
-	static private $appInfo = array();
68
-	static private $appTypes = array();
69
-	static private $loadedApps = array();
70
-	static private $altLogin = array();
71
-	static private $alreadyRegistered = [];
72
-	const officialApp = 200;
73
-
74
-	/**
75
-	 * clean the appId
76
-	 *
77
-	 * @param string|boolean $app AppId that needs to be cleaned
78
-	 * @return string
79
-	 */
80
-	public static function cleanAppId($app) {
81
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
-	}
83
-
84
-	/**
85
-	 * Check if an app is loaded
86
-	 *
87
-	 * @param string $app
88
-	 * @return bool
89
-	 */
90
-	public static function isAppLoaded($app) {
91
-		return in_array($app, self::$loadedApps, true);
92
-	}
93
-
94
-	/**
95
-	 * loads all apps
96
-	 *
97
-	 * @param string[] | string | null $types
98
-	 * @return bool
99
-	 *
100
-	 * This function walks through the ownCloud directory and loads all apps
101
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
102
-	 * exists.
103
-	 *
104
-	 * if $types is set, only apps of those types will be loaded
105
-	 */
106
-	public static function loadApps($types = null) {
107
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
-			return false;
109
-		}
110
-		// Load the enabled apps here
111
-		$apps = self::getEnabledApps();
112
-
113
-		// Add each apps' folder as allowed class path
114
-		foreach($apps as $app) {
115
-			$path = self::getAppPath($app);
116
-			if($path !== false) {
117
-				self::registerAutoloading($app, $path);
118
-			}
119
-		}
120
-
121
-		// prevent app.php from printing output
122
-		ob_start();
123
-		foreach ($apps as $app) {
124
-			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
-				self::loadApp($app);
126
-			}
127
-		}
128
-		ob_end_clean();
129
-
130
-		return true;
131
-	}
132
-
133
-	/**
134
-	 * load a single app
135
-	 *
136
-	 * @param string $app
137
-	 */
138
-	public static function loadApp($app) {
139
-		self::$loadedApps[] = $app;
140
-		$appPath = self::getAppPath($app);
141
-		if($appPath === false) {
142
-			return;
143
-		}
144
-
145
-		// in case someone calls loadApp() directly
146
-		self::registerAutoloading($app, $appPath);
147
-
148
-		if (is_file($appPath . '/appinfo/app.php')) {
149
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
-			self::requireAppFile($app);
151
-			if (self::isType($app, array('authentication'))) {
152
-				// since authentication apps affect the "is app enabled for group" check,
153
-				// the enabled apps cache needs to be cleared to make sure that the
154
-				// next time getEnableApps() is called it will also include apps that were
155
-				// enabled for groups
156
-				self::$enabledAppsCache = array();
157
-			}
158
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
159
-		}
160
-
161
-		$info = self::getAppInfo($app);
162
-		if (!empty($info['activity']['filters'])) {
163
-			foreach ($info['activity']['filters'] as $filter) {
164
-				\OC::$server->getActivityManager()->registerFilter($filter);
165
-			}
166
-		}
167
-		if (!empty($info['activity']['settings'])) {
168
-			foreach ($info['activity']['settings'] as $setting) {
169
-				\OC::$server->getActivityManager()->registerSetting($setting);
170
-			}
171
-		}
172
-		if (!empty($info['activity']['providers'])) {
173
-			foreach ($info['activity']['providers'] as $provider) {
174
-				\OC::$server->getActivityManager()->registerProvider($provider);
175
-			}
176
-		}
177
-		if (!empty($info['collaboration']['plugins'])) {
178
-			// deal with one or many plugin entries
179
-			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
180
-				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
181
-			foreach ($plugins as $plugin) {
182
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
183
-					$pluginInfo = [
184
-						'shareType' => $plugin['@attributes']['share-type'],
185
-						'class' => $plugin['@value'],
186
-					];
187
-					\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
188
-				} else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
189
-					\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
190
-				}
191
-			}
192
-		}
193
-	}
194
-
195
-	/**
196
-	 * @internal
197
-	 * @param string $app
198
-	 * @param string $path
199
-	 */
200
-	public static function registerAutoloading($app, $path) {
201
-		$key = $app . '-' . $path;
202
-		if(isset(self::$alreadyRegistered[$key])) {
203
-			return;
204
-		}
205
-		self::$alreadyRegistered[$key] = true;
206
-		// Register on PSR-4 composer autoloader
207
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
208
-		\OC::$server->registerNamespace($app, $appNamespace);
209
-		\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
210
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
211
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
212
-		}
213
-
214
-		// Register on legacy autoloader
215
-		\OC::$loader->addValidRoot($path);
216
-	}
217
-
218
-	/**
219
-	 * Load app.php from the given app
220
-	 *
221
-	 * @param string $app app name
222
-	 */
223
-	private static function requireAppFile($app) {
224
-		try {
225
-			// encapsulated here to avoid variable scope conflicts
226
-			require_once $app . '/appinfo/app.php';
227
-		} catch (Error $ex) {
228
-			\OC::$server->getLogger()->logException($ex);
229
-			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
230
-			if (!in_array($app, $blacklist)) {
231
-				self::disable($app);
232
-			}
233
-		}
234
-	}
235
-
236
-	/**
237
-	 * check if an app is of a specific type
238
-	 *
239
-	 * @param string $app
240
-	 * @param string|array $types
241
-	 * @return bool
242
-	 */
243
-	public static function isType($app, $types) {
244
-		if (is_string($types)) {
245
-			$types = array($types);
246
-		}
247
-		$appTypes = self::getAppTypes($app);
248
-		foreach ($types as $type) {
249
-			if (array_search($type, $appTypes) !== false) {
250
-				return true;
251
-			}
252
-		}
253
-		return false;
254
-	}
255
-
256
-	/**
257
-	 * get the types of an app
258
-	 *
259
-	 * @param string $app
260
-	 * @return array
261
-	 */
262
-	private static function getAppTypes($app) {
263
-		//load the cache
264
-		if (count(self::$appTypes) == 0) {
265
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
266
-		}
267
-
268
-		if (isset(self::$appTypes[$app])) {
269
-			return explode(',', self::$appTypes[$app]);
270
-		} else {
271
-			return array();
272
-		}
273
-	}
274
-
275
-	/**
276
-	 * read app types from info.xml and cache them in the database
277
-	 */
278
-	public static function setAppTypes($app) {
279
-		$appData = self::getAppInfo($app);
280
-		if(!is_array($appData)) {
281
-			return;
282
-		}
283
-
284
-		if (isset($appData['types'])) {
285
-			$appTypes = implode(',', $appData['types']);
286
-		} else {
287
-			$appTypes = '';
288
-			$appData['types'] = [];
289
-		}
290
-
291
-		\OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
292
-
293
-		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
294
-			$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
295
-			if ($enabled !== 'yes' && $enabled !== 'no') {
296
-				\OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
297
-			}
298
-		}
299
-	}
300
-
301
-	/**
302
-	 * get all enabled apps
303
-	 */
304
-	protected static $enabledAppsCache = array();
305
-
306
-	/**
307
-	 * Returns apps enabled for the current user.
308
-	 *
309
-	 * @param bool $forceRefresh whether to refresh the cache
310
-	 * @param bool $all whether to return apps for all users, not only the
311
-	 * currently logged in one
312
-	 * @return string[]
313
-	 */
314
-	public static function getEnabledApps($forceRefresh = false, $all = false) {
315
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
316
-			return array();
317
-		}
318
-		// in incognito mode or when logged out, $user will be false,
319
-		// which is also the case during an upgrade
320
-		$appManager = \OC::$server->getAppManager();
321
-		if ($all) {
322
-			$user = null;
323
-		} else {
324
-			$user = \OC::$server->getUserSession()->getUser();
325
-		}
326
-
327
-		if (is_null($user)) {
328
-			$apps = $appManager->getInstalledApps();
329
-		} else {
330
-			$apps = $appManager->getEnabledAppsForUser($user);
331
-		}
332
-		$apps = array_filter($apps, function ($app) {
333
-			return $app !== 'files';//we add this manually
334
-		});
335
-		sort($apps);
336
-		array_unshift($apps, 'files');
337
-		return $apps;
338
-	}
339
-
340
-	/**
341
-	 * checks whether or not an app is enabled
342
-	 *
343
-	 * @param string $app app
344
-	 * @return bool
345
-	 *
346
-	 * This function checks whether or not an app is enabled.
347
-	 */
348
-	public static function isEnabled($app) {
349
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
350
-	}
351
-
352
-	/**
353
-	 * enables an app
354
-	 *
355
-	 * @param string $appId
356
-	 * @param array $groups (optional) when set, only these groups will have access to the app
357
-	 * @throws \Exception
358
-	 * @return void
359
-	 *
360
-	 * This function set an app as enabled in appconfig.
361
-	 */
362
-	public function enable($appId,
363
-						   $groups = null) {
364
-		self::$enabledAppsCache = []; // flush
365
-
366
-		// Check if app is already downloaded
367
-		$installer = new Installer(
368
-			\OC::$server->getAppFetcher(),
369
-			\OC::$server->getHTTPClientService(),
370
-			\OC::$server->getTempManager(),
371
-			\OC::$server->getLogger(),
372
-			\OC::$server->getConfig()
373
-		);
374
-		$isDownloaded = $installer->isDownloaded($appId);
375
-
376
-		if(!$isDownloaded) {
377
-			$installer->downloadApp($appId);
378
-		}
379
-
380
-		$installer->installApp($appId);
381
-
382
-		$appManager = \OC::$server->getAppManager();
383
-		if (!is_null($groups)) {
384
-			$groupManager = \OC::$server->getGroupManager();
385
-			$groupsList = [];
386
-			foreach ($groups as $group) {
387
-				$groupItem = $groupManager->get($group);
388
-				if ($groupItem instanceof \OCP\IGroup) {
389
-					$groupsList[] = $groupManager->get($group);
390
-				}
391
-			}
392
-			$appManager->enableAppForGroups($appId, $groupsList);
393
-		} else {
394
-			$appManager->enableApp($appId);
395
-		}
396
-	}
397
-
398
-	/**
399
-	 * @param string $app
400
-	 * @return bool
401
-	 */
402
-	public static function removeApp($app) {
403
-		if (\OC::$server->getAppManager()->isShipped($app)) {
404
-			return false;
405
-		}
406
-
407
-		$installer = new Installer(
408
-			\OC::$server->getAppFetcher(),
409
-			\OC::$server->getHTTPClientService(),
410
-			\OC::$server->getTempManager(),
411
-			\OC::$server->getLogger(),
412
-			\OC::$server->getConfig()
413
-		);
414
-		return $installer->removeApp($app);
415
-	}
416
-
417
-	/**
418
-	 * This function set an app as disabled in appconfig.
419
-	 *
420
-	 * @param string $app app
421
-	 * @throws Exception
422
-	 */
423
-	public static function disable($app) {
424
-		// flush
425
-		self::$enabledAppsCache = array();
426
-
427
-		// run uninstall steps
428
-		$appData = OC_App::getAppInfo($app);
429
-		if (!is_null($appData)) {
430
-			OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
431
-		}
432
-
433
-		// emit disable hook - needed anymore ?
434
-		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
435
-
436
-		// finally disable it
437
-		$appManager = \OC::$server->getAppManager();
438
-		$appManager->disableApp($app);
439
-	}
440
-
441
-	// This is private as well. It simply works, so don't ask for more details
442
-	private static function proceedNavigation($list) {
443
-		usort($list, function($a, $b) {
444
-			if (isset($a['order']) && isset($b['order'])) {
445
-				return ($a['order'] < $b['order']) ? -1 : 1;
446
-			} else if (isset($a['order']) || isset($b['order'])) {
447
-				return isset($a['order']) ? -1 : 1;
448
-			} else {
449
-				return ($a['name'] < $b['name']) ? -1 : 1;
450
-			}
451
-		});
452
-
453
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
454
-		foreach ($list as $index => &$navEntry) {
455
-			if ($navEntry['id'] == $activeApp) {
456
-				$navEntry['active'] = true;
457
-			} else {
458
-				$navEntry['active'] = false;
459
-			}
460
-		}
461
-		unset($navEntry);
462
-
463
-		return $list;
464
-	}
465
-
466
-	/**
467
-	 * Get the path where to install apps
468
-	 *
469
-	 * @return string|false
470
-	 */
471
-	public static function getInstallPath() {
472
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
473
-			return false;
474
-		}
475
-
476
-		foreach (OC::$APPSROOTS as $dir) {
477
-			if (isset($dir['writable']) && $dir['writable'] === true) {
478
-				return $dir['path'];
479
-			}
480
-		}
481
-
482
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
483
-		return null;
484
-	}
485
-
486
-
487
-	/**
488
-	 * search for an app in all app-directories
489
-	 *
490
-	 * @param string $appId
491
-	 * @return false|string
492
-	 */
493
-	public static function findAppInDirectories($appId) {
494
-		$sanitizedAppId = self::cleanAppId($appId);
495
-		if($sanitizedAppId !== $appId) {
496
-			return false;
497
-		}
498
-		static $app_dir = array();
499
-
500
-		if (isset($app_dir[$appId])) {
501
-			return $app_dir[$appId];
502
-		}
503
-
504
-		$possibleApps = array();
505
-		foreach (OC::$APPSROOTS as $dir) {
506
-			if (file_exists($dir['path'] . '/' . $appId)) {
507
-				$possibleApps[] = $dir;
508
-			}
509
-		}
510
-
511
-		if (empty($possibleApps)) {
512
-			return false;
513
-		} elseif (count($possibleApps) === 1) {
514
-			$dir = array_shift($possibleApps);
515
-			$app_dir[$appId] = $dir;
516
-			return $dir;
517
-		} else {
518
-			$versionToLoad = array();
519
-			foreach ($possibleApps as $possibleApp) {
520
-				$version = self::getAppVersionByPath($possibleApp['path']);
521
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
522
-					$versionToLoad = array(
523
-						'dir' => $possibleApp,
524
-						'version' => $version,
525
-					);
526
-				}
527
-			}
528
-			$app_dir[$appId] = $versionToLoad['dir'];
529
-			return $versionToLoad['dir'];
530
-			//TODO - write test
531
-		}
532
-	}
533
-
534
-	/**
535
-	 * Get the directory for the given app.
536
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
537
-	 *
538
-	 * @param string $appId
539
-	 * @return string|false
540
-	 */
541
-	public static function getAppPath($appId) {
542
-		if ($appId === null || trim($appId) === '') {
543
-			return false;
544
-		}
545
-
546
-		if (($dir = self::findAppInDirectories($appId)) != false) {
547
-			return $dir['path'] . '/' . $appId;
548
-		}
549
-		return false;
550
-	}
551
-
552
-	/**
553
-	 * Get the path for the given app on the access
554
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
555
-	 *
556
-	 * @param string $appId
557
-	 * @return string|false
558
-	 */
559
-	public static function getAppWebPath($appId) {
560
-		if (($dir = self::findAppInDirectories($appId)) != false) {
561
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
562
-		}
563
-		return false;
564
-	}
565
-
566
-	/**
567
-	 * get the last version of the app from appinfo/info.xml
568
-	 *
569
-	 * @param string $appId
570
-	 * @param bool $useCache
571
-	 * @return string
572
-	 */
573
-	public static function getAppVersion($appId, $useCache = true) {
574
-		if($useCache && isset(self::$appVersion[$appId])) {
575
-			return self::$appVersion[$appId];
576
-		}
577
-
578
-		$file = self::getAppPath($appId);
579
-		self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
580
-		return self::$appVersion[$appId];
581
-	}
582
-
583
-	/**
584
-	 * get app's version based on it's path
585
-	 *
586
-	 * @param string $path
587
-	 * @return string
588
-	 */
589
-	public static function getAppVersionByPath($path) {
590
-		$infoFile = $path . '/appinfo/info.xml';
591
-		$appData = self::getAppInfo($infoFile, true);
592
-		return isset($appData['version']) ? $appData['version'] : '';
593
-	}
594
-
595
-
596
-	/**
597
-	 * Read all app metadata from the info.xml file
598
-	 *
599
-	 * @param string $appId id of the app or the path of the info.xml file
600
-	 * @param bool $path
601
-	 * @param string $lang
602
-	 * @return array|null
603
-	 * @note all data is read from info.xml, not just pre-defined fields
604
-	 */
605
-	public static function getAppInfo($appId, $path = false, $lang = null) {
606
-		if ($path) {
607
-			$file = $appId;
608
-		} else {
609
-			if ($lang === null && isset(self::$appInfo[$appId])) {
610
-				return self::$appInfo[$appId];
611
-			}
612
-			$appPath = self::getAppPath($appId);
613
-			if($appPath === false) {
614
-				return null;
615
-			}
616
-			$file = $appPath . '/appinfo/info.xml';
617
-		}
618
-
619
-		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
620
-		$data = $parser->parse($file);
621
-
622
-		if (is_array($data)) {
623
-			$data = OC_App::parseAppInfo($data, $lang);
624
-		}
625
-		if(isset($data['ocsid'])) {
626
-			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
627
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
628
-				$data['ocsid'] = $storedId;
629
-			}
630
-		}
631
-
632
-		if ($lang === null) {
633
-			self::$appInfo[$appId] = $data;
634
-		}
635
-
636
-		return $data;
637
-	}
638
-
639
-	/**
640
-	 * Returns the navigation
641
-	 *
642
-	 * @return array
643
-	 *
644
-	 * This function returns an array containing all entries added. The
645
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
646
-	 * given for each app the following keys exist:
647
-	 *   - active: boolean, signals if the user is on this navigation entry
648
-	 */
649
-	public static function getNavigation() {
650
-		$entries = OC::$server->getNavigationManager()->getAll();
651
-		return self::proceedNavigation($entries);
652
-	}
653
-
654
-	/**
655
-	 * Returns the Settings Navigation
656
-	 *
657
-	 * @return string[]
658
-	 *
659
-	 * This function returns an array containing all settings pages added. The
660
-	 * entries are sorted by the key 'order' ascending.
661
-	 */
662
-	public static function getSettingsNavigation() {
663
-		$entries = OC::$server->getNavigationManager()->getAll('settings');
664
-		return self::proceedNavigation($entries);
665
-	}
666
-
667
-	/**
668
-	 * get the id of loaded app
669
-	 *
670
-	 * @return string
671
-	 */
672
-	public static function getCurrentApp() {
673
-		$request = \OC::$server->getRequest();
674
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
675
-		$topFolder = substr($script, 0, strpos($script, '/'));
676
-		if (empty($topFolder)) {
677
-			$path_info = $request->getPathInfo();
678
-			if ($path_info) {
679
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
680
-			}
681
-		}
682
-		if ($topFolder == 'apps') {
683
-			$length = strlen($topFolder);
684
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
685
-		} else {
686
-			return $topFolder;
687
-		}
688
-	}
689
-
690
-	/**
691
-	 * @param string $type
692
-	 * @return array
693
-	 */
694
-	public static function getForms($type) {
695
-		$forms = array();
696
-		switch ($type) {
697
-			case 'admin':
698
-				$source = self::$adminForms;
699
-				break;
700
-			case 'personal':
701
-				$source = self::$personalForms;
702
-				break;
703
-			default:
704
-				return array();
705
-		}
706
-		foreach ($source as $form) {
707
-			$forms[] = include $form;
708
-		}
709
-		return $forms;
710
-	}
711
-
712
-	/**
713
-	 * register an admin form to be shown
714
-	 *
715
-	 * @param string $app
716
-	 * @param string $page
717
-	 */
718
-	public static function registerAdmin($app, $page) {
719
-		self::$adminForms[] = $app . '/' . $page . '.php';
720
-	}
721
-
722
-	/**
723
-	 * register a personal form to be shown
724
-	 * @param string $app
725
-	 * @param string $page
726
-	 */
727
-	public static function registerPersonal($app, $page) {
728
-		self::$personalForms[] = $app . '/' . $page . '.php';
729
-	}
730
-
731
-	/**
732
-	 * @param array $entry
733
-	 */
734
-	public static function registerLogIn(array $entry) {
735
-		self::$altLogin[] = $entry;
736
-	}
737
-
738
-	/**
739
-	 * @return array
740
-	 */
741
-	public static function getAlternativeLogIns() {
742
-		return self::$altLogin;
743
-	}
744
-
745
-	/**
746
-	 * get a list of all apps in the apps folder
747
-	 *
748
-	 * @return array an array of app names (string IDs)
749
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
750
-	 */
751
-	public static function getAllApps() {
752
-
753
-		$apps = array();
754
-
755
-		foreach (OC::$APPSROOTS as $apps_dir) {
756
-			if (!is_readable($apps_dir['path'])) {
757
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
758
-				continue;
759
-			}
760
-			$dh = opendir($apps_dir['path']);
761
-
762
-			if (is_resource($dh)) {
763
-				while (($file = readdir($dh)) !== false) {
764
-
765
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
766
-
767
-						$apps[] = $file;
768
-					}
769
-				}
770
-			}
771
-		}
772
-
773
-		$apps = array_unique($apps);
774
-
775
-		return $apps;
776
-	}
777
-
778
-	/**
779
-	 * List all apps, this is used in apps.php
780
-	 *
781
-	 * @return array
782
-	 */
783
-	public function listAllApps() {
784
-		$installedApps = OC_App::getAllApps();
785
-
786
-		$appManager = \OC::$server->getAppManager();
787
-		//we don't want to show configuration for these
788
-		$blacklist = $appManager->getAlwaysEnabledApps();
789
-		$appList = array();
790
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
791
-		$urlGenerator = \OC::$server->getURLGenerator();
792
-
793
-		foreach ($installedApps as $app) {
794
-			if (array_search($app, $blacklist) === false) {
795
-
796
-				$info = OC_App::getAppInfo($app, false, $langCode);
797
-				if (!is_array($info)) {
798
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
799
-					continue;
800
-				}
801
-
802
-				if (!isset($info['name'])) {
803
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
804
-					continue;
805
-				}
806
-
807
-				$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
808
-				$info['groups'] = null;
809
-				if ($enabled === 'yes') {
810
-					$active = true;
811
-				} else if ($enabled === 'no') {
812
-					$active = false;
813
-				} else {
814
-					$active = true;
815
-					$info['groups'] = $enabled;
816
-				}
817
-
818
-				$info['active'] = $active;
819
-
820
-				if ($appManager->isShipped($app)) {
821
-					$info['internal'] = true;
822
-					$info['level'] = self::officialApp;
823
-					$info['removable'] = false;
824
-				} else {
825
-					$info['internal'] = false;
826
-					$info['removable'] = true;
827
-				}
828
-
829
-				$appPath = self::getAppPath($app);
830
-				if($appPath !== false) {
831
-					$appIcon = $appPath . '/img/' . $app . '.svg';
832
-					if (file_exists($appIcon)) {
833
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
834
-						$info['previewAsIcon'] = true;
835
-					} else {
836
-						$appIcon = $appPath . '/img/app.svg';
837
-						if (file_exists($appIcon)) {
838
-							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
839
-							$info['previewAsIcon'] = true;
840
-						}
841
-					}
842
-				}
843
-				// fix documentation
844
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
845
-					foreach ($info['documentation'] as $key => $url) {
846
-						// If it is not an absolute URL we assume it is a key
847
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
848
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
849
-							$url = $urlGenerator->linkToDocs($url);
850
-						}
851
-
852
-						$info['documentation'][$key] = $url;
853
-					}
854
-				}
855
-
856
-				$info['version'] = OC_App::getAppVersion($app);
857
-				$appList[] = $info;
858
-			}
859
-		}
860
-
861
-		return $appList;
862
-	}
863
-
864
-	/**
865
-	 * Returns the internal app ID or false
866
-	 * @param string $ocsID
867
-	 * @return string|false
868
-	 */
869
-	public static function getInternalAppIdByOcs($ocsID) {
870
-		if(is_numeric($ocsID)) {
871
-			$idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
872
-			if(array_search($ocsID, $idArray)) {
873
-				return array_search($ocsID, $idArray);
874
-			}
875
-		}
876
-		return false;
877
-	}
878
-
879
-	public static function shouldUpgrade($app) {
880
-		$versions = self::getAppVersions();
881
-		$currentVersion = OC_App::getAppVersion($app);
882
-		if ($currentVersion && isset($versions[$app])) {
883
-			$installedVersion = $versions[$app];
884
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
885
-				return true;
886
-			}
887
-		}
888
-		return false;
889
-	}
890
-
891
-	/**
892
-	 * Adjust the number of version parts of $version1 to match
893
-	 * the number of version parts of $version2.
894
-	 *
895
-	 * @param string $version1 version to adjust
896
-	 * @param string $version2 version to take the number of parts from
897
-	 * @return string shortened $version1
898
-	 */
899
-	private static function adjustVersionParts($version1, $version2) {
900
-		$version1 = explode('.', $version1);
901
-		$version2 = explode('.', $version2);
902
-		// reduce $version1 to match the number of parts in $version2
903
-		while (count($version1) > count($version2)) {
904
-			array_pop($version1);
905
-		}
906
-		// if $version1 does not have enough parts, add some
907
-		while (count($version1) < count($version2)) {
908
-			$version1[] = '0';
909
-		}
910
-		return implode('.', $version1);
911
-	}
912
-
913
-	/**
914
-	 * Check whether the current ownCloud version matches the given
915
-	 * application's version requirements.
916
-	 *
917
-	 * The comparison is made based on the number of parts that the
918
-	 * app info version has. For example for ownCloud 6.0.3 if the
919
-	 * app info version is expecting version 6.0, the comparison is
920
-	 * made on the first two parts of the ownCloud version.
921
-	 * This means that it's possible to specify "requiremin" => 6
922
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
923
-	 *
924
-	 * @param string $ocVersion ownCloud version to check against
925
-	 * @param array $appInfo app info (from xml)
926
-	 *
927
-	 * @return boolean true if compatible, otherwise false
928
-	 */
929
-	public static function isAppCompatible($ocVersion, $appInfo) {
930
-		$requireMin = '';
931
-		$requireMax = '';
932
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
933
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
934
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
935
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
936
-		} else if (isset($appInfo['requiremin'])) {
937
-			$requireMin = $appInfo['requiremin'];
938
-		} else if (isset($appInfo['require'])) {
939
-			$requireMin = $appInfo['require'];
940
-		}
941
-
942
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
943
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
944
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
945
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
946
-		} else if (isset($appInfo['requiremax'])) {
947
-			$requireMax = $appInfo['requiremax'];
948
-		}
949
-
950
-		if (is_array($ocVersion)) {
951
-			$ocVersion = implode('.', $ocVersion);
952
-		}
953
-
954
-		if (!empty($requireMin)
955
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
956
-		) {
957
-
958
-			return false;
959
-		}
960
-
961
-		if (!empty($requireMax)
962
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
963
-		) {
964
-			return false;
965
-		}
966
-
967
-		return true;
968
-	}
969
-
970
-	/**
971
-	 * get the installed version of all apps
972
-	 */
973
-	public static function getAppVersions() {
974
-		static $versions;
975
-
976
-		if(!$versions) {
977
-			$appConfig = \OC::$server->getAppConfig();
978
-			$versions = $appConfig->getValues(false, 'installed_version');
979
-		}
980
-		return $versions;
981
-	}
982
-
983
-	/**
984
-	 * @param string $app
985
-	 * @param \OCP\IConfig $config
986
-	 * @param \OCP\IL10N $l
987
-	 * @return bool
988
-	 *
989
-	 * @throws Exception if app is not compatible with this version of ownCloud
990
-	 * @throws Exception if no app-name was specified
991
-	 */
992
-	public function installApp($app,
993
-							   \OCP\IConfig $config,
994
-							   \OCP\IL10N $l) {
995
-		if ($app !== false) {
996
-			// check if the app is compatible with this version of ownCloud
997
-			$info = self::getAppInfo($app);
998
-			if(!is_array($info)) {
999
-				throw new \Exception(
1000
-					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1001
-						[$info['name']]
1002
-					)
1003
-				);
1004
-			}
1005
-
1006
-			$version = \OCP\Util::getVersion();
1007
-			if (!self::isAppCompatible($version, $info)) {
1008
-				throw new \Exception(
1009
-					$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1010
-						array($info['name'])
1011
-					)
1012
-				);
1013
-			}
1014
-
1015
-			// check for required dependencies
1016
-			self::checkAppDependencies($config, $l, $info);
1017
-
1018
-			$config->setAppValue($app, 'enabled', 'yes');
1019
-			if (isset($appData['id'])) {
1020
-				$config->setAppValue($app, 'ocsid', $appData['id']);
1021
-			}
1022
-
1023
-			if(isset($info['settings']) && is_array($info['settings'])) {
1024
-				$appPath = self::getAppPath($app);
1025
-				self::registerAutoloading($app, $appPath);
1026
-				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
1027
-			}
1028
-
1029
-			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1030
-		} else {
1031
-			if(empty($appName) ) {
1032
-				throw new \Exception($l->t("No app name specified"));
1033
-			} else {
1034
-				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1035
-			}
1036
-		}
1037
-
1038
-		return $app;
1039
-	}
1040
-
1041
-	/**
1042
-	 * update the database for the app and call the update script
1043
-	 *
1044
-	 * @param string $appId
1045
-	 * @return bool
1046
-	 */
1047
-	public static function updateApp($appId) {
1048
-		$appPath = self::getAppPath($appId);
1049
-		if($appPath === false) {
1050
-			return false;
1051
-		}
1052
-		self::registerAutoloading($appId, $appPath);
1053
-
1054
-		$appData = self::getAppInfo($appId);
1055
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1056
-
1057
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1058
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1059
-		} else {
1060
-			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1061
-			$ms->migrate();
1062
-		}
1063
-
1064
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1065
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1066
-		unset(self::$appVersion[$appId]);
1067
-
1068
-		// run upgrade code
1069
-		if (file_exists($appPath . '/appinfo/update.php')) {
1070
-			self::loadApp($appId);
1071
-			include $appPath . '/appinfo/update.php';
1072
-		}
1073
-		self::setupBackgroundJobs($appData['background-jobs']);
1074
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1075
-			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1076
-		}
1077
-
1078
-		//set remote/public handlers
1079
-		if (array_key_exists('ocsid', $appData)) {
1080
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1081
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1082
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1083
-		}
1084
-		foreach ($appData['remote'] as $name => $path) {
1085
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1086
-		}
1087
-		foreach ($appData['public'] as $name => $path) {
1088
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1089
-		}
1090
-
1091
-		self::setAppTypes($appId);
1092
-
1093
-		$version = \OC_App::getAppVersion($appId);
1094
-		\OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1095
-
1096
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1097
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1098
-		));
1099
-
1100
-		return true;
1101
-	}
1102
-
1103
-	/**
1104
-	 * @param string $appId
1105
-	 * @param string[] $steps
1106
-	 * @throws \OC\NeedsUpdateException
1107
-	 */
1108
-	public static function executeRepairSteps($appId, array $steps) {
1109
-		if (empty($steps)) {
1110
-			return;
1111
-		}
1112
-		// load the app
1113
-		self::loadApp($appId);
1114
-
1115
-		$dispatcher = OC::$server->getEventDispatcher();
1116
-
1117
-		// load the steps
1118
-		$r = new Repair([], $dispatcher);
1119
-		foreach ($steps as $step) {
1120
-			try {
1121
-				$r->addStep($step);
1122
-			} catch (Exception $ex) {
1123
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1124
-				\OC::$server->getLogger()->logException($ex);
1125
-			}
1126
-		}
1127
-		// run the steps
1128
-		$r->run();
1129
-	}
1130
-
1131
-	public static function setupBackgroundJobs(array $jobs) {
1132
-		$queue = \OC::$server->getJobList();
1133
-		foreach ($jobs as $job) {
1134
-			$queue->add($job);
1135
-		}
1136
-	}
1137
-
1138
-	/**
1139
-	 * @param string $appId
1140
-	 * @param string[] $steps
1141
-	 */
1142
-	private static function setupLiveMigrations($appId, array $steps) {
1143
-		$queue = \OC::$server->getJobList();
1144
-		foreach ($steps as $step) {
1145
-			$queue->add('OC\Migration\BackgroundRepair', [
1146
-				'app' => $appId,
1147
-				'step' => $step]);
1148
-		}
1149
-	}
1150
-
1151
-	/**
1152
-	 * @param string $appId
1153
-	 * @return \OC\Files\View|false
1154
-	 */
1155
-	public static function getStorage($appId) {
1156
-		if (OC_App::isEnabled($appId)) { //sanity check
1157
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1158
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1159
-				if (!$view->file_exists($appId)) {
1160
-					$view->mkdir($appId);
1161
-				}
1162
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1163
-			} else {
1164
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1165
-				return false;
1166
-			}
1167
-		} else {
1168
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1169
-			return false;
1170
-		}
1171
-	}
1172
-
1173
-	protected static function findBestL10NOption($options, $lang) {
1174
-		$fallback = $similarLangFallback = $englishFallback = false;
1175
-
1176
-		$lang = strtolower($lang);
1177
-		$similarLang = $lang;
1178
-		if (strpos($similarLang, '_')) {
1179
-			// For "de_DE" we want to find "de" and the other way around
1180
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1181
-		}
1182
-
1183
-		foreach ($options as $option) {
1184
-			if (is_array($option)) {
1185
-				if ($fallback === false) {
1186
-					$fallback = $option['@value'];
1187
-				}
1188
-
1189
-				if (!isset($option['@attributes']['lang'])) {
1190
-					continue;
1191
-				}
1192
-
1193
-				$attributeLang = strtolower($option['@attributes']['lang']);
1194
-				if ($attributeLang === $lang) {
1195
-					return $option['@value'];
1196
-				}
1197
-
1198
-				if ($attributeLang === $similarLang) {
1199
-					$similarLangFallback = $option['@value'];
1200
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1201
-					if ($similarLangFallback === false) {
1202
-						$similarLangFallback =  $option['@value'];
1203
-					}
1204
-				}
1205
-			} else {
1206
-				$englishFallback = $option;
1207
-			}
1208
-		}
1209
-
1210
-		if ($similarLangFallback !== false) {
1211
-			return $similarLangFallback;
1212
-		} else if ($englishFallback !== false) {
1213
-			return $englishFallback;
1214
-		}
1215
-		return (string) $fallback;
1216
-	}
1217
-
1218
-	/**
1219
-	 * parses the app data array and enhanced the 'description' value
1220
-	 *
1221
-	 * @param array $data the app data
1222
-	 * @param string $lang
1223
-	 * @return array improved app data
1224
-	 */
1225
-	public static function parseAppInfo(array $data, $lang = null) {
1226
-
1227
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1228
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1229
-		}
1230
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1231
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1232
-		}
1233
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1234
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1235
-		} else if (isset($data['description']) && is_string($data['description'])) {
1236
-			$data['description'] = trim($data['description']);
1237
-		} else  {
1238
-			$data['description'] = '';
1239
-		}
1240
-
1241
-		return $data;
1242
-	}
1243
-
1244
-	/**
1245
-	 * @param \OCP\IConfig $config
1246
-	 * @param \OCP\IL10N $l
1247
-	 * @param array $info
1248
-	 * @throws \Exception
1249
-	 */
1250
-	public static function checkAppDependencies($config, $l, $info) {
1251
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1252
-		$missing = $dependencyAnalyzer->analyze($info);
1253
-		if (!empty($missing)) {
1254
-			$missingMsg = implode(PHP_EOL, $missing);
1255
-			throw new \Exception(
1256
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1257
-					[$info['name'], $missingMsg]
1258
-				)
1259
-			);
1260
-		}
1261
-	}
64
+    static private $appVersion = [];
65
+    static private $adminForms = array();
66
+    static private $personalForms = array();
67
+    static private $appInfo = array();
68
+    static private $appTypes = array();
69
+    static private $loadedApps = array();
70
+    static private $altLogin = array();
71
+    static private $alreadyRegistered = [];
72
+    const officialApp = 200;
73
+
74
+    /**
75
+     * clean the appId
76
+     *
77
+     * @param string|boolean $app AppId that needs to be cleaned
78
+     * @return string
79
+     */
80
+    public static function cleanAppId($app) {
81
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
+    }
83
+
84
+    /**
85
+     * Check if an app is loaded
86
+     *
87
+     * @param string $app
88
+     * @return bool
89
+     */
90
+    public static function isAppLoaded($app) {
91
+        return in_array($app, self::$loadedApps, true);
92
+    }
93
+
94
+    /**
95
+     * loads all apps
96
+     *
97
+     * @param string[] | string | null $types
98
+     * @return bool
99
+     *
100
+     * This function walks through the ownCloud directory and loads all apps
101
+     * it can find. A directory contains an app if the file /appinfo/info.xml
102
+     * exists.
103
+     *
104
+     * if $types is set, only apps of those types will be loaded
105
+     */
106
+    public static function loadApps($types = null) {
107
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
+            return false;
109
+        }
110
+        // Load the enabled apps here
111
+        $apps = self::getEnabledApps();
112
+
113
+        // Add each apps' folder as allowed class path
114
+        foreach($apps as $app) {
115
+            $path = self::getAppPath($app);
116
+            if($path !== false) {
117
+                self::registerAutoloading($app, $path);
118
+            }
119
+        }
120
+
121
+        // prevent app.php from printing output
122
+        ob_start();
123
+        foreach ($apps as $app) {
124
+            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
+                self::loadApp($app);
126
+            }
127
+        }
128
+        ob_end_clean();
129
+
130
+        return true;
131
+    }
132
+
133
+    /**
134
+     * load a single app
135
+     *
136
+     * @param string $app
137
+     */
138
+    public static function loadApp($app) {
139
+        self::$loadedApps[] = $app;
140
+        $appPath = self::getAppPath($app);
141
+        if($appPath === false) {
142
+            return;
143
+        }
144
+
145
+        // in case someone calls loadApp() directly
146
+        self::registerAutoloading($app, $appPath);
147
+
148
+        if (is_file($appPath . '/appinfo/app.php')) {
149
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
+            self::requireAppFile($app);
151
+            if (self::isType($app, array('authentication'))) {
152
+                // since authentication apps affect the "is app enabled for group" check,
153
+                // the enabled apps cache needs to be cleared to make sure that the
154
+                // next time getEnableApps() is called it will also include apps that were
155
+                // enabled for groups
156
+                self::$enabledAppsCache = array();
157
+            }
158
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
159
+        }
160
+
161
+        $info = self::getAppInfo($app);
162
+        if (!empty($info['activity']['filters'])) {
163
+            foreach ($info['activity']['filters'] as $filter) {
164
+                \OC::$server->getActivityManager()->registerFilter($filter);
165
+            }
166
+        }
167
+        if (!empty($info['activity']['settings'])) {
168
+            foreach ($info['activity']['settings'] as $setting) {
169
+                \OC::$server->getActivityManager()->registerSetting($setting);
170
+            }
171
+        }
172
+        if (!empty($info['activity']['providers'])) {
173
+            foreach ($info['activity']['providers'] as $provider) {
174
+                \OC::$server->getActivityManager()->registerProvider($provider);
175
+            }
176
+        }
177
+        if (!empty($info['collaboration']['plugins'])) {
178
+            // deal with one or many plugin entries
179
+            $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
180
+                [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
181
+            foreach ($plugins as $plugin) {
182
+                if($plugin['@attributes']['type'] === 'collaborator-search') {
183
+                    $pluginInfo = [
184
+                        'shareType' => $plugin['@attributes']['share-type'],
185
+                        'class' => $plugin['@value'],
186
+                    ];
187
+                    \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
188
+                } else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
189
+                    \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
190
+                }
191
+            }
192
+        }
193
+    }
194
+
195
+    /**
196
+     * @internal
197
+     * @param string $app
198
+     * @param string $path
199
+     */
200
+    public static function registerAutoloading($app, $path) {
201
+        $key = $app . '-' . $path;
202
+        if(isset(self::$alreadyRegistered[$key])) {
203
+            return;
204
+        }
205
+        self::$alreadyRegistered[$key] = true;
206
+        // Register on PSR-4 composer autoloader
207
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
208
+        \OC::$server->registerNamespace($app, $appNamespace);
209
+        \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
210
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
211
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
212
+        }
213
+
214
+        // Register on legacy autoloader
215
+        \OC::$loader->addValidRoot($path);
216
+    }
217
+
218
+    /**
219
+     * Load app.php from the given app
220
+     *
221
+     * @param string $app app name
222
+     */
223
+    private static function requireAppFile($app) {
224
+        try {
225
+            // encapsulated here to avoid variable scope conflicts
226
+            require_once $app . '/appinfo/app.php';
227
+        } catch (Error $ex) {
228
+            \OC::$server->getLogger()->logException($ex);
229
+            $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
230
+            if (!in_array($app, $blacklist)) {
231
+                self::disable($app);
232
+            }
233
+        }
234
+    }
235
+
236
+    /**
237
+     * check if an app is of a specific type
238
+     *
239
+     * @param string $app
240
+     * @param string|array $types
241
+     * @return bool
242
+     */
243
+    public static function isType($app, $types) {
244
+        if (is_string($types)) {
245
+            $types = array($types);
246
+        }
247
+        $appTypes = self::getAppTypes($app);
248
+        foreach ($types as $type) {
249
+            if (array_search($type, $appTypes) !== false) {
250
+                return true;
251
+            }
252
+        }
253
+        return false;
254
+    }
255
+
256
+    /**
257
+     * get the types of an app
258
+     *
259
+     * @param string $app
260
+     * @return array
261
+     */
262
+    private static function getAppTypes($app) {
263
+        //load the cache
264
+        if (count(self::$appTypes) == 0) {
265
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
266
+        }
267
+
268
+        if (isset(self::$appTypes[$app])) {
269
+            return explode(',', self::$appTypes[$app]);
270
+        } else {
271
+            return array();
272
+        }
273
+    }
274
+
275
+    /**
276
+     * read app types from info.xml and cache them in the database
277
+     */
278
+    public static function setAppTypes($app) {
279
+        $appData = self::getAppInfo($app);
280
+        if(!is_array($appData)) {
281
+            return;
282
+        }
283
+
284
+        if (isset($appData['types'])) {
285
+            $appTypes = implode(',', $appData['types']);
286
+        } else {
287
+            $appTypes = '';
288
+            $appData['types'] = [];
289
+        }
290
+
291
+        \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
292
+
293
+        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
294
+            $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
295
+            if ($enabled !== 'yes' && $enabled !== 'no') {
296
+                \OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
297
+            }
298
+        }
299
+    }
300
+
301
+    /**
302
+     * get all enabled apps
303
+     */
304
+    protected static $enabledAppsCache = array();
305
+
306
+    /**
307
+     * Returns apps enabled for the current user.
308
+     *
309
+     * @param bool $forceRefresh whether to refresh the cache
310
+     * @param bool $all whether to return apps for all users, not only the
311
+     * currently logged in one
312
+     * @return string[]
313
+     */
314
+    public static function getEnabledApps($forceRefresh = false, $all = false) {
315
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
316
+            return array();
317
+        }
318
+        // in incognito mode or when logged out, $user will be false,
319
+        // which is also the case during an upgrade
320
+        $appManager = \OC::$server->getAppManager();
321
+        if ($all) {
322
+            $user = null;
323
+        } else {
324
+            $user = \OC::$server->getUserSession()->getUser();
325
+        }
326
+
327
+        if (is_null($user)) {
328
+            $apps = $appManager->getInstalledApps();
329
+        } else {
330
+            $apps = $appManager->getEnabledAppsForUser($user);
331
+        }
332
+        $apps = array_filter($apps, function ($app) {
333
+            return $app !== 'files';//we add this manually
334
+        });
335
+        sort($apps);
336
+        array_unshift($apps, 'files');
337
+        return $apps;
338
+    }
339
+
340
+    /**
341
+     * checks whether or not an app is enabled
342
+     *
343
+     * @param string $app app
344
+     * @return bool
345
+     *
346
+     * This function checks whether or not an app is enabled.
347
+     */
348
+    public static function isEnabled($app) {
349
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
350
+    }
351
+
352
+    /**
353
+     * enables an app
354
+     *
355
+     * @param string $appId
356
+     * @param array $groups (optional) when set, only these groups will have access to the app
357
+     * @throws \Exception
358
+     * @return void
359
+     *
360
+     * This function set an app as enabled in appconfig.
361
+     */
362
+    public function enable($appId,
363
+                            $groups = null) {
364
+        self::$enabledAppsCache = []; // flush
365
+
366
+        // Check if app is already downloaded
367
+        $installer = new Installer(
368
+            \OC::$server->getAppFetcher(),
369
+            \OC::$server->getHTTPClientService(),
370
+            \OC::$server->getTempManager(),
371
+            \OC::$server->getLogger(),
372
+            \OC::$server->getConfig()
373
+        );
374
+        $isDownloaded = $installer->isDownloaded($appId);
375
+
376
+        if(!$isDownloaded) {
377
+            $installer->downloadApp($appId);
378
+        }
379
+
380
+        $installer->installApp($appId);
381
+
382
+        $appManager = \OC::$server->getAppManager();
383
+        if (!is_null($groups)) {
384
+            $groupManager = \OC::$server->getGroupManager();
385
+            $groupsList = [];
386
+            foreach ($groups as $group) {
387
+                $groupItem = $groupManager->get($group);
388
+                if ($groupItem instanceof \OCP\IGroup) {
389
+                    $groupsList[] = $groupManager->get($group);
390
+                }
391
+            }
392
+            $appManager->enableAppForGroups($appId, $groupsList);
393
+        } else {
394
+            $appManager->enableApp($appId);
395
+        }
396
+    }
397
+
398
+    /**
399
+     * @param string $app
400
+     * @return bool
401
+     */
402
+    public static function removeApp($app) {
403
+        if (\OC::$server->getAppManager()->isShipped($app)) {
404
+            return false;
405
+        }
406
+
407
+        $installer = new Installer(
408
+            \OC::$server->getAppFetcher(),
409
+            \OC::$server->getHTTPClientService(),
410
+            \OC::$server->getTempManager(),
411
+            \OC::$server->getLogger(),
412
+            \OC::$server->getConfig()
413
+        );
414
+        return $installer->removeApp($app);
415
+    }
416
+
417
+    /**
418
+     * This function set an app as disabled in appconfig.
419
+     *
420
+     * @param string $app app
421
+     * @throws Exception
422
+     */
423
+    public static function disable($app) {
424
+        // flush
425
+        self::$enabledAppsCache = array();
426
+
427
+        // run uninstall steps
428
+        $appData = OC_App::getAppInfo($app);
429
+        if (!is_null($appData)) {
430
+            OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
431
+        }
432
+
433
+        // emit disable hook - needed anymore ?
434
+        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
435
+
436
+        // finally disable it
437
+        $appManager = \OC::$server->getAppManager();
438
+        $appManager->disableApp($app);
439
+    }
440
+
441
+    // This is private as well. It simply works, so don't ask for more details
442
+    private static function proceedNavigation($list) {
443
+        usort($list, function($a, $b) {
444
+            if (isset($a['order']) && isset($b['order'])) {
445
+                return ($a['order'] < $b['order']) ? -1 : 1;
446
+            } else if (isset($a['order']) || isset($b['order'])) {
447
+                return isset($a['order']) ? -1 : 1;
448
+            } else {
449
+                return ($a['name'] < $b['name']) ? -1 : 1;
450
+            }
451
+        });
452
+
453
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
454
+        foreach ($list as $index => &$navEntry) {
455
+            if ($navEntry['id'] == $activeApp) {
456
+                $navEntry['active'] = true;
457
+            } else {
458
+                $navEntry['active'] = false;
459
+            }
460
+        }
461
+        unset($navEntry);
462
+
463
+        return $list;
464
+    }
465
+
466
+    /**
467
+     * Get the path where to install apps
468
+     *
469
+     * @return string|false
470
+     */
471
+    public static function getInstallPath() {
472
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
473
+            return false;
474
+        }
475
+
476
+        foreach (OC::$APPSROOTS as $dir) {
477
+            if (isset($dir['writable']) && $dir['writable'] === true) {
478
+                return $dir['path'];
479
+            }
480
+        }
481
+
482
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
483
+        return null;
484
+    }
485
+
486
+
487
+    /**
488
+     * search for an app in all app-directories
489
+     *
490
+     * @param string $appId
491
+     * @return false|string
492
+     */
493
+    public static function findAppInDirectories($appId) {
494
+        $sanitizedAppId = self::cleanAppId($appId);
495
+        if($sanitizedAppId !== $appId) {
496
+            return false;
497
+        }
498
+        static $app_dir = array();
499
+
500
+        if (isset($app_dir[$appId])) {
501
+            return $app_dir[$appId];
502
+        }
503
+
504
+        $possibleApps = array();
505
+        foreach (OC::$APPSROOTS as $dir) {
506
+            if (file_exists($dir['path'] . '/' . $appId)) {
507
+                $possibleApps[] = $dir;
508
+            }
509
+        }
510
+
511
+        if (empty($possibleApps)) {
512
+            return false;
513
+        } elseif (count($possibleApps) === 1) {
514
+            $dir = array_shift($possibleApps);
515
+            $app_dir[$appId] = $dir;
516
+            return $dir;
517
+        } else {
518
+            $versionToLoad = array();
519
+            foreach ($possibleApps as $possibleApp) {
520
+                $version = self::getAppVersionByPath($possibleApp['path']);
521
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
522
+                    $versionToLoad = array(
523
+                        'dir' => $possibleApp,
524
+                        'version' => $version,
525
+                    );
526
+                }
527
+            }
528
+            $app_dir[$appId] = $versionToLoad['dir'];
529
+            return $versionToLoad['dir'];
530
+            //TODO - write test
531
+        }
532
+    }
533
+
534
+    /**
535
+     * Get the directory for the given app.
536
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
537
+     *
538
+     * @param string $appId
539
+     * @return string|false
540
+     */
541
+    public static function getAppPath($appId) {
542
+        if ($appId === null || trim($appId) === '') {
543
+            return false;
544
+        }
545
+
546
+        if (($dir = self::findAppInDirectories($appId)) != false) {
547
+            return $dir['path'] . '/' . $appId;
548
+        }
549
+        return false;
550
+    }
551
+
552
+    /**
553
+     * Get the path for the given app on the access
554
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
555
+     *
556
+     * @param string $appId
557
+     * @return string|false
558
+     */
559
+    public static function getAppWebPath($appId) {
560
+        if (($dir = self::findAppInDirectories($appId)) != false) {
561
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
562
+        }
563
+        return false;
564
+    }
565
+
566
+    /**
567
+     * get the last version of the app from appinfo/info.xml
568
+     *
569
+     * @param string $appId
570
+     * @param bool $useCache
571
+     * @return string
572
+     */
573
+    public static function getAppVersion($appId, $useCache = true) {
574
+        if($useCache && isset(self::$appVersion[$appId])) {
575
+            return self::$appVersion[$appId];
576
+        }
577
+
578
+        $file = self::getAppPath($appId);
579
+        self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
580
+        return self::$appVersion[$appId];
581
+    }
582
+
583
+    /**
584
+     * get app's version based on it's path
585
+     *
586
+     * @param string $path
587
+     * @return string
588
+     */
589
+    public static function getAppVersionByPath($path) {
590
+        $infoFile = $path . '/appinfo/info.xml';
591
+        $appData = self::getAppInfo($infoFile, true);
592
+        return isset($appData['version']) ? $appData['version'] : '';
593
+    }
594
+
595
+
596
+    /**
597
+     * Read all app metadata from the info.xml file
598
+     *
599
+     * @param string $appId id of the app or the path of the info.xml file
600
+     * @param bool $path
601
+     * @param string $lang
602
+     * @return array|null
603
+     * @note all data is read from info.xml, not just pre-defined fields
604
+     */
605
+    public static function getAppInfo($appId, $path = false, $lang = null) {
606
+        if ($path) {
607
+            $file = $appId;
608
+        } else {
609
+            if ($lang === null && isset(self::$appInfo[$appId])) {
610
+                return self::$appInfo[$appId];
611
+            }
612
+            $appPath = self::getAppPath($appId);
613
+            if($appPath === false) {
614
+                return null;
615
+            }
616
+            $file = $appPath . '/appinfo/info.xml';
617
+        }
618
+
619
+        $parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
620
+        $data = $parser->parse($file);
621
+
622
+        if (is_array($data)) {
623
+            $data = OC_App::parseAppInfo($data, $lang);
624
+        }
625
+        if(isset($data['ocsid'])) {
626
+            $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
627
+            if($storedId !== '' && $storedId !== $data['ocsid']) {
628
+                $data['ocsid'] = $storedId;
629
+            }
630
+        }
631
+
632
+        if ($lang === null) {
633
+            self::$appInfo[$appId] = $data;
634
+        }
635
+
636
+        return $data;
637
+    }
638
+
639
+    /**
640
+     * Returns the navigation
641
+     *
642
+     * @return array
643
+     *
644
+     * This function returns an array containing all entries added. The
645
+     * entries are sorted by the key 'order' ascending. Additional to the keys
646
+     * given for each app the following keys exist:
647
+     *   - active: boolean, signals if the user is on this navigation entry
648
+     */
649
+    public static function getNavigation() {
650
+        $entries = OC::$server->getNavigationManager()->getAll();
651
+        return self::proceedNavigation($entries);
652
+    }
653
+
654
+    /**
655
+     * Returns the Settings Navigation
656
+     *
657
+     * @return string[]
658
+     *
659
+     * This function returns an array containing all settings pages added. The
660
+     * entries are sorted by the key 'order' ascending.
661
+     */
662
+    public static function getSettingsNavigation() {
663
+        $entries = OC::$server->getNavigationManager()->getAll('settings');
664
+        return self::proceedNavigation($entries);
665
+    }
666
+
667
+    /**
668
+     * get the id of loaded app
669
+     *
670
+     * @return string
671
+     */
672
+    public static function getCurrentApp() {
673
+        $request = \OC::$server->getRequest();
674
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
675
+        $topFolder = substr($script, 0, strpos($script, '/'));
676
+        if (empty($topFolder)) {
677
+            $path_info = $request->getPathInfo();
678
+            if ($path_info) {
679
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
680
+            }
681
+        }
682
+        if ($topFolder == 'apps') {
683
+            $length = strlen($topFolder);
684
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
685
+        } else {
686
+            return $topFolder;
687
+        }
688
+    }
689
+
690
+    /**
691
+     * @param string $type
692
+     * @return array
693
+     */
694
+    public static function getForms($type) {
695
+        $forms = array();
696
+        switch ($type) {
697
+            case 'admin':
698
+                $source = self::$adminForms;
699
+                break;
700
+            case 'personal':
701
+                $source = self::$personalForms;
702
+                break;
703
+            default:
704
+                return array();
705
+        }
706
+        foreach ($source as $form) {
707
+            $forms[] = include $form;
708
+        }
709
+        return $forms;
710
+    }
711
+
712
+    /**
713
+     * register an admin form to be shown
714
+     *
715
+     * @param string $app
716
+     * @param string $page
717
+     */
718
+    public static function registerAdmin($app, $page) {
719
+        self::$adminForms[] = $app . '/' . $page . '.php';
720
+    }
721
+
722
+    /**
723
+     * register a personal form to be shown
724
+     * @param string $app
725
+     * @param string $page
726
+     */
727
+    public static function registerPersonal($app, $page) {
728
+        self::$personalForms[] = $app . '/' . $page . '.php';
729
+    }
730
+
731
+    /**
732
+     * @param array $entry
733
+     */
734
+    public static function registerLogIn(array $entry) {
735
+        self::$altLogin[] = $entry;
736
+    }
737
+
738
+    /**
739
+     * @return array
740
+     */
741
+    public static function getAlternativeLogIns() {
742
+        return self::$altLogin;
743
+    }
744
+
745
+    /**
746
+     * get a list of all apps in the apps folder
747
+     *
748
+     * @return array an array of app names (string IDs)
749
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
750
+     */
751
+    public static function getAllApps() {
752
+
753
+        $apps = array();
754
+
755
+        foreach (OC::$APPSROOTS as $apps_dir) {
756
+            if (!is_readable($apps_dir['path'])) {
757
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
758
+                continue;
759
+            }
760
+            $dh = opendir($apps_dir['path']);
761
+
762
+            if (is_resource($dh)) {
763
+                while (($file = readdir($dh)) !== false) {
764
+
765
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
766
+
767
+                        $apps[] = $file;
768
+                    }
769
+                }
770
+            }
771
+        }
772
+
773
+        $apps = array_unique($apps);
774
+
775
+        return $apps;
776
+    }
777
+
778
+    /**
779
+     * List all apps, this is used in apps.php
780
+     *
781
+     * @return array
782
+     */
783
+    public function listAllApps() {
784
+        $installedApps = OC_App::getAllApps();
785
+
786
+        $appManager = \OC::$server->getAppManager();
787
+        //we don't want to show configuration for these
788
+        $blacklist = $appManager->getAlwaysEnabledApps();
789
+        $appList = array();
790
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
791
+        $urlGenerator = \OC::$server->getURLGenerator();
792
+
793
+        foreach ($installedApps as $app) {
794
+            if (array_search($app, $blacklist) === false) {
795
+
796
+                $info = OC_App::getAppInfo($app, false, $langCode);
797
+                if (!is_array($info)) {
798
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
799
+                    continue;
800
+                }
801
+
802
+                if (!isset($info['name'])) {
803
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
804
+                    continue;
805
+                }
806
+
807
+                $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
808
+                $info['groups'] = null;
809
+                if ($enabled === 'yes') {
810
+                    $active = true;
811
+                } else if ($enabled === 'no') {
812
+                    $active = false;
813
+                } else {
814
+                    $active = true;
815
+                    $info['groups'] = $enabled;
816
+                }
817
+
818
+                $info['active'] = $active;
819
+
820
+                if ($appManager->isShipped($app)) {
821
+                    $info['internal'] = true;
822
+                    $info['level'] = self::officialApp;
823
+                    $info['removable'] = false;
824
+                } else {
825
+                    $info['internal'] = false;
826
+                    $info['removable'] = true;
827
+                }
828
+
829
+                $appPath = self::getAppPath($app);
830
+                if($appPath !== false) {
831
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
832
+                    if (file_exists($appIcon)) {
833
+                        $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
834
+                        $info['previewAsIcon'] = true;
835
+                    } else {
836
+                        $appIcon = $appPath . '/img/app.svg';
837
+                        if (file_exists($appIcon)) {
838
+                            $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
839
+                            $info['previewAsIcon'] = true;
840
+                        }
841
+                    }
842
+                }
843
+                // fix documentation
844
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
845
+                    foreach ($info['documentation'] as $key => $url) {
846
+                        // If it is not an absolute URL we assume it is a key
847
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
848
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
849
+                            $url = $urlGenerator->linkToDocs($url);
850
+                        }
851
+
852
+                        $info['documentation'][$key] = $url;
853
+                    }
854
+                }
855
+
856
+                $info['version'] = OC_App::getAppVersion($app);
857
+                $appList[] = $info;
858
+            }
859
+        }
860
+
861
+        return $appList;
862
+    }
863
+
864
+    /**
865
+     * Returns the internal app ID or false
866
+     * @param string $ocsID
867
+     * @return string|false
868
+     */
869
+    public static function getInternalAppIdByOcs($ocsID) {
870
+        if(is_numeric($ocsID)) {
871
+            $idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
872
+            if(array_search($ocsID, $idArray)) {
873
+                return array_search($ocsID, $idArray);
874
+            }
875
+        }
876
+        return false;
877
+    }
878
+
879
+    public static function shouldUpgrade($app) {
880
+        $versions = self::getAppVersions();
881
+        $currentVersion = OC_App::getAppVersion($app);
882
+        if ($currentVersion && isset($versions[$app])) {
883
+            $installedVersion = $versions[$app];
884
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
885
+                return true;
886
+            }
887
+        }
888
+        return false;
889
+    }
890
+
891
+    /**
892
+     * Adjust the number of version parts of $version1 to match
893
+     * the number of version parts of $version2.
894
+     *
895
+     * @param string $version1 version to adjust
896
+     * @param string $version2 version to take the number of parts from
897
+     * @return string shortened $version1
898
+     */
899
+    private static function adjustVersionParts($version1, $version2) {
900
+        $version1 = explode('.', $version1);
901
+        $version2 = explode('.', $version2);
902
+        // reduce $version1 to match the number of parts in $version2
903
+        while (count($version1) > count($version2)) {
904
+            array_pop($version1);
905
+        }
906
+        // if $version1 does not have enough parts, add some
907
+        while (count($version1) < count($version2)) {
908
+            $version1[] = '0';
909
+        }
910
+        return implode('.', $version1);
911
+    }
912
+
913
+    /**
914
+     * Check whether the current ownCloud version matches the given
915
+     * application's version requirements.
916
+     *
917
+     * The comparison is made based on the number of parts that the
918
+     * app info version has. For example for ownCloud 6.0.3 if the
919
+     * app info version is expecting version 6.0, the comparison is
920
+     * made on the first two parts of the ownCloud version.
921
+     * This means that it's possible to specify "requiremin" => 6
922
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
923
+     *
924
+     * @param string $ocVersion ownCloud version to check against
925
+     * @param array $appInfo app info (from xml)
926
+     *
927
+     * @return boolean true if compatible, otherwise false
928
+     */
929
+    public static function isAppCompatible($ocVersion, $appInfo) {
930
+        $requireMin = '';
931
+        $requireMax = '';
932
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
933
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
934
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
935
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
936
+        } else if (isset($appInfo['requiremin'])) {
937
+            $requireMin = $appInfo['requiremin'];
938
+        } else if (isset($appInfo['require'])) {
939
+            $requireMin = $appInfo['require'];
940
+        }
941
+
942
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
943
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
944
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
945
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
946
+        } else if (isset($appInfo['requiremax'])) {
947
+            $requireMax = $appInfo['requiremax'];
948
+        }
949
+
950
+        if (is_array($ocVersion)) {
951
+            $ocVersion = implode('.', $ocVersion);
952
+        }
953
+
954
+        if (!empty($requireMin)
955
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
956
+        ) {
957
+
958
+            return false;
959
+        }
960
+
961
+        if (!empty($requireMax)
962
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
963
+        ) {
964
+            return false;
965
+        }
966
+
967
+        return true;
968
+    }
969
+
970
+    /**
971
+     * get the installed version of all apps
972
+     */
973
+    public static function getAppVersions() {
974
+        static $versions;
975
+
976
+        if(!$versions) {
977
+            $appConfig = \OC::$server->getAppConfig();
978
+            $versions = $appConfig->getValues(false, 'installed_version');
979
+        }
980
+        return $versions;
981
+    }
982
+
983
+    /**
984
+     * @param string $app
985
+     * @param \OCP\IConfig $config
986
+     * @param \OCP\IL10N $l
987
+     * @return bool
988
+     *
989
+     * @throws Exception if app is not compatible with this version of ownCloud
990
+     * @throws Exception if no app-name was specified
991
+     */
992
+    public function installApp($app,
993
+                                \OCP\IConfig $config,
994
+                                \OCP\IL10N $l) {
995
+        if ($app !== false) {
996
+            // check if the app is compatible with this version of ownCloud
997
+            $info = self::getAppInfo($app);
998
+            if(!is_array($info)) {
999
+                throw new \Exception(
1000
+                    $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1001
+                        [$info['name']]
1002
+                    )
1003
+                );
1004
+            }
1005
+
1006
+            $version = \OCP\Util::getVersion();
1007
+            if (!self::isAppCompatible($version, $info)) {
1008
+                throw new \Exception(
1009
+                    $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1010
+                        array($info['name'])
1011
+                    )
1012
+                );
1013
+            }
1014
+
1015
+            // check for required dependencies
1016
+            self::checkAppDependencies($config, $l, $info);
1017
+
1018
+            $config->setAppValue($app, 'enabled', 'yes');
1019
+            if (isset($appData['id'])) {
1020
+                $config->setAppValue($app, 'ocsid', $appData['id']);
1021
+            }
1022
+
1023
+            if(isset($info['settings']) && is_array($info['settings'])) {
1024
+                $appPath = self::getAppPath($app);
1025
+                self::registerAutoloading($app, $appPath);
1026
+                \OC::$server->getSettingsManager()->setupSettings($info['settings']);
1027
+            }
1028
+
1029
+            \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1030
+        } else {
1031
+            if(empty($appName) ) {
1032
+                throw new \Exception($l->t("No app name specified"));
1033
+            } else {
1034
+                throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1035
+            }
1036
+        }
1037
+
1038
+        return $app;
1039
+    }
1040
+
1041
+    /**
1042
+     * update the database for the app and call the update script
1043
+     *
1044
+     * @param string $appId
1045
+     * @return bool
1046
+     */
1047
+    public static function updateApp($appId) {
1048
+        $appPath = self::getAppPath($appId);
1049
+        if($appPath === false) {
1050
+            return false;
1051
+        }
1052
+        self::registerAutoloading($appId, $appPath);
1053
+
1054
+        $appData = self::getAppInfo($appId);
1055
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1056
+
1057
+        if (file_exists($appPath . '/appinfo/database.xml')) {
1058
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1059
+        } else {
1060
+            $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1061
+            $ms->migrate();
1062
+        }
1063
+
1064
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1065
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1066
+        unset(self::$appVersion[$appId]);
1067
+
1068
+        // run upgrade code
1069
+        if (file_exists($appPath . '/appinfo/update.php')) {
1070
+            self::loadApp($appId);
1071
+            include $appPath . '/appinfo/update.php';
1072
+        }
1073
+        self::setupBackgroundJobs($appData['background-jobs']);
1074
+        if(isset($appData['settings']) && is_array($appData['settings'])) {
1075
+            \OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1076
+        }
1077
+
1078
+        //set remote/public handlers
1079
+        if (array_key_exists('ocsid', $appData)) {
1080
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1081
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1082
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1083
+        }
1084
+        foreach ($appData['remote'] as $name => $path) {
1085
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1086
+        }
1087
+        foreach ($appData['public'] as $name => $path) {
1088
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1089
+        }
1090
+
1091
+        self::setAppTypes($appId);
1092
+
1093
+        $version = \OC_App::getAppVersion($appId);
1094
+        \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1095
+
1096
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1097
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1098
+        ));
1099
+
1100
+        return true;
1101
+    }
1102
+
1103
+    /**
1104
+     * @param string $appId
1105
+     * @param string[] $steps
1106
+     * @throws \OC\NeedsUpdateException
1107
+     */
1108
+    public static function executeRepairSteps($appId, array $steps) {
1109
+        if (empty($steps)) {
1110
+            return;
1111
+        }
1112
+        // load the app
1113
+        self::loadApp($appId);
1114
+
1115
+        $dispatcher = OC::$server->getEventDispatcher();
1116
+
1117
+        // load the steps
1118
+        $r = new Repair([], $dispatcher);
1119
+        foreach ($steps as $step) {
1120
+            try {
1121
+                $r->addStep($step);
1122
+            } catch (Exception $ex) {
1123
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1124
+                \OC::$server->getLogger()->logException($ex);
1125
+            }
1126
+        }
1127
+        // run the steps
1128
+        $r->run();
1129
+    }
1130
+
1131
+    public static function setupBackgroundJobs(array $jobs) {
1132
+        $queue = \OC::$server->getJobList();
1133
+        foreach ($jobs as $job) {
1134
+            $queue->add($job);
1135
+        }
1136
+    }
1137
+
1138
+    /**
1139
+     * @param string $appId
1140
+     * @param string[] $steps
1141
+     */
1142
+    private static function setupLiveMigrations($appId, array $steps) {
1143
+        $queue = \OC::$server->getJobList();
1144
+        foreach ($steps as $step) {
1145
+            $queue->add('OC\Migration\BackgroundRepair', [
1146
+                'app' => $appId,
1147
+                'step' => $step]);
1148
+        }
1149
+    }
1150
+
1151
+    /**
1152
+     * @param string $appId
1153
+     * @return \OC\Files\View|false
1154
+     */
1155
+    public static function getStorage($appId) {
1156
+        if (OC_App::isEnabled($appId)) { //sanity check
1157
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1158
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1159
+                if (!$view->file_exists($appId)) {
1160
+                    $view->mkdir($appId);
1161
+                }
1162
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1163
+            } else {
1164
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1165
+                return false;
1166
+            }
1167
+        } else {
1168
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1169
+            return false;
1170
+        }
1171
+    }
1172
+
1173
+    protected static function findBestL10NOption($options, $lang) {
1174
+        $fallback = $similarLangFallback = $englishFallback = false;
1175
+
1176
+        $lang = strtolower($lang);
1177
+        $similarLang = $lang;
1178
+        if (strpos($similarLang, '_')) {
1179
+            // For "de_DE" we want to find "de" and the other way around
1180
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1181
+        }
1182
+
1183
+        foreach ($options as $option) {
1184
+            if (is_array($option)) {
1185
+                if ($fallback === false) {
1186
+                    $fallback = $option['@value'];
1187
+                }
1188
+
1189
+                if (!isset($option['@attributes']['lang'])) {
1190
+                    continue;
1191
+                }
1192
+
1193
+                $attributeLang = strtolower($option['@attributes']['lang']);
1194
+                if ($attributeLang === $lang) {
1195
+                    return $option['@value'];
1196
+                }
1197
+
1198
+                if ($attributeLang === $similarLang) {
1199
+                    $similarLangFallback = $option['@value'];
1200
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1201
+                    if ($similarLangFallback === false) {
1202
+                        $similarLangFallback =  $option['@value'];
1203
+                    }
1204
+                }
1205
+            } else {
1206
+                $englishFallback = $option;
1207
+            }
1208
+        }
1209
+
1210
+        if ($similarLangFallback !== false) {
1211
+            return $similarLangFallback;
1212
+        } else if ($englishFallback !== false) {
1213
+            return $englishFallback;
1214
+        }
1215
+        return (string) $fallback;
1216
+    }
1217
+
1218
+    /**
1219
+     * parses the app data array and enhanced the 'description' value
1220
+     *
1221
+     * @param array $data the app data
1222
+     * @param string $lang
1223
+     * @return array improved app data
1224
+     */
1225
+    public static function parseAppInfo(array $data, $lang = null) {
1226
+
1227
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1228
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1229
+        }
1230
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1231
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1232
+        }
1233
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1234
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1235
+        } else if (isset($data['description']) && is_string($data['description'])) {
1236
+            $data['description'] = trim($data['description']);
1237
+        } else  {
1238
+            $data['description'] = '';
1239
+        }
1240
+
1241
+        return $data;
1242
+    }
1243
+
1244
+    /**
1245
+     * @param \OCP\IConfig $config
1246
+     * @param \OCP\IL10N $l
1247
+     * @param array $info
1248
+     * @throws \Exception
1249
+     */
1250
+    public static function checkAppDependencies($config, $l, $info) {
1251
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1252
+        $missing = $dependencyAnalyzer->analyze($info);
1253
+        if (!empty($missing)) {
1254
+            $missingMsg = implode(PHP_EOL, $missing);
1255
+            throw new \Exception(
1256
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1257
+                    [$info['name'], $missingMsg]
1258
+                )
1259
+            );
1260
+        }
1261
+    }
1262 1262
 }
Please login to merge, or discard this patch.
core/Controller/AutoCompleteController.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -31,59 +31,59 @@
 block discarded – undo
31 31
 use OCP\Share;
32 32
 
33 33
 class AutoCompleteController extends Controller {
34
-	/** @var ISearch */
35
-	private $collaboratorSearch;
36
-	/** @var IManager */
37
-	private $autoCompleteManager;
34
+    /** @var ISearch */
35
+    private $collaboratorSearch;
36
+    /** @var IManager */
37
+    private $autoCompleteManager;
38 38
 
39
-	public function __construct($appName, IRequest $request, ISearch $collaboratorSearch, IManager $autoCompleteManager) {
40
-		parent::__construct($appName, $request);
39
+    public function __construct($appName, IRequest $request, ISearch $collaboratorSearch, IManager $autoCompleteManager) {
40
+        parent::__construct($appName, $request);
41 41
 
42
-		$this->collaboratorSearch = $collaboratorSearch;
43
-		$this->autoCompleteManager = $autoCompleteManager;
44
-	}
42
+        $this->collaboratorSearch = $collaboratorSearch;
43
+        $this->autoCompleteManager = $autoCompleteManager;
44
+    }
45 45
 
46
-	/**
47
-	 * @NoAdminRequired
48
-	 *
49
-	 * @param string $itemType
50
-	 * @param string $itemId
51
-	 * @param string|null $sorter can be piped, top prio first, e.g.: "commenters|share-recipients"
52
-	 * @param array $shareTypes
53
-	 * @return DataResponse
54
-	 */
55
-	public function get($itemType, $itemId, $sorter = null, $shareTypes = [Share::SHARE_TYPE_USER]) {
56
-		// if enumeration/user listings are disabled, we'll receive an empty
57
-		// result from search() – thus nothing else to do here.
58
-		list($results,) = $this->collaboratorSearch->search('', $shareTypes, false, 20, 0);
46
+    /**
47
+     * @NoAdminRequired
48
+     *
49
+     * @param string $itemType
50
+     * @param string $itemId
51
+     * @param string|null $sorter can be piped, top prio first, e.g.: "commenters|share-recipients"
52
+     * @param array $shareTypes
53
+     * @return DataResponse
54
+     */
55
+    public function get($itemType, $itemId, $sorter = null, $shareTypes = [Share::SHARE_TYPE_USER]) {
56
+        // if enumeration/user listings are disabled, we'll receive an empty
57
+        // result from search() – thus nothing else to do here.
58
+        list($results,) = $this->collaboratorSearch->search('', $shareTypes, false, 20, 0);
59 59
 
60
-		// there won't be exact matches without a search string
61
-		unset($results['exact']);
60
+        // there won't be exact matches without a search string
61
+        unset($results['exact']);
62 62
 
63
-		$sorters = array_reverse(explode('|', $sorter));
64
-		$this->autoCompleteManager->runSorters($sorters, $results, [
65
-			'itemType' => $itemType,
66
-			'itemId' => $itemId,
67
-		]);
63
+        $sorters = array_reverse(explode('|', $sorter));
64
+        $this->autoCompleteManager->runSorters($sorters, $results, [
65
+            'itemType' => $itemType,
66
+            'itemId' => $itemId,
67
+        ]);
68 68
 
69
-		// transform to expected format
70
-		$results = $this->prepareResultArray($results);
69
+        // transform to expected format
70
+        $results = $this->prepareResultArray($results);
71 71
 
72
-		return new DataResponse($results);
73
-	}
72
+        return new DataResponse($results);
73
+    }
74 74
 
75 75
 
76
-	protected function prepareResultArray(array $results) {
77
-		$output = [];
78
-		foreach ($results as $type => $subResult) {
79
-			foreach ($subResult as $result) {
80
-				$output[] = [
81
-					'id' => $result['value']['shareWith'],
82
-					'label' => $result['label'],
83
-					'source' => $type,
84
-				];
85
-			}
86
-		}
87
-		return $output;
88
-	}
76
+    protected function prepareResultArray(array $results) {
77
+        $output = [];
78
+        foreach ($results as $type => $subResult) {
79
+            foreach ($subResult as $result) {
80
+                $output[] = [
81
+                    'id' => $result['value']['shareWith'],
82
+                    'label' => $result['label'],
83
+                    'source' => $type,
84
+                ];
85
+            }
86
+        }
87
+        return $output;
88
+    }
89 89
 }
Please login to merge, or discard this patch.
lib/public/Collaboration/AutoComplete/ISorter.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -33,18 +33,18 @@
 block discarded – undo
33 33
  */
34 34
 interface ISorter {
35 35
 
36
-	/**
37
-	 * @return string The ID of the sorter, e.g. commenters
38
-	 * @since 13.0.0
39
-	 */
40
-	public function getId();
36
+    /**
37
+     * @return string The ID of the sorter, e.g. commenters
38
+     * @since 13.0.0
39
+     */
40
+    public function getId();
41 41
 
42
-	/**
43
-	 * executes the sort action
44
-	 *
45
-	 * @param array $sortArray the array to be sorted, provided as reference
46
-	 * @param array $context carries key 'itemType' and 'itemId' of the source object (e.g. a file)
47
-	 * @since 13.0.0
48
-	 */
49
-	public function sort(array &$sortArray, array $context);
42
+    /**
43
+     * executes the sort action
44
+     *
45
+     * @param array $sortArray the array to be sorted, provided as reference
46
+     * @param array $context carries key 'itemType' and 'itemId' of the source object (e.g. a file)
47
+     * @since 13.0.0
48
+     */
49
+    public function sort(array &$sortArray, array $context);
50 50
 }
Please login to merge, or discard this patch.