Completed
Pull Request — master (#8603)
by Björn
18:17 queued 02:41
created
apps/updatenotification/lib/Notification/Notifier.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -102,6 +102,9 @@
 block discarded – undo
102 102
 		return \OC_App::getAppVersions();
103 103
 	}
104 104
 
105
+	/**
106
+	 * @param string $appId
107
+	 */
105 108
 	protected function getAppInfo($appId) {
106 109
 		return \OC_App::getAppInfo($appId);
107 110
 	}
Please login to merge, or discard this patch.
Indentation   +137 added lines, -137 removed lines patch added patch discarded remove patch
@@ -38,141 +38,141 @@
 block discarded – undo
38 38
 
39 39
 class Notifier implements INotifier {
40 40
 
41
-	/** @var IURLGenerator */
42
-	protected $url;
43
-
44
-	/** @var IConfig */
45
-	protected $config;
46
-
47
-	/** @var IManager */
48
-	protected $notificationManager;
49
-
50
-	/** @var IFactory */
51
-	protected $l10NFactory;
52
-
53
-	/** @var IUserSession */
54
-	protected $userSession;
55
-
56
-	/** @var IGroupManager */
57
-	protected $groupManager;
58
-
59
-	/** @var string[] */
60
-	protected $appVersions;
61
-
62
-	/**
63
-	 * Notifier constructor.
64
-	 *
65
-	 * @param IURLGenerator $url
66
-	 * @param IConfig $config
67
-	 * @param IManager $notificationManager
68
-	 * @param IFactory $l10NFactory
69
-	 * @param IUserSession $userSession
70
-	 * @param IGroupManager $groupManager
71
-	 */
72
-	public function __construct(IURLGenerator $url, IConfig $config, IManager $notificationManager, IFactory $l10NFactory, IUserSession $userSession, IGroupManager $groupManager) {
73
-		$this->url = $url;
74
-		$this->notificationManager = $notificationManager;
75
-		$this->config = $config;
76
-		$this->l10NFactory = $l10NFactory;
77
-		$this->userSession = $userSession;
78
-		$this->groupManager = $groupManager;
79
-		$this->appVersions = $this->getAppVersions();
80
-	}
81
-
82
-	/**
83
-	 * @param INotification $notification
84
-	 * @param string $languageCode The code of the language that should be used to prepare the notification
85
-	 * @return INotification
86
-	 * @throws \InvalidArgumentException When the notification was not prepared by a notifier
87
-	 * @since 9.0.0
88
-	 */
89
-	public function prepare(INotification $notification, $languageCode): INotification {
90
-		if ($notification->getApp() !== 'updatenotification') {
91
-			throw new \InvalidArgumentException('Unknown app id');
92
-		}
93
-
94
-		$l = $this->l10NFactory->get('updatenotification', $languageCode);
95
-		if ($notification->getSubject() === 'connection_error') {
96
-			$errors = (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0);
97
-			if ($errors === 0) {
98
-				$this->notificationManager->markProcessed($notification);
99
-				throw new \InvalidArgumentException('Update checked worked again');
100
-			}
101
-
102
-			$notification->setParsedSubject($l->t('The update server could not be reached since %d days to check for new updates.', [$errors]))
103
-				->setParsedMessage($l->t('Please check the Nextcloud and server log files for errors.'));
104
-		} elseif ($notification->getObjectType() === 'core') {
105
-			$this->updateAlreadyInstalledCheck($notification, $this->getCoreVersions());
106
-
107
-			$parameters = $notification->getSubjectParameters();
108
-			$notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']]));
109
-
110
-			if ($this->isAdmin()) {
111
-				$notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater');
112
-			}
113
-		} else {
114
-			$appInfo = $this->getAppInfo($notification->getObjectType());
115
-			$appName = ($appInfo === null) ? $notification->getObjectType() : $appInfo['name'];
116
-
117
-			if (isset($this->appVersions[$notification->getObjectType()])) {
118
-				$this->updateAlreadyInstalledCheck($notification, $this->appVersions[$notification->getObjectType()]);
119
-			}
120
-
121
-			$notification->setParsedSubject($l->t('Update for %1$s to version %2$s is available.', [$appName, $notification->getObjectId()]))
122
-				->setRichSubject($l->t('Update for {app} to version %s is available.', [$notification->getObjectId()]), [
123
-					'app' => [
124
-						'type' => 'app',
125
-						'id' => $notification->getObjectType(),
126
-						'name' => $appName,
127
-					]
128
-				]);
129
-
130
-			if ($this->isAdmin()) {
131
-				$notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps', ['category' => 'updates']) . '#app-' . $notification->getObjectType());
132
-			}
133
-		}
134
-
135
-		$notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('updatenotification', 'notification.svg')));
136
-
137
-		return $notification;
138
-	}
139
-
140
-	/**
141
-	 * Remove the notification and prevent rendering, when the update is installed
142
-	 *
143
-	 * @param INotification $notification
144
-	 * @param string $installedVersion
145
-	 * @throws \InvalidArgumentException When the update is already installed
146
-	 */
147
-	protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) {
148
-		if (version_compare($notification->getObjectId(), $installedVersion, '<=')) {
149
-			$this->notificationManager->markProcessed($notification);
150
-			throw new \InvalidArgumentException('Update already installed');
151
-		}
152
-	}
153
-
154
-	/**
155
-	 * @return bool
156
-	 */
157
-	protected function isAdmin(): bool {
158
-		$user = $this->userSession->getUser();
159
-
160
-		if ($user instanceof IUser) {
161
-			return $this->groupManager->isAdmin($user->getUID());
162
-		}
163
-
164
-		return false;
165
-	}
166
-
167
-	protected function getCoreVersions(): string {
168
-		return implode('.', Util::getVersion());
169
-	}
170
-
171
-	protected function getAppVersions(): array {
172
-		return \OC_App::getAppVersions();
173
-	}
174
-
175
-	protected function getAppInfo($appId) {
176
-		return \OC_App::getAppInfo($appId);
177
-	}
41
+    /** @var IURLGenerator */
42
+    protected $url;
43
+
44
+    /** @var IConfig */
45
+    protected $config;
46
+
47
+    /** @var IManager */
48
+    protected $notificationManager;
49
+
50
+    /** @var IFactory */
51
+    protected $l10NFactory;
52
+
53
+    /** @var IUserSession */
54
+    protected $userSession;
55
+
56
+    /** @var IGroupManager */
57
+    protected $groupManager;
58
+
59
+    /** @var string[] */
60
+    protected $appVersions;
61
+
62
+    /**
63
+     * Notifier constructor.
64
+     *
65
+     * @param IURLGenerator $url
66
+     * @param IConfig $config
67
+     * @param IManager $notificationManager
68
+     * @param IFactory $l10NFactory
69
+     * @param IUserSession $userSession
70
+     * @param IGroupManager $groupManager
71
+     */
72
+    public function __construct(IURLGenerator $url, IConfig $config, IManager $notificationManager, IFactory $l10NFactory, IUserSession $userSession, IGroupManager $groupManager) {
73
+        $this->url = $url;
74
+        $this->notificationManager = $notificationManager;
75
+        $this->config = $config;
76
+        $this->l10NFactory = $l10NFactory;
77
+        $this->userSession = $userSession;
78
+        $this->groupManager = $groupManager;
79
+        $this->appVersions = $this->getAppVersions();
80
+    }
81
+
82
+    /**
83
+     * @param INotification $notification
84
+     * @param string $languageCode The code of the language that should be used to prepare the notification
85
+     * @return INotification
86
+     * @throws \InvalidArgumentException When the notification was not prepared by a notifier
87
+     * @since 9.0.0
88
+     */
89
+    public function prepare(INotification $notification, $languageCode): INotification {
90
+        if ($notification->getApp() !== 'updatenotification') {
91
+            throw new \InvalidArgumentException('Unknown app id');
92
+        }
93
+
94
+        $l = $this->l10NFactory->get('updatenotification', $languageCode);
95
+        if ($notification->getSubject() === 'connection_error') {
96
+            $errors = (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0);
97
+            if ($errors === 0) {
98
+                $this->notificationManager->markProcessed($notification);
99
+                throw new \InvalidArgumentException('Update checked worked again');
100
+            }
101
+
102
+            $notification->setParsedSubject($l->t('The update server could not be reached since %d days to check for new updates.', [$errors]))
103
+                ->setParsedMessage($l->t('Please check the Nextcloud and server log files for errors.'));
104
+        } elseif ($notification->getObjectType() === 'core') {
105
+            $this->updateAlreadyInstalledCheck($notification, $this->getCoreVersions());
106
+
107
+            $parameters = $notification->getSubjectParameters();
108
+            $notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']]));
109
+
110
+            if ($this->isAdmin()) {
111
+                $notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater');
112
+            }
113
+        } else {
114
+            $appInfo = $this->getAppInfo($notification->getObjectType());
115
+            $appName = ($appInfo === null) ? $notification->getObjectType() : $appInfo['name'];
116
+
117
+            if (isset($this->appVersions[$notification->getObjectType()])) {
118
+                $this->updateAlreadyInstalledCheck($notification, $this->appVersions[$notification->getObjectType()]);
119
+            }
120
+
121
+            $notification->setParsedSubject($l->t('Update for %1$s to version %2$s is available.', [$appName, $notification->getObjectId()]))
122
+                ->setRichSubject($l->t('Update for {app} to version %s is available.', [$notification->getObjectId()]), [
123
+                    'app' => [
124
+                        'type' => 'app',
125
+                        'id' => $notification->getObjectType(),
126
+                        'name' => $appName,
127
+                    ]
128
+                ]);
129
+
130
+            if ($this->isAdmin()) {
131
+                $notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps', ['category' => 'updates']) . '#app-' . $notification->getObjectType());
132
+            }
133
+        }
134
+
135
+        $notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('updatenotification', 'notification.svg')));
136
+
137
+        return $notification;
138
+    }
139
+
140
+    /**
141
+     * Remove the notification and prevent rendering, when the update is installed
142
+     *
143
+     * @param INotification $notification
144
+     * @param string $installedVersion
145
+     * @throws \InvalidArgumentException When the update is already installed
146
+     */
147
+    protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) {
148
+        if (version_compare($notification->getObjectId(), $installedVersion, '<=')) {
149
+            $this->notificationManager->markProcessed($notification);
150
+            throw new \InvalidArgumentException('Update already installed');
151
+        }
152
+    }
153
+
154
+    /**
155
+     * @return bool
156
+     */
157
+    protected function isAdmin(): bool {
158
+        $user = $this->userSession->getUser();
159
+
160
+        if ($user instanceof IUser) {
161
+            return $this->groupManager->isAdmin($user->getUID());
162
+        }
163
+
164
+        return false;
165
+    }
166
+
167
+    protected function getCoreVersions(): string {
168
+        return implode('.', Util::getVersion());
169
+    }
170
+
171
+    protected function getAppVersions(): array {
172
+        return \OC_App::getAppVersions();
173
+    }
174
+
175
+    protected function getAppInfo($appId) {
176
+        return \OC_App::getAppInfo($appId);
177
+    }
178 178
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-declare(strict_types=1);
2
+declare(strict_types = 1);
3 3
 /**
4 4
  * @copyright Copyright (c) 2016, ownCloud, Inc.
5 5
  *
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 			$notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']]));
109 109
 
110 110
 			if ($this->isAdmin()) {
111
-				$notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater');
111
+				$notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index').'#updater');
112 112
 			}
113 113
 		} else {
114 114
 			$appInfo = $this->getAppInfo($notification->getObjectType());
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 				]);
129 129
 
130 130
 			if ($this->isAdmin()) {
131
-				$notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps', ['category' => 'updates']) . '#app-' . $notification->getObjectType());
131
+				$notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps', ['category' => 'updates']).'#app-'.$notification->getObjectType());
132 132
 			}
133 133
 		}
134 134
 
Please login to merge, or discard this patch.
apps/user_ldap/lib/Command/SetConfig.php 3 patches
Doc Comments   -2 removed lines patch added patch discarded remove patch
@@ -74,8 +74,6 @@
 block discarded – undo
74 74
 	/**
75 75
 	 * save the configuration value as provided
76 76
 	 * @param string $configID
77
-	 * @param string $configKey
78
-	 * @param string $configValue
79 77
 	 */
