Completed
Push — master ( c76c8a...69e92e )
by Morris
181:30 queued 162:37
created

PersonalInfo::getForm()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 54

Duplication

Lines 5
Ratio 9.26 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 0
dl 5
loc 54
rs 9.0036
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2017 Arthur Schiwon <[email protected]>
4
 *
5
 * @author Arthur Schiwon <[email protected]>
6
 * @author Morris Jobke <[email protected]>
7
 * @author Thomas Citharel <[email protected]>
8
 *
9
 * @license GNU AGPL version 3 or any later version
10
 *
11
 * This program is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU Affero General Public License as
13
 * published by the Free Software Foundation, either version 3 of the
14
 * License, or (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU Affero General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Affero General Public License
22
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23
 *
24
 */
25
26
namespace OC\Settings\Personal;
27
28
use OC\Accounts\AccountManager;
29
use OCA\FederatedFileSharing\AppInfo\Application;
30
use OCP\App\IAppManager;
31
use OCP\AppFramework\Http\TemplateResponse;
32
use OCP\Files\FileInfo;
33
use OCP\IConfig;
34
use OCP\IGroup;
35
use OCP\IGroupManager;
36
use OCP\IL10N;
37
use OCP\IUser;
38
use OCP\IUserManager;
39
use OCP\L10N\IFactory;
40
use OCP\Settings\ISettings;
41
42
class PersonalInfo implements ISettings {
43
44
	/** @var IConfig */
45
	private $config;
46
	/** @var IUserManager */
47
	private $userManager;
48
	/** @var AccountManager */
49
	private $accountManager;
50
	/** @var IGroupManager */
51
	private $groupManager;
52
	/** @var IAppManager */
53
	private $appManager;
54
	/** @var IFactory */
55
	private $l10nFactory;
56
	/** @var IL10N */
57
	private $l;
58
59
	/**
60
	 * @param IConfig $config
61
	 * @param IUserManager $userManager
62
	 * @param IGroupManager $groupManager
63
	 * @param AccountManager $accountManager
64
	 * @param IFactory $l10nFactory
65
	 * @param IL10N $l
66
	 */
67
	public function __construct(
68
		IConfig $config,
69
		IUserManager $userManager,
70
		IGroupManager $groupManager,
71
		AccountManager $accountManager,
72
		IAppManager $appManager,
73
		IFactory $l10nFactory,
74
		IL10N $l
75
	) {
76
		$this->config = $config;
77
		$this->userManager = $userManager;
78
		$this->accountManager = $accountManager;
79
		$this->groupManager = $groupManager;
80
		$this->appManager = $appManager;
81
		$this->l10nFactory = $l10nFactory;
82
		$this->l = $l;
83
	}
84
85
	/**
86
	 * @return TemplateResponse returns the instance with all parameters set, ready to be rendered
87
	 * @since 9.1
88
	 */
89
	public function getForm() {
90
		$federatedFileSharingEnabled = $this->appManager->isEnabledForUser('federatedfilesharing');
91
		$lookupServerUploadEnabled = false;
92
		if($federatedFileSharingEnabled) {
93
			$federatedFileSharing = new Application();
94
			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
95
			$lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled();
96
		}
97
98
		$uid = \OC_User::getUser();
99
		$user = $this->userManager->get($uid);
100
		$userData = $this->accountManager->getUser($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userManager->get($uid) on line 99 can be null; however, OC\Accounts\AccountManager::getUser() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
101
102
		$storageInfo = \OC_Helper::getStorageInfo('/');
103 View Code Duplication
		if ($storageInfo['quota'] === FileInfo::SPACE_UNLIMITED) {
104
			$totalSpace = $this->l->t('Unlimited');
105
		} else {
106
			$totalSpace = \OC_Helper::humanFileSize($storageInfo['total']);
107
		}
108
109
		$languageParameters = $this->getLanguages($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userManager->get($uid) on line 99 can be null; however, OC\Settings\Personal\PersonalInfo::getLanguages() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
110
		$localeParameters = $this->getLocales($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userManager->get($uid) on line 99 can be null; however, OC\Settings\Personal\PersonalInfo::getLocales() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
111
		$messageParameters = $this->getMessageParameters($userData);
112
113
		$parameters = [
114
			'total_space' => $totalSpace,
115
			'usage' => \OC_Helper::humanFileSize($storageInfo['used']),
116
			'usage_relative' => round($storageInfo['relative']),
117
			'quota' => $storageInfo['quota'],
118
			'avatarChangeSupported' => $user->canChangeAvatar(),
119
			'lookupServerUploadEnabled' => $lookupServerUploadEnabled,
120
			'avatarScope' => $userData[AccountManager::PROPERTY_AVATAR]['scope'],
121
			'displayNameChangeSupported' => $user->canChangeDisplayName(),
122
			'displayName' => $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'],
123
			'displayNameScope' => $userData[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
124
			'email' => $userData[AccountManager::PROPERTY_EMAIL]['value'],
125
			'emailScope' => $userData[AccountManager::PROPERTY_EMAIL]['scope'],
126
			'emailVerification' => $userData[AccountManager::PROPERTY_EMAIL]['verified'],
127
			'phone' => $userData[AccountManager::PROPERTY_PHONE]['value'],
128
			'phoneScope' => $userData[AccountManager::PROPERTY_PHONE]['scope'],
129
			'address' => $userData[AccountManager::PROPERTY_ADDRESS]['value'],
130
			'addressScope' => $userData[AccountManager::PROPERTY_ADDRESS]['scope'],
131
			'website' =>  $userData[AccountManager::PROPERTY_WEBSITE]['value'],
132
			'websiteScope' =>  $userData[AccountManager::PROPERTY_WEBSITE]['scope'],
133
			'websiteVerification' => $userData[AccountManager::PROPERTY_WEBSITE]['verified'],
134
			'twitter' => $userData[AccountManager::PROPERTY_TWITTER]['value'],
135
			'twitterScope' => $userData[AccountManager::PROPERTY_TWITTER]['scope'],
136
			'twitterVerification' => $userData[AccountManager::PROPERTY_TWITTER]['verified'],
137
			'groups' => $this->getGroups($user),
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userManager->get($uid) on line 99 can be null; however, OC\Settings\Personal\PersonalInfo::getGroups() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
138
		] + $messageParameters + $languageParameters + $localeParameters;
139
140
141
		return new TemplateResponse('settings', 'settings/personal/personal.info', $parameters, '');
142
	}
143
144
	/**
145
	 * @return string the section ID, e.g. 'sharing'
146
	 * @since 9.1
147
	 */
148
	public function getSection() {
149
		return 'personal-info';
150
	}
151
152
	/**
153
	 * @return int whether the form should be rather on the top or bottom of
154
	 * the admin section. The forms are arranged in ascending order of the
155
	 * priority values. It is required to return a value between 0 and 100.
156
	 *
157
	 * E.g.: 70
158
	 * @since 9.1
159
	 */
160
	public function getPriority() {
161
		return 10;
162
	}
163
164
	/**
165
	 * returns a sorted list of the user's group GIDs
166
	 *
167
	 * @param IUser $user
168
	 * @return array
169
	 */
170
	private function getGroups(IUser $user) {
171
		$groups = array_map(
172
			function(IGroup $group) {
173
				return $group->getDisplayName();
174
			},
175
			$this->groupManager->getUserGroups($user)
176
		);
177
		sort($groups);
178
179
		return $groups;
180
	}
181
182
	/**
183
	 * returns the user language, common language and other languages in an
184
	 * associative array
185
	 *
186
	 * @param IUser $user
187
	 * @return array
188
	 */
189
	private function getLanguages(IUser $user) {
190
		$forceLanguage = $this->config->getSystemValue('force_language', false);
191
		if($forceLanguage !== false) {
192
			return [];
193
		}
194
195
		$uid = $user->getUID();
196
197
		$userConfLang = $this->config->getUserValue($uid, 'core', 'lang', $this->l10nFactory->findLanguage());
198
		$languages = $this->l10nFactory->getLanguages();
199
200
		// associate the user language with the proper array
201
		$userLangIndex = array_search($userConfLang, array_column($languages['commonlanguages'], 'code'));
202
		$userLang = $languages['commonlanguages'][$userLangIndex];
203
		// search in the other languages
204
		if ($userLangIndex === false) {
205
			$userLangIndex = array_search($userConfLang, array_column($languages['languages'], 'code'));		
206
			$userLang = $languages['languages'][$userLangIndex];
207
		}
208
		// if user language is not available but set somehow: show the actual code as name
209
		if (!is_array($userLang)) {
210
			$userLang = [
211
				'code' => $userConfLang,
212
				'name' => $userConfLang,
213
			];
214
		}
215
216
		return array_merge(
217
			array('activelanguage' => $userLang),
218
			$languages
219
		);
220
	}
221
222
	private function getLocales(IUser $user) {
223
		$forceLanguage = $this->config->getSystemValue('force_locale', false);
224
		if($forceLanguage !== false) {
225
			return [];
226
		}
227
228
		$uid = $user->getUID();
229
230
		$userLocaleString = $this->config->getUserValue($uid, 'core', 'locale', 'en_US');
231
232
		$userLang = $this->config->getUserValue($uid, 'core', 'lang', $this->l10nFactory->findLanguage());
233
234
		$localeCodes = $this->l10nFactory->findAvailableLocales();
235
236
		$userLocale = array_filter($localeCodes, function($value) use ($userLocaleString) {
237
			return $userLocaleString === $value['code'];
238
		});
239
240
		if (!empty($userLocale))
241
		{
242
			$userLocale = reset($userLocale);
243
		}
244
245
		$localesForLanguage = array_filter($localeCodes, function($localeCode) use ($userLang) {
246
			return 0 === strpos($localeCode['code'], $userLang);
247
		});
248
249
		return [
250
			'activelocaleLang' => $userLocaleString,
251
			'activelocale' => $userLocale,
252
			'locales' => $localeCodes,
253
			'localesForLanguage' => $localesForLanguage,
254
		];
255
	}
256
257
	/**
258
	 * @param array $userData
259
	 * @return array
260
	 */
261
	private function getMessageParameters(array $userData) {
262
		$needVerifyMessage = [AccountManager::PROPERTY_EMAIL, AccountManager::PROPERTY_WEBSITE, AccountManager::PROPERTY_TWITTER];
263
		$messageParameters = [];
264
		foreach ($needVerifyMessage as $property) {
265
			switch ($userData[$property]['verified']) {
266
				case AccountManager::VERIFIED:
267
					$message = $this->l->t('Verifying');
268
					break;
269
				case AccountManager::VERIFICATION_IN_PROGRESS:
270
					$message = $this->l->t('Verifying …');
271
					break;
272
				default:
273
					$message = $this->l->t('Verify');
274
			}
275
			$messageParameters[$property . 'Message'] = $message;
276
		}
277
		return $messageParameters;
278
	}
279
280
}
281