80 78
 	protected function setValue($configID, $key, $value) {
81 79
 		$configHolder = new Configuration($configID);
Please login to merge, or discard this patch.
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -34,53 +34,53 @@
 block discarded – undo
34 34
 
35 35
 class SetConfig extends Command {
36 36
 
37
-	protected function configure() {
38
-		$this
39
-			->setName('ldap:set-config')
40
-			->setDescription('modifies an LDAP configuration')
41
-			->addArgument(
42
-					'configID',
43
-					InputArgument::REQUIRED,
44
-					'the configuration ID'
45
-				     )
46
-			->addArgument(
47
-					'configKey',
48
-					InputArgument::REQUIRED,
49
-					'the configuration key'
50
-				     )
51
-			->addArgument(
52
-					'configValue',
53
-					InputArgument::REQUIRED,
54
-					'the new configuration value'
55
-				     )
56
-		;
57
-	}
37
+    protected function configure() {
38
+        $this
39
+            ->setName('ldap:set-config')
40
+            ->setDescription('modifies an LDAP configuration')
41
+            ->addArgument(
42
+                    'configID',
43
+                    InputArgument::REQUIRED,
44
+                    'the configuration ID'
45
+                        )
46
+            ->addArgument(
47
+                    'configKey',
48
+                    InputArgument::REQUIRED,
49
+                    'the configuration key'
50
+                        )
51
+            ->addArgument(
52
+                    'configValue',
53
+                    InputArgument::REQUIRED,
54
+                    'the new configuration value'
55
+                        )
56
+        ;
57
+    }
58 58
 
59
-	protected function execute(InputInterface $input, OutputInterface $output) {
60
-		$helper = new Helper(\OC::$server->getConfig());
61
-		$availableConfigs = $helper->getServerConfigurationPrefixes();
62
-		$configID = $input->getArgument('configID');
63
-		if(!in_array($configID, $availableConfigs)) {
64
-			$output->writeln("Invalid configID");
65
-			return;
66
-		}
59
+    protected function execute(InputInterface $input, OutputInterface $output) {
60
+        $helper = new Helper(\OC::$server->getConfig());
61
+        $availableConfigs = $helper->getServerConfigurationPrefixes();
62
+        $configID = $input->getArgument('configID');
63
+        if(!in_array($configID, $availableConfigs)) {
64
+            $output->writeln("Invalid configID");
65
+            return;
66
+        }
67 67
 
68
-		$this->setValue(
69
-			$configID,
70
-			$input->getArgument('configKey'),
71
-			$input->getArgument('configValue')
72
-		);
73
-	}
68
+        $this->setValue(
69
+            $configID,
70
+            $input->getArgument('configKey'),
71
+            $input->getArgument('configValue')
72
+        );
73
+    }
74 74
 
75
-	/**
76
-	 * save the configuration value as provided
77
-	 * @param string $configID
78
-	 * @param string $configKey
79
-	 * @param string $configValue
80
-	 */
81
-	protected function setValue($configID, $key, $value) {
82
-		$configHolder = new Configuration($configID);
83
-		$configHolder->$key = $value;
84
-		$configHolder->saveConfiguration();
85
-	}
75
+    /**
76
+     * save the configuration value as provided
77
+     * @param string $configID
78
+     * @param string $configKey
79
+     * @param string $configValue
80
+     */
81
+    protected function setValue($configID, $key, $value) {
82
+        $configHolder = new Configuration($configID);
83
+        $configHolder->$key = $value;
84
+        $configHolder->saveConfiguration();
85
+    }
86 86
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@
 block discarded – undo
60 60
 		$helper = new Helper(\OC::$server->getConfig());
61 61
 		$availableConfigs = $helper->getServerConfigurationPrefixes();
62 62
 		$configID = $input->getArgument('configID');
63
-		if(!in_array($configID, $availableConfigs)) {
63
+		if (!in_array($configID, $availableConfigs)) {
64 64
 			$output->writeln("Invalid configID");
65 65
 			return;
66 66
 		}
Please login to merge, or discard this patch.
apps/user_ldap/lib/Jobs/UpdateGroups.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@
 block discarded – undo
77 77
 	}
78 78
 
79 79
 	/**
80
-	 * @return int
80
+	 * @return string
81 81
 	 */
82 82
 	static private function getRefreshInterval() {
83 83
 		//defaults to every hour
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -45,14 +45,14 @@  discard block
 block discarded – undo
45 45
 
46 46
 	static private $groupBE;
47 47
 
48
-	public function __construct(){
48
+	public function __construct() {
49 49
 		$this->interval = self::getRefreshInterval();
50 50
 	}
51 51
 
52 52
 	/**
53 53
 	 * @param mixed $argument
54 54
 	 */
55
-	public function run($argument){
55
+	public function run($argument) {
56 56
 		self::updateGroups();
57 57
 	}
58 58
 
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
 		$knownGroups = array_keys(self::getKnownGroups());
63 63
 		$actualGroups = self::getGroupBE()->getGroups();
64 64
 
65
-		if(empty($actualGroups) && empty($knownGroups)) {
65
+		if (empty($actualGroups) && empty($knownGroups)) {
66 66
 			\OCP\Util::writeLog('user_ldap',
67 67
 				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
68 68
 				\OCP\Util::INFO);
@@ -94,26 +94,26 @@  discard block
 block discarded – undo
94 94
 			SET `owncloudusers` = ?
95 95
 			WHERE `owncloudname` = ?
96 96
 		');
97
-		foreach($groups as $group) {
97
+		foreach ($groups as $group) {
98 98
 			//we assume, that self::$groupsFromDB has been retrieved already
99 99
 			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
100 100
 			$actualUsers = self::getGroupBE()->usersInGroup($group);
101 101
 			$hasChanged = false;
102
-			foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
102
+			foreach (array_diff($knownUsers, $actualUsers) as $removedUser) {
103 103
 				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
104 104
 				\OCP\Util::writeLog('user_ldap',
105 105
 				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
106 106
 				\OCP\Util::INFO);
107 107
 				$hasChanged = true;
108 108
 			}
109
-			foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
109
+			foreach (array_diff($actualUsers, $knownUsers) as $addedUser) {
110 110
 				\OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
111 111
 				\OCP\Util::writeLog('user_ldap',
112 112
 				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
113 113
 				\OCP\Util::INFO);
114 114
 				$hasChanged = true;
115 115
 			}
116
-			if($hasChanged) {
116
+			if ($hasChanged) {
117 117
 				$query->execute(array(serialize($actualUsers), $group));
118 118
 			}
119 119
 		}
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
133 133
 			VALUES (?, ?)
134 134
 		');
135
-		foreach($createdGroups as $createdGroup) {
135
+		foreach ($createdGroups as $createdGroup) {
136 136
 			\OCP\Util::writeLog('user_ldap',
137 137
 				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
138 138
 				\OCP\Util::INFO);
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 			FROM `*PREFIX*ldap_group_members`
155 155
 			WHERE `owncloudname` = ?
156 156
 		');
157
-		foreach($removedGroups as $removedGroup) {
157
+		foreach ($removedGroups as $removedGroup) {
158 158
 			\OCP\Util::writeLog('user_ldap',
159 159
 				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
160 160
 				\OCP\Util::INFO);
@@ -169,13 +169,13 @@  discard block
 block discarded – undo
169 169
 	 * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
170 170
 	 */
171 171
 	static private function getGroupBE() {
172
-		if(!is_null(self::$groupBE)) {
172
+		if (!is_null(self::$groupBE)) {
173 173
 			return self::$groupBE;
174 174
 		}
175 175
 		$helper = new Helper(\OC::$server->getConfig());
176 176
 		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
177 177
 		$ldapWrapper = new LDAP();
178
-		if(count($configPrefixes) === 1) {
178
+		if (count($configPrefixes) === 1) {
179 179
 			//avoid the proxy when there is only one LDAP server configured
180 180
 			$dbc = \OC::$server->getDatabaseConnection();
181 181
 			$userManager = new Manager(
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
 	 * @return array
205 205
 	 */
206 206
 	static private function getKnownGroups() {
207
-		if(is_array(self::$groupsFromDB)) {
207
+		if (is_array(self::$groupsFromDB)) {
208 208
 			return self::$groupsFromDB;
209 209
 		}
210 210
 		$query = \OCP\DB::prepare('
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 		');
214 214
 		$result = $query->execute()->fetchAll();
215 215
 		self::$groupsFromDB = array();
216
-		foreach($result as $dataset) {
216
+		foreach ($result as $dataset) {
217 217
 			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
218 218
 		}
219 219
 
Please login to merge, or discard this patch.
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -45,183 +45,183 @@
 block discarded – undo
45 45
 use OCA\User_LDAP\User\Manager;
46 46
 
47 47
 class UpdateGroups extends \OC\BackgroundJob\TimedJob {
48
-	static private $groupsFromDB;
49
-
50
-	static private $groupBE;
51
-
52
-	public function __construct(){
53
-		$this->interval = self::getRefreshInterval();
54
-	}
55
-
56
-	/**
57
-	 * @param mixed $argument
58
-	 */
59
-	public function run($argument){
60
-		self::updateGroups();
61
-	}
62
-
63
-	static public function updateGroups() {
64
-		\OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG);
65
-
66
-		$knownGroups = array_keys(self::getKnownGroups());
67
-		$actualGroups = self::getGroupBE()->getGroups();
68
-
69
-		if(empty($actualGroups) && empty($knownGroups)) {
70
-			\OCP\Util::writeLog('user_ldap',
71
-				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
72
-				\OCP\Util::INFO);
73
-			return;
74
-		}
75
-
76
-		self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
77
-		self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
78
-		self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
79
-
80
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG);
81
-	}
82
-
83
-	/**
84
-	 * @return int
85
-	 */
86
-	static private function getRefreshInterval() {
87
-		//defaults to every hour
88
-		return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
89
-	}
90
-
91
-	/**
92
-	 * @param string[] $groups
93
-	 */
94
-	static private function handleKnownGroups($groups) {
95
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG);
96
-		$query = \OCP\DB::prepare('
48
+    static private $groupsFromDB;
49
+
50
+    static private $groupBE;
51
+
52
+    public function __construct(){
53
+        $this->interval = self::getRefreshInterval();
54
+    }
55
+
56
+    /**
57
+     * @param mixed $argument
58
+     */
59
+    public function run($argument){
60
+        self::updateGroups();
61
+    }
62
+
63
+    static public function updateGroups() {
64
+        \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG);
65
+
66
+        $knownGroups = array_keys(self::getKnownGroups());
67
+        $actualGroups = self::getGroupBE()->getGroups();
68
+
69
+        if(empty($actualGroups) && empty($knownGroups)) {
70
+            \OCP\Util::writeLog('user_ldap',
71
+                'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
72
+                \OCP\Util::INFO);
73
+            return;
74
+        }
75
+
76
+        self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
77
+        self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
78
+        self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
79
+
80
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG);
81
+    }
82
+
83
+    /**
84
+     * @return int
85
+     */
86
+    static private function getRefreshInterval() {
87
+        //defaults to every hour
88
+        return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
89
+    }
90
+
91
+    /**
92
+     * @param string[] $groups
93
+     */
94
+    static private function handleKnownGroups($groups) {
95
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG);
96
+        $query = \OCP\DB::prepare('
97 97
 			UPDATE `*PREFIX*ldap_group_members`
98 98
 			SET `owncloudusers` = ?
99 99
 			WHERE `owncloudname` = ?
100 100
 		');
101
-		foreach($groups as $group) {
102
-			//we assume, that self::$groupsFromDB has been retrieved already
103
-			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
104
-			$actualUsers = self::getGroupBE()->usersInGroup($group);
105
-			$hasChanged = false;
106
-			foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
107
-				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
108
-				\OCP\Util::writeLog('user_ldap',
109
-				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
110
-				\OCP\Util::INFO);
111
-				$hasChanged = true;
112
-			}
113
-			foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
114
-				\OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
115
-				\OCP\Util::writeLog('user_ldap',
116
-				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
117
-				\OCP\Util::INFO);
118
-				$hasChanged = true;
119
-			}
120
-			if($hasChanged) {
121
-				$query->execute(array(serialize($actualUsers), $group));
122
-			}
123
-		}
124
-		\OCP\Util::writeLog('user_ldap',
125
-			'bgJ "updateGroups" – FINISHED dealing with known Groups.',
126
-			\OCP\Util::DEBUG);
127
-	}
128
-
129
-	/**
130
-	 * @param string[] $createdGroups
131
-	 */
132
-	static private function handleCreatedGroups($createdGroups) {
133
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG);
134
-		$query = \OCP\DB::prepare('
101
+        foreach($groups as $group) {
102
+            //we assume, that self::$groupsFromDB has been retrieved already
103
+            $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
104
+            $actualUsers = self::getGroupBE()->usersInGroup($group);
105
+            $hasChanged = false;
106
+            foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
107
+                \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
108
+                \OCP\Util::writeLog('user_ldap',
109
+                'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
110
+                \OCP\Util::INFO);
111
+                $hasChanged = true;
112
+            }
113
+            foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
114
+                \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
115
+                \OCP\Util::writeLog('user_ldap',
116
+                'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
117
+                \OCP\Util::INFO);
118
+                $hasChanged = true;
119
+            }
120
+            if($hasChanged) {
121
+                $query->execute(array(serialize($actualUsers), $group));
122
+            }
123
+        }
124
+        \OCP\Util::writeLog('user_ldap',
125
+            'bgJ "updateGroups" – FINISHED dealing with known Groups.',
126
+            \OCP\Util::DEBUG);
127
+    }
128
+
129
+    /**
130
+     * @param string[] $createdGroups
131
+     */
132
+    static private function handleCreatedGroups($createdGroups) {
133
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG);
134
+        $query = \OCP\DB::prepare('
135 135
 			INSERT
136 136
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
137 137
 			VALUES (?, ?)
138 138
 		');
139
-		foreach($createdGroups as $createdGroup) {
140
-			\OCP\Util::writeLog('user_ldap',
141
-				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
142
-				\OCP\Util::INFO);
143
-			$users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
144
-			$query->execute(array($createdGroup, $users));
145
-		}
146
-		\OCP\Util::writeLog('user_ldap',
147
-			'bgJ "updateGroups" – FINISHED dealing with created Groups.',
148
-			\OCP\Util::DEBUG);
149
-	}
150
-
151
-	/**
152
-	 * @param string[] $removedGroups
153
-	 */
154
-	static private function handleRemovedGroups($removedGroups) {
155
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG);
156
-		$query = \OCP\DB::prepare('
139
+        foreach($createdGroups as $createdGroup) {
140
+            \OCP\Util::writeLog('user_ldap',
141
+                'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
142
+                \OCP\Util::INFO);
143
+            $users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
144
+            $query->execute(array($createdGroup, $users));
145
+        }
146
+        \OCP\Util::writeLog('user_ldap',
147
+            'bgJ "updateGroups" – FINISHED dealing with created Groups.',
148
+            \OCP\Util::DEBUG);
149
+    }
150
+
151
+    /**
152
+     * @param string[] $removedGroups
153
+     */
154
+    static private function handleRemovedGroups($removedGroups) {
155
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG);
156
+        $query = \OCP\DB::prepare('
157 157
 			DELETE
158 158
 			FROM `*PREFIX*ldap_group_members`
159 159
 			WHERE `owncloudname` = ?
160 160
 		');
161
-		foreach($removedGroups as $removedGroup) {
162
-			\OCP\Util::writeLog('user_ldap',
163
-				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
164
-				\OCP\Util::INFO);
165
-			$query->execute(array($removedGroup));
166
-		}
167
-		\OCP\Util::writeLog('user_ldap',
168
-			'bgJ "updateGroups" – FINISHED dealing with removed groups.',
169
-			\OCP\Util::DEBUG);
170
-	}
171
-
172
-	/**
173
-	 * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
174
-	 */
175
-	static private function getGroupBE() {
176
-		if(!is_null(self::$groupBE)) {
177
-			return self::$groupBE;
178
-		}
179
-		$helper = new Helper(\OC::$server->getConfig());
180
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
181
-		$ldapWrapper = new LDAP();
182
-		if(count($configPrefixes) === 1) {
183
-			//avoid the proxy when there is only one LDAP server configured
184
-			$dbc = \OC::$server->getDatabaseConnection();
185
-			$userManager = new Manager(
186
-				\OC::$server->getConfig(),
187
-				new FilesystemHelper(),
188
-				new LogWrapper(),
189
-				\OC::$server->getAvatarManager(),
190
-				new \OCP\Image(),
191
-				$dbc,
192
-				\OC::$server->getUserManager(),
193
-				\OC::$server->getNotificationManager());
194
-			$connector = new Connection($ldapWrapper, $configPrefixes[0]);
195
-			$ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig());
196
-			$groupMapper = new GroupMapping($dbc);
197
-			$userMapper  = new UserMapping($dbc);
198
-			$ldapAccess->setGroupMapper($groupMapper);
199
-			$ldapAccess->setUserMapper($userMapper);
200
-			self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager'));
201
-		} else {
202
-			self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager'));
203
-		}
204
-
205
-		return self::$groupBE;
206
-	}
207
-
208
-	/**
209
-	 * @return array
210
-	 */
211
-	static private function getKnownGroups() {
212
-		if(is_array(self::$groupsFromDB)) {
213
-			return self::$groupsFromDB;
214
-		}
215
-		$query = \OCP\DB::prepare('
161
+        foreach($removedGroups as $removedGroup) {
162
+            \OCP\Util::writeLog('user_ldap',
163
+                'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
164
+                \OCP\Util::INFO);
165
+            $query->execute(array($removedGroup));
166
+        }
167
+        \OCP\Util::writeLog('user_ldap',
168
+            'bgJ "updateGroups" – FINISHED dealing with removed groups.',
169
+            \OCP\Util::DEBUG);
170
+    }
171
+
172
+    /**
173
+     * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
174
+     */
175
+    static private function getGroupBE() {
176
+        if(!is_null(self::$groupBE)) {
177
+            return self::$groupBE;
178
+        }
179
+        $helper = new Helper(\OC::$server->getConfig());
180
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
181
+        $ldapWrapper = new LDAP();
182
+        if(count($configPrefixes) === 1) {
183
+            //avoid the proxy when there is only one LDAP server configured
184
+            $dbc = \OC::$server->getDatabaseConnection();
185
+            $userManager = new Manager(
186
+                \OC::$server->getConfig(),
187
+                new FilesystemHelper(),
188
+                new LogWrapper(),
189
+                \OC::$server->getAvatarManager(),
190
+                new \OCP\Image(),
191
+                $dbc,
192
+                \OC::$server->getUserManager(),
193
+                \OC::$server->getNotificationManager());
194
+            $connector = new Connection($ldapWrapper, $configPrefixes[0]);
195
+            $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig());
196
+            $groupMapper = new GroupMapping($dbc);
197
+            $userMapper  = new UserMapping($dbc);
198
+            $ldapAccess->setGroupMapper($groupMapper);
199
+            $ldapAccess->setUserMapper($userMapper);
200
+            self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager'));
201
+        } else {
202
+            self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager'));
203
+        }
204
+
205
+        return self::$groupBE;
206
+    }
207
+
208
+    /**
209
+     * @return array
210
+     */
211
+    static private function getKnownGroups() {
212
+        if(is_array(self::$groupsFromDB)) {
213
+            return self::$groupsFromDB;
214
+        }
215
+        $query = \OCP\DB::prepare('
216 216
 			SELECT `owncloudname`, `owncloudusers`
217 217
 			FROM `*PREFIX*ldap_group_members`
218 218
 		');
219
-		$result = $query->execute()->fetchAll();
220
-		self::$groupsFromDB = array();
221
-		foreach($result as $dataset) {
222
-			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
223
-		}
224
-
225
-		return self::$groupsFromDB;
226
-	}
219
+        $result = $query->execute()->fetchAll();
220
+        self::$groupsFromDB = array();
221
+        foreach($result as $dataset) {
222
+            self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
223
+        }
224
+
225
+        return self::$groupsFromDB;
226
+    }
227 227
 }
Please login to merge, or discard this patch.
lib/private/AllConfig.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -112,7 +112,7 @@
 block discarded – undo
112 112
 	 * Looks up a system wide defined value
113 113
 	 *
114 114
 	 * @param string $key the key of the value, under which it was saved
115
-	 * @param mixed $default the default value to be returned if the value isn't set
115
+	 * @param string $default the default value to be returned if the value isn't set
116 116
 	 * @return mixed the value or $default
117 117
 	 */
118 118
 	public function getSystemValue($key, $default = '') {
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	 * because the database connection was created with an uninitialized config
88 88
 	 */
89 89
 	private function fixDIInit() {
90
-		if($this->connection === null) {
90
+		if ($this->connection === null) {
91 91
 			$this->connection = \OC::$server->getDatabaseConnection();
92 92
 		}
93 93
 	}
@@ -218,9 +218,9 @@  discard block
 block discarded – undo
218 218
 		$prevValue = $this->getUserValue($userId, $appName, $key, null);
219 219
 
220 220
 		if ($prevValue !== null) {
221
-			if ($prevValue === (string)$value) {
221
+			if ($prevValue === (string) $value) {
222 222
 				return;
223
-			} else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
223
+			} else if ($preCondition !== null && $prevValue !== (string) $preCondition) {
224 224
 				throw new PreConditionNotMetException();
225 225
 			} else {
226 226
 				$qb = $this->connection->getQueryBuilder();
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
 		// TODO - FIXME
306 306
 		$this->fixDIInit();
307 307
 
308
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
308
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
309 309
 				'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
310 310
 		$this->connection->executeUpdate($sql, array($userId, $appName, $key));
311 311
 
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
 		// TODO - FIXME
324 324
 		$this->fixDIInit();
325 325
 
326
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
326
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
327 327
 			'WHERE `userid` = ?';
328 328
 		$this->connection->executeUpdate($sql, array($userId));
329 329
 
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 		// TODO - FIXME
340 340
 		$this->fixDIInit();
341 341
 
342
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
342
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
343 343
 				'WHERE `appid` = ?';
344 344
 		$this->connection->executeUpdate($sql, array($appName));
345 345
 
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
 			return $this->userCache[$userId];
363 363
 		}
364 364
 		if ($userId === null || $userId === '') {
365
-			$this->userCache[$userId]=array();
365
+			$this->userCache[$userId] = array();
366 366
 			return $this->userCache[$userId];
367 367
 		}
368 368
 
@@ -409,12 +409,12 @@  discard block
 block discarded – undo
409 409
 			array_unshift($queryParams, $key);
410 410
 			array_unshift($queryParams, $appName);
411 411
 
412
-			$placeholders = (count($chunk) === 50) ? $placeholders50 :  implode(',', array_fill(0, count($chunk), '?'));
412
+			$placeholders = (count($chunk) === 50) ? $placeholders50 : implode(',', array_fill(0, count($chunk), '?'));
413 413
 
414
-			$query    = 'SELECT `userid`, `configvalue` ' .
415
-						'FROM `*PREFIX*preferences` ' .
416
-						'WHERE `appid` = ? AND `configkey` = ? ' .
417
-						'AND `userid` IN (' . $placeholders . ')';
414
+			$query = 'SELECT `userid`, `configvalue` '.
415
+						'FROM `*PREFIX*preferences` '.
416
+						'WHERE `appid` = ? AND `configkey` = ? '.
417
+						'AND `userid` IN ('.$placeholders.')';
418 418
 			$result = $this->connection->executeQuery($query, $queryParams);
419 419
 
420 420
 			while ($row = $result->fetch()) {
@@ -437,10 +437,10 @@  discard block
 block discarded – undo
437 437
 		// TODO - FIXME
438 438
 		$this->fixDIInit();
439 439
 
440
-		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
440
+		$sql = 'SELECT `userid` FROM `*PREFIX*preferences` '.
441 441
 				'WHERE `appid` = ? AND `configkey` = ? ';
442 442
 
443
-		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
443
+		if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
444 444
 			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
445 445
 			$sql .= 'AND to_char(`configvalue`) = ?';
446 446
 		} else {
Please login to merge, or discard this patch.
Indentation   +423 added lines, -423 removed lines patch added patch discarded remove patch
@@ -39,427 +39,427 @@
 block discarded – undo
39 39
  * Class to combine all the configuration options ownCloud offers
40 40
  */
41 41
 class AllConfig implements \OCP\IConfig {
42
-	/** @var SystemConfig */
43
-	private $systemConfig;
44
-
45
-	/** @var IDBConnection */
46
-	private $connection;
47
-
48
-	/**
49
-	 * 3 dimensional array with the following structure:
50
-	 * [ $userId =>
51
-	 *     [ $appId =>
52
-	 *         [ $key => $value ]
53
-	 *     ]
54
-	 * ]
55
-	 *
56
-	 * database table: preferences
57
-	 *
58
-	 * methods that use this:
59
-	 *   - setUserValue
60
-	 *   - getUserValue
61
-	 *   - getUserKeys
62
-	 *   - deleteUserValue
63
-	 *   - deleteAllUserValues
64
-	 *   - deleteAppFromAllUsers
65
-	 *
66
-	 * @var CappedMemoryCache $userCache
67
-	 */
68
-	private $userCache;
69
-
70
-	/**
71
-	 * @param SystemConfig $systemConfig
72
-	 */
73
-	public function __construct(SystemConfig $systemConfig) {
74
-		$this->userCache = new CappedMemoryCache();
75
-		$this->systemConfig = $systemConfig;
76
-	}
77
-
78
-	/**
79
-	 * TODO - FIXME This fixes an issue with base.php that cause cyclic
80
-	 * dependencies, especially with autoconfig setup
81
-	 *
82
-	 * Replace this by properly injected database connection. Currently the
83
-	 * base.php triggers the getDatabaseConnection too early which causes in
84
-	 * autoconfig setup case a too early distributed database connection and
85
-	 * the autoconfig then needs to reinit all already initialized dependencies
86
-	 * that use the database connection.
87
-	 *
88
-	 * otherwise a SQLite database is created in the wrong directory
89
-	 * because the database connection was created with an uninitialized config
90
-	 */
91
-	private function fixDIInit() {
92
-		if($this->connection === null) {
93
-			$this->connection = \OC::$server->getDatabaseConnection();
94
-		}
95
-	}
96
-
97
-	/**
98
-	 * Sets and deletes system wide values
99
-	 *
100
-	 * @param array $configs Associative array with `key => value` pairs
101
-	 *                       If value is null, the config key will be deleted
102
-	 */
103
-	public function setSystemValues(array $configs) {
104
-		$this->systemConfig->setValues($configs);
105
-	}
106
-
107
-	/**
108
-	 * Sets a new system wide value
109
-	 *
110
-	 * @param string $key the key of the value, under which will be saved
111
-	 * @param mixed $value the value that should be stored
112
-	 */
113
-	public function setSystemValue($key, $value) {
114
-		$this->systemConfig->setValue($key, $value);
115
-	}
116
-
117
-	/**
118
-	 * Looks up a system wide defined value
119
-	 *
120
-	 * @param string $key the key of the value, under which it was saved
121
-	 * @param mixed $default the default value to be returned if the value isn't set
122
-	 * @return mixed the value or $default
123
-	 */
124
-	public function getSystemValue($key, $default = '') {
125
-		return $this->systemConfig->getValue($key, $default);
126
-	}
127
-
128
-	/**
129
-	 * Looks up a system wide defined value and filters out sensitive data
130
-	 *
131
-	 * @param string $key the key of the value, under which it was saved
132
-	 * @param mixed $default the default value to be returned if the value isn't set
133
-	 * @return mixed the value or $default
134
-	 */
135
-	public function getFilteredSystemValue($key, $default = '') {
136
-		return $this->systemConfig->getFilteredValue($key, $default);
137
-	}
138
-
139
-	/**
140
-	 * Delete a system wide defined value
141
-	 *
142
-	 * @param string $key the key of the value, under which it was saved
143
-	 */
144
-	public function deleteSystemValue($key) {
145
-		$this->systemConfig->deleteValue($key);
146
-	}
147
-
148
-	/**
149
-	 * Get all keys stored for an app
150
-	 *
151
-	 * @param string $appName the appName that we stored the value under
152
-	 * @return string[] the keys stored for the app
153
-	 */
154
-	public function getAppKeys($appName) {
155
-		return \OC::$server->query(\OC\AppConfig::class)->getKeys($appName);
156
-	}
157
-
158
-	/**
159
-	 * Writes a new app wide value
160
-	 *
161
-	 * @param string $appName the appName that we want to store the value under
162
-	 * @param string $key the key of the value, under which will be saved
163
-	 * @param string|float|int $value the value that should be stored
164
-	 */
165
-	public function setAppValue($appName, $key, $value) {
166
-		\OC::$server->query(\OC\AppConfig::class)->setValue($appName, $key, $value);
167
-	}
168
-
169
-	/**
170
-	 * Looks up an app wide defined value
171
-	 *
172
-	 * @param string $appName the appName that we stored the value under
173
-	 * @param string $key the key of the value, under which it was saved
174
-	 * @param string $default the default value to be returned if the value isn't set
175
-	 * @return string the saved value
176
-	 */
177
-	public function getAppValue($appName, $key, $default = '') {
178
-		return \OC::$server->query(\OC\AppConfig::class)->getValue($appName, $key, $default);
179
-	}
180
-
181
-	/**
182
-	 * Delete an app wide defined value
183
-	 *
184
-	 * @param string $appName the appName that we stored the value under
185
-	 * @param string $key the key of the value, under which it was saved
186
-	 */
187
-	public function deleteAppValue($appName, $key) {
188
-		\OC::$server->query(\OC\AppConfig::class)->deleteKey($appName, $key);
189
-	}
190
-
191
-	/**
192
-	 * Removes all keys in appconfig belonging to the app
193
-	 *
194
-	 * @param string $appName the appName the configs are stored under
195
-	 */
196
-	public function deleteAppValues($appName) {
197
-		\OC::$server->query(\OC\AppConfig::class)->deleteApp($appName);
198
-	}
199
-
200
-
201
-	/**
202
-	 * Set a user defined value
203
-	 *
204
-	 * @param string $userId the userId of the user that we want to store the value under
205
-	 * @param string $appName the appName that we want to store the value under
206
-	 * @param string $key the key under which the value is being stored
207
-	 * @param string|float|int $value the value that you want to store
208
-	 * @param string $preCondition only update if the config value was previously the value passed as $preCondition
209
-	 * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
210
-	 * @throws \UnexpectedValueException when trying to store an unexpected value
211
-	 */
212
-	public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
213
-		if (!is_int($value) && !is_float($value) && !is_string($value)) {
214
-			throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value');
215
-		}
216
-
217
-		// TODO - FIXME
218
-		$this->fixDIInit();
219
-
220
-		$prevValue = $this->getUserValue($userId, $appName, $key, null);
221
-
222
-		if ($prevValue !== null) {
223
-			if ($prevValue === (string)$value) {
224
-				return;
225
-			} else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
226
-				throw new PreConditionNotMetException();
227
-			} else {
228
-				$qb = $this->connection->getQueryBuilder();
229
-				$qb->update('preferences')
230
-					->set('configvalue', $qb->createNamedParameter($value))
231
-					->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId)))
232
-					->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName)))
233
-					->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
234
-				$qb->execute();
235
-
236
-				$this->userCache[$userId][$appName][$key] = $value;
237
-				return;
238
-			}
239
-		}
240
-
241
-		$preconditionArray = [];
242
-		if (isset($preCondition)) {
243
-			$preconditionArray = [
244
-				'configvalue' => $preCondition,
245
-			];
246
-		}
247
-
248
-		$this->connection->setValues('preferences', [
249
-			'userid' => $userId,
250
-			'appid' => $appName,
251
-			'configkey' => $key,
252
-		], [
253
-			'configvalue' => $value,
254
-		], $preconditionArray);
255
-
256
-		// only add to the cache if we already loaded data for the user
257
-		if (isset($this->userCache[$userId])) {
258
-			if (!isset($this->userCache[$userId][$appName])) {
259
-				$this->userCache[$userId][$appName] = array();
260
-			}
261
-			$this->userCache[$userId][$appName][$key] = $value;
262
-		}
263
-	}
264
-
265
-	/**
266
-	 * Getting a user defined value
267
-	 *
268
-	 * @param string $userId the userId of the user that we want to store the value under
269
-	 * @param string $appName the appName that we stored the value under
270
-	 * @param string $key the key under which the value is being stored
271
-	 * @param mixed $default the default value to be returned if the value isn't set
272
-	 * @return string
273
-	 */
274
-	public function getUserValue($userId, $appName, $key, $default = '') {
275
-		$data = $this->getUserValues($userId);
276
-		if (isset($data[$appName]) and isset($data[$appName][$key])) {
277
-			return $data[$appName][$key];
278
-		} else {
279
-			return $default;
280
-		}
281
-	}
282
-
283
-	/**
284
-	 * Get the keys of all stored by an app for the user
285
-	 *
286
-	 * @param string $userId the userId of the user that we want to store the value under
287
-	 * @param string $appName the appName that we stored the value under
288
-	 * @return string[]
289
-	 */
290
-	public function getUserKeys($userId, $appName) {
291
-		$data = $this->getUserValues($userId);
292
-		if (isset($data[$appName])) {
293
-			return array_keys($data[$appName]);
294
-		} else {
295
-			return array();
296
-		}
297
-	}
298
-
299
-	/**
300
-	 * Delete a user value
301
-	 *
302
-	 * @param string $userId the userId of the user that we want to store the value under
303
-	 * @param string $appName the appName that we stored the value under
304
-	 * @param string $key the key under which the value is being stored
305
-	 */
306
-	public function deleteUserValue($userId, $appName, $key) {
307
-		// TODO - FIXME
308
-		$this->fixDIInit();
309
-
310
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
311
-				'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
312
-		$this->connection->executeUpdate($sql, array($userId, $appName, $key));
313
-
314
-		if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) {
315
-			unset($this->userCache[$userId][$appName][$key]);
316
-		}
317
-	}
318
-
319
-	/**
320
-	 * Delete all user values
321
-	 *
322
-	 * @param string $userId the userId of the user that we want to remove all values from
323
-	 */
324
-	public function deleteAllUserValues($userId) {
325
-		// TODO - FIXME
326
-		$this->fixDIInit();
327
-
328
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
329
-			'WHERE `userid` = ?';
330
-		$this->connection->executeUpdate($sql, array($userId));
331
-
332
-		unset($this->userCache[$userId]);
333
-	}
334
-
335
-	/**
336
-	 * Delete all user related values of one app
337
-	 *
338
-	 * @param string $appName the appName of the app that we want to remove all values from
339
-	 */
340
-	public function deleteAppFromAllUsers($appName) {
341
-		// TODO - FIXME
342
-		$this->fixDIInit();
343
-
344
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
345
-				'WHERE `appid` = ?';
346
-		$this->connection->executeUpdate($sql, array($appName));
347
-
348
-		foreach ($this->userCache as &$userCache) {
349
-			unset($userCache[$appName]);
350
-		}
351
-	}
352
-
353
-	/**
354
-	 * Returns all user configs sorted by app of one user
355
-	 *
356
-	 * @param string $userId the user ID to get the app configs from
357
-	 * @return array[] - 2 dimensional array with the following structure:
358
-	 *     [ $appId =>
359
-	 *         [ $key => $value ]
360
-	 *     ]
361
-	 */
362
-	private function getUserValues($userId) {
363
-		if (isset($this->userCache[$userId])) {
364
-			return $this->userCache[$userId];
365
-		}
366
-		if ($userId === null || $userId === '') {
367
-			$this->userCache[$userId]=array();
368
-			return $this->userCache[$userId];
369
-		}
370
-
371
-		// TODO - FIXME
372
-		$this->fixDIInit();
373
-
374
-		$data = array();
375
-		$query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
376
-		$result = $this->connection->executeQuery($query, array($userId));
377
-		while ($row = $result->fetch()) {
378
-			$appId = $row['appid'];
379
-			if (!isset($data[$appId])) {
380
-				$data[$appId] = array();
381
-			}
382
-			$data[$appId][$row['configkey']] = $row['configvalue'];
383
-		}
384
-		$this->userCache[$userId] = $data;
385
-		return $data;
386
-	}
387
-
388
-	/**
389
-	 * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
390
-	 *
391
-	 * @param string $appName app to get the value for
392
-	 * @param string $key the key to get the value for
393
-	 * @param array $userIds the user IDs to fetch the values for
394
-	 * @return array Mapped values: userId => value
395
-	 */
396
-	public function getUserValueForUsers($appName, $key, $userIds) {
397
-		// TODO - FIXME
398
-		$this->fixDIInit();
399
-
400
-		if (empty($userIds) || !is_array($userIds)) {
401
-			return array();
402
-		}
403
-
404
-		$chunkedUsers = array_chunk($userIds, 50, true);
405
-		$placeholders50 = implode(',', array_fill(0, 50, '?'));
406
-
407
-		$userValues = array();
408
-		foreach ($chunkedUsers as $chunk) {
409
-			$queryParams = $chunk;
410
-			// create [$app, $key, $chunkedUsers]
411
-			array_unshift($queryParams, $key);
412
-			array_unshift($queryParams, $appName);
413
-
414
-			$placeholders = (count($chunk) === 50) ? $placeholders50 :  implode(',', array_fill(0, count($chunk), '?'));
415
-
416
-			$query    = 'SELECT `userid`, `configvalue` ' .
417
-						'FROM `*PREFIX*preferences` ' .
418
-						'WHERE `appid` = ? AND `configkey` = ? ' .
419
-						'AND `userid` IN (' . $placeholders . ')';
420
-			$result = $this->connection->executeQuery($query, $queryParams);
421
-
422
-			while ($row = $result->fetch()) {
423
-				$userValues[$row['userid']] = $row['configvalue'];
424
-			}
425
-		}
426
-
427
-		return $userValues;
428
-	}
429
-
430
-	/**
431
-	 * Determines the users that have the given value set for a specific app-key-pair
432
-	 *
433
-	 * @param string $appName the app to get the user for
434
-	 * @param string $key the key to get the user for
435
-	 * @param string $value the value to get the user for
436
-	 * @return array of user IDs
437
-	 */
438
-	public function getUsersForUserValue($appName, $key, $value) {
439
-		// TODO - FIXME
440
-		$this->fixDIInit();
441
-
442
-		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
443
-				'WHERE `appid` = ? AND `configkey` = ? ';
444
-
445
-		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
446
-			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
447
-			$sql .= 'AND to_char(`configvalue`) = ?';
448
-		} else {
449
-			$sql .= 'AND `configvalue` = ?';
450
-		}
451
-
452
-		$result = $this->connection->executeQuery($sql, array($appName, $key, $value));
453
-
454
-		$userIDs = array();
455
-		while ($row = $result->fetch()) {
456
-			$userIDs[] = $row['userid'];
457
-		}
458
-
459
-		return $userIDs;
460
-	}
461
-
462
-	public function getSystemConfig() {
463
-		return $this->systemConfig;
464
-	}
42
+    /** @var SystemConfig */
43
+    private $systemConfig;
44
+
45
+    /** @var IDBConnection */
46
+    private $connection;
47
+
48
+    /**
49
+     * 3 dimensional array with the following structure:
50
+     * [ $userId =>
51
+     *     [ $appId =>
52
+     *         [ $key => $value ]
53
+     *     ]
54
+     * ]
55
+     *
56
+     * database table: preferences
57
+     *
58
+     * methods that use this:
59
+     *   - setUserValue
60
+     *   - getUserValue
61
+     *   - getUserKeys
62
+     *   - deleteUserValue
63
+     *   - deleteAllUserValues
64
+     *   - deleteAppFromAllUsers
65
+     *
66
+     * @var CappedMemoryCache $userCache
67
+     */
68
+    private $userCache;
69
+
70
+    /**
71
+     * @param SystemConfig $systemConfig
72
+     */
73
+    public function __construct(SystemConfig $systemConfig) {
74
+        $this->userCache = new CappedMemoryCache();
75
+        $this->systemConfig = $systemConfig;
76
+    }
77
+
78
+    /**
79
+     * TODO - FIXME This fixes an issue with base.php that cause cyclic
80
+     * dependencies, especially with autoconfig setup
81
+     *
82
+     * Replace this by properly injected database connection. Currently the
83
+     * base.php triggers the getDatabaseConnection too early which causes in
84
+     * autoconfig setup case a too early distributed database connection and
85
+     * the autoconfig then needs to reinit all already initialized dependencies
86
+     * that use the database connection.
87
+     *
88
+     * otherwise a SQLite database is created in the wrong directory
89
+     * because the database connection was created with an uninitialized config
90
+     */
91
+    private function fixDIInit() {
92
+        if($this->connection === null) {
93
+            $this->connection = \OC::$server->getDatabaseConnection();
94
+        }
95
+    }
96
+
97
+    /**
98
+     * Sets and deletes system wide values
99
+     *
100
+     * @param array $configs Associative array with `key => value` pairs
101
+     *                       If value is null, the config key will be deleted
102
+     */
103
+    public function setSystemValues(array $configs) {
104
+        $this->systemConfig->setValues($configs);
105
+    }
106
+
107
+    /**
108
+     * Sets a new system wide value
109
+     *
110
+     * @param string $key the key of the value, under which will be saved
111
+     * @param mixed $value the value that should be stored
112
+     */
113
+    public function setSystemValue($key, $value) {
114
+        $this->systemConfig->setValue($key, $value);
115
+    }
116
+
117
+    /**
118
+     * Looks up a system wide defined value
119
+     *
120
+     * @param string $key the key of the value, under which it was saved
121
+     * @param mixed $default the default value to be returned if the value isn't set
122
+     * @return mixed the value or $default
123
+     */
124
+    public function getSystemValue($key, $default = '') {
125
+        return $this->systemConfig->getValue($key, $default);
126
+    }
127
+
128
+    /**
129
+     * Looks up a system wide defined value and filters out sensitive data
130
+     *
131
+     * @param string $key the key of the value, under which it was saved
132
+     * @param mixed $default the default value to be returned if the value isn't set
133
+     * @return mixed the value or $default
134
+     */
135
+    public function getFilteredSystemValue($key, $default = '') {
136
+        return $this->systemConfig->getFilteredValue($key, $default);
137
+    }
138
+
139
+    /**
140
+     * Delete a system wide defined value
141
+     *
142
+     * @param string $key the key of the value, under which it was saved
143
+     */
144
+    public function deleteSystemValue($key) {
145
+        $this->systemConfig->deleteValue($key);
146
+    }
147
+
148
+    /**
149
+     * Get all keys stored for an app
150
+     *
151
+     * @param string $appName the appName that we stored the value under
152
+     * @return string[] the keys stored for the app
153
+     */
154
+    public function getAppKeys($appName) {
155
+        return \OC::$server->query(\OC\AppConfig::class)->getKeys($appName);
156
+    }
157
+
158
+    /**
159
+     * Writes a new app wide value
160
+     *
161
+     * @param string $appName the appName that we want to store the value under
162
+     * @param string $key the key of the value, under which will be saved
163
+     * @param string|float|int $value the value that should be stored
164
+     */
165
+    public function setAppValue($appName, $key, $value) {
166
+        \OC::$server->query(\OC\AppConfig::class)->setValue($appName, $key, $value);
167
+    }
168
+
169
+    /**
170
+     * Looks up an app wide defined value
171
+     *
172
+     * @param string $appName the appName that we stored the value under
173
+     * @param string $key the key of the value, under which it was saved
174
+     * @param string $default the default value to be returned if the value isn't set
175
+     * @return string the saved value
176
+     */
177
+    public function getAppValue($appName, $key, $default = '') {
178
+        return \OC::$server->query(\OC\AppConfig::class)->getValue($appName, $key, $default);
179
+    }
180
+
181
+    /**
182
+     * Delete an app wide defined value
183
+     *
184
+     * @param string $appName the appName that we stored the value under
185
+     * @param string $key the key of the value, under which it was saved
186
+     */
187
+    public function deleteAppValue($appName, $key) {
188
+        \OC::$server->query(\OC\AppConfig::class)->deleteKey($appName, $key);
189
+    }
190
+
191
+    /**
192
+     * Removes all keys in appconfig belonging to the app
193
+     *
194
+     * @param string $appName the appName the configs are stored under
195
+     */
196
+    public function deleteAppValues($appName) {
197
+        \OC::$server->query(\OC\AppConfig::class)->deleteApp($appName);
198
+    }
199
+
200
+
201
+    /**
202
+     * Set a user defined value
203
+     *
204
+     * @param string $userId the userId of the user that we want to store the value under
205
+     * @param string $appName the appName that we want to store the value under
206
+     * @param string $key the key under which the value is being stored
207
+     * @param string|float|int $value the value that you want to store
208
+     * @param string $preCondition only update if the config value was previously the value passed as $preCondition
209
+     * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
210
+     * @throws \UnexpectedValueException when trying to store an unexpected value
211
+     */
212
+    public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
213
+        if (!is_int($value) && !is_float($value) && !is_string($value)) {
214
+            throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value');
215
+        }
216
+
217
+        // TODO - FIXME
218
+        $this->fixDIInit();
219
+
220
+        $prevValue = $this->getUserValue($userId, $appName, $key, null);
221
+
222
+        if ($prevValue !== null) {
223
+            if ($prevValue === (string)$value) {
224
+                return;
225
+            } else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
226
+                throw new PreConditionNotMetException();
227
+            } else {
228
+                $qb = $this->connection->getQueryBuilder();
229
+                $qb->update('preferences')
230
+                    ->set('configvalue', $qb->createNamedParameter($value))
231
+                    ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId)))
232
+                    ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName)))
233
+                    ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
234
+                $qb->execute();
235
+
236
+                $this->userCache[$userId][$appName][$key] = $value;
237
+                return;
238
+            }
239
+        }
240
+
241
+        $preconditionArray = [];
242
+        if (isset($preCondition)) {
243
+            $preconditionArray = [
244
+                'configvalue' => $preCondition,
245
+            ];
246
+        }
247
+
248
+        $this->connection->setValues('preferences', [
249
+            'userid' => $userId,
250
+            'appid' => $appName,
251
+            'configkey' => $key,
252
+        ], [
253
+            'configvalue' => $value,
254
+        ], $preconditionArray);
255
+
256
+        // only add to the cache if we already loaded data for the user
257
+        if (isset($this->userCache[$userId])) {
258
+            if (!isset($this->userCache[$userId][$appName])) {
259
+                $this->userCache[$userId][$appName] = array();
260
+            }
261
+            $this->userCache[$userId][$appName][$key] = $value;
262
+        }
263
+    }
264
+
265
+    /**
266
+     * Getting a user defined value
267
+     *
268
+     * @param string $userId the userId of the user that we want to store the value under
269
+     * @param string $appName the appName that we stored the value under
270
+     * @param string $key the key under which the value is being stored
271
+     * @param mixed $default the default value to be returned if the value isn't set
272
+     * @return string
273
+     */
274
+    public function getUserValue($userId, $appName, $key, $default = '') {
275
+        $data = $this->getUserValues($userId);
276
+        if (isset($data[$appName]) and isset($data[$appName][$key])) {
277
+            return $data[$appName][$key];
278
+        } else {
279
+            return $default;
280
+        }
281
+    }
282
+
283
+    /**
284
+     * Get the keys of all stored by an app for the user
285
+     *
286
+     * @param string $userId the userId of the user that we want to store the value under
287
+     * @param string $appName the appName that we stored the value under
288
+     * @return string[]
289
+     */
290
+    public function getUserKeys($userId, $appName) {
291
+        $data = $this->getUserValues($userId);
292
+        if (isset($data[$appName])) {
293
+            return array_keys($data[$appName]);
294
+        } else {
295
+            return array();
296
+        }
297
+    }
298
+
299
+    /**
300
+     * Delete a user value
301
+     *
302
+     * @param string $userId the userId of the user that we want to store the value under
303
+     * @param string $appName the appName that we stored the value under
304
+     * @param string $key the key under which the value is being stored
305
+     */
306
+    public function deleteUserValue($userId, $appName, $key) {
307
+        // TODO - FIXME
308
+        $this->fixDIInit();
309
+
310
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
311
+                'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
312
+        $this->connection->executeUpdate($sql, array($userId, $appName, $key));
313
+
314
+        if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) {
315
+            unset($this->userCache[$userId][$appName][$key]);
316
+        }
317
+    }
318
+
319
+    /**
320
+     * Delete all user values
321
+     *
322
+     * @param string $userId the userId of the user that we want to remove all values from
323
+     */
324
+    public function deleteAllUserValues($userId) {
325
+        // TODO - FIXME
326
+        $this->fixDIInit();
327
+
328
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
329
+            'WHERE `userid` = ?';
330
+        $this->connection->executeUpdate($sql, array($userId));
331
+
332
+        unset($this->userCache[$userId]);
333
+    }
334
+
335
+    /**
336
+     * Delete all user related values of one app
337
+     *
338
+     * @param string $appName the appName of the app that we want to remove all values from
339
+     */
340
+    public function deleteAppFromAllUsers($appName) {
341
+        // TODO - FIXME
342
+        $this->fixDIInit();
343
+
344
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
345
+                'WHERE `appid` = ?';
346
+        $this->connection->executeUpdate($sql, array($appName));
347
+
348
+        foreach ($this->userCache as &$userCache) {
349
+            unset($userCache[$appName]);
350
+        }
351
+    }
352
+
353
+    /**
354
+     * Returns all user configs sorted by app of one user
355
+     *
356
+     * @param string $userId the user ID to get the app configs from
357
+     * @return array[] - 2 dimensional array with the following structure:
358
+     *     [ $appId =>
359
+     *         [ $key => $value ]
360
+     *     ]
361
+     */
362
+    private function getUserValues($userId) {
363
+        if (isset($this->userCache[$userId])) {
364
+            return $this->userCache[$userId];
365
+        }
366
+        if ($userId === null || $userId === '') {
367
+            $this->userCache[$userId]=array();
368
+            return $this->userCache[$userId];
369
+        }
370
+
371
+        // TODO - FIXME
372
+        $this->fixDIInit();
373
+
374
+        $data = array();
375
+        $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
376
+        $result = $this->connection->executeQuery($query, array($userId));
377
+        while ($row = $result->fetch()) {
378
+            $appId = $row['appid'];
379
+            if (!isset($data[$appId])) {
380
+                $data[$appId] = array();
381
+            }
382
+            $data[$appId][$row['configkey']] = $row['configvalue'];
383
+        }
384
+        $this->userCache[$userId] = $data;
385
+        return $data;
386
+    }
387
+
388
+    /**
389
+     * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
390
+     *
391
+     * @param string $appName app to get the value for
392
+     * @param string $key the key to get the value for
393
+     * @param array $userIds the user IDs to fetch the values for
394
+     * @return array Mapped values: userId => value
395
+     */
396
+    public function getUserValueForUsers($appName, $key, $userIds) {
397
+        // TODO - FIXME
398
+        $this->fixDIInit();
399
+
400
+        if (empty($userIds) || !is_array($userIds)) {
401
+            return array();
402
+        }
403
+
404
+        $chunkedUsers = array_chunk($userIds, 50, true);
405
+        $placeholders50 = implode(',', array_fill(0, 50, '?'));
406
+
407
+        $userValues = array();
408
+        foreach ($chunkedUsers as $chunk) {
409
+            $queryParams = $chunk;
410
+            // create [$app, $key, $chunkedUsers]
411
+            array_unshift($queryParams, $key);
412
+            array_unshift($queryParams, $appName);
413
+
414
+            $placeholders = (count($chunk) === 50) ? $placeholders50 :  implode(',', array_fill(0, count($chunk), '?'));
415
+
416
+            $query    = 'SELECT `userid`, `configvalue` ' .
417
+                        'FROM `*PREFIX*preferences` ' .
418
+                        'WHERE `appid` = ? AND `configkey` = ? ' .
419
+                        'AND `userid` IN (' . $placeholders . ')';
420
+            $result = $this->connection->executeQuery($query, $queryParams);
421
+
422
+            while ($row = $result->fetch()) {
423
+                $userValues[$row['userid']] = $row['configvalue'];
424
+            }
425
+        }
426
+
427
+        return $userValues;
428
+    }
429
+
430
+    /**
431
+     * Determines the users that have the given value set for a specific app-key-pair
432
+     *
433
+     * @param string $appName the app to get the user for
434
+     * @param string $key the key to get the user for
435
+     * @param string $value the value to get the user for
436
+     * @return array of user IDs
437
+     */
438
+    public function getUsersForUserValue($appName, $key, $value) {
439
+        // TODO - FIXME
440
+        $this->fixDIInit();
441
+
442
+        $sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
443
+                'WHERE `appid` = ? AND `configkey` = ? ';
444
+
445
+        if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
446
+            //oracle hack: need to explicitly cast CLOB to CHAR for comparison
447
+            $sql .= 'AND to_char(`configvalue`) = ?';
448
+        } else {
449
+            $sql .= 'AND `configvalue` = ?';
450
+        }
451
+
452
+        $result = $this->connection->executeQuery($sql, array($appName, $key, $value));
453
+
454
+        $userIDs = array();
455
+        while ($row = $result->fetch()) {
456
+            $userIDs[] = $row['userid'];
457
+        }
458
+
459
+        return $userIDs;
460
+    }
461
+
462
+    public function getSystemConfig() {
463
+        return $this->systemConfig;
464
+    }
465 465
 }
Please login to merge, or discard this patch.
lib/private/App/CodeChecker/NodeVisitor.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -296,6 +296,9 @@
 block discarded – undo
296 296
 		}
297 297
 	}
298 298
 
299
+	/**
300
+	 * @param string $name
301
+	 */
299 302
 	private function buildReason($name, $errorCode) {
300 303
 		if (isset($this->errorMessages[$errorCode])) {
301 304
 			$desc = $this->list->getDescription($errorCode, $name);
Please login to merge, or discard this patch.
Indentation   +276 added lines, -276 removed lines patch added patch discarded remove patch
@@ -29,280 +29,280 @@
 block discarded – undo
29 29
 use PhpParser\NodeVisitorAbstract;
30 30
 
31 31
 class NodeVisitor extends NodeVisitorAbstract {
32
-	/** @var ICheck */
33
-	protected $list;
34
-
35
-	/** @var string */
36
-	protected $blackListDescription;
37
-	/** @var string[] */
38
-	protected $blackListedClassNames;
39
-	/** @var string[] */
40
-	protected $blackListedConstants;
41
-	/** @var string[] */
42
-	protected $blackListedFunctions;
43
-	/** @var string[] */
44
-	protected $blackListedMethods;
45
-	/** @var bool */
46
-	protected $checkEqualOperatorUsage;
47
-	/** @var string[] */
48
-	protected $errorMessages;
49
-
50
-	/**
51
-	 * @param ICheck $list
52
-	 */
53
-	public function __construct(ICheck $list) {
54
-		$this->list = $list;
55
-
56
-		$this->blackListedClassNames = [];
57
-		foreach ($list->getClasses() as $class => $blackListInfo) {
58
-			if (is_numeric($class) && is_string($blackListInfo)) {
59
-				$class = $blackListInfo;
60
-				$blackListInfo = null;
61
-			}
62
-
63
-			$class = strtolower($class);
64
-			$this->blackListedClassNames[$class] = $class;
65
-		}
66
-
67
-		$this->blackListedConstants = [];
68
-		foreach ($list->getConstants() as $constantName => $blackListInfo) {
69
-			$constantName = strtolower($constantName);
70
-			$this->blackListedConstants[$constantName] = $constantName;
71
-		}
72
-
73
-		$this->blackListedFunctions = [];
74
-		foreach ($list->getFunctions() as $functionName => $blackListInfo) {
75
-			$functionName = strtolower($functionName);
76
-			$this->blackListedFunctions[$functionName] = $functionName;
77
-		}
78
-
79
-		$this->blackListedMethods = [];
80
-		foreach ($list->getMethods() as $functionName => $blackListInfo) {
81
-			$functionName = strtolower($functionName);
82
-			$this->blackListedMethods[$functionName] = $functionName;
83
-		}
84
-
85
-		$this->checkEqualOperatorUsage = $list->checkStrongComparisons();
86
-
87
-		$this->errorMessages = [
88
-			CodeChecker::CLASS_EXTENDS_NOT_ALLOWED => "%s class must not be extended",
89
-			CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED => "%s interface must not be implemented",
90
-			CodeChecker::STATIC_CALL_NOT_ALLOWED => "Static method of %s class must not be called",
91
-			CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED => "Constant of %s class must not not be fetched",
92
-			CodeChecker::CLASS_NEW_NOT_ALLOWED => "%s class must not be instantiated",
93
-			CodeChecker::CLASS_USE_NOT_ALLOWED => "%s class must not be imported with a use statement",
94
-			CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED => "Method of %s class must not be called",
95
-
96
-			CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED => "is discouraged",
97
-		];
98
-	}
99
-
100
-	/** @var array */
101
-	public $errors = [];
102
-
103
-	public function enterNode(Node $node) {
104
-		if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\Equal) {
105
-			$this->errors[]= [
106
-				'disallowedToken' => '==',
107
-				'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED,
108
-				'line' => $node->getLine(),
109
-				'reason' => $this->buildReason('==', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED)
110
-			];
111
-		}
112
-		if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\NotEqual) {
113
-			$this->errors[]= [
114
-				'disallowedToken' => '!=',
115
-				'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED,
116
-				'line' => $node->getLine(),
117
-				'reason' => $this->buildReason('!=', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED)
118
-			];
119
-		}
120
-		if ($node instanceof Node\Stmt\Class_) {
121
-			if (!is_null($node->extends)) {
122
-				$this->checkBlackList($node->extends->toString(), CodeChecker::CLASS_EXTENDS_NOT_ALLOWED, $node);
123
-			}
124
-			foreach ($node->implements as $implements) {
125
-				$this->checkBlackList($implements->toString(), CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED, $node);
126
-			}
127
-		}
128
-		if ($node instanceof Node\Expr\StaticCall) {
129
-			if (!is_null($node->class)) {
130
-				if ($node->class instanceof Name) {
131
-					$this->checkBlackList($node->class->toString(), CodeChecker::STATIC_CALL_NOT_ALLOWED, $node);
132
-
133
-					$this->checkBlackListFunction($node->class->toString(), $node->name, $node);
134
-					$this->checkBlackListMethod($node->class->toString(), $node->name, $node);
135
-				}
136
-
137
-				if ($node->class instanceof Node\Expr\Variable) {
138
-					/**
139
-					 * TODO: find a way to detect something like this:
140
-					 *       $c = "OC_API";
141
-					 *       $n = $c::call();
142
-					 */
143
-					// $this->checkBlackListMethod($node->class->..., $node->name, $node);
144
-				}
145
-			}
146
-		}
147
-		if ($node instanceof Node\Expr\MethodCall) {
148
-			if (!is_null($node->var)) {
149
-				if ($node->var instanceof Node\Expr\Variable) {
150
-					/**
151
-					 * TODO: find a way to detect something like this:
152
-					 *       $c = new OC_API();
153
-					 *       $n = $c::call();
154
-					 *       $n = $c->call();
155
-					 */
156
-					// $this->checkBlackListMethod($node->var->..., $node->name, $node);
157
-				}
158
-			}
159
-		}
160
-		if ($node instanceof Node\Expr\ClassConstFetch) {
161
-			if (!is_null($node->class)) {
162
-				if ($node->class instanceof Name) {
163
-					$this->checkBlackList($node->class->toString(), CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, $node);
164
-				}
165
-				if ($node->class instanceof Node\Expr\Variable) {
166
-					/**
167
-					 * TODO: find a way to detect something like this:
168
-					 *       $c = "OC_API";
169
-					 *       $n = $i::ADMIN_AUTH;
170
-					 */
171
-				} else {
172
-					$this->checkBlackListConstant($node->class->toString(), $node->name, $node);
173
-				}
174
-			}
175
-		}
176
-		if ($node instanceof Node\Expr\New_) {
177
-			if (!is_null($node->class)) {
178
-				if ($node->class instanceof Name) {
179
-					$this->checkBlackList($node->class->toString(), CodeChecker::CLASS_NEW_NOT_ALLOWED, $node);
180
-				}
181
-				if ($node->class instanceof Node\Expr\Variable) {
182
-					/**
183
-					 * TODO: find a way to detect something like this:
184
-					 *       $c = "OC_API";
185
-					 *       $n = new $i;
186
-					 */
187
-				}
188
-			}
189
-		}
190
-		if ($node instanceof Node\Stmt\UseUse) {
191
-			$this->checkBlackList($node->name->toString(), CodeChecker::CLASS_USE_NOT_ALLOWED, $node);
192
-			if ($node->alias) {
193
-				$this->addUseNameToBlackList($node->name->toString(), $node->alias);
194
-			} else {
195
-				$this->addUseNameToBlackList($node->name->toString(), $node->name->getLast());
196
-			}
197
-		}
198
-	}
199
-
200
-	/**
201
-	 * Check whether an alias was introduced for a namespace of a blacklisted class
202
-	 *
203
-	 * Example:
204
-	 * - Blacklist entry:      OCP\AppFramework\IApi
205
-	 * - Name:                 OCP\AppFramework
206
-	 * - Alias:                OAF
207
-	 * =>  new blacklist entry:  OAF\IApi
208
-	 *
209
-	 * @param string $name
210
-	 * @param string $alias
211
-	 */
212
-	private function addUseNameToBlackList($name, $alias) {
213
-		$name = strtolower($name);
214
-		$alias = strtolower($alias);
215
-
216
-		foreach ($this->blackListedClassNames as $blackListedAlias => $blackListedClassName) {
217
-			if (strpos($blackListedClassName, $name . '\\') === 0) {
218
-				$aliasedClassName = str_replace($name, $alias, $blackListedClassName);
219
-				$this->blackListedClassNames[$aliasedClassName] = $blackListedClassName;
220
-			}
221
-		}
222
-
223
-		foreach ($this->blackListedConstants as $blackListedAlias => $blackListedConstant) {
224
-			if (strpos($blackListedConstant, $name . '\\') === 0 || strpos($blackListedConstant, $name . '::') === 0) {
225
-				$aliasedConstantName = str_replace($name, $alias, $blackListedConstant);
226
-				$this->blackListedConstants[$aliasedConstantName] = $blackListedConstant;
227
-			}
228
-		}
229
-
230
-		foreach ($this->blackListedFunctions as $blackListedAlias => $blackListedFunction) {
231
-			if (strpos($blackListedFunction, $name . '\\') === 0 || strpos($blackListedFunction, $name . '::') === 0) {
232
-				$aliasedFunctionName = str_replace($name, $alias, $blackListedFunction);
233
-				$this->blackListedFunctions[$aliasedFunctionName] = $blackListedFunction;
234
-			}
235
-		}
236
-
237
-		foreach ($this->blackListedMethods as $blackListedAlias => $blackListedMethod) {
238
-			if (strpos($blackListedMethod, $name . '\\') === 0 || strpos($blackListedMethod, $name . '::') === 0) {
239
-				$aliasedMethodName = str_replace($name, $alias, $blackListedMethod);
240
-				$this->blackListedMethods[$aliasedMethodName] = $blackListedMethod;
241
-			}
242
-		}
243
-	}
244
-
245
-	private function checkBlackList($name, $errorCode, Node $node) {
246
-		$lowerName = strtolower($name);
247
-
248
-		if (isset($this->blackListedClassNames[$lowerName])) {
249
-			$this->errors[]= [
250
-				'disallowedToken' => $name,
251
-				'errorCode' => $errorCode,
252
-				'line' => $node->getLine(),
253
-				'reason' => $this->buildReason($this->blackListedClassNames[$lowerName], $errorCode)
254
-			];
255
-		}
256
-	}
257
-
258
-	private function checkBlackListConstant($class, $constantName, Node $node) {
259
-		$name = $class . '::' . $constantName;
260
-		$lowerName = strtolower($name);
261
-
262
-		if (isset($this->blackListedConstants[$lowerName])) {
263
-			$this->errors[]= [
264
-				'disallowedToken' => $name,
265
-				'errorCode' => CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED,
266
-				'line' => $node->getLine(),
267
-				'reason' => $this->buildReason($this->blackListedConstants[$lowerName], CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED)
268
-			];
269
-		}
270
-	}
271
-
272
-	private function checkBlackListFunction($class, $functionName, Node $node) {
273
-		$name = $class . '::' . $functionName;
274
-		$lowerName = strtolower($name);
275
-
276
-		if (isset($this->blackListedFunctions[$lowerName])) {
277
-			$this->errors[]= [
278
-				'disallowedToken' => $name,
279
-				'errorCode' => CodeChecker::STATIC_CALL_NOT_ALLOWED,
280
-				'line' => $node->getLine(),
281
-				'reason' => $this->buildReason($this->blackListedFunctions[$lowerName], CodeChecker::STATIC_CALL_NOT_ALLOWED)
282
-			];
283
-		}
284
-	}
285
-
286
-	private function checkBlackListMethod($class, $functionName, Node $node) {
287
-		$name = $class . '::' . $functionName;
288
-		$lowerName = strtolower($name);
289
-
290
-		if (isset($this->blackListedMethods[$lowerName])) {
291
-			$this->errors[]= [
292
-				'disallowedToken' => $name,
293
-				'errorCode' => CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED,
294
-				'line' => $node->getLine(),
295
-				'reason' => $this->buildReason($this->blackListedMethods[$lowerName], CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED)
296
-			];
297
-		}
298
-	}
299
-
300
-	private function buildReason($name, $errorCode) {
301
-		if (isset($this->errorMessages[$errorCode])) {
302
-			$desc = $this->list->getDescription($errorCode, $name);
303
-			return sprintf($this->errorMessages[$errorCode], $desc);
304
-		}
305
-
306
-		return "$name usage not allowed - error: $errorCode";
307
-	}
32
+    /** @var ICheck */
33
+    protected $list;
34
+
35
+    /** @var string */
36
+    protected $blackListDescription;
37
+    /** @var string[] */
38
+    protected $blackListedClassNames;
39
+    /** @var string[] */
40
+    protected $blackListedConstants;
41
+    /** @var string[] */
42
+    protected $blackListedFunctions;
43
+    /** @var string[] */
44
+    protected $blackListedMethods;
45
+    /** @var bool */
46
+    protected $checkEqualOperatorUsage;
47
+    /** @var string[] */
48
+    protected $errorMessages;
49
+
50
+    /**
51
+     * @param ICheck $list
52
+     */
53
+    public function __construct(ICheck $list) {
54
+        $this->list = $list;
55
+
56
+        $this->blackListedClassNames = [];
57
+        foreach ($list->getClasses() as $class => $blackListInfo) {
58
+            if (is_numeric($class) && is_string($blackListInfo)) {
59
+                $class = $blackListInfo;
60
+                $blackListInfo = null;
61
+            }
62
+
63
+            $class = strtolower($class);
64
+            $this->blackListedClassNames[$class] = $class;
65
+        }
66
+
67
+        $this->blackListedConstants = [];
68
+        foreach ($list->getConstants() as $constantName => $blackListInfo) {
69
+            $constantName = strtolower($constantName);
70
+            $this->blackListedConstants[$constantName] = $constantName;
71
+        }
72
+
73
+        $this->blackListedFunctions = [];
74
+        foreach ($list->getFunctions() as $functionName => $blackListInfo) {
75
+            $functionName = strtolower($functionName);
76
+            $this->blackListedFunctions[$functionName] = $functionName;
77
+        }
78
+
79
+        $this->blackListedMethods = [];
80
+        foreach ($list->getMethods() as $functionName => $blackListInfo) {
81
+            $functionName = strtolower($functionName);
82
+            $this->blackListedMethods[$functionName] = $functionName;
83
+        }
84
+
85
+        $this->checkEqualOperatorUsage = $list->checkStrongComparisons();
86
+
87
+        $this->errorMessages = [
88
+            CodeChecker::CLASS_EXTENDS_NOT_ALLOWED => "%s class must not be extended",
89
+            CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED => "%s interface must not be implemented",
90
+            CodeChecker::STATIC_CALL_NOT_ALLOWED => "Static method of %s class must not be called",
91
+            CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED => "Constant of %s class must not not be fetched",
92
+            CodeChecker::CLASS_NEW_NOT_ALLOWED => "%s class must not be instantiated",
93
+            CodeChecker::CLASS_USE_NOT_ALLOWED => "%s class must not be imported with a use statement",
94
+            CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED => "Method of %s class must not be called",
95
+
96
+            CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED => "is discouraged",
97
+        ];
98
+    }
99
+
100
+    /** @var array */
101
+    public $errors = [];
102
+
103
+    public function enterNode(Node $node) {
104
+        if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\Equal) {
105
+            $this->errors[]= [
106
+                'disallowedToken' => '==',
107
+                'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED,
108
+                'line' => $node->getLine(),
109
+                'reason' => $this->buildReason('==', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED)
110
+            ];
111
+        }
112
+        if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\NotEqual) {
113
+            $this->errors[]= [
114
+                'disallowedToken' => '!=',
115
+                'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED,
116
+                'line' => $node->getLine(),
117
+                'reason' => $this->buildReason('!=', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED)
118
+            ];
119
+        }
120
+        if ($node instanceof Node\Stmt\Class_) {
121
+            if (!is_null($node->extends)) {
122
+                $this->checkBlackList($node->extends->toString(), CodeChecker::CLASS_EXTENDS_NOT_ALLOWED, $node);
123
+            }
124
+            foreach ($node->implements as $implements) {
125
+                $this->checkBlackList($implements->toString(), CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED, $node);
126
+            }
127
+        }
128
+        if ($node instanceof Node\Expr\StaticCall) {
129
+            if (!is_null($node->class)) {
130
+                if ($node->class instanceof Name) {
131
+                    $this->checkBlackList($node->class->toString(), CodeChecker::STATIC_CALL_NOT_ALLOWED, $node);
132
+
133
+                    $this->checkBlackListFunction($node->class->toString(), $node->name, $node);
134
+                    $this->checkBlackListMethod($node->class->toString(), $node->name, $node);
135
+                }
136
+
137
+                if ($node->class instanceof Node\Expr\Variable) {
138
+                    /**
139
+                     * TODO: find a way to detect something like this:
140
+                     *       $c = "OC_API";
141
+                     *       $n = $c::call();
142
+                     */
143
+                    // $this->checkBlackListMethod($node->class->..., $node->name, $node);
144
+                }
145
+            }
146
+        }
147
+        if ($node instanceof Node\Expr\MethodCall) {
148
+            if (!is_null($node->var)) {
149
+                if ($node->var instanceof Node\Expr\Variable) {
150
+                    /**
151
+                     * TODO: find a way to detect something like this:
152
+                     *       $c = new OC_API();
153
+                     *       $n = $c::call();
154
+                     *       $n = $c->call();
155
+                     */
156
+                    // $this->checkBlackListMethod($node->var->..., $node->name, $node);
157
+                }
158
+            }
159
+        }
160
+        if ($node instanceof Node\Expr\ClassConstFetch) {
161
+            if (!is_null($node->class)) {
162
+                if ($node->class instanceof Name) {
163
+                    $this->checkBlackList($node->class->toString(), CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, $node);
164
+                }
165
+                if ($node->class instanceof Node\Expr\Variable) {
166
+                    /**
167
+                     * TODO: find a way to detect something like this:
168
+                     *       $c = "OC_API";
169
+                     *       $n = $i::ADMIN_AUTH;
170
+                     */
171
+                } else {
172
+                    $this->checkBlackListConstant($node->class->toString(), $node->name, $node);
173
+                }
174
+            }
175
+        }
176
+        if ($node instanceof Node\Expr\New_) {
177
+            if (!is_null($node->class)) {
178
+                if ($node->class instanceof Name) {
179
+                    $this->checkBlackList($node->class->toString(), CodeChecker::CLASS_NEW_NOT_ALLOWED, $node);
180
+                }
181
+                if ($node->class instanceof Node\Expr\Variable) {
182
+                    /**
183
+                     * TODO: find a way to detect something like this:
184
+                     *       $c = "OC_API";
185
+                     *       $n = new $i;
186
+                     */
187
+                }
188
+            }
189
+        }
190
+        if ($node instanceof Node\Stmt\UseUse) {
191
+            $this->checkBlackList($node->name->toString(), CodeChecker::CLASS_USE_NOT_ALLOWED, $node);
192
+            if ($node->alias) {
193
+                $this->addUseNameToBlackList($node->name->toString(), $node->alias);
194
+            } else {
195
+                $this->addUseNameToBlackList($node->name->toString(), $node->name->getLast());
196
+            }
197
+        }
198
+    }
199
+
200
+    /**
201
+     * Check whether an alias was introduced for a namespace of a blacklisted class
202
+     *
203
+     * Example:
204
+     * - Blacklist entry:      OCP\AppFramework\IApi
205
+     * - Name:                 OCP\AppFramework
206
+     * - Alias:                OAF
207
+     * =>  new blacklist entry:  OAF\IApi
208
+     *
209
+     * @param string $name
210
+     * @param string $alias
211
+     */
212
+    private function addUseNameToBlackList($name, $alias) {
213
+        $name = strtolower($name);
214
+        $alias = strtolower($alias);
215
+
216
+        foreach ($this->blackListedClassNames as $blackListedAlias => $blackListedClassName) {
217
+            if (strpos($blackListedClassName, $name . '\\') === 0) {
218
+                $aliasedClassName = str_replace($name, $alias, $blackListedClassName);
219
+                $this->blackListedClassNames[$aliasedClassName] = $blackListedClassName;
220
+            }
221
+        }
222
+
223
+        foreach ($this->blackListedConstants as $blackListedAlias => $blackListedConstant) {
224
+            if (strpos($blackListedConstant, $name . '\\') === 0 || strpos($blackListedConstant, $name . '::') === 0) {
225
+                $aliasedConstantName = str_replace($name, $alias, $blackListedConstant);
226
+                $this->blackListedConstants[$aliasedConstantName] = $blackListedConstant;
227
+            }
228
+        }
229
+
230
+        foreach ($this->blackListedFunctions as $blackListedAlias => $blackListedFunction) {
231
+            if (strpos($blackListedFunction, $name . '\\') === 0 || strpos($blackListedFunction, $name . '::') === 0) {
232
+                $aliasedFunctionName = str_replace($name, $alias, $blackListedFunction);
233
+                $this->blackListedFunctions[$aliasedFunctionName] = $blackListedFunction;
234
+            }
235
+        }
236
+
237
+        foreach ($this->blackListedMethods as $blackListedAlias => $blackListedMethod) {
238
+            if (strpos($blackListedMethod, $name . '\\') === 0 || strpos($blackListedMethod, $name . '::') === 0) {
239
+                $aliasedMethodName = str_replace($name, $alias, $blackListedMethod);
240
+                $this->blackListedMethods[$aliasedMethodName] = $blackListedMethod;
241
+            }
242
+        }
243
+    }
244
+
245
+    private function checkBlackList($name, $errorCode, Node $node) {
246
+        $lowerName = strtolower($name);
247
+
248
+        if (isset($this->blackListedClassNames[$lowerName])) {
249
+            $this->errors[]= [
250
+                'disallowedToken' => $name,
251
+                'errorCode' => $errorCode,
252
+                'line' => $node->getLine(),
253
+                'reason' => $this->buildReason($this->blackListedClassNames[$lowerName], $errorCode)
254
+            ];
255
+        }
256
+    }
257
+
258
+    private function checkBlackListConstant($class, $constantName, Node $node) {
259
+        $name = $class . '::' . $constantName;
260
+        $lowerName = strtolower($name);
261
+
262
+        if (isset($this->blackListedConstants[$lowerName])) {
263
+            $this->errors[]= [
264
+                'disallowedToken' => $name,
265
+                'errorCode' => CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED,
266
+                'line' => $node->getLine(),
267
+                'reason' => $this->buildReason($this->blackListedConstants[$lowerName], CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED)
268
+            ];
269
+        }
270
+    }
271
+
272
+    private function checkBlackListFunction($class, $functionName, Node $node) {
273
+        $name = $class . '::' . $functionName;
274
+        $lowerName = strtolower($name);
275
+
276
+        if (isset($this->blackListedFunctions[$lowerName])) {
277
+            $this->errors[]= [
278
+                'disallowedToken' => $name,
279
+                'errorCode' => CodeChecker::STATIC_CALL_NOT_ALLOWED,
280
+                'line' => $node->getLine(),
281
+                'reason' => $this->buildReason($this->blackListedFunctions[$lowerName], CodeChecker::STATIC_CALL_NOT_ALLOWED)
282
+            ];
283
+        }
284
+    }
285
+
286
+    private function checkBlackListMethod($class, $functionName, Node $node) {
287
+        $name = $class . '::' . $functionName;
288
+        $lowerName = strtolower($name);
289
+
290
+        if (isset($this->blackListedMethods[$lowerName])) {
291
+            $this->errors[]= [
292
+                'disallowedToken' => $name,
293
+                'errorCode' => CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED,
294
+                'line' => $node->getLine(),
295
+                'reason' => $this->buildReason($this->blackListedMethods[$lowerName], CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED)
296
+            ];
297
+        }
298
+    }
299
+
300
+    private function buildReason($name, $errorCode) {
301
+        if (isset($this->errorMessages[$errorCode])) {
302
+            $desc = $this->list->getDescription($errorCode, $name);
303
+            return sprintf($this->errorMessages[$errorCode], $desc);
304
+        }
305
+
306
+        return "$name usage not allowed - error: $errorCode";
307
+    }
308 308
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 
103 103
 	public function enterNode(Node $node) {
104 104
 		if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\Equal) {
105
-			$this->errors[]= [
105
+			$this->errors[] = [
106 106
 				'disallowedToken' => '==',
107 107
 				'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED,
108 108
 				'line' => $node->getLine(),
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 			];
111 111
 		}
112 112
 		if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\NotEqual) {
113
-			$this->errors[]= [
113
+			$this->errors[] = [
114 114
 				'disallowedToken' => '!=',
115 115
 				'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED,
116 116
 				'line' => $node->getLine(),
@@ -214,28 +214,28 @@  discard block
 block discarded – undo
214 214
 		$alias = strtolower($alias);
215 215
 
216 216
 		foreach ($this->blackListedClassNames as $blackListedAlias => $blackListedClassName) {
217
-			if (strpos($blackListedClassName, $name . '\\') === 0) {
217
+			if (strpos($blackListedClassName, $name.'\\') === 0) {
218 218
 				$aliasedClassName = str_replace($name, $alias, $blackListedClassName);
219 219
 				$this->blackListedClassNames[$aliasedClassName] = $blackListedClassName;
220 220
 			}
221 221
 		}
222 222
 
223 223
 		foreach ($this->blackListedConstants as $blackListedAlias => $blackListedConstant) {
224
-			if (strpos($blackListedConstant, $name . '\\') === 0 || strpos($blackListedConstant, $name . '::') === 0) {
224
+			if (strpos($blackListedConstant, $name.'\\') === 0 || strpos($blackListedConstant, $name.'::') === 0) {
225 225
 				$aliasedConstantName = str_replace($name, $alias, $blackListedConstant);
226 226
 				$this->blackListedConstants[$aliasedConstantName] = $blackListedConstant;
227 227
 			}
228 228
 		}
229 229
 
230 230
 		foreach ($this->blackListedFunctions as $blackListedAlias => $blackListedFunction) {
231
-			if (strpos($blackListedFunction, $name . '\\') === 0 || strpos($blackListedFunction, $name . '::') === 0) {
231
+			if (strpos($blackListedFunction, $name.'\\') === 0 || strpos($blackListedFunction, $name.'::') === 0) {
232 232
 				$aliasedFunctionName = str_replace($name, $alias, $blackListedFunction);
233 233
 				$this->blackListedFunctions[$aliasedFunctionName] = $blackListedFunction;
234 234
 			}
235 235
 		}
236 236
 
237 237
 		foreach ($this->blackListedMethods as $blackListedAlias => $blackListedMethod) {
238
-			if (strpos($blackListedMethod, $name . '\\') === 0 || strpos($blackListedMethod, $name . '::') === 0) {
238
+			if (strpos($blackListedMethod, $name.'\\') === 0 || strpos($blackListedMethod, $name.'::') === 0) {
239 239
 				$aliasedMethodName = str_replace($name, $alias, $blackListedMethod);
240 240
 				$this->blackListedMethods[$aliasedMethodName] = $blackListedMethod;
241 241
 			}
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
 		$lowerName = strtolower($name);
247 247
 
248 248
 		if (isset($this->blackListedClassNames[$lowerName])) {
249
-			$this->errors[]= [
249
+			$this->errors[] = [
250 250
 				'disallowedToken' => $name,
251 251
 				'errorCode' => $errorCode,
252 252
 				'line' => $node->getLine(),
@@ -256,11 +256,11 @@  discard block
 block discarded – undo
256 256
 	}
257 257
 
258 258
 	private function checkBlackListConstant($class, $constantName, Node $node) {
259
-		$name = $class . '::' . $constantName;
259
+		$name = $class.'::'.$constantName;
260 260
 		$lowerName = strtolower($name);
261 261
 
262 262
 		if (isset($this->blackListedConstants[$lowerName])) {
263
-			$this->errors[]= [
263
+			$this->errors[] = [
264 264
 				'disallowedToken' => $name,
265 265
 				'errorCode' => CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED,
266 266
 				'line' => $node->getLine(),
@@ -270,11 +270,11 @@  discard block
 block discarded – undo
270 270
 	}
271 271
 
272 272
 	private function checkBlackListFunction($class, $functionName, Node $node) {
273
-		$name = $class . '::' . $functionName;
273
+		$name = $class.'::'.$functionName;
274 274
 		$lowerName = strtolower($name);
275 275
 
276 276
 		if (isset($this->blackListedFunctions[$lowerName])) {
277
-			$this->errors[]= [
277
+			$this->errors[] = [
278 278
 				'disallowedToken' => $name,
279 279
 				'errorCode' => CodeChecker::STATIC_CALL_NOT_ALLOWED,
280 280
 				'line' => $node->getLine(),
@@ -284,11 +284,11 @@  discard block
 block discarded – undo
284 284
 	}
285 285
 
286 286
 	private function checkBlackListMethod($class, $functionName, Node $node) {
287
-		$name = $class . '::' . $functionName;
287
+		$name = $class.'::'.$functionName;
288 288
 		$lowerName = strtolower($name);
289 289
 
290 290
 		if (isset($this->blackListedMethods[$lowerName])) {
291
-			$this->errors[]= [
291
+			$this->errors[] = [
292 292
 				'disallowedToken' => $name,
293 293
 				'errorCode' => CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED,
294 294
 				'line' => $node->getLine(),
Please login to merge, or discard this patch.
lib/private/DateTimeFormatter.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 	/**
94 94
 	 * Formats the date of the given timestamp
95 95
 	 *
96
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
96
+	 * @param integer	$timestamp	Either a Unix timestamp or DateTime object
97 97
 	 * @param string	$format			Either 'full', 'long', 'medium' or 'short'
98 98
 	 * 				full:	e.g. 'EEEE, MMMM d, y'	=> 'Wednesday, August 20, 2014'
99 99
 	 * 				long:	e.g. 'MMMM d, y'		=> 'August 20, 2014'
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 	/**
193 193
 	 * Gives the relative past time of the timestamp
194 194
 	 *
195
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
195
+	 * @param integer	$timestamp	Either a Unix timestamp or DateTime object
196 196
 	 * @param int|\DateTime	$baseTimestamp	Timestamp to compare $timestamp against, defaults to current time
197 197
 	 * @return string	Dates returned are:
198 198
 	 * 				< 60 sec	=> seconds ago
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 	/**
229 229
 	 * Formats the date and time of the given timestamp
230 230
 	 *
231
-	 * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
231
+	 * @param integer $timestamp	Either a Unix timestamp or DateTime object
232 232
 	 * @param string		$formatDate		See formatDate() for description
233 233
 	 * @param string		$formatTime		See formatTime() for description
234 234
 	 * @param \DateTimeZone	$timeZone	The timezone to use
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
 	 * @return string Formatted date and time string
238 238
 	 */
239 239
 	public function formatDateTime($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
240
-		return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l);
240
+		return $this->format($timestamp, 'datetime', $formatDate.'|'.$formatTime, $timeZone, $l);
241 241
 	}
242 242
 
243 243
 	/**
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 			$formatDate .= '^';
257 257
 		}
258 258
 
259
-		return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l);
259
+		return $this->format($timestamp, 'datetime', $formatDate.'|'.$formatTime, $timeZone, $l);
260 260
 	}
261 261
 
262 262
 	/**
Please login to merge, or discard this patch.
Indentation   +268 added lines, -268 removed lines patch added patch discarded remove patch
@@ -25,294 +25,294 @@
 block discarded – undo
25 25
 namespace OC;
26 26
 
27 27
 class DateTimeFormatter implements \OCP\IDateTimeFormatter {
28
-	/** @var \DateTimeZone */
29
-	protected $defaultTimeZone;
28
+    /** @var \DateTimeZone */
29
+    protected $defaultTimeZone;
30 30
 
31
-	/** @var \OCP\IL10N */
32
-	protected $defaultL10N;
31
+    /** @var \OCP\IL10N */
32
+    protected $defaultL10N;
33 33
 
34
-	/**
35
-	 * Constructor
36
-	 *
37
-	 * @param \DateTimeZone $defaultTimeZone Set the timezone for the format
38
-	 * @param \OCP\IL10N $defaultL10N Set the language for the format
39
-	 */
40
-	public function __construct(\DateTimeZone $defaultTimeZone, \OCP\IL10N $defaultL10N) {
41
-		$this->defaultTimeZone = $defaultTimeZone;
42
-		$this->defaultL10N = $defaultL10N;
43
-	}
34
+    /**
35
+     * Constructor
36
+     *
37
+     * @param \DateTimeZone $defaultTimeZone Set the timezone for the format
38
+     * @param \OCP\IL10N $defaultL10N Set the language for the format
39
+     */
40
+    public function __construct(\DateTimeZone $defaultTimeZone, \OCP\IL10N $defaultL10N) {
41
+        $this->defaultTimeZone = $defaultTimeZone;
42
+        $this->defaultL10N = $defaultL10N;
43
+    }
44 44
 
45
-	/**
46
-	 * Get TimeZone to use
47
-	 *
48
-	 * @param \DateTimeZone $timeZone	The timezone to use
49
-	 * @return \DateTimeZone		The timezone to use, falling back to the current user's timezone
50
-	 */
51
-	protected function getTimeZone($timeZone = null) {
52
-		if ($timeZone === null) {
53
-			$timeZone = $this->defaultTimeZone;
54
-		}
45
+    /**
46
+     * Get TimeZone to use
47
+     *
48
+     * @param \DateTimeZone $timeZone	The timezone to use
49
+     * @return \DateTimeZone		The timezone to use, falling back to the current user's timezone
50
+     */
51
+    protected function getTimeZone($timeZone = null) {
52
+        if ($timeZone === null) {
53
+            $timeZone = $this->defaultTimeZone;
54
+        }
55 55
 
56
-		return $timeZone;
57
-	}
56
+        return $timeZone;
57
+    }
58 58
 
59
-	/**
60
-	 * Get \OCP\IL10N to use
61
-	 *
62
-	 * @param \OCP\IL10N $l	The locale to use
63
-	 * @return \OCP\IL10N		The locale to use, falling back to the current user's locale
64
-	 */
65
-	protected function getLocale($l = null) {
66
-		if ($l === null) {
67
-			$l = $this->defaultL10N;
68
-		}
59
+    /**
60
+     * Get \OCP\IL10N to use
61
+     *
62
+     * @param \OCP\IL10N $l	The locale to use
63
+     * @return \OCP\IL10N		The locale to use, falling back to the current user's locale
64
+     */
65
+    protected function getLocale($l = null) {
66
+        if ($l === null) {
67
+            $l = $this->defaultL10N;
68
+        }
69 69
 
70
-		return $l;
71
-	}
70
+        return $l;
71
+    }
72 72
 
73
-	/**
74
-	 * Generates a DateTime object with the given timestamp and TimeZone
75
-	 *
76
-	 * @param mixed $timestamp
77
-	 * @param \DateTimeZone $timeZone	The timezone to use
78
-	 * @return \DateTime
79
-	 */
80
-	protected function getDateTime($timestamp, \DateTimeZone $timeZone = null) {
81
-		if ($timestamp === null) {
82
-			return new \DateTime('now', $timeZone);
83
-		} else if (!$timestamp instanceof \DateTime) {
84
-			$dateTime = new \DateTime('now', $timeZone);
85
-			$dateTime->setTimestamp($timestamp);
86
-			return $dateTime;
87
-		}
88
-		if ($timeZone) {
89
-			$timestamp->setTimezone($timeZone);
90
-		}
91
-		return $timestamp;
92
-	}
73
+    /**
74
+     * Generates a DateTime object with the given timestamp and TimeZone
75
+     *
76
+     * @param mixed $timestamp
77
+     * @param \DateTimeZone $timeZone	The timezone to use
78
+     * @return \DateTime
79
+     */
80
+    protected function getDateTime($timestamp, \DateTimeZone $timeZone = null) {
81
+        if ($timestamp === null) {
82
+            return new \DateTime('now', $timeZone);
83
+        } else if (!$timestamp instanceof \DateTime) {
84
+            $dateTime = new \DateTime('now', $timeZone);
85
+            $dateTime->setTimestamp($timestamp);
86
+            return $dateTime;
87
+        }
88
+        if ($timeZone) {
89
+            $timestamp->setTimezone($timeZone);
90
+        }
91
+        return $timestamp;
92
+    }
93 93
 
94
-	/**
95
-	 * Formats the date of the given timestamp
96
-	 *
97
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
98
-	 * @param string	$format			Either 'full', 'long', 'medium' or 'short'
99
-	 * 				full:	e.g. 'EEEE, MMMM d, y'	=> 'Wednesday, August 20, 2014'
100
-	 * 				long:	e.g. 'MMMM d, y'		=> 'August 20, 2014'
101
-	 * 				medium:	e.g. 'MMM d, y'			=> 'Aug 20, 2014'
102
-	 * 				short:	e.g. 'M/d/yy'			=> '8/20/14'
103
-	 * 				The exact format is dependent on the language
104
-	 * @param \DateTimeZone	$timeZone	The timezone to use
105
-	 * @param \OCP\IL10N	$l			The locale to use
106
-	 * @return string Formatted date string
107
-	 */
108
-	public function formatDate($timestamp, $format = 'long', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
109
-		return $this->format($timestamp, 'date', $format, $timeZone, $l);
110
-	}
94
+    /**
95
+     * Formats the date of the given timestamp
96
+     *
97
+     * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
98
+     * @param string	$format			Either 'full', 'long', 'medium' or 'short'
99
+     * 				full:	e.g. 'EEEE, MMMM d, y'	=> 'Wednesday, August 20, 2014'
100
+     * 				long:	e.g. 'MMMM d, y'		=> 'August 20, 2014'
101
+     * 				medium:	e.g. 'MMM d, y'			=> 'Aug 20, 2014'
102
+     * 				short:	e.g. 'M/d/yy'			=> '8/20/14'
103
+     * 				The exact format is dependent on the language
104
+     * @param \DateTimeZone	$timeZone	The timezone to use
105
+     * @param \OCP\IL10N	$l			The locale to use
106
+     * @return string Formatted date string
107
+     */
108
+    public function formatDate($timestamp, $format = 'long', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
109
+        return $this->format($timestamp, 'date', $format, $timeZone, $l);
110
+    }
111 111
 
112
-	/**
113
-	 * Formats the date of the given timestamp
114
-	 *
115
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
116
-	 * @param string	$format			Either 'full', 'long', 'medium' or 'short'
117
-	 * 				full:	e.g. 'EEEE, MMMM d, y'	=> 'Wednesday, August 20, 2014'
118
-	 * 				long:	e.g. 'MMMM d, y'		=> 'August 20, 2014'
119
-	 * 				medium:	e.g. 'MMM d, y'			=> 'Aug 20, 2014'
120
-	 * 				short:	e.g. 'M/d/yy'			=> '8/20/14'
121
-	 * 				The exact format is dependent on the language
122
-	 * 					Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable
123
-	 * @param \DateTimeZone	$timeZone	The timezone to use
124
-	 * @param \OCP\IL10N	$l			The locale to use
125
-	 * @return string Formatted relative date string
126
-	 */
127
-	public function formatDateRelativeDay($timestamp, $format = 'long', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
128
-		if (substr($format, -1) !== '*' && substr($format, -1) !== '*') {
129
-			$format .= '^';
130
-		}
112
+    /**
113
+     * Formats the date of the given timestamp
114
+     *
115
+     * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
116
+     * @param string	$format			Either 'full', 'long', 'medium' or 'short'
117
+     * 				full:	e.g. 'EEEE, MMMM d, y'	=> 'Wednesday, August 20, 2014'
118
+     * 				long:	e.g. 'MMMM d, y'		=> 'August 20, 2014'
119
+     * 				medium:	e.g. 'MMM d, y'			=> 'Aug 20, 2014'
120
+     * 				short:	e.g. 'M/d/yy'			=> '8/20/14'
121
+     * 				The exact format is dependent on the language
122
+     * 					Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable
123
+     * @param \DateTimeZone	$timeZone	The timezone to use
124
+     * @param \OCP\IL10N	$l			The locale to use
125
+     * @return string Formatted relative date string
126
+     */
127
+    public function formatDateRelativeDay($timestamp, $format = 'long', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
128
+        if (substr($format, -1) !== '*' && substr($format, -1) !== '*') {
129
+            $format .= '^';
130
+        }
131 131
 
132
-		return $this->format($timestamp, 'date', $format, $timeZone, $l);
133
-	}
132
+        return $this->format($timestamp, 'date', $format, $timeZone, $l);
133
+    }
134 134
 
135
-	/**
136
-	 * Gives the relative date of the timestamp
137
-	 * Only works for past dates
138
-	 *
139
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
140
-	 * @param int|\DateTime	$baseTimestamp	Timestamp to compare $timestamp against, defaults to current time
141
-	 * @return string	Dates returned are:
142
-	 * 				<  1 month	=> Today, Yesterday, n days ago
143
-	 * 				< 13 month	=> last month, n months ago
144
-	 * 				>= 13 month	=> last year, n years ago
145
-	 * @param \OCP\IL10N	$l			The locale to use
146
-	 * @return string Formatted date span
147
-	 */
148
-	public function formatDateSpan($timestamp, $baseTimestamp = null, \OCP\IL10N $l = null) {
149
-		$l = $this->getLocale($l);
150
-		$timestamp = $this->getDateTime($timestamp);
151
-		$timestamp->setTime(0, 0, 0);
135
+    /**
136
+     * Gives the relative date of the timestamp
137
+     * Only works for past dates
138
+     *
139
+     * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
140
+     * @param int|\DateTime	$baseTimestamp	Timestamp to compare $timestamp against, defaults to current time
141
+     * @return string	Dates returned are:
142
+     * 				<  1 month	=> Today, Yesterday, n days ago
143
+     * 				< 13 month	=> last month, n months ago
144
+     * 				>= 13 month	=> last year, n years ago
145
+     * @param \OCP\IL10N	$l			The locale to use
146
+     * @return string Formatted date span
147
+     */
148
+    public function formatDateSpan($timestamp, $baseTimestamp = null, \OCP\IL10N $l = null) {
149
+        $l = $this->getLocale($l);
150
+        $timestamp = $this->getDateTime($timestamp);
151
+        $timestamp->setTime(0, 0, 0);
152 152
 
153
-		if ($baseTimestamp === null) {
154
-			$baseTimestamp = time();
155
-		}
156
-		$baseTimestamp = $this->getDateTime($baseTimestamp);
157
-		$baseTimestamp->setTime(0, 0, 0);
158
-		$dateInterval = $timestamp->diff($baseTimestamp);
153
+        if ($baseTimestamp === null) {
154
+            $baseTimestamp = time();
155
+        }
156
+        $baseTimestamp = $this->getDateTime($baseTimestamp);
157
+        $baseTimestamp->setTime(0, 0, 0);
158
+        $dateInterval = $timestamp->diff($baseTimestamp);
159 159
 
160
-		if ($dateInterval->y == 0 && $dateInterval->m == 0 && $dateInterval->d == 0) {
161
-			return $l->t('today');
162
-		} else if ($dateInterval->y == 0 && $dateInterval->m == 0 && $dateInterval->d == 1) {
163
-			if ($timestamp > $baseTimestamp) {
164
-				return $l->t('tomorrow');
165
-			} else {
166
-				return $l->t('yesterday');
167
-			}
168
-		} else if ($dateInterval->y == 0 && $dateInterval->m == 0) {
169
-			if ($timestamp > $baseTimestamp) {
170
-				return $l->n('in %n day', 'in %n days', $dateInterval->d);
171
-			} else {
172
-				return $l->n('%n day ago', '%n days ago', $dateInterval->d);
173
-			}
174
-		} else if ($dateInterval->y == 0 && $dateInterval->m == 1) {
175
-			if ($timestamp > $baseTimestamp) {
176
-				return $l->t('next month');
177
-			} else {
178
-				return $l->t('last month');
179
-			}
180
-		} else if ($dateInterval->y == 0) {
181
-			if ($timestamp > $baseTimestamp) {
182
-				return $l->n('in %n month', 'in %n months', $dateInterval->m);
183
-			} else {
184
-				return $l->n('%n month ago', '%n months ago', $dateInterval->m);
185
-			}
186
-		} else if ($dateInterval->y == 1) {
187
-			if ($timestamp > $baseTimestamp) {
188
-				return $l->t('next year');
189
-			} else {
190
-				return $l->t('last year');
191
-			}
192
-		}
193
-		if ($timestamp > $baseTimestamp) {
194
-			return $l->n('in %n year', 'in %n years', $dateInterval->y);
195
-		} else {
196
-			return $l->n('%n year ago', '%n years ago', $dateInterval->y);
197
-		}
198
-	}
160
+        if ($dateInterval->y == 0 && $dateInterval->m == 0 && $dateInterval->d == 0) {
161
+            return $l->t('today');
162
+        } else if ($dateInterval->y == 0 && $dateInterval->m == 0 && $dateInterval->d == 1) {
163
+            if ($timestamp > $baseTimestamp) {
164
+                return $l->t('tomorrow');
165
+            } else {
166
+                return $l->t('yesterday');
167
+            }
168
+        } else if ($dateInterval->y == 0 && $dateInterval->m == 0) {
169
+            if ($timestamp > $baseTimestamp) {
170
+                return $l->n('in %n day', 'in %n days', $dateInterval->d);
171
+            } else {
172
+                return $l->n('%n day ago', '%n days ago', $dateInterval->d);
173
+            }
174
+        } else if ($dateInterval->y == 0 && $dateInterval->m == 1) {
175
+            if ($timestamp > $baseTimestamp) {
176
+                return $l->t('next month');
177
+            } else {
178
+                return $l->t('last month');
179
+            }
180
+        } else if ($dateInterval->y == 0) {
181
+            if ($timestamp > $baseTimestamp) {
182
+                return $l->n('in %n month', 'in %n months', $dateInterval->m);
183
+            } else {
184
+                return $l->n('%n month ago', '%n months ago', $dateInterval->m);
185
+            }
186
+        } else if ($dateInterval->y == 1) {
187
+            if ($timestamp > $baseTimestamp) {
188
+                return $l->t('next year');
189
+            } else {
190
+                return $l->t('last year');
191
+            }
192
+        }
193
+        if ($timestamp > $baseTimestamp) {
194
+            return $l->n('in %n year', 'in %n years', $dateInterval->y);
195
+        } else {
196
+            return $l->n('%n year ago', '%n years ago', $dateInterval->y);
197
+        }
198
+    }
199 199
 
200
-	/**
201
-	 * Formats the time of the given timestamp
202
-	 *
203
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
204
-	 * @param string	$format			Either 'full', 'long', 'medium' or 'short'
205
-	 * 				full:	e.g. 'h:mm:ss a zzzz'	=> '11:42:13 AM GMT+0:00'
206
-	 * 				long:	e.g. 'h:mm:ss a z'		=> '11:42:13 AM GMT'
207
-	 * 				medium:	e.g. 'h:mm:ss a'		=> '11:42:13 AM'
208
-	 * 				short:	e.g. 'h:mm a'			=> '11:42 AM'
209
-	 * 				The exact format is dependent on the language
210
-	 * @param \DateTimeZone	$timeZone	The timezone to use
211
-	 * @param \OCP\IL10N	$l			The locale to use
212
-	 * @return string Formatted time string
213
-	 */
214
-	public function formatTime($timestamp, $format = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
215
-		return $this->format($timestamp, 'time', $format, $timeZone, $l);
216
-	}
200
+    /**
201
+     * Formats the time of the given timestamp
202
+     *
203
+     * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
204
+     * @param string	$format			Either 'full', 'long', 'medium' or 'short'
205
+     * 				full:	e.g. 'h:mm:ss a zzzz'	=> '11:42:13 AM GMT+0:00'
206
+     * 				long:	e.g. 'h:mm:ss a z'		=> '11:42:13 AM GMT'
207
+     * 				medium:	e.g. 'h:mm:ss a'		=> '11:42:13 AM'
208
+     * 				short:	e.g. 'h:mm a'			=> '11:42 AM'
209
+     * 				The exact format is dependent on the language
210
+     * @param \DateTimeZone	$timeZone	The timezone to use
211
+     * @param \OCP\IL10N	$l			The locale to use
212
+     * @return string Formatted time string
213
+     */
214
+    public function formatTime($timestamp, $format = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
215
+        return $this->format($timestamp, 'time', $format, $timeZone, $l);
216
+    }
217 217
 
218
-	/**
219
-	 * Gives the relative past time of the timestamp
220
-	 *
221
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
222
-	 * @param int|\DateTime	$baseTimestamp	Timestamp to compare $timestamp against, defaults to current time
223
-	 * @return string	Dates returned are:
224
-	 * 				< 60 sec	=> seconds ago
225
-	 * 				<  1 hour	=> n minutes ago
226
-	 * 				<  1 day	=> n hours ago
227
-	 * 				<  1 month	=> Yesterday, n days ago
228
-	 * 				< 13 month	=> last month, n months ago
229
-	 * 				>= 13 month	=> last year, n years ago
230
-	 * @param \OCP\IL10N	$l			The locale to use
231
-	 * @return string Formatted time span
232
-	 */
233
-	public function formatTimeSpan($timestamp, $baseTimestamp = null, \OCP\IL10N $l = null) {
234
-		$l = $this->getLocale($l);
235
-		$timestamp = $this->getDateTime($timestamp);
236
-		if ($baseTimestamp === null) {
237
-			$baseTimestamp = time();
238
-		}
239
-		$baseTimestamp = $this->getDateTime($baseTimestamp);
218
+    /**
219
+     * Gives the relative past time of the timestamp
220
+     *
221
+     * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
222
+     * @param int|\DateTime	$baseTimestamp	Timestamp to compare $timestamp against, defaults to current time
223
+     * @return string	Dates returned are:
224
+     * 				< 60 sec	=> seconds ago
225
+     * 				<  1 hour	=> n minutes ago
226
+     * 				<  1 day	=> n hours ago
227
+     * 				<  1 month	=> Yesterday, n days ago
228
+     * 				< 13 month	=> last month, n months ago
229
+     * 				>= 13 month	=> last year, n years ago
230
+     * @param \OCP\IL10N	$l			The locale to use
231
+     * @return string Formatted time span
232
+     */
233
+    public function formatTimeSpan($timestamp, $baseTimestamp = null, \OCP\IL10N $l = null) {
234
+        $l = $this->getLocale($l);
235
+        $timestamp = $this->getDateTime($timestamp);
236
+        if ($baseTimestamp === null) {
237
+            $baseTimestamp = time();
238
+        }
239
+        $baseTimestamp = $this->getDateTime($baseTimestamp);
240 240
 
241
-		$diff = $timestamp->diff($baseTimestamp);
242
-		if ($diff->y > 0 || $diff->m > 0 || $diff->d > 0) {
243
-			return $this->formatDateSpan($timestamp, $baseTimestamp, $l);
244
-		}
241
+        $diff = $timestamp->diff($baseTimestamp);
242
+        if ($diff->y > 0 || $diff->m > 0 || $diff->d > 0) {
243
+            return $this->formatDateSpan($timestamp, $baseTimestamp, $l);
244
+        }
245 245
 
246
-		if ($diff->h > 0) {
247
-			if ($timestamp > $baseTimestamp) {
248
-				return $l->n('in %n hour', 'in %n hours', $diff->h);
249
-			} else {
250
-				return $l->n('%n hour ago', '%n hours ago', $diff->h);
251
-			}
252
-		} else if ($diff->i > 0) {
253
-			if ($timestamp > $baseTimestamp) {
254
-				return $l->n('in %n minute', 'in %n minutes', $diff->i);
255
-			} else {
256
-				return $l->n('%n minute ago', '%n minutes ago', $diff->i);
257
-			}
258
-		}
259
-		if ($timestamp > $baseTimestamp) {
260
-			return $l->t('in a few seconds');
261
-		} else {
262
-			return $l->t('seconds ago');
263
-		}
264
-	}
246
+        if ($diff->h > 0) {
247
+            if ($timestamp > $baseTimestamp) {
248
+                return $l->n('in %n hour', 'in %n hours', $diff->h);
249
+            } else {
250
+                return $l->n('%n hour ago', '%n hours ago', $diff->h);
251
+            }
252
+        } else if ($diff->i > 0) {
253
+            if ($timestamp > $baseTimestamp) {
254
+                return $l->n('in %n minute', 'in %n minutes', $diff->i);
255
+            } else {
256
+                return $l->n('%n minute ago', '%n minutes ago', $diff->i);
257
+            }
258
+        }
259
+        if ($timestamp > $baseTimestamp) {
260
+            return $l->t('in a few seconds');
261
+        } else {
262
+            return $l->t('seconds ago');
263
+        }
264
+    }
265 265
 
266
-	/**
267
-	 * Formats the date and time of the given timestamp
268
-	 *
269
-	 * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
270
-	 * @param string		$formatDate		See formatDate() for description
271
-	 * @param string		$formatTime		See formatTime() for description
272
-	 * @param \DateTimeZone	$timeZone	The timezone to use
273
-	 * @param \OCP\IL10N	$l			The locale to use
274
-	 * @return string Formatted date and time string
275
-	 */
276
-	public function formatDateTime($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
277
-		return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l);
278
-	}
266
+    /**
267
+     * Formats the date and time of the given timestamp
268
+     *
269
+     * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
270
+     * @param string		$formatDate		See formatDate() for description
271
+     * @param string		$formatTime		See formatTime() for description
272
+     * @param \DateTimeZone	$timeZone	The timezone to use
273
+     * @param \OCP\IL10N	$l			The locale to use
274
+     * @return string Formatted date and time string
275
+     */
276
+    public function formatDateTime($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
277
+        return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l);
278
+    }
279 279
 
280
-	/**
281
-	 * Formats the date and time of the given timestamp
282
-	 *
283
-	 * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
284
-	 * @param string	$formatDate		See formatDate() for description
285
-	 * 					Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable
286
-	 * @param string	$formatTime		See formatTime() for description
287
-	 * @param \DateTimeZone	$timeZone	The timezone to use
288
-	 * @param \OCP\IL10N	$l			The locale to use
289
-	 * @return string Formatted relative date and time string
290
-	 */
291
-	public function formatDateTimeRelativeDay($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
292
-		if (substr($formatDate, -1) !== '^' && substr($formatDate, -1) !== '*') {
293
-			$formatDate .= '^';
294
-		}
280
+    /**
281
+     * Formats the date and time of the given timestamp
282
+     *
283
+     * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
284
+     * @param string	$formatDate		See formatDate() for description
285
+     * 					Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable
286
+     * @param string	$formatTime		See formatTime() for description
287
+     * @param \DateTimeZone	$timeZone	The timezone to use
288
+     * @param \OCP\IL10N	$l			The locale to use
289
+     * @return string Formatted relative date and time string
290
+     */
291
+    public function formatDateTimeRelativeDay($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
292
+        if (substr($formatDate, -1) !== '^' && substr($formatDate, -1) !== '*') {
293
+            $formatDate .= '^';
294
+        }
295 295
 
296
-		return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l);
297
-	}
296
+        return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l);
297
+    }
298 298
 
299
-	/**
300
-	 * Formats the date and time of the given timestamp
301
-	 *
302
-	 * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
303
-	 * @param string		$type		One of 'date', 'datetime' or 'time'
304
-	 * @param string		$format		Format string
305
-	 * @param \DateTimeZone	$timeZone	The timezone to use
306
-	 * @param \OCP\IL10N	$l			The locale to use
307
-	 * @return string Formatted date and time string
308
-	 */
309
-	protected function format($timestamp, $type, $format, \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
310
-		$l = $this->getLocale($l);
311
-		$timeZone = $this->getTimeZone($timeZone);
312
-		$timestamp = $this->getDateTime($timestamp, $timeZone);
299
+    /**
300
+     * Formats the date and time of the given timestamp
301
+     *
302
+     * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
303
+     * @param string		$type		One of 'date', 'datetime' or 'time'
304
+     * @param string		$format		Format string
305
+     * @param \DateTimeZone	$timeZone	The timezone to use
306
+     * @param \OCP\IL10N	$l			The locale to use
307
+     * @return string Formatted date and time string
308
+     */
309
+    protected function format($timestamp, $type, $format, \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
310
+        $l = $this->getLocale($l);
311
+        $timeZone = $this->getTimeZone($timeZone);
312
+        $timestamp = $this->getDateTime($timestamp, $timeZone);
313 313
 
314
-		return $l->l($type, $timestamp, array(
315
-			'width' => $format,
316
-		));
317
-	}
314
+        return $l->l($type, $timestamp, array(
315
+            'width' => $format,
316
+        ));
317
+    }
318 318
 }
Please login to merge, or discard this patch.
lib/private/DB/Connection.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 	 * If an SQLLogger is configured, the execution is logged.
174 174
 	 *
175 175
 	 * @param string                                      $query  The SQL query to execute.
176
-	 * @param array                                       $params The parameters to bind to the query, if any.
176
+	 * @param string[]                                       $params The parameters to bind to the query, if any.
177 177
 	 * @param array                                       $types  The types the previous parameters are in.
178 178
 	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
179 179
 	 *
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	 * columns or sequences.
219 219
 	 *
220 220
 	 * @param string $seqName Name of the sequence object from which the ID should be returned.
221
-	 * @return string A string representation of the last inserted ID.
221
+	 * @return integer A string representation of the last inserted ID.
222 222
 	 */
223 223
 	public function lastInsertId($seqName = null) {
224 224
 		if ($seqName) {
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 			return parent::connect();
59 59
 		} catch (DBALException $e) {
60 60
 			// throw a new exception to prevent leaking info from the stacktrace
61
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
61
+			throw new DBALException('Failed to connect to the database: '.$e->getMessage(), $e->getCode());
62 62
 		}
63 63
 	}
64 64
 
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 		// 0 is the method where we use `getCallerBacktrace`
111 111
 		// 1 is the target method which uses the method we want to log
112 112
 		if (isset($traces[1])) {
113
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
113
+			return $traces[1]['file'].':'.$traces[1]['line'];
114 114
 		}
115 115
 
116 116
 		return '';
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 	 * @param int $offset
157 157
 	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
158 158
 	 */
159
-	public function prepare( $statement, $limit=null, $offset=null ) {
159
+	public function prepare($statement, $limit = null, $offset = null) {
160 160
 		if ($limit === -1) {
161 161
 			$limit = null;
162 162
 		}
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
 			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
322 322
 		}
323 323
 
324
-		$tableName = $this->tablePrefix . $tableName;
324
+		$tableName = $this->tablePrefix.$tableName;
325 325
 		$this->lockedTable = $tableName;
326 326
 		$this->adapter->lockTable($tableName);
327 327
 	}
@@ -342,11 +342,11 @@  discard block
 block discarded – undo
342 342
 	 * @return string
343 343
 	 */
344 344
 	public function getError() {
345
-		$msg = $this->errorCode() . ': ';
345
+		$msg = $this->errorCode().': ';
346 346
 		$errorInfo = $this->errorInfo();
347 347
 		if (is_array($errorInfo)) {
348
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
349
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
348
+			$msg .= 'SQLSTATE = '.$errorInfo[0].', ';
349
+			$msg .= 'Driver Code = '.$errorInfo[1].', ';
350 350
 			$msg .= 'Driver Message = '.$errorInfo[2];
351 351
 		}
352 352
 		return $msg;
@@ -358,9 +358,9 @@  discard block
 block discarded – undo
358 358
 	 * @param string $table table name without the prefix
359 359
 	 */
360 360
 	public function dropTable($table) {
361
-		$table = $this->tablePrefix . trim($table);
361
+		$table = $this->tablePrefix.trim($table);
362 362
 		$schema = $this->getSchemaManager();
363
-		if($schema->tablesExist(array($table))) {
363
+		if ($schema->tablesExist(array($table))) {
364 364
 			$schema->dropTable($table);
365 365
 		}
366 366
 	}
@@ -371,8 +371,8 @@  discard block
 block discarded – undo
371 371
 	 * @param string $table table name without the prefix
372 372
 	 * @return bool
373 373
 	 */
374
-	public function tableExists($table){
375
-		$table = $this->tablePrefix . trim($table);
374
+	public function tableExists($table) {
375
+		$table = $this->tablePrefix.trim($table);
376 376
 		$schema = $this->getSchemaManager();
377 377
 		return $schema->tablesExist(array($table));
378 378
 	}
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
 	 * @return string
384 384
 	 */
385 385
 	protected function replaceTablePrefix($statement) {
386
-		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
386
+		return str_replace('*PREFIX*', $this->tablePrefix, $statement);
387 387
 	}
388 388
 
389 389
 	/**
Please login to merge, or discard this patch.
Indentation   +401 added lines, -401 removed lines patch added patch discarded remove patch
@@ -42,405 +42,405 @@
 block discarded – undo
42 42
 use OCP\PreConditionNotMetException;
43 43
 
44 44
 class Connection extends \Doctrine\DBAL\Connection implements IDBConnection {
45
-	/**
46
-	 * @var string $tablePrefix
47
-	 */
48
-	protected $tablePrefix;
49
-
50
-	/**
51
-	 * @var \OC\DB\Adapter $adapter
52
-	 */
53
-	protected $adapter;
54
-
55
-	protected $lockedTable = null;
56
-
57
-	public function connect() {
58
-		try {
59
-			return parent::connect();
60
-		} catch (DBALException $e) {
61
-			// throw a new exception to prevent leaking info from the stacktrace
62
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
63
-		}
64
-	}
65
-
66
-	/**
67
-	 * Returns a QueryBuilder for the connection.
68
-	 *
69
-	 * @return \OCP\DB\QueryBuilder\IQueryBuilder
70
-	 */
71
-	public function getQueryBuilder() {
72
-		return new QueryBuilder(
73
-			$this,
74
-			\OC::$server->getSystemConfig(),
75
-			\OC::$server->getLogger()
76
-		);
77
-	}
78
-
79
-	/**
80
-	 * Gets the QueryBuilder for the connection.
81
-	 *
82
-	 * @return \Doctrine\DBAL\Query\QueryBuilder
83
-	 * @deprecated please use $this->getQueryBuilder() instead
84
-	 */
85
-	public function createQueryBuilder() {
86
-		$backtrace = $this->getCallerBacktrace();
87
-		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
88
-		return parent::createQueryBuilder();
89
-	}
90
-
91
-	/**
92
-	 * Gets the ExpressionBuilder for the connection.
93
-	 *
94
-	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
95
-	 * @deprecated please use $this->getQueryBuilder()->expr() instead
96
-	 */
97
-	public function getExpressionBuilder() {
98
-		$backtrace = $this->getCallerBacktrace();
99
-		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
100
-		return parent::getExpressionBuilder();
101
-	}
102
-
103
-	/**
104
-	 * Get the file and line that called the method where `getCallerBacktrace()` was used
105
-	 *
106
-	 * @return string
107
-	 */
108
-	protected function getCallerBacktrace() {
109
-		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
110
-
111
-		// 0 is the method where we use `getCallerBacktrace`
112
-		// 1 is the target method which uses the method we want to log
113
-		if (isset($traces[1])) {
114
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
115
-		}
116
-
117
-		return '';
118
-	}
119
-
120
-	/**
121
-	 * @return string
122
-	 */
123
-	public function getPrefix() {
124
-		return $this->tablePrefix;
125
-	}
126
-
127
-	/**
128
-	 * Initializes a new instance of the Connection class.
129
-	 *
130
-	 * @param array $params  The connection parameters.
131
-	 * @param \Doctrine\DBAL\Driver $driver
132
-	 * @param \Doctrine\DBAL\Configuration $config
133
-	 * @param \Doctrine\Common\EventManager $eventManager
134
-	 * @throws \Exception
135
-	 */
136
-	public function __construct(array $params, Driver $driver, Configuration $config = null,
137
-		EventManager $eventManager = null)
138
-	{
139
-		if (!isset($params['adapter'])) {
140
-			throw new \Exception('adapter not set');
141
-		}
142
-		if (!isset($params['tablePrefix'])) {
143
-			throw new \Exception('tablePrefix not set');
144
-		}
145
-		parent::__construct($params, $driver, $config, $eventManager);
146
-		$this->adapter = new $params['adapter']($this);
147
-		$this->tablePrefix = $params['tablePrefix'];
148
-
149
-		parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
150
-	}
151
-
152
-	/**
153
-	 * Prepares an SQL statement.
154
-	 *
155
-	 * @param string $statement The SQL statement to prepare.
156
-	 * @param int $limit
157
-	 * @param int $offset
158
-	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
159
-	 */
160
-	public function prepare( $statement, $limit=null, $offset=null ) {
161
-		if ($limit === -1) {
162
-			$limit = null;
163
-		}
164
-		if (!is_null($limit)) {
165
-			$platform = $this->getDatabasePlatform();
166
-			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
167
-		}
168
-		$statement = $this->replaceTablePrefix($statement);
169
-		$statement = $this->adapter->fixupStatement($statement);
170
-
171
-		return parent::prepare($statement);
172
-	}
173
-
174
-	/**
175
-	 * Executes an, optionally parametrized, SQL query.
176
-	 *
177
-	 * If the query is parametrized, a prepared statement is used.
178
-	 * If an SQLLogger is configured, the execution is logged.
179
-	 *
180
-	 * @param string                                      $query  The SQL query to execute.
181
-	 * @param array                                       $params The parameters to bind to the query, if any.
182
-	 * @param array                                       $types  The types the previous parameters are in.
183
-	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
184
-	 *
185
-	 * @return \Doctrine\DBAL\Driver\Statement The executed statement.
186
-	 *
187
-	 * @throws \Doctrine\DBAL\DBALException
188
-	 */
189
-	public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
190
-	{
191
-		$query = $this->replaceTablePrefix($query);
192
-		$query = $this->adapter->fixupStatement($query);
193
-		return parent::executeQuery($query, $params, $types, $qcp);
194
-	}
195
-
196
-	/**
197
-	 * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
198
-	 * and returns the number of affected rows.
199
-	 *
200
-	 * This method supports PDO binding types as well as DBAL mapping types.
201
-	 *
202
-	 * @param string $query  The SQL query.
203
-	 * @param array  $params The query parameters.
204
-	 * @param array  $types  The parameter types.
205
-	 *
206
-	 * @return integer The number of affected rows.
207
-	 *
208
-	 * @throws \Doctrine\DBAL\DBALException
209
-	 */
210
-	public function executeUpdate($query, array $params = array(), array $types = array())
211
-	{
212
-		$query = $this->replaceTablePrefix($query);
213
-		$query = $this->adapter->fixupStatement($query);
214
-		return parent::executeUpdate($query, $params, $types);
215
-	}
216
-
217
-	/**
218
-	 * Returns the ID of the last inserted row, or the last value from a sequence object,
219
-	 * depending on the underlying driver.
220
-	 *
221
-	 * Note: This method may not return a meaningful or consistent result across different drivers,
222
-	 * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
223
-	 * columns or sequences.
224
-	 *
225
-	 * @param string $seqName Name of the sequence object from which the ID should be returned.
226
-	 * @return string A string representation of the last inserted ID.
227
-	 */
228
-	public function lastInsertId($seqName = null) {
229
-		if ($seqName) {
230
-			$seqName = $this->replaceTablePrefix($seqName);
231
-		}
232
-		return $this->adapter->lastInsertId($seqName);
233
-	}
234
-
235
-	// internal use
236
-	public function realLastInsertId($seqName = null) {
237
-		return parent::lastInsertId($seqName);
238
-	}
239
-
240
-	/**
241
-	 * Insert a row if the matching row does not exists.
242
-	 *
243
-	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
244
-	 * @param array $input data that should be inserted into the table  (column name => value)
245
-	 * @param array|null $compare List of values that should be checked for "if not exists"
246
-	 *				If this is null or an empty array, all keys of $input will be compared
247
-	 *				Please note: text fields (clob) must not be used in the compare array
248
-	 * @return int number of inserted rows
249
-	 * @throws \Doctrine\DBAL\DBALException
250
-	 */
251
-	public function insertIfNotExist($table, $input, array $compare = null) {
252
-		return $this->adapter->insertIfNotExist($table, $input, $compare);
253
-	}
254
-
255
-	private function getType($value) {
256
-		if (is_bool($value)) {
257
-			return IQueryBuilder::PARAM_BOOL;
258
-		} else if (is_int($value)) {
259
-			return IQueryBuilder::PARAM_INT;
260
-		} else {
261
-			return IQueryBuilder::PARAM_STR;
262
-		}
263
-	}
264
-
265
-	/**
266
-	 * Insert or update a row value
267
-	 *
268
-	 * @param string $table
269
-	 * @param array $keys (column name => value)
270
-	 * @param array $values (column name => value)
271
-	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
272
-	 * @return int number of new rows
273
-	 * @throws \Doctrine\DBAL\DBALException
274
-	 * @throws PreConditionNotMetException
275
-	 * @suppress SqlInjectionChecker
276
-	 */
277
-	public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
278
-		try {
279
-			$insertQb = $this->getQueryBuilder();
280
-			$insertQb->insert($table)
281
-				->values(
282
-					array_map(function($value) use ($insertQb) {
283
-						return $insertQb->createNamedParameter($value, $this->getType($value));
284
-					}, array_merge($keys, $values))
285
-				);
286
-			return $insertQb->execute();
287
-		} catch (ConstraintViolationException $e) {
288
-			// value already exists, try update
289
-			$updateQb = $this->getQueryBuilder();
290
-			$updateQb->update($table);
291
-			foreach ($values as $name => $value) {
292
-				$updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
293
-			}
294
-			$where = $updateQb->expr()->andX();
295
-			$whereValues = array_merge($keys, $updatePreconditionValues);
296
-			foreach ($whereValues as $name => $value) {
297
-				$where->add($updateQb->expr()->eq(
298
-					$name,
299
-					$updateQb->createNamedParameter($value, $this->getType($value)),
300
-					$this->getType($value)
301
-				));
302
-			}
303
-			$updateQb->where($where);
304
-			$affected = $updateQb->execute();
305
-
306
-			if ($affected === 0 && !empty($updatePreconditionValues)) {
307
-				throw new PreConditionNotMetException();
308
-			}
309
-
310
-			return 0;
311
-		}
312
-	}
313
-
314
-	/**
315
-	 * Create an exclusive read+write lock on a table
316
-	 *
317
-	 * @param string $tableName
318
-	 * @throws \BadMethodCallException When trying to acquire a second lock
319
-	 * @since 9.1.0
320
-	 */
321
-	public function lockTable($tableName) {
322
-		if ($this->lockedTable !== null) {
323
-			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
324
-		}
325
-
326
-		$tableName = $this->tablePrefix . $tableName;
327
-		$this->lockedTable = $tableName;
328
-		$this->adapter->lockTable($tableName);
329
-	}
330
-
331
-	/**
332
-	 * Release a previous acquired lock again
333
-	 *
334
-	 * @since 9.1.0
335
-	 */
336
-	public function unlockTable() {
337
-		$this->adapter->unlockTable();
338
-		$this->lockedTable = null;
339
-	}
340
-
341
-	/**
342
-	 * returns the error code and message as a string for logging
343
-	 * works with DoctrineException
344
-	 * @return string
345
-	 */
346
-	public function getError() {
347
-		$msg = $this->errorCode() . ': ';
348
-		$errorInfo = $this->errorInfo();
349
-		if (is_array($errorInfo)) {
350
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
351
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
352
-			$msg .= 'Driver Message = '.$errorInfo[2];
353
-		}
354
-		return $msg;
355
-	}
356
-
357
-	/**
358
-	 * Drop a table from the database if it exists
359
-	 *
360
-	 * @param string $table table name without the prefix
361
-	 */
362
-	public function dropTable($table) {
363
-		$table = $this->tablePrefix . trim($table);
364
-		$schema = $this->getSchemaManager();
365
-		if($schema->tablesExist(array($table))) {
366
-			$schema->dropTable($table);
367
-		}
368
-	}
369
-
370
-	/**
371
-	 * Check if a table exists
372
-	 *
373
-	 * @param string $table table name without the prefix
374
-	 * @return bool
375
-	 */
376
-	public function tableExists($table){
377
-		$table = $this->tablePrefix . trim($table);
378
-		$schema = $this->getSchemaManager();
379
-		return $schema->tablesExist(array($table));
380
-	}
381
-
382
-	// internal use
383
-	/**
384
-	 * @param string $statement
385
-	 * @return string
386
-	 */
387
-	protected function replaceTablePrefix($statement) {
388
-		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
389
-	}
390
-
391
-	/**
392
-	 * Check if a transaction is active
393
-	 *
394
-	 * @return bool
395
-	 * @since 8.2.0
396
-	 */
397
-	public function inTransaction() {
398
-		return $this->getTransactionNestingLevel() > 0;
399
-	}
400
-
401
-	/**
402
-	 * Espace a parameter to be used in a LIKE query
403
-	 *
404
-	 * @param string $param
405
-	 * @return string
406
-	 */
407
-	public function escapeLikeParameter($param) {
408
-		return addcslashes($param, '\\_%');
409
-	}
410
-
411
-	/**
412
-	 * Check whether or not the current database support 4byte wide unicode
413
-	 *
414
-	 * @return bool
415
-	 * @since 11.0.0
416
-	 */
417
-	public function supports4ByteText() {
418
-		if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
419
-			return true;
420
-		}
421
-		return $this->getParams()['charset'] === 'utf8mb4';
422
-	}
423
-
424
-
425
-	/**
426
-	 * Create the schema of the connected database
427
-	 *
428
-	 * @return Schema
429
-	 */
430
-	public function createSchema() {
431
-		$schemaManager = new MDB2SchemaManager($this);
432
-		$migrator = $schemaManager->getMigrator();
433
-		return $migrator->createSchema();
434
-	}
435
-
436
-	/**
437
-	 * Migrate the database to the given schema
438
-	 *
439
-	 * @param Schema $toSchema
440
-	 */
441
-	public function migrateToSchema(Schema $toSchema) {
442
-		$schemaManager = new MDB2SchemaManager($this);
443
-		$migrator = $schemaManager->getMigrator();
444
-		$migrator->migrate($toSchema);
445
-	}
45
+    /**
46
+     * @var string $tablePrefix
47
+     */
48
+    protected $tablePrefix;
49
+
50
+    /**
51
+     * @var \OC\DB\Adapter $adapter
52
+     */
53
+    protected $adapter;
54
+
55
+    protected $lockedTable = null;
56
+
57
+    public function connect() {
58
+        try {
59
+            return parent::connect();
60
+        } catch (DBALException $e) {
61
+            // throw a new exception to prevent leaking info from the stacktrace
62
+            throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
63
+        }
64
+    }
65
+
66
+    /**
67
+     * Returns a QueryBuilder for the connection.
68
+     *
69
+     * @return \OCP\DB\QueryBuilder\IQueryBuilder
70
+     */
71
+    public function getQueryBuilder() {
72
+        return new QueryBuilder(
73
+            $this,
74
+            \OC::$server->getSystemConfig(),
75
+            \OC::$server->getLogger()
76
+        );
77
+    }
78
+
79
+    /**
80
+     * Gets the QueryBuilder for the connection.
81
+     *
82
+     * @return \Doctrine\DBAL\Query\QueryBuilder
83
+     * @deprecated please use $this->getQueryBuilder() instead
84
+     */
85
+    public function createQueryBuilder() {
86
+        $backtrace = $this->getCallerBacktrace();
87
+        \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
88
+        return parent::createQueryBuilder();
89
+    }
90
+
91
+    /**
92
+     * Gets the ExpressionBuilder for the connection.
93
+     *
94
+     * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
95
+     * @deprecated please use $this->getQueryBuilder()->expr() instead
96
+     */
97
+    public function getExpressionBuilder() {
98
+        $backtrace = $this->getCallerBacktrace();
99
+        \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
100
+        return parent::getExpressionBuilder();
101
+    }
102
+
103
+    /**
104
+     * Get the file and line that called the method where `getCallerBacktrace()` was used
105
+     *
106
+     * @return string
107
+     */
108
+    protected function getCallerBacktrace() {
109
+        $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
110
+
111
+        // 0 is the method where we use `getCallerBacktrace`
112
+        // 1 is the target method which uses the method we want to log
113
+        if (isset($traces[1])) {
114
+            return $traces[1]['file'] . ':' . $traces[1]['line'];
115
+        }
116
+
117
+        return '';
118
+    }
119
+
120
+    /**
121
+     * @return string
122
+     */
123
+    public function getPrefix() {
124
+        return $this->tablePrefix;
125
+    }
126
+
127
+    /**
128
+     * Initializes a new instance of the Connection class.
129
+     *
130
+     * @param array $params  The connection parameters.
131
+     * @param \Doctrine\DBAL\Driver $driver
132
+     * @param \Doctrine\DBAL\Configuration $config
133
+     * @param \Doctrine\Common\EventManager $eventManager
134
+     * @throws \Exception
135
+     */
136
+    public function __construct(array $params, Driver $driver, Configuration $config = null,
137
+        EventManager $eventManager = null)
138
+    {
139
+        if (!isset($params['adapter'])) {
140
+            throw new \Exception('adapter not set');
141
+        }
142
+        if (!isset($params['tablePrefix'])) {
143
+            throw new \Exception('tablePrefix not set');
144
+        }
145
+        parent::__construct($params, $driver, $config, $eventManager);
146
+        $this->adapter = new $params['adapter']($this);
147
+        $this->tablePrefix = $params['tablePrefix'];
148
+
149
+        parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
150
+    }
151
+
152
+    /**
153
+     * Prepares an SQL statement.
154
+     *
155
+     * @param string $statement The SQL statement to prepare.
156
+     * @param int $limit
157
+     * @param int $offset
158
+     * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
159
+     */
160
+    public function prepare( $statement, $limit=null, $offset=null ) {
161
+        if ($limit === -1) {
162
+            $limit = null;
163
+        }
164
+        if (!is_null($limit)) {
165
+            $platform = $this->getDatabasePlatform();
166
+            $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
167
+        }
168
+        $statement = $this->replaceTablePrefix($statement);
169
+        $statement = $this->adapter->fixupStatement($statement);
170
+
171
+        return parent::prepare($statement);
172
+    }
173
+
174
+    /**
175
+     * Executes an, optionally parametrized, SQL query.
176
+     *
177
+     * If the query is parametrized, a prepared statement is used.
178
+     * If an SQLLogger is configured, the execution is logged.
179
+     *
180
+     * @param string                                      $query  The SQL query to execute.
181
+     * @param array                                       $params The parameters to bind to the query, if any.
182
+     * @param array                                       $types  The types the previous parameters are in.
183
+     * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
184
+     *
185
+     * @return \Doctrine\DBAL\Driver\Statement The executed statement.
186
+     *
187
+     * @throws \Doctrine\DBAL\DBALException
188
+     */
189
+    public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
190
+    {
191
+        $query = $this->replaceTablePrefix($query);
192
+        $query = $this->adapter->fixupStatement($query);
193
+        return parent::executeQuery($query, $params, $types, $qcp);
194
+    }
195
+
196
+    /**
197
+     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
198
+     * and returns the number of affected rows.
199
+     *
200
+     * This method supports PDO binding types as well as DBAL mapping types.
201
+     *
202
+     * @param string $query  The SQL query.
203
+     * @param array  $params The query parameters.
204
+     * @param array  $types  The parameter types.
205
+     *
206
+     * @return integer The number of affected rows.
207
+     *
208
+     * @throws \Doctrine\DBAL\DBALException
209
+     */
210
+    public function executeUpdate($query, array $params = array(), array $types = array())
211
+    {
212
+        $query = $this->replaceTablePrefix($query);
213
+        $query = $this->adapter->fixupStatement($query);
214
+        return parent::executeUpdate($query, $params, $types);
215
+    }
216
+
217
+    /**
218
+     * Returns the ID of the last inserted row, or the last value from a sequence object,
219
+     * depending on the underlying driver.
220
+     *
221
+     * Note: This method may not return a meaningful or consistent result across different drivers,
222
+     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
223
+     * columns or sequences.
224
+     *
225
+     * @param string $seqName Name of the sequence object from which the ID should be returned.
226
+     * @return string A string representation of the last inserted ID.
227
+     */
228
+    public function lastInsertId($seqName = null) {
229
+        if ($seqName) {
230
+            $seqName = $this->replaceTablePrefix($seqName);
231
+        }
232
+        return $this->adapter->lastInsertId($seqName);
233
+    }
234
+
235
+    // internal use
236
+    public function realLastInsertId($seqName = null) {
237
+        return parent::lastInsertId($seqName);
238
+    }
239
+
240
+    /**
241
+     * Insert a row if the matching row does not exists.
242
+     *
243
+     * @param string $table The table name (will replace *PREFIX* with the actual prefix)
244
+     * @param array $input data that should be inserted into the table  (column name => value)
245
+     * @param array|null $compare List of values that should be checked for "if not exists"
246
+     *				If this is null or an empty array, all keys of $input will be compared
247
+     *				Please note: text fields (clob) must not be used in the compare array
248
+     * @return int number of inserted rows
249
+     * @throws \Doctrine\DBAL\DBALException
250
+     */
251
+    public function insertIfNotExist($table, $input, array $compare = null) {
252
+        return $this->adapter->insertIfNotExist($table, $input, $compare);
253
+    }
254
+
255
+    private function getType($value) {
256
+        if (is_bool($value)) {
257
+            return IQueryBuilder::PARAM_BOOL;
258
+        } else if (is_int($value)) {
259
+            return IQueryBuilder::PARAM_INT;
260
+        } else {
261
+            return IQueryBuilder::PARAM_STR;
262
+        }
263
+    }
264
+
265
+    /**
266
+     * Insert or update a row value
267
+     *
268
+     * @param string $table
269
+     * @param array $keys (column name => value)
270
+     * @param array $values (column name => value)
271
+     * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
272
+     * @return int number of new rows
273
+     * @throws \Doctrine\DBAL\DBALException
274
+     * @throws PreConditionNotMetException
275
+     * @suppress SqlInjectionChecker
276
+     */
277
+    public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
278
+        try {
279
+            $insertQb = $this->getQueryBuilder();
280
+            $insertQb->insert($table)
281
+                ->values(
282
+                    array_map(function($value) use ($insertQb) {
283
+                        return $insertQb->createNamedParameter($value, $this->getType($value));
284
+                    }, array_merge($keys, $values))
285
+                );
286
+            return $insertQb->execute();
287
+        } catch (ConstraintViolationException $e) {
288
+            // value already exists, try update
289
+            $updateQb = $this->getQueryBuilder();
290
+            $updateQb->update($table);
291
+            foreach ($values as $name => $value) {
292
+                $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
293
+            }
294
+            $where = $updateQb->expr()->andX();
295
+            $whereValues = array_merge($keys, $updatePreconditionValues);
296
+            foreach ($whereValues as $name => $value) {
297
+                $where->add($updateQb->expr()->eq(
298
+                    $name,
299
+                    $updateQb->createNamedParameter($value, $this->getType($value)),
300
+                    $this->getType($value)
301
+                ));
302
+            }
303
+            $updateQb->where($where);
304
+            $affected = $updateQb->execute();
305
+
306
+            if ($affected === 0 && !empty($updatePreconditionValues)) {
307
+                throw new PreConditionNotMetException();
308
+            }
309
+
310
+            return 0;
311
+        }
312
+    }
313
+
314
+    /**
315
+     * Create an exclusive read+write lock on a table
316
+     *
317
+     * @param string $tableName
318
+     * @throws \BadMethodCallException When trying to acquire a second lock
319
+     * @since 9.1.0
320
+     */
321
+    public function lockTable($tableName) {
322
+        if ($this->lockedTable !== null) {
323
+            throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
324
+        }
325
+
326
+        $tableName = $this->tablePrefix . $tableName;
327
+        $this->lockedTable = $tableName;
328
+        $this->adapter->lockTable($tableName);
329
+    }
330
+
331
+    /**
332
+     * Release a previous acquired lock again
333
+     *
334
+     * @since 9.1.0
335
+     */
336
+    public function unlockTable() {
337
+        $this->adapter->unlockTable();
338
+        $this->lockedTable = null;
339
+    }
340
+
341
+    /**
342
+     * returns the error code and message as a string for logging
343
+     * works with DoctrineException
344
+     * @return string
345
+     */
346
+    public function getError() {
347
+        $msg = $this->errorCode() . ': ';
348
+        $errorInfo = $this->errorInfo();
349
+        if (is_array($errorInfo)) {
350
+            $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
351
+            $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
352
+            $msg .= 'Driver Message = '.$errorInfo[2];
353
+        }
354
+        return $msg;
355
+    }
356
+
357
+    /**
358
+     * Drop a table from the database if it exists
359
+     *
360
+     * @param string $table table name without the prefix
361
+     */
362
+    public function dropTable($table) {
363
+        $table = $this->tablePrefix . trim($table);
364
+        $schema = $this->getSchemaManager();
365
+        if($schema->tablesExist(array($table))) {
366
+            $schema->dropTable($table);
367
+        }
368
+    }
369
+
370
+    /**
371
+     * Check if a table exists
372
+     *
373
+     * @param string $table table name without the prefix
374
+     * @return bool
375
+     */
376
+    public function tableExists($table){
377
+        $table = $this->tablePrefix . trim($table);
378
+        $schema = $this->getSchemaManager();
379
+        return $schema->tablesExist(array($table));
380
+    }
381
+
382
+    // internal use
383
+    /**
384
+     * @param string $statement
385
+     * @return string
386
+     */
387
+    protected function replaceTablePrefix($statement) {
388
+        return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
389
+    }
390
+
391
+    /**
392
+     * Check if a transaction is active
393
+     *
394
+     * @return bool
395
+     * @since 8.2.0
396
+     */
397
+    public function inTransaction() {
398
+        return $this->getTransactionNestingLevel() > 0;
399
+    }
400
+
401
+    /**
402
+     * Espace a parameter to be used in a LIKE query
403
+     *
404
+     * @param string $param
405
+     * @return string
406
+     */
407
+    public function escapeLikeParameter($param) {
408
+        return addcslashes($param, '\\_%');
409
+    }
410
+
411
+    /**
412
+     * Check whether or not the current database support 4byte wide unicode
413
+     *
414
+     * @return bool
415
+     * @since 11.0.0
416
+     */
417
+    public function supports4ByteText() {
418
+        if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
419
+            return true;
420
+        }
421
+        return $this->getParams()['charset'] === 'utf8mb4';
422
+    }
423
+
424
+
425
+    /**
426
+     * Create the schema of the connected database
427
+     *
428
+     * @return Schema
429
+     */
430
+    public function createSchema() {
431
+        $schemaManager = new MDB2SchemaManager($this);
432
+        $migrator = $schemaManager->getMigrator();
433
+        return $migrator->createSchema();
434
+    }
435
+
436
+    /**
437
+     * Migrate the database to the given schema
438
+     *
439
+     * @param Schema $toSchema
440
+     */
441
+    public function migrateToSchema(Schema $toSchema) {
442
+        $schemaManager = new MDB2SchemaManager($this);
443
+        $migrator = $schemaManager->getMigrator();
444
+        $migrator->migrate($toSchema);
445
+    }
446 446
 }
Please login to merge, or discard this patch.
lib/private/Files/Cache/Scanner.php 3 patches
Doc Comments   +11 added lines patch added patch discarded remove patch
@@ -386,6 +386,14 @@  discard block
 block discarded – undo
386 386
 		return $size;
387 387
 	}
388 388
 
389
+	/**
390
+	 * @param string $path
391
+	 * @param boolean $recursive
392
+	 * @param integer $reuse
393
+	 * @param integer|null $folderId
394
+	 * @param boolean $lock
395
+	 * @param integer $size
396
+	 */
389 397
 	private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
390 398
 		// we put this in it's own function so it cleans up the memory before we start recursing
391 399
 		$existingChildren = $this->getExistingChildren($folderId);
@@ -485,6 +493,9 @@  discard block
 block discarded – undo
485 493
 		}
486 494
 	}
487 495
 
496
+	/**
497
+	 * @param string|boolean $path
498
+	 */
488 499
 	private function runBackgroundScanJob(callable $callback, $path) {
489 500
 		try {
490 501
 			$callback();
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
 		}
328 328
 		if ($lock) {
329 329
 			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
330
-				$this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
330
+				$this->storage->acquireLock('scanner::'.$path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
331 331
 				$this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
332 332
 			}
333 333
 		}
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 		if ($lock) {
340 340
 			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
341 341
 				$this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
342
-				$this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
342
+				$this->storage->releaseLock('scanner::'.$path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
343 343
 			}
344 344
 		}
345 345
 		return $data;
@@ -428,7 +428,7 @@  discard block
 block discarded – undo
428 428
 		$exceptionOccurred = false;
429 429
 		$childQueue = [];
430 430
 		foreach ($newChildren as $file) {
431
-			$child = $path ? $path . '/' . $file : $file;
431
+			$child = $path ? $path.'/'.$file : $file;
432 432
 			try {
433 433
 				$existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
434 434
 				$data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
@@ -453,7 +453,7 @@  discard block
 block discarded – undo
453 453
 					\OC::$server->getDatabaseConnection()->beginTransaction();
454 454
 				}
455 455
 				\OC::$server->getLogger()->logException($ex, [
456
-					'message' => 'Exception while scanning file "' . $child . '"',
456
+					'message' => 'Exception while scanning file "'.$child.'"',
457 457
 					'level' => \OCP\Util::DEBUG,
458 458
 					'app' => 'core',
459 459
 				]);
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
 		}
468 468
 		$removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
469 469
 		foreach ($removedChildren as $childName) {
470
-			$child = $path ? $path . '/' . $childName : $childName;
470
+			$child = $path ? $path.'/'.$childName : $childName;
471 471
 			$this->removeFromCache($child);
472 472
 		}
473 473
 		if ($this->useTransactions) {
@@ -507,13 +507,13 @@  discard block
 block discarded – undo
507 507
 	 */
508 508
 	public function backgroundScan() {
509 509
 		if (!$this->cache->inCache('')) {
510
-			$this->runBackgroundScanJob(function () {
510
+			$this->runBackgroundScanJob(function() {
511 511
 				$this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
512 512
 			}, '');
513 513
 		} else {
514 514
 			$lastPath = null;
515 515
 			while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
516
-				$this->runBackgroundScanJob(function () use ($path) {
516
+				$this->runBackgroundScanJob(function() use ($path) {
517 517
 					$this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
518 518
 				}, $path);
519 519
 				// FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
Please login to merge, or discard this patch.
Indentation   +497 added lines, -497 removed lines patch added patch discarded remove patch
@@ -52,501 +52,501 @@
 block discarded – undo
52 52
  * @package OC\Files\Cache
53 53
  */
54 54
 class Scanner extends BasicEmitter implements IScanner {
55
-	/**
56
-	 * @var \OC\Files\Storage\Storage $storage
57
-	 */
58
-	protected $storage;
59
-
60
-	/**
61
-	 * @var string $storageId
62
-	 */
63
-	protected $storageId;
64
-
65
-	/**
66
-	 * @var \OC\Files\Cache\Cache $cache
67
-	 */
68
-	protected $cache;
69
-
70
-	/**
71
-	 * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache
72
-	 */
73
-	protected $cacheActive;
74
-
75
-	/**
76
-	 * @var bool $useTransactions whether to use transactions
77
-	 */
78
-	protected $useTransactions = true;
79
-
80
-	/**
81
-	 * @var \OCP\Lock\ILockingProvider
82
-	 */
83
-	protected $lockingProvider;
84
-
85
-	public function __construct(\OC\Files\Storage\Storage $storage) {
86
-		$this->storage = $storage;
87
-		$this->storageId = $this->storage->getId();
88
-		$this->cache = $storage->getCache();
89
-		$this->cacheActive = !\OC::$server->getConfig()->getSystemValue('filesystem_cache_readonly', false);
90
-		$this->lockingProvider = \OC::$server->getLockingProvider();
91
-	}
92
-
93
-	/**
94
-	 * Whether to wrap the scanning of a folder in a database transaction
95
-	 * On default transactions are used
96
-	 *
97
-	 * @param bool $useTransactions
98
-	 */
99
-	public function setUseTransactions($useTransactions) {
100
-		$this->useTransactions = $useTransactions;
101
-	}
102
-
103
-	/**
104
-	 * get all the metadata of a file or folder
105
-	 * *
106
-	 *
107
-	 * @param string $path
108
-	 * @return array an array of metadata of the file
109
-	 */
110
-	protected function getData($path) {
111
-		$data = $this->storage->getMetaData($path);
112
-		if (is_null($data)) {
113
-			\OCP\Util::writeLog(Scanner::class, "!!! Path '$path' is not accessible or present !!!", \OCP\Util::DEBUG);
114
-		}
115
-		return $data;
116
-	}
117
-
118
-	/**
119
-	 * scan a single file and store it in the cache
120
-	 *
121
-	 * @param string $file
122
-	 * @param int $reuseExisting
123
-	 * @param int $parentId
124
-	 * @param array | null $cacheData existing data in the cache for the file to be scanned
125
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
126
-	 * @return array an array of metadata of the scanned file
127
-	 * @throws \OC\ServerNotAvailableException
128
-	 * @throws \OCP\Lock\LockedException
129
-	 */
130
-	public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
131
-		if ($file !== '') {
132
-			try {
133
-				$this->storage->verifyPath(dirname($file), basename($file));
134
-			} catch (\Exception $e) {
135
-				return null;
136
-			}
137
-		}
138
-		// only proceed if $file is not a partial file nor a blacklisted file
139
-		if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) {
140
-
141
-			//acquire a lock
142
-			if ($lock) {
143
-				if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
144
-					$this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
145
-				}
146
-			}
147
-
148
-			try {
149
-				$data = $this->getData($file);
150
-			} catch (ForbiddenException $e) {
151
-				if ($lock) {
152
-					if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
153
-						$this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
154
-					}
155
-				}
156
-
157
-				return null;
158
-			}
159
-
160
-			try {
161
-				if ($data) {
162
-
163
-					// pre-emit only if it was a file. By that we avoid counting/treating folders as files
164
-					if ($data['mimetype'] !== 'httpd/unix-directory') {
165
-						$this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId));
166
-						\OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId));
167
-					}
168
-
169
-					$parent = dirname($file);
170
-					if ($parent === '.' or $parent === '/') {
171
-						$parent = '';
172
-					}
173
-					if ($parentId === -1) {
174
-						$parentId = $this->cache->getParentId($file);
175
-					}
176
-
177
-					// scan the parent if it's not in the cache (id -1) and the current file is not the root folder
178
-					if ($file and $parentId === -1) {
179
-						$parentData = $this->scanFile($parent);
180
-						if (!$parentData) {
181
-							return null;
182
-						}
183
-						$parentId = $parentData['fileid'];
184
-					}
185
-					if ($parent) {
186
-						$data['parent'] = $parentId;
187
-					}
188
-					if (is_null($cacheData)) {
189
-						/** @var CacheEntry $cacheData */
190
-						$cacheData = $this->cache->get($file);
191
-					}
192
-					if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) {
193
-						// prevent empty etag
194
-						if (empty($cacheData['etag'])) {
195
-							$etag = $data['etag'];
196
-						} else {
197
-							$etag = $cacheData['etag'];
198
-						}
199
-						$fileId = $cacheData['fileid'];
200
-						$data['fileid'] = $fileId;
201
-						// only reuse data if the file hasn't explicitly changed
202
-						if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) {
203
-							$data['mtime'] = $cacheData['mtime'];
204
-							if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) {
205
-								$data['size'] = $cacheData['size'];
206
-							}
207
-							if ($reuseExisting & self::REUSE_ETAG) {
208
-								$data['etag'] = $etag;
209
-							}
210
-						}
211
-						// Only update metadata that has changed
212
-						$newData = array_diff_assoc($data, $cacheData->getData());
213
-					} else {
214
-						$newData = $data;
215
-						$fileId = -1;
216
-					}
217
-					if (!empty($newData)) {
218
-						// Reset the checksum if the data has changed
219
-						$newData['checksum'] = '';
220
-						$data['fileid'] = $this->addToCache($file, $newData, $fileId);
221
-					}
222
-					if (isset($cacheData['size'])) {
223
-						$data['oldSize'] = $cacheData['size'];
224
-					} else {
225
-						$data['oldSize'] = 0;
226
-					}
227
-
228
-					if (isset($cacheData['encrypted'])) {
229
-						$data['encrypted'] = $cacheData['encrypted'];
230
-					}
231
-
232
-					// post-emit only if it was a file. By that we avoid counting/treating folders as files
233
-					if ($data['mimetype'] !== 'httpd/unix-directory') {
234
-						$this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId));
235
-						\OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId));
236
-					}
237
-
238
-				} else {
239
-					$this->removeFromCache($file);
240
-				}
241
-			} catch (\Exception $e) {
242
-				if ($lock) {
243
-					if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
244
-						$this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
245
-					}
246
-				}
247
-				throw $e;
248
-			}
249
-
250
-			//release the acquired lock
251
-			if ($lock) {
252
-				if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
253
-					$this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
254
-				}
255
-			}
256
-
257
-			if ($data && !isset($data['encrypted'])) {
258
-				$data['encrypted'] = false;
259
-			}
260
-			return $data;
261
-		}
262
-
263
-		return null;
264
-	}
265
-
266
-	protected function removeFromCache($path) {
267
-		\OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path));
268
-		$this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path));
269
-		if ($this->cacheActive) {
270
-			$this->cache->remove($path);
271
-		}
272
-	}
273
-
274
-	/**
275
-	 * @param string $path
276
-	 * @param array $data
277
-	 * @param int $fileId
278
-	 * @return int the id of the added file
279
-	 */
280
-	protected function addToCache($path, $data, $fileId = -1) {
281
-		if (isset($data['scan_permissions'])) {
282
-			$data['permissions'] = $data['scan_permissions'];
283
-		}
284
-		\OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
285
-		$this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data));
286
-		if ($this->cacheActive) {
287
-			if ($fileId !== -1) {
288
-				$this->cache->update($fileId, $data);
289
-				return $fileId;
290
-			} else {
291
-				return $this->cache->put($path, $data);
292
-			}
293
-		} else {
294
-			return -1;
295
-		}
296
-	}
297
-
298
-	/**
299
-	 * @param string $path
300
-	 * @param array $data
301
-	 * @param int $fileId
302
-	 */
303
-	protected function updateCache($path, $data, $fileId = -1) {
304
-		\OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
305
-		$this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data));
306
-		if ($this->cacheActive) {
307
-			if ($fileId !== -1) {
308
-				$this->cache->update($fileId, $data);
309
-			} else {
310
-				$this->cache->put($path, $data);
311
-			}
312
-		}
313
-	}
314
-
315
-	/**
316
-	 * scan a folder and all it's children
317
-	 *
318
-	 * @param string $path
319
-	 * @param bool $recursive
320
-	 * @param int $reuse
321
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
322
-	 * @return array an array of the meta data of the scanned file or folder
323
-	 */
324
-	public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
325
-		if ($reuse === -1) {
326
-			$reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
327
-		}
328
-		if ($lock) {
329
-			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
330
-				$this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
331
-				$this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
332
-			}
333
-		}
334
-		$data = $this->scanFile($path, $reuse, -1, null, $lock);
335
-		if ($data and $data['mimetype'] === 'httpd/unix-directory') {
336
-			$size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock);
337
-			$data['size'] = $size;
338
-		}
339
-		if ($lock) {
340
-			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
341
-				$this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
342
-				$this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
343
-			}
344
-		}
345
-		return $data;
346
-	}
347
-
348
-	/**
349
-	 * Get the children currently in the cache
350
-	 *
351
-	 * @param int $folderId
352
-	 * @return array[]
353
-	 */
354
-	protected function getExistingChildren($folderId) {
355
-		$existingChildren = array();
356
-		$children = $this->cache->getFolderContentsById($folderId);
357
-		foreach ($children as $child) {
358
-			$existingChildren[$child['name']] = $child;
359
-		}
360
-		return $existingChildren;
361
-	}
362
-
363
-	/**
364
-	 * Get the children from the storage
365
-	 *
366
-	 * @param string $folder
367
-	 * @return string[]
368
-	 */
369
-	protected function getNewChildren($folder) {
370
-		$children = array();
371
-		if ($dh = $this->storage->opendir($folder)) {
372
-			if (is_resource($dh)) {
373
-				while (($file = readdir($dh)) !== false) {
374
-					if (!Filesystem::isIgnoredDir($file)) {
375
-						$children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/');
376
-					}
377
-				}
378
-			}
379
-		}
380
-		return $children;
381
-	}
382
-
383
-	/**
384
-	 * scan all the files and folders in a folder
385
-	 *
386
-	 * @param string $path
387
-	 * @param bool $recursive
388
-	 * @param int $reuse
389
-	 * @param int $folderId id for the folder to be scanned
390
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
391
-	 * @return int the size of the scanned folder or -1 if the size is unknown at this stage
392
-	 */
393
-	protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) {
394
-		if ($reuse === -1) {
395
-			$reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
396
-		}
397
-		$this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId));
398
-		$size = 0;
399
-		if (!is_null($folderId)) {
400
-			$folderId = $this->cache->getId($path);
401
-		}
402
-		$childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size);
403
-
404
-		foreach ($childQueue as $child => $childId) {
405
-			$childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock);
406
-			if ($childSize === -1) {
407
-				$size = -1;
408
-			} else if ($size !== -1) {
409
-				$size += $childSize;
410
-			}
411
-		}
412
-		if ($this->cacheActive) {
413
-			$this->cache->update($folderId, array('size' => $size));
414
-		}
415
-		$this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId));
416
-		return $size;
417
-	}
418
-
419
-	private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
420
-		// we put this in it's own function so it cleans up the memory before we start recursing
421
-		$existingChildren = $this->getExistingChildren($folderId);
422
-		$newChildren = $this->getNewChildren($path);
423
-
424
-		if ($this->useTransactions) {
425
-			\OC::$server->getDatabaseConnection()->beginTransaction();
426
-		}
427
-
428
-		$exceptionOccurred = false;
429
-		$childQueue = [];
430
-		foreach ($newChildren as $file) {
431
-			$child = $path ? $path . '/' . $file : $file;
432
-			try {
433
-				$existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
434
-				$data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
435
-				if ($data) {
436
-					if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) {
437
-						$childQueue[$child] = $data['fileid'];
438
-					} else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) {
439
-						// only recurse into folders which aren't fully scanned
440
-						$childQueue[$child] = $data['fileid'];
441
-					} else if ($data['size'] === -1) {
442
-						$size = -1;
443
-					} else if ($size !== -1) {
444
-						$size += $data['size'];
445
-					}
446
-				}
447
-			} catch (\Doctrine\DBAL\DBALException $ex) {
448
-				// might happen if inserting duplicate while a scanning
449
-				// process is running in parallel
450
-				// log and ignore
451
-				if ($this->useTransactions) {
452
-					\OC::$server->getDatabaseConnection()->rollback();
453
-					\OC::$server->getDatabaseConnection()->beginTransaction();
454
-				}
455
-				\OC::$server->getLogger()->logException($ex, [
456
-					'message' => 'Exception while scanning file "' . $child . '"',
457
-					'level' => \OCP\Util::DEBUG,
458
-					'app' => 'core',
459
-				]);
460
-				$exceptionOccurred = true;
461
-			} catch (\OCP\Lock\LockedException $e) {
462
-				if ($this->useTransactions) {
463
-					\OC::$server->getDatabaseConnection()->rollback();
464
-				}
465
-				throw $e;
466
-			}
467
-		}
468
-		$removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
469
-		foreach ($removedChildren as $childName) {
470
-			$child = $path ? $path . '/' . $childName : $childName;
471
-			$this->removeFromCache($child);
472
-		}
473
-		if ($this->useTransactions) {
474
-			\OC::$server->getDatabaseConnection()->commit();
475
-		}
476
-		if ($exceptionOccurred) {
477
-			// It might happen that the parallel scan process has already
478
-			// inserted mimetypes but those weren't available yet inside the transaction
479
-			// To make sure to have the updated mime types in such cases,
480
-			// we reload them here
481
-			\OC::$server->getMimeTypeLoader()->reset();
482
-		}
483
-		return $childQueue;
484
-	}
485
-
486
-	/**
487
-	 * check if the file should be ignored when scanning
488
-	 * NOTE: files with a '.part' extension are ignored as well!
489
-	 *       prevents unfinished put requests to be scanned
490
-	 *
491
-	 * @param string $file
492
-	 * @return boolean
493
-	 */
494
-	public static function isPartialFile($file) {
495
-		if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
496
-			return true;
497
-		}
498
-		if (strpos($file, '.part/') !== false) {
499
-			return true;
500
-		}
501
-
502
-		return false;
503
-	}
504
-
505
-	/**
506
-	 * walk over any folders that are not fully scanned yet and scan them
507
-	 */
508
-	public function backgroundScan() {
509
-		if (!$this->cache->inCache('')) {
510
-			$this->runBackgroundScanJob(function () {
511
-				$this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
512
-			}, '');
513
-		} else {
514
-			$lastPath = null;
515
-			while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
516
-				$this->runBackgroundScanJob(function () use ($path) {
517
-					$this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
518
-				}, $path);
519
-				// FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
520
-				// to make this possible
521
-				$lastPath = $path;
522
-			}
523
-		}
524
-	}
525
-
526
-	private function runBackgroundScanJob(callable $callback, $path) {
527
-		try {
528
-			$callback();
529
-			\OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path));
530
-			if ($this->cacheActive && $this->cache instanceof Cache) {
531
-				$this->cache->correctFolderSize($path);
532
-			}
533
-		} catch (\OCP\Files\StorageInvalidException $e) {
534
-			// skip unavailable storages
535
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
536
-			// skip unavailable storages
537
-		} catch (\OCP\Files\ForbiddenException $e) {
538
-			// skip forbidden storages
539
-		} catch (\OCP\Lock\LockedException $e) {
540
-			// skip unavailable storages
541
-		}
542
-	}
543
-
544
-	/**
545
-	 * Set whether the cache is affected by scan operations
546
-	 *
547
-	 * @param boolean $active The active state of the cache
548
-	 */
549
-	public function setCacheActive($active) {
550
-		$this->cacheActive = $active;
551
-	}
55
+    /**
56
+     * @var \OC\Files\Storage\Storage $storage
57
+     */
58
+    protected $storage;
59
+
60
+    /**
61
+     * @var string $storageId
62
+     */
63
+    protected $storageId;
64
+
65
+    /**
66
+     * @var \OC\Files\Cache\Cache $cache
67
+     */
68
+    protected $cache;
69
+
70
+    /**
71
+     * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache
72
+     */
73
+    protected $cacheActive;
74
+
75
+    /**
76
+     * @var bool $useTransactions whether to use transactions
77
+     */
78
+    protected $useTransactions = true;
79
+
80
+    /**
81
+     * @var \OCP\Lock\ILockingProvider
82
+     */
83
+    protected $lockingProvider;
84
+
85
+    public function __construct(\OC\Files\Storage\Storage $storage) {
86
+        $this->storage = $storage;
87
+        $this->storageId = $this->storage->getId();
88
+        $this->cache = $storage->getCache();
89
+        $this->cacheActive = !\OC::$server->getConfig()->getSystemValue('filesystem_cache_readonly', false);
90
+        $this->lockingProvider = \OC::$server->getLockingProvider();
91
+    }
92
+
93
+    /**
94
+     * Whether to wrap the scanning of a folder in a database transaction
95
+     * On default transactions are used
96
+     *
97
+     * @param bool $useTransactions
98
+     */
99
+    public function setUseTransactions($useTransactions) {
100
+        $this->useTransactions = $useTransactions;
101
+    }
102
+
103
+    /**
104
+     * get all the metadata of a file or folder
105
+     * *
106
+     *
107
+     * @param string $path
108
+     * @return array an array of metadata of the file
109
+     */
110
+    protected function getData($path) {
111
+        $data = $this->storage->getMetaData($path);
112
+        if (is_null($data)) {
113
+            \OCP\Util::writeLog(Scanner::class, "!!! Path '$path' is not accessible or present !!!", \OCP\Util::DEBUG);
114
+        }
115
+        return $data;
116
+    }
117
+
118
+    /**
119
+     * scan a single file and store it in the cache
120
+     *
121
+     * @param string $file
122
+     * @param int $reuseExisting
123
+     * @param int $parentId
124
+     * @param array | null $cacheData existing data in the cache for the file to be scanned
125
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
126
+     * @return array an array of metadata of the scanned file
127
+     * @throws \OC\ServerNotAvailableException
128
+     * @throws \OCP\Lock\LockedException
129
+     */
130
+    public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
131
+        if ($file !== '') {
132
+            try {
133
+                $this->storage->verifyPath(dirname($file), basename($file));
134
+            } catch (\Exception $e) {
135
+                return null;
136
+            }
137
+        }
138
+        // only proceed if $file is not a partial file nor a blacklisted file
139
+        if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) {
140
+
141
+            //acquire a lock
142
+            if ($lock) {
143
+                if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
144
+                    $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
145
+                }
146
+            }
147
+
148
+            try {
149
+                $data = $this->getData($file);
150
+            } catch (ForbiddenException $e) {
151
+                if ($lock) {
152
+                    if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
153
+                        $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
154
+                    }
155
+                }
156
+
157
+                return null;
158
+            }
159
+
160
+            try {
161
+                if ($data) {
162
+
163
+                    // pre-emit only if it was a file. By that we avoid counting/treating folders as files
164
+                    if ($data['mimetype'] !== 'httpd/unix-directory') {
165
+                        $this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId));
166
+                        \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId));
167
+                    }
168
+
169
+                    $parent = dirname($file);
170
+                    if ($parent === '.' or $parent === '/') {
171
+                        $parent = '';
172
+                    }
173
+                    if ($parentId === -1) {
174
+                        $parentId = $this->cache->getParentId($file);
175
+                    }
176
+
177
+                    // scan the parent if it's not in the cache (id -1) and the current file is not the root folder
178
+                    if ($file and $parentId === -1) {
179
+                        $parentData = $this->scanFile($parent);
180
+                        if (!$parentData) {
181
+                            return null;
182
+                        }
183
+                        $parentId = $parentData['fileid'];
184
+                    }
185
+                    if ($parent) {
186
+                        $data['parent'] = $parentId;
187
+                    }
188
+                    if (is_null($cacheData)) {
189
+                        /** @var CacheEntry $cacheData */
190
+                        $cacheData = $this->cache->get($file);
191
+                    }
192
+                    if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) {
193
+                        // prevent empty etag
194
+                        if (empty($cacheData['etag'])) {
195
+                            $etag = $data['etag'];
196
+                        } else {
197
+                            $etag = $cacheData['etag'];
198
+                        }
199
+                        $fileId = $cacheData['fileid'];
200
+                        $data['fileid'] = $fileId;
201
+                        // only reuse data if the file hasn't explicitly changed
202
+                        if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) {
203
+                            $data['mtime'] = $cacheData['mtime'];
204
+                            if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) {
205
+                                $data['size'] = $cacheData['size'];
206
+                            }
207
+                            if ($reuseExisting & self::REUSE_ETAG) {
208
+                                $data['etag'] = $etag;
209
+                            }
210
+                        }
211
+                        // Only update metadata that has changed
212
+                        $newData = array_diff_assoc($data, $cacheData->getData());
213
+                    } else {
214
+                        $newData = $data;
215
+                        $fileId = -1;
216
+                    }
217
+                    if (!empty($newData)) {
218
+                        // Reset the checksum if the data has changed
219
+                        $newData['checksum'] = '';
220
+                        $data['fileid'] = $this->addToCache($file, $newData, $fileId);
221
+                    }
222
+                    if (isset($cacheData['size'])) {
223
+                        $data['oldSize'] = $cacheData['size'];
224
+                    } else {
225
+                        $data['oldSize'] = 0;
226
+                    }
227
+
228
+                    if (isset($cacheData['encrypted'])) {
229
+                        $data['encrypted'] = $cacheData['encrypted'];
230
+                    }
231
+
232
+                    // post-emit only if it was a file. By that we avoid counting/treating folders as files
233
+                    if ($data['mimetype'] !== 'httpd/unix-directory') {
234
+                        $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId));
235
+                        \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId));
236
+                    }
237
+
238
+                } else {
239
+                    $this->removeFromCache($file);
240
+                }
241
+            } catch (\Exception $e) {
242
+                if ($lock) {
243
+                    if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
244
+                        $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
245
+                    }
246
+                }
247
+                throw $e;
248
+            }
249
+
250
+            //release the acquired lock
251
+            if ($lock) {
252
+                if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
253
+                    $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
254
+                }
255
+            }
256
+
257
+            if ($data && !isset($data['encrypted'])) {
258
+                $data['encrypted'] = false;
259
+            }
260
+            return $data;
261
+        }
262
+
263
+        return null;
264
+    }
265
+
266
+    protected function removeFromCache($path) {
267
+        \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path));
268
+        $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path));
269
+        if ($this->cacheActive) {
270
+            $this->cache->remove($path);
271
+        }
272
+    }
273
+
274
+    /**
275
+     * @param string $path
276
+     * @param array $data
277
+     * @param int $fileId
278
+     * @return int the id of the added file
279
+     */
280
+    protected function addToCache($path, $data, $fileId = -1) {
281
+        if (isset($data['scan_permissions'])) {
282
+            $data['permissions'] = $data['scan_permissions'];
283
+        }
284
+        \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
285
+        $this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data));
286
+        if ($this->cacheActive) {
287
+            if ($fileId !== -1) {
288
+                $this->cache->update($fileId, $data);
289
+                return $fileId;
290
+            } else {
291
+                return $this->cache->put($path, $data);
292
+            }
293
+        } else {
294
+            return -1;
295
+        }
296
+    }
297
+
298
+    /**
299
+     * @param string $path
300
+     * @param array $data
301
+     * @param int $fileId
302
+     */
303
+    protected function updateCache($path, $data, $fileId = -1) {
304
+        \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
305
+        $this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data));
306
+        if ($this->cacheActive) {
307
+            if ($fileId !== -1) {
308
+                $this->cache->update($fileId, $data);
309
+            } else {
310
+                $this->cache->put($path, $data);
311
+            }
312
+        }
313
+    }
314
+
315
+    /**
316
+     * scan a folder and all it's children
317
+     *
318
+     * @param string $path
319
+     * @param bool $recursive
320
+     * @param int $reuse
321
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
322
+     * @return array an array of the meta data of the scanned file or folder
323
+     */
324
+    public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
325
+        if ($reuse === -1) {
326
+            $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
327
+        }
328
+        if ($lock) {
329
+            if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
330
+                $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
331
+                $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
332
+            }
333
+        }
334
+        $data = $this->scanFile($path, $reuse, -1, null, $lock);
335
+        if ($data and $data['mimetype'] === 'httpd/unix-directory') {
336
+            $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock);
337
+            $data['size'] = $size;
338
+        }
339
+        if ($lock) {
340
+            if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
341
+                $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
342
+                $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
343
+            }
344
+        }
345
+        return $data;
346
+    }
347
+
348
+    /**
349
+     * Get the children currently in the cache
350
+     *
351
+     * @param int $folderId
352
+     * @return array[]
353
+     */
354
+    protected function getExistingChildren($folderId) {
355
+        $existingChildren = array();
356
+        $children = $this->cache->getFolderContentsById($folderId);
357
+        foreach ($children as $child) {
358
+            $existingChildren[$child['name']] = $child;
359
+        }
360
+        return $existingChildren;
361
+    }
362
+
363
+    /**
364
+     * Get the children from the storage
365
+     *
366
+     * @param string $folder
367
+     * @return string[]
368
+     */
369
+    protected function getNewChildren($folder) {
370
+        $children = array();
371
+        if ($dh = $this->storage->opendir($folder)) {
372
+            if (is_resource($dh)) {
373
+                while (($file = readdir($dh)) !== false) {
374
+                    if (!Filesystem::isIgnoredDir($file)) {
375
+                        $children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/');
376
+                    }
377
+                }
378
+            }
379
+        }
380
+        return $children;
381
+    }
382
+
383
+    /**
384
+     * scan all the files and folders in a folder
385
+     *
386
+     * @param string $path
387
+     * @param bool $recursive
388
+     * @param int $reuse
389
+     * @param int $folderId id for the folder to be scanned
390
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
391
+     * @return int the size of the scanned folder or -1 if the size is unknown at this stage
392
+     */
393
+    protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) {
394
+        if ($reuse === -1) {
395
+            $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
396
+        }
397
+        $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId));
398
+        $size = 0;
399
+        if (!is_null($folderId)) {
400
+            $folderId = $this->cache->getId($path);
401
+        }
402
+        $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size);
403
+
404
+        foreach ($childQueue as $child => $childId) {
405
+            $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock);
406
+            if ($childSize === -1) {
407
+                $size = -1;
408
+            } else if ($size !== -1) {
409
+                $size += $childSize;
410
+            }
411
+        }
412
+        if ($this->cacheActive) {
413
+            $this->cache->update($folderId, array('size' => $size));
414
+        }
415
+        $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId));
416
+        return $size;
417
+    }
418
+
419
+    private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
420
+        // we put this in it's own function so it cleans up the memory before we start recursing
421
+        $existingChildren = $this->getExistingChildren($folderId);
422
+        $newChildren = $this->getNewChildren($path);
423
+
424
+        if ($this->useTransactions) {
425
+            \OC::$server->getDatabaseConnection()->beginTransaction();
426
+        }
427
+
428
+        $exceptionOccurred = false;
429
+        $childQueue = [];
430
+        foreach ($newChildren as $file) {
431
+            $child = $path ? $path . '/' . $file : $file;
432
+            try {
433
+                $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
434
+                $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
435
+                if ($data) {
436
+                    if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) {
437
+                        $childQueue[$child] = $data['fileid'];
438
+                    } else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) {
439
+                        // only recurse into folders which aren't fully scanned
440
+                        $childQueue[$child] = $data['fileid'];
441
+                    } else if ($data['size'] === -1) {
442
+                        $size = -1;
443
+                    } else if ($size !== -1) {
444
+                        $size += $data['size'];
445
+                    }
446
+                }
447
+            } catch (\Doctrine\DBAL\DBALException $ex) {
448
+                // might happen if inserting duplicate while a scanning
449
+                // process is running in parallel
450
+                // log and ignore
451
+                if ($this->useTransactions) {
452
+                    \OC::$server->getDatabaseConnection()->rollback();
453
+                    \OC::$server->getDatabaseConnection()->beginTransaction();
454
+                }
455
+                \OC::$server->getLogger()->logException($ex, [
456
+                    'message' => 'Exception while scanning file "' . $child . '"',
457
+                    'level' => \OCP\Util::DEBUG,
458
+                    'app' => 'core',
459
+                ]);
460
+                $exceptionOccurred = true;
461
+            } catch (\OCP\Lock\LockedException $e) {
462
+                if ($this->useTransactions) {
463
+                    \OC::$server->getDatabaseConnection()->rollback();
464
+                }
465
+                throw $e;
466
+            }
467
+        }
468
+        $removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
469
+        foreach ($removedChildren as $childName) {
470
+            $child = $path ? $path . '/' . $childName : $childName;
471
+            $this->removeFromCache($child);
472
+        }
473
+        if ($this->useTransactions) {
474
+            \OC::$server->getDatabaseConnection()->commit();
475
+        }
476
+        if ($exceptionOccurred) {
477
+            // It might happen that the parallel scan process has already
478
+            // inserted mimetypes but those weren't available yet inside the transaction
479
+            // To make sure to have the updated mime types in such cases,
480
+            // we reload them here
481
+            \OC::$server->getMimeTypeLoader()->reset();
482
+        }
483
+        return $childQueue;
484
+    }
485
+
486
+    /**
487
+     * check if the file should be ignored when scanning
488
+     * NOTE: files with a '.part' extension are ignored as well!
489
+     *       prevents unfinished put requests to be scanned
490
+     *
491
+     * @param string $file
492
+     * @return boolean
493
+     */
494
+    public static function isPartialFile($file) {
495
+        if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
496
+            return true;
497
+        }
498
+        if (strpos($file, '.part/') !== false) {
499
+            return true;
500
+        }
501
+
502
+        return false;
503
+    }
504
+
505
+    /**
506
+     * walk over any folders that are not fully scanned yet and scan them
507
+     */
508
+    public function backgroundScan() {
509
+        if (!$this->cache->inCache('')) {
510
+            $this->runBackgroundScanJob(function () {
511
+                $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
512
+            }, '');
513
+        } else {
514
+            $lastPath = null;
515
+            while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
516
+                $this->runBackgroundScanJob(function () use ($path) {
517
+                    $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
518
+                }, $path);
519
+                // FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
520
+                // to make this possible
521
+                $lastPath = $path;
522
+            }
523
+        }
524
+    }
525
+
526
+    private function runBackgroundScanJob(callable $callback, $path) {
527
+        try {
528
+            $callback();
529
+            \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path));
530
+            if ($this->cacheActive && $this->cache instanceof Cache) {
531
+                $this->cache->correctFolderSize($path);
532
+            }
533
+        } catch (\OCP\Files\StorageInvalidException $e) {
534
+            // skip unavailable storages
535
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
536
+            // skip unavailable storages
537
+        } catch (\OCP\Files\ForbiddenException $e) {
538
+            // skip forbidden storages
539
+        } catch (\OCP\Lock\LockedException $e) {
540
+            // skip unavailable storages
541
+        }
542
+    }
543
+
544
+    /**
545
+     * Set whether the cache is affected by scan operations
546
+     *
547
+     * @param boolean $active The active state of the cache
548
+     */
549
+    public function setCacheActive($active) {
550
+        $this->cacheActive = $active;
551
+    }
552 552
 }
Please login to merge, or discard this patch.
lib/private/Files/Config/UserMountCache.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -206,7 +206,7 @@
 block discarded – undo
206 206
 	}
207 207
 
208 208
 	/**
209
-	 * @param $fileId
209
+	 * @param integer $fileId
210 210
 	 * @return array
211 211
 	 * @throws \OCP\Files\NotFoundException
212 212
 	 */
Please login to merge, or discard this patch.
Indentation   +346 added lines, -346 removed lines patch added patch discarded remove patch
@@ -44,350 +44,350 @@
 block discarded – undo
44 44
  * Cache mounts points per user in the cache so we can easilly look them up
45 45
  */
46 46
 class UserMountCache implements IUserMountCache {
47
-	/**
48
-	 * @var IDBConnection
49
-	 */
50
-	private $connection;
51
-
52
-	/**
53
-	 * @var IUserManager
54
-	 */
55
-	private $userManager;
56
-
57
-	/**
58
-	 * Cached mount info.
59
-	 * Map of $userId to ICachedMountInfo.
60
-	 *
61
-	 * @var ICache
62
-	 **/
63
-	private $mountsForUsers;
64
-
65
-	/**
66
-	 * @var ILogger
67
-	 */
68
-	private $logger;
69
-
70
-	/**
71
-	 * @var ICache
72
-	 */
73
-	private $cacheInfoCache;
74
-
75
-	/**
76
-	 * UserMountCache constructor.
77
-	 *
78
-	 * @param IDBConnection $connection
79
-	 * @param IUserManager $userManager
80
-	 * @param ILogger $logger
81
-	 */
82
-	public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) {
83
-		$this->connection = $connection;
84
-		$this->userManager = $userManager;
85
-		$this->logger = $logger;
86
-		$this->cacheInfoCache = new CappedMemoryCache();
87
-		$this->mountsForUsers = new CappedMemoryCache();
88
-	}
89
-
90
-	public function registerMounts(IUser $user, array $mounts) {
91
-		// filter out non-proper storages coming from unit tests
92
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
93
-			return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache();
94
-		});
95
-		/** @var ICachedMountInfo[] $newMounts */
96
-		$newMounts = array_map(function (IMountPoint $mount) use ($user) {
97
-			// filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
98
-			if ($mount->getStorageRootId() === -1) {
99
-				return null;
100
-			} else {
101
-				return new LazyStorageMountInfo($user, $mount);
102
-			}
103
-		}, $mounts);
104
-		$newMounts = array_values(array_filter($newMounts));
105
-
106
-		$cachedMounts = $this->getMountsForUser($user);
107
-		$mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
108
-			// since we are only looking for mounts for a specific user comparing on root id is enough
109
-			return $mount1->getRootId() - $mount2->getRootId();
110
-		};
111
-
112
-		/** @var ICachedMountInfo[] $addedMounts */
113
-		$addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff);
114
-		/** @var ICachedMountInfo[] $removedMounts */
115
-		$removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff);
116
-
117
-		$changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
118
-
119
-		foreach ($addedMounts as $mount) {
120
-			$this->addToCache($mount);
121
-			$this->mountsForUsers[$user->getUID()][] = $mount;
122
-		}
123
-		foreach ($removedMounts as $mount) {
124
-			$this->removeFromCache($mount);
125
-			$index = array_search($mount, $this->mountsForUsers[$user->getUID()]);
126
-			unset($this->mountsForUsers[$user->getUID()][$index]);
127
-		}
128
-		foreach ($changedMounts as $mount) {
129
-			$this->updateCachedMount($mount);
130
-		}
131
-	}
132
-
133
-	/**
134
-	 * @param ICachedMountInfo[] $newMounts
135
-	 * @param ICachedMountInfo[] $cachedMounts
136
-	 * @return ICachedMountInfo[]
137
-	 */
138
-	private function findChangedMounts(array $newMounts, array $cachedMounts) {
139
-		$changed = [];
140
-		foreach ($newMounts as $newMount) {
141
-			foreach ($cachedMounts as $cachedMount) {
142
-				if (
143
-					$newMount->getRootId() === $cachedMount->getRootId() &&
144
-					(
145
-						$newMount->getMountPoint() !== $cachedMount->getMountPoint() ||
146
-						$newMount->getStorageId() !== $cachedMount->getStorageId() ||
147
-						$newMount->getMountId() !== $cachedMount->getMountId()
148
-					)
149
-				) {
150
-					$changed[] = $newMount;
151
-				}
152
-			}
153
-		}
154
-		return $changed;
155
-	}
156
-
157
-	private function addToCache(ICachedMountInfo $mount) {
158
-		if ($mount->getStorageId() !== -1) {
159
-			$this->connection->insertIfNotExist('*PREFIX*mounts', [
160
-				'storage_id' => $mount->getStorageId(),
161
-				'root_id' => $mount->getRootId(),
162
-				'user_id' => $mount->getUser()->getUID(),
163
-				'mount_point' => $mount->getMountPoint(),
164
-				'mount_id' => $mount->getMountId()
165
-			], ['root_id', 'user_id']);
166
-		} else {
167
-			// in some cases this is legitimate, like orphaned shares
168
-			$this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
169
-		}
170
-	}
171
-
172
-	private function updateCachedMount(ICachedMountInfo $mount) {
173
-		$builder = $this->connection->getQueryBuilder();
174
-
175
-		$query = $builder->update('mounts')
176
-			->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
177
-			->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
178
-			->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
179
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
180
-			->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
181
-
182
-		$query->execute();
183
-	}
184
-
185
-	private function removeFromCache(ICachedMountInfo $mount) {
186
-		$builder = $this->connection->getQueryBuilder();
187
-
188
-		$query = $builder->delete('mounts')
189
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
190
-			->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
191
-		$query->execute();
192
-	}
193
-
194
-	private function dbRowToMountInfo(array $row) {
195
-		$user = $this->userManager->get($row['user_id']);
196
-		if (is_null($user)) {
197
-			return null;
198
-		}
199
-		$mount_id = $row['mount_id'];
200
-		if (!is_null($mount_id)) {
201
-			$mount_id = (int) $mount_id;
202
-		}
203
-		return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : '');
204
-	}
205
-
206
-	/**
207
-	 * @param IUser $user
208
-	 * @return ICachedMountInfo[]
209
-	 */
210
-	public function getMountsForUser(IUser $user) {
211
-		if (!isset($this->mountsForUsers[$user->getUID()])) {
212
-			$builder = $this->connection->getQueryBuilder();
213
-			$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
214
-				->from('mounts', 'm')
215
-				->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
216
-				->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID())));
217
-
218
-			$rows = $query->execute()->fetchAll();
219
-
220
-			$this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
221
-		}
222
-		return $this->mountsForUsers[$user->getUID()];
223
-	}
224
-
225
-	/**
226
-	 * @param int $numericStorageId
227
-	 * @param string|null $user limit the results to a single user
228
-	 * @return CachedMountInfo[]
229
-	 */
230
-	public function getMountsForStorageId($numericStorageId, $user = null) {
231
-		$builder = $this->connection->getQueryBuilder();
232
-		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
233
-			->from('mounts', 'm')
234
-			->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
235
-			->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
236
-
237
-		if ($user) {
238
-			$query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
239
-		}
240
-
241
-		$rows = $query->execute()->fetchAll();
242
-
243
-		return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
244
-	}
245
-
246
-	/**
247
-	 * @param int $rootFileId
248
-	 * @return CachedMountInfo[]
249
-	 */
250
-	public function getMountsForRootId($rootFileId) {
251
-		$builder = $this->connection->getQueryBuilder();
252
-		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
253
-			->from('mounts', 'm')
254
-			->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
255
-			->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
256
-
257
-		$rows = $query->execute()->fetchAll();
258
-
259
-		return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
260
-	}
261
-
262
-	/**
263
-	 * @param $fileId
264
-	 * @return array
265
-	 * @throws \OCP\Files\NotFoundException
266
-	 */
267
-	private function getCacheInfoFromFileId($fileId) {
268
-		if (!isset($this->cacheInfoCache[$fileId])) {
269
-			$builder = $this->connection->getQueryBuilder();
270
-			$query = $builder->select('storage', 'path', 'mimetype')
271
-				->from('filecache')
272
-				->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
273
-
274
-			$row = $query->execute()->fetch();
275
-			if (is_array($row)) {
276
-				$this->cacheInfoCache[$fileId] = [
277
-					(int)$row['storage'],
278
-					$row['path'],
279
-					(int)$row['mimetype']
280
-				];
281
-			} else {
282
-				throw new NotFoundException('File with id "' . $fileId . '" not found');
283
-			}
284
-		}
285
-		return $this->cacheInfoCache[$fileId];
286
-	}
287
-
288
-	/**
289
-	 * @param int $fileId
290
-	 * @param string|null $user optionally restrict the results to a single user
291
-	 * @return ICachedMountFileInfo[]
292
-	 * @since 9.0.0
293
-	 */
294
-	public function getMountsForFileId($fileId, $user = null) {
295
-		try {
296
-			list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId);
297
-		} catch (NotFoundException $e) {
298
-			return [];
299
-		}
300
-		$mountsForStorage = $this->getMountsForStorageId($storageId, $user);
301
-
302
-		// filter mounts that are from the same storage but a different directory
303
-		$filteredMounts = array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
304
-			if ($fileId === $mount->getRootId()) {
305
-				return true;
306
-			}
307
-			$internalMountPath = $mount->getRootInternalPath();
308
-
309
-			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
310
-		});
311
-
312
-		return array_map(function (ICachedMountInfo $mount) use ($internalPath) {
313
-			return new CachedMountFileInfo(
314
-				$mount->getUser(),
315
-				$mount->getStorageId(),
316
-				$mount->getRootId(),
317
-				$mount->getMountPoint(),
318
-				$mount->getMountId(),
319
-				$mount->getRootInternalPath(),
320
-				$internalPath
321
-			);
322
-		}, $filteredMounts);
323
-	}
324
-
325
-	/**
326
-	 * Remove all cached mounts for a user
327
-	 *
328
-	 * @param IUser $user
329
-	 */
330
-	public function removeUserMounts(IUser $user) {
331
-		$builder = $this->connection->getQueryBuilder();
332
-
333
-		$query = $builder->delete('mounts')
334
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
335
-		$query->execute();
336
-	}
337
-
338
-	public function removeUserStorageMount($storageId, $userId) {
339
-		$builder = $this->connection->getQueryBuilder();
340
-
341
-		$query = $builder->delete('mounts')
342
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
343
-			->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
344
-		$query->execute();
345
-	}
346
-
347
-	public function remoteStorageMounts($storageId) {
348
-		$builder = $this->connection->getQueryBuilder();
349
-
350
-		$query = $builder->delete('mounts')
351
-			->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
352
-		$query->execute();
353
-	}
354
-
355
-	/**
356
-	 * @param array $users
357
-	 * @return array
358
-	 * @suppress SqlInjectionChecker
359
-	 */
360
-	public function getUsedSpaceForUsers(array $users) {
361
-		$builder = $this->connection->getQueryBuilder();
362
-
363
-		$slash = $builder->createNamedParameter('/');
364
-
365
-		$mountPoint = $builder->func()->concat(
366
-			$builder->func()->concat($slash, 'user_id'),
367
-			$slash
368
-		);
369
-
370
-		$userIds = array_map(function (IUser $user) {
371
-			return $user->getUID();
372
-		}, $users);
373
-
374
-		$query = $builder->select('m.user_id', 'f.size')
375
-			->from('mounts', 'm')
376
-			->innerJoin('m', 'filecache', 'f',
377
-				$builder->expr()->andX(
378
-					$builder->expr()->eq('m.storage_id', 'f.storage'),
379
-					$builder->expr()->eq('f.path', $builder->createNamedParameter('files'))
380
-				))
381
-			->where($builder->expr()->eq('m.mount_point', $mountPoint))
382
-			->andWhere($builder->expr()->in('m.user_id', $builder->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY)));
383
-
384
-		$result = $query->execute();
385
-
386
-		$results = [];
387
-		while ($row = $result->fetch()) {
388
-			$results[$row['user_id']] = $row['size'];
389
-		}
390
-		$result->closeCursor();
391
-		return $results;
392
-	}
47
+    /**
48
+     * @var IDBConnection
49
+     */
50
+    private $connection;
51
+
52
+    /**
53
+     * @var IUserManager
54
+     */
55
+    private $userManager;
56
+
57
+    /**
58
+     * Cached mount info.
59
+     * Map of $userId to ICachedMountInfo.
60
+     *
61
+     * @var ICache
62
+     **/
63
+    private $mountsForUsers;
64
+
65
+    /**
66
+     * @var ILogger
67
+     */
68
+    private $logger;
69
+
70
+    /**
71
+     * @var ICache
72
+     */
73
+    private $cacheInfoCache;
74
+
75
+    /**
76
+     * UserMountCache constructor.
77
+     *
78
+     * @param IDBConnection $connection
79
+     * @param IUserManager $userManager
80
+     * @param ILogger $logger
81
+     */
82
+    public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) {
83
+        $this->connection = $connection;
84
+        $this->userManager = $userManager;
85
+        $this->logger = $logger;
86
+        $this->cacheInfoCache = new CappedMemoryCache();
87
+        $this->mountsForUsers = new CappedMemoryCache();
88
+    }
89
+
90
+    public function registerMounts(IUser $user, array $mounts) {
91
+        // filter out non-proper storages coming from unit tests
92
+        $mounts = array_filter($mounts, function (IMountPoint $mount) {
93
+            return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache();
94
+        });
95
+        /** @var ICachedMountInfo[] $newMounts */
96
+        $newMounts = array_map(function (IMountPoint $mount) use ($user) {
97
+            // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
98
+            if ($mount->getStorageRootId() === -1) {
99
+                return null;
100
+            } else {
101
+                return new LazyStorageMountInfo($user, $mount);
102
+            }
103
+        }, $mounts);
104
+        $newMounts = array_values(array_filter($newMounts));
105
+
106
+        $cachedMounts = $this->getMountsForUser($user);
107
+        $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
108
+            // since we are only looking for mounts for a specific user comparing on root id is enough
109
+            return $mount1->getRootId() - $mount2->getRootId();
110
+        };
111
+
112
+        /** @var ICachedMountInfo[] $addedMounts */
113
+        $addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff);
114
+        /** @var ICachedMountInfo[] $removedMounts */
115
+        $removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff);
116
+
117
+        $changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
118
+
119
+        foreach ($addedMounts as $mount) {
120
+            $this->addToCache($mount);
121
+            $this->mountsForUsers[$user->getUID()][] = $mount;
122
+        }
123
+        foreach ($removedMounts as $mount) {
124
+            $this->removeFromCache($mount);
125
+            $index = array_search($mount, $this->mountsForUsers[$user->getUID()]);
126
+            unset($this->mountsForUsers[$user->getUID()][$index]);
127
+        }
128
+        foreach ($changedMounts as $mount) {
129
+            $this->updateCachedMount($mount);
130
+        }
131
+    }
132
+
133
+    /**
134
+     * @param ICachedMountInfo[] $newMounts
135
+     * @param ICachedMountInfo[] $cachedMounts
136
+     * @return ICachedMountInfo[]
137
+     */
138
+    private function findChangedMounts(array $newMounts, array $cachedMounts) {
139
+        $changed = [];
140
+        foreach ($newMounts as $newMount) {
141
+            foreach ($cachedMounts as $cachedMount) {
142
+                if (
143
+                    $newMount->getRootId() === $cachedMount->getRootId() &&
144
+                    (
145
+                        $newMount->getMountPoint() !== $cachedMount->getMountPoint() ||
146
+                        $newMount->getStorageId() !== $cachedMount->getStorageId() ||
147
+                        $newMount->getMountId() !== $cachedMount->getMountId()
148
+                    )
149
+                ) {
150
+                    $changed[] = $newMount;
151
+                }
152
+            }
153
+        }
154
+        return $changed;
155
+    }
156
+
157
+    private function addToCache(ICachedMountInfo $mount) {
158
+        if ($mount->getStorageId() !== -1) {
159
+            $this->connection->insertIfNotExist('*PREFIX*mounts', [
160
+                'storage_id' => $mount->getStorageId(),
161
+                'root_id' => $mount->getRootId(),
162
+                'user_id' => $mount->getUser()->getUID(),
163
+                'mount_point' => $mount->getMountPoint(),
164
+                'mount_id' => $mount->getMountId()
165
+            ], ['root_id', 'user_id']);
166
+        } else {
167
+            // in some cases this is legitimate, like orphaned shares
168
+            $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
169
+        }
170
+    }
171
+
172
+    private function updateCachedMount(ICachedMountInfo $mount) {
173
+        $builder = $this->connection->getQueryBuilder();
174
+
175
+        $query = $builder->update('mounts')
176
+            ->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
177
+            ->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
178
+            ->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
179
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
180
+            ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
181
+
182
+        $query->execute();
183
+    }
184
+
185
+    private function removeFromCache(ICachedMountInfo $mount) {
186
+        $builder = $this->connection->getQueryBuilder();
187
+
188
+        $query = $builder->delete('mounts')
189
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
190
+            ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
191
+        $query->execute();
192
+    }
193
+
194
+    private function dbRowToMountInfo(array $row) {
195
+        $user = $this->userManager->get($row['user_id']);
196
+        if (is_null($user)) {
197
+            return null;
198
+        }
199
+        $mount_id = $row['mount_id'];
200
+        if (!is_null($mount_id)) {
201
+            $mount_id = (int) $mount_id;
202
+        }
203
+        return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : '');
204
+    }
205
+
206
+    /**
207
+     * @param IUser $user
208
+     * @return ICachedMountInfo[]
209
+     */
210
+    public function getMountsForUser(IUser $user) {
211
+        if (!isset($this->mountsForUsers[$user->getUID()])) {
212
+            $builder = $this->connection->getQueryBuilder();
213
+            $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
214
+                ->from('mounts', 'm')
215
+                ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
216
+                ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID())));
217
+
218
+            $rows = $query->execute()->fetchAll();
219
+
220
+            $this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
221
+        }
222
+        return $this->mountsForUsers[$user->getUID()];
223
+    }
224
+
225
+    /**
226
+     * @param int $numericStorageId
227
+     * @param string|null $user limit the results to a single user
228
+     * @return CachedMountInfo[]
229
+     */
230
+    public function getMountsForStorageId($numericStorageId, $user = null) {
231
+        $builder = $this->connection->getQueryBuilder();
232
+        $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
233
+            ->from('mounts', 'm')
234
+            ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
235
+            ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
236
+
237
+        if ($user) {
238
+            $query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
239
+        }
240
+
241
+        $rows = $query->execute()->fetchAll();
242
+
243
+        return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
244
+    }
245
+
246
+    /**
247
+     * @param int $rootFileId
248
+     * @return CachedMountInfo[]
249
+     */
250
+    public function getMountsForRootId($rootFileId) {
251
+        $builder = $this->connection->getQueryBuilder();
252
+        $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
253
+            ->from('mounts', 'm')
254
+            ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
255
+            ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
256
+
257
+        $rows = $query->execute()->fetchAll();
258
+
259
+        return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
260
+    }
261
+
262
+    /**
263
+     * @param $fileId
264
+     * @return array
265
+     * @throws \OCP\Files\NotFoundException
266
+     */
267
+    private function getCacheInfoFromFileId($fileId) {
268
+        if (!isset($this->cacheInfoCache[$fileId])) {
269
+            $builder = $this->connection->getQueryBuilder();
270
+            $query = $builder->select('storage', 'path', 'mimetype')
271
+                ->from('filecache')
272
+                ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
273
+
274
+            $row = $query->execute()->fetch();
275
+            if (is_array($row)) {
276
+                $this->cacheInfoCache[$fileId] = [
277
+                    (int)$row['storage'],
278
+                    $row['path'],
279
+                    (int)$row['mimetype']
280
+                ];
281
+            } else {
282
+                throw new NotFoundException('File with id "' . $fileId . '" not found');
283
+            }
284
+        }
285
+        return $this->cacheInfoCache[$fileId];
286
+    }
287
+
288
+    /**
289
+     * @param int $fileId
290
+     * @param string|null $user optionally restrict the results to a single user
291
+     * @return ICachedMountFileInfo[]
292
+     * @since 9.0.0
293
+     */
294
+    public function getMountsForFileId($fileId, $user = null) {
295
+        try {
296
+            list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId);
297
+        } catch (NotFoundException $e) {
298
+            return [];
299
+        }
300
+        $mountsForStorage = $this->getMountsForStorageId($storageId, $user);
301
+
302
+        // filter mounts that are from the same storage but a different directory
303
+        $filteredMounts = array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
304
+            if ($fileId === $mount->getRootId()) {
305
+                return true;
306
+            }
307
+            $internalMountPath = $mount->getRootInternalPath();
308
+
309
+            return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
310
+        });
311
+
312
+        return array_map(function (ICachedMountInfo $mount) use ($internalPath) {
313
+            return new CachedMountFileInfo(
314
+                $mount->getUser(),
315
+                $mount->getStorageId(),
316
+                $mount->getRootId(),
317
+                $mount->getMountPoint(),
318
+                $mount->getMountId(),
319
+                $mount->getRootInternalPath(),
320
+                $internalPath
321
+            );
322
+        }, $filteredMounts);
323
+    }
324
+
325
+    /**
326
+     * Remove all cached mounts for a user
327
+     *
328
+     * @param IUser $user
329
+     */
330
+    public function removeUserMounts(IUser $user) {
331
+        $builder = $this->connection->getQueryBuilder();
332
+
333
+        $query = $builder->delete('mounts')
334
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
335
+        $query->execute();
336
+    }
337
+
338
+    public function removeUserStorageMount($storageId, $userId) {
339
+        $builder = $this->connection->getQueryBuilder();
340
+
341
+        $query = $builder->delete('mounts')
342
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
343
+            ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
344
+        $query->execute();
345
+    }
346
+
347
+    public function remoteStorageMounts($storageId) {
348
+        $builder = $this->connection->getQueryBuilder();
349
+
350
+        $query = $builder->delete('mounts')
351
+            ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
352
+        $query->execute();
353
+    }
354
+
355
+    /**
356
+     * @param array $users
357
+     * @return array
358
+     * @suppress SqlInjectionChecker
359
+     */
360
+    public function getUsedSpaceForUsers(array $users) {
361
+        $builder = $this->connection->getQueryBuilder();
362
+
363
+        $slash = $builder->createNamedParameter('/');
364
+
365
+        $mountPoint = $builder->func()->concat(
366
+            $builder->func()->concat($slash, 'user_id'),
367
+            $slash
368
+        );
369
+
370
+        $userIds = array_map(function (IUser $user) {
371
+            return $user->getUID();
372
+        }, $users);
373
+
374
+        $query = $builder->select('m.user_id', 'f.size')
375
+            ->from('mounts', 'm')
376
+            ->innerJoin('m', 'filecache', 'f',
377
+                $builder->expr()->andX(
378
+                    $builder->expr()->eq('m.storage_id', 'f.storage'),
379
+                    $builder->expr()->eq('f.path', $builder->createNamedParameter('files'))
380
+                ))
381
+            ->where($builder->expr()->eq('m.mount_point', $mountPoint))
382
+            ->andWhere($builder->expr()->in('m.user_id', $builder->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY)));
383
+
384
+        $result = $query->execute();
385
+
386
+        $results = [];
387
+        while ($row = $result->fetch()) {
388
+            $results[$row['user_id']] = $row['size'];
389
+        }
390
+        $result->closeCursor();
391
+        return $results;
392
+    }
393 393
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -89,11 +89,11 @@  discard block
 block discarded – undo
89 89
 
90 90
 	public function registerMounts(IUser $user, array $mounts) {
91 91
 		// filter out non-proper storages coming from unit tests
92
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
92
+		$mounts = array_filter($mounts, function(IMountPoint $mount) {
93 93
 			return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache();
94 94
 		});
95 95
 		/** @var ICachedMountInfo[] $newMounts */
96
-		$newMounts = array_map(function (IMountPoint $mount) use ($user) {
96
+		$newMounts = array_map(function(IMountPoint $mount) use ($user) {
97 97
 			// filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
98 98
 			if ($mount->getStorageRootId() === -1) {
99 99
 				return null;
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 		$newMounts = array_values(array_filter($newMounts));
105 105
 
106 106
 		$cachedMounts = $this->getMountsForUser($user);
107
-		$mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
107
+		$mountDiff = function(ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
108 108
 			// since we are only looking for mounts for a specific user comparing on root id is enough
109 109
 			return $mount1->getRootId() - $mount2->getRootId();
110 110
 		};
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 			], ['root_id', 'user_id']);
166 166
 		} else {
167 167
 			// in some cases this is legitimate, like orphaned shares
168
-			$this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
168
+			$this->logger->debug('Could not get storage info for mount at '.$mount->getMountPoint());
169 169
 		}
170 170
 	}
171 171
 
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 		if (!is_null($mount_id)) {
201 201
 			$mount_id = (int) $mount_id;
202 202
 		}
203
-		return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : '');
203
+		return new CachedMountInfo($user, (int) $row['storage_id'], (int) $row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : '');
204 204
 	}
205 205
 
206 206
 	/**
@@ -274,12 +274,12 @@  discard block
 block discarded – undo
274 274
 			$row = $query->execute()->fetch();
275 275
 			if (is_array($row)) {
276 276
 				$this->cacheInfoCache[$fileId] = [
277
-					(int)$row['storage'],
277
+					(int) $row['storage'],
278 278
 					$row['path'],
279
-					(int)$row['mimetype']
279
+					(int) $row['mimetype']
280 280
 				];
281 281
 			} else {
282
-				throw new NotFoundException('File with id "' . $fileId . '" not found');
282
+				throw new NotFoundException('File with id "'.$fileId.'" not found');
283 283
 			}
284 284
 		}
285 285
 		return $this->cacheInfoCache[$fileId];
@@ -300,16 +300,16 @@  discard block
 block discarded – undo
300 300
 		$mountsForStorage = $this->getMountsForStorageId($storageId, $user);
301 301
 
302 302
 		// filter mounts that are from the same storage but a different directory
303
-		$filteredMounts = array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
303
+		$filteredMounts = array_filter($mountsForStorage, function(ICachedMountInfo $mount) use ($internalPath, $fileId) {
304 304
 			if ($fileId === $mount->getRootId()) {
305 305
 				return true;
306 306
 			}
307 307
 			$internalMountPath = $mount->getRootInternalPath();
308 308
 
309
-			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
309
+			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath.'/';
310 310
 		});
311 311
 
312
-		return array_map(function (ICachedMountInfo $mount) use ($internalPath) {
312
+		return array_map(function(ICachedMountInfo $mount) use ($internalPath) {
313 313
 			return new CachedMountFileInfo(
314 314
 				$mount->getUser(),
315 315
 				$mount->getStorageId(),
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 			$slash
368 368
 		);
369 369
 
370
-		$userIds = array_map(function (IUser $user) {
370
+		$userIds = array_map(function(IUser $user) {
371 371
 			return $user->getUID();
372 372
 		}, $users);
373 373
 
Please login to merge, or discard this patch.