Completed
Pull Request — master (#3869)
by Jan-Christoph
28:51 queued 16:40
created
settings/routes.php 1 patch
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -36,77 +36,77 @@
 block discarded – undo
36 36
 
37 37
 $application = new Application();
38 38
 $application->registerRoutes($this, [
39
-	'resources' => [
40
-		'users' => ['url' => '/settings/users/users'],
41
-		'AuthSettings' => ['url' => '/settings/personal/authtokens'],
42
-	],
43
-	'routes' => [
44
-		['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
45
-		['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
46
-		['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
47
-		['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
48
-		['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
49
-		['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
50
-		['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
51
-		['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
52
-		['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
53
-		['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
54
-		['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
55
-		['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
56
-		['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
57
-		['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
58
-		['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
59
-		['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
60
-		['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
61
-		['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
62
-		['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
63
-		['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
64
-		['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
65
-		['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
66
-		['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
67
-		['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
68
-		['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
69
-		['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
70
-		['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
71
-		['name' => 'Personal#setLanguage', 'url' => '/settings/ajax/setlanguage.php', 'verb' => 'POST'],
72
-		['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
73
-		['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
74
-		['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
75
-		['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
76
-		['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
77
-	]
39
+    'resources' => [
40
+        'users' => ['url' => '/settings/users/users'],
41
+        'AuthSettings' => ['url' => '/settings/personal/authtokens'],
42
+    ],
43
+    'routes' => [
44
+        ['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
45
+        ['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
46
+        ['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
47
+        ['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
48
+        ['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
49
+        ['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
50
+        ['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
51
+        ['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
52
+        ['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
53
+        ['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
54
+        ['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
55
+        ['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
56
+        ['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
57
+        ['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
58
+        ['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
59
+        ['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
60
+        ['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
61
+        ['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
62
+        ['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
63
+        ['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
64
+        ['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
65
+        ['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
66
+        ['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
67
+        ['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
68
+        ['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
69
+        ['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
70
+        ['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
71
+        ['name' => 'Personal#setLanguage', 'url' => '/settings/ajax/setlanguage.php', 'verb' => 'POST'],
72
+        ['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
73
+        ['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
74
+        ['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
75
+        ['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
76
+        ['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
77
+    ]
78 78
 ]);
79 79
 
80 80
 /** @var $this \OCP\Route\IRouter */
81 81
 
82 82
 // Settings pages
83 83
 $this->create('settings_help', '/settings/help')
84
-	->actionInclude('settings/help.php');
84
+    ->actionInclude('settings/help.php');
85 85
 $this->create('settings_personal', '/settings/personal')
86
-	->actionInclude('settings/personal.php');
86
+    ->actionInclude('settings/personal.php');
87 87
 $this->create('settings_users', '/settings/users')
88
-	->actionInclude('settings/users.php');
88
+    ->actionInclude('settings/users.php');
89 89
 // Settings ajax actions
90 90
 // users
91 91
 $this->create('settings_ajax_setquota', '/settings/ajax/setquota.php')
92
-	->actionInclude('settings/ajax/setquota.php');
92
+    ->actionInclude('settings/ajax/setquota.php');
93 93
 $this->create('settings_ajax_togglegroups', '/settings/ajax/togglegroups.php')
94
-	->actionInclude('settings/ajax/togglegroups.php');
94
+    ->actionInclude('settings/ajax/togglegroups.php');
95 95
 $this->create('settings_ajax_togglesubadmins', '/settings/ajax/togglesubadmins.php')
96
-	->actionInclude('settings/ajax/togglesubadmins.php');
96
+    ->actionInclude('settings/ajax/togglesubadmins.php');
97 97
 $this->create('settings_ajax_changegorupname', '/settings/ajax/changegroupname.php')
98
-	->actionInclude('settings/ajax/changegroupname.php');
98
+    ->actionInclude('settings/ajax/changegroupname.php');
99 99
 // apps
100 100
 $this->create('settings_ajax_enableapp', '/settings/ajax/enableapp.php')
101
-	->actionInclude('settings/ajax/enableapp.php');
101
+    ->actionInclude('settings/ajax/enableapp.php');
102 102
 $this->create('settings_ajax_disableapp', '/settings/ajax/disableapp.php')
103
-	->actionInclude('settings/ajax/disableapp.php');
103
+    ->actionInclude('settings/ajax/disableapp.php');
104 104
 $this->create('settings_ajax_updateapp', '/settings/ajax/updateapp.php')
105
-	->actionInclude('settings/ajax/updateapp.php');
105
+    ->actionInclude('settings/ajax/updateapp.php');
106 106
 $this->create('settings_ajax_uninstallapp', '/settings/ajax/uninstallapp.php')
107
-	->actionInclude('settings/ajax/uninstallapp.php');
107
+    ->actionInclude('settings/ajax/uninstallapp.php');
108 108
 $this->create('settings_ajax_navigationdetect', '/settings/ajax/navigationdetect.php')
109
-	->actionInclude('settings/ajax/navigationdetect.php');
109
+    ->actionInclude('settings/ajax/navigationdetect.php');
110 110
 // admin
111 111
 $this->create('settings_ajax_excludegroups', '/settings/ajax/excludegroups.php')
112
-	->actionInclude('settings/ajax/excludegroups.php');
112
+    ->actionInclude('settings/ajax/excludegroups.php');
Please login to merge, or discard this patch.
lib/private/Accounts/Hooks.php 1 patch
Indentation   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -27,73 +27,73 @@
 block discarded – undo
27 27
 
28 28
 class Hooks {
29 29
 
30
-	/** @var  AccountManager */
31
-	private $accountManager = null;
32
-
33
-	/** @var ILogger */
34
-	private $logger;
35
-
36
-	/**
37
-	 * Hooks constructor.
38
-	 *
39
-	 * @param ILogger $logger
40
-	 */
41
-	public function __construct(ILogger $logger) {
42
-		$this->logger = $logger;
43
-	}
44
-
45
-	/**
46
-	 * update accounts table if email address or display name was changed from outside
47
-	 *
48
-	 * @param array $params
49
-	 */
50
-	public function changeUserHook($params) {
51
-
52
-		$accountManager = $this->getAccountManager();
53
-
54
-		/** @var IUser $user */
55
-		$user = isset($params['user']) ? $params['user'] : null;
56
-		$feature = isset($params['feature']) ? $params['feature'] : null;
57
-		$newValue = isset($params['value']) ? $params['value'] : null;
58
-
59
-		if (is_null($user) || is_null($feature) || is_null($newValue)) {
60
-			$this->logger->warning('Missing expected parameters in change user hook');
61
-			return;
62
-		}
63
-
64
-		$accountData = $accountManager->getUser($user);
65
-
66
-		switch ($feature) {
67
-			case 'eMailAddress':
68
-				if ($accountData[AccountManager::PROPERTY_EMAIL]['value'] !== $newValue) {
69
-					$accountData[AccountManager::PROPERTY_EMAIL]['value'] = $newValue;
70
-					$accountManager->updateUser($user, $accountData);
71
-				}
72
-				break;
73
-			case 'displayName':
74
-				if ($accountData[AccountManager::PROPERTY_DISPLAYNAME]['value'] !== $newValue) {
75
-					$accountData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $newValue;
76
-					$accountManager->updateUser($user, $accountData);
77
-				}
78
-				break;
79
-		}
80
-
81
-	}
82
-
83
-	/**
84
-	 * return instance of accountManager
85
-	 *
86
-	 * @return AccountManager
87
-	 */
88
-	protected function getAccountManager() {
89
-		if (is_null($this->accountManager)) {
90
-			$this->accountManager = new AccountManager(
91
-				\OC::$server->getDatabaseConnection(),
92
-				\OC::$server->getEventDispatcher(),
93
-				\OC::$server->getJobList()
94
-			);
95
-		}
96
-		return $this->accountManager;
97
-	}
30
+    /** @var  AccountManager */
31
+    private $accountManager = null;
32
+
33
+    /** @var ILogger */
34
+    private $logger;
35
+
36
+    /**
37
+     * Hooks constructor.
38
+     *
39
+     * @param ILogger $logger
40
+     */
41
+    public function __construct(ILogger $logger) {
42
+        $this->logger = $logger;
43
+    }
44
+
45
+    /**
46
+     * update accounts table if email address or display name was changed from outside
47
+     *
48
+     * @param array $params
49
+     */
50
+    public function changeUserHook($params) {
51
+
52
+        $accountManager = $this->getAccountManager();
53
+
54
+        /** @var IUser $user */
55
+        $user = isset($params['user']) ? $params['user'] : null;
56
+        $feature = isset($params['feature']) ? $params['feature'] : null;
57
+        $newValue = isset($params['value']) ? $params['value'] : null;
58
+
59
+        if (is_null($user) || is_null($feature) || is_null($newValue)) {
60
+            $this->logger->warning('Missing expected parameters in change user hook');
61
+            return;
62
+        }
63
+
64
+        $accountData = $accountManager->getUser($user);
65
+
66
+        switch ($feature) {
67
+            case 'eMailAddress':
68
+                if ($accountData[AccountManager::PROPERTY_EMAIL]['value'] !== $newValue) {
69
+                    $accountData[AccountManager::PROPERTY_EMAIL]['value'] = $newValue;
70
+                    $accountManager->updateUser($user, $accountData);
71
+                }
72
+                break;
73
+            case 'displayName':
74
+                if ($accountData[AccountManager::PROPERTY_DISPLAYNAME]['value'] !== $newValue) {
75
+                    $accountData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $newValue;
76
+                    $accountManager->updateUser($user, $accountData);
77
+                }
78
+                break;
79
+        }
80
+
81
+    }
82
+
83
+    /**
84
+     * return instance of accountManager
85
+     *
86
+     * @return AccountManager
87
+     */
88
+    protected function getAccountManager() {
89
+        if (is_null($this->accountManager)) {
90
+            $this->accountManager = new AccountManager(
91
+                \OC::$server->getDatabaseConnection(),
92
+                \OC::$server->getEventDispatcher(),
93
+                \OC::$server->getJobList()
94
+            );
95
+        }
96
+        return $this->accountManager;
97
+    }
98 98
 
99 99
 }
Please login to merge, or discard this patch.
apps/lookup_server_connector/lib/UpdateLookupServer.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -35,107 +35,107 @@
 block discarded – undo
35 35
  * @package OCA\LookupServerConnector
36 36
  */
37 37
 class UpdateLookupServer {
38
-	/** @var AccountManager */
39
-	private $accountManager;
40
-	/** @var IClientService */
41
-	private $clientService;
42
-	/** @var Signer */
43
-	private $signer;
44
-	/** @var IJobList */
45
-	private $jobList;
46
-	/** @var string URL point to lookup server */
47
-	private $lookupServer = 'https://lookup.nextcloud.com';
38
+    /** @var AccountManager */
39
+    private $accountManager;
40
+    /** @var IClientService */
41
+    private $clientService;
42
+    /** @var Signer */
43
+    private $signer;
44
+    /** @var IJobList */
45
+    private $jobList;
46
+    /** @var string URL point to lookup server */
47
+    private $lookupServer = 'https://lookup.nextcloud.com';
48 48
 
49
-	/**
50
-	 * @param AccountManager $accountManager
51
-	 * @param IClientService $clientService
52
-	 * @param Signer $signer
53
-	 * @param IJobList $jobList
54
-	 * @param string $lookupServer if nothing is given we use the default lookup server
55
-	 */
56
-	public function __construct(AccountManager $accountManager,
57
-								IClientService $clientService,
58
-								Signer $signer,
59
-								IJobList $jobList,
60
-								$lookupServer = '') {
61
-		$this->accountManager = $accountManager;
62
-		$this->clientService = $clientService;
63
-		$this->signer = $signer;
64
-		$this->jobList = $jobList;
65
-		if ($lookupServer !== '') {
66
-			$this->lookupServer = $lookupServer;
67
-		}
68
-		$this->lookupServer = rtrim($this->lookupServer, '/');
69
-		$this->lookupServer .= '/users';
70
-	}
49
+    /**
50
+     * @param AccountManager $accountManager
51
+     * @param IClientService $clientService
52
+     * @param Signer $signer
53
+     * @param IJobList $jobList
54
+     * @param string $lookupServer if nothing is given we use the default lookup server
55
+     */
56
+    public function __construct(AccountManager $accountManager,
57
+                                IClientService $clientService,
58
+                                Signer $signer,
59
+                                IJobList $jobList,
60
+                                $lookupServer = '') {
61
+        $this->accountManager = $accountManager;
62
+        $this->clientService = $clientService;
63
+        $this->signer = $signer;
64
+        $this->jobList = $jobList;
65
+        if ($lookupServer !== '') {
66
+            $this->lookupServer = $lookupServer;
67
+        }
68
+        $this->lookupServer = rtrim($this->lookupServer, '/');
69
+        $this->lookupServer .= '/users';
70
+    }
71 71
 
72
-	/**
73
-	 * @param IUser $user
74
-	 */
75
-	public function userUpdated(IUser $user) {
76
-		$userData = $this->accountManager->getUser($user);
77
-		$publicData = [];
72
+    /**
73
+     * @param IUser $user
74
+     */
75
+    public function userUpdated(IUser $user) {
76
+        $userData = $this->accountManager->getUser($user);
77
+        $publicData = [];
78 78
 
79
-		foreach ($userData as $key => $data) {
80
-			if ($data['scope'] === AccountManager::VISIBILITY_PUBLIC) {
81
-				$publicData[$key] = $data;
82
-			}
83
-		}
79
+        foreach ($userData as $key => $data) {
80
+            if ($data['scope'] === AccountManager::VISIBILITY_PUBLIC) {
81
+                $publicData[$key] = $data;
82
+            }
83
+        }
84 84
 
85
-		$this->sendToLookupServer($user, $publicData);
86
-	}
85
+        $this->sendToLookupServer($user, $publicData);
86
+    }
87 87
 
88
-	/**
89
-	 * send public user data to the lookup server
90
-	 *
91
-	 * @param IUser $user
92
-	 * @param array $publicData
93
-	 */
94
-	protected function sendToLookupServer(IUser $user, array $publicData) {
88
+    /**
89
+     * send public user data to the lookup server
90
+     *
91
+     * @param IUser $user
92
+     * @param array $publicData
93
+     */
94
+    protected function sendToLookupServer(IUser $user, array $publicData) {
95 95
 
96
-		$dataArray = ['federationId' => $user->getCloudId()];
96
+        $dataArray = ['federationId' => $user->getCloudId()];
97 97
 
98
-		if (!empty($publicData)) {
99
-			$dataArray['name'] = isset($publicData[AccountManager::PROPERTY_DISPLAYNAME]) ? $publicData[AccountManager::PROPERTY_DISPLAYNAME]['value'] : '';
100
-			$dataArray['email'] = isset($publicData[AccountManager::PROPERTY_EMAIL]) ? $publicData[AccountManager::PROPERTY_EMAIL]['value'] : '';
101
-			$dataArray['address'] = isset($publicData[AccountManager::PROPERTY_ADDRESS]) ? $publicData[AccountManager::PROPERTY_ADDRESS]['value'] : '';
102
-			$dataArray['website'] = isset($publicData[AccountManager::PROPERTY_WEBSITE]) ? $publicData[AccountManager::PROPERTY_WEBSITE]['value'] : '';
103
-			$dataArray['twitter'] = isset($publicData[AccountManager::PROPERTY_TWITTER]) ? $publicData[AccountManager::PROPERTY_TWITTER]['value'] : '';
104
-			$dataArray['phone'] = isset($publicData[AccountManager::PROPERTY_PHONE]) ? $publicData[AccountManager::PROPERTY_PHONE]['value'] : '';
105
-			$dataArray['verificationStatus'] =
106
-				[
107
-					AccountManager::PROPERTY_WEBSITE => isset($publicData[AccountManager::PROPERTY_WEBSITE]) ? $publicData[AccountManager::PROPERTY_WEBSITE]['verified'] : '',
108
-					AccountManager::PROPERTY_TWITTER => isset($publicData[AccountManager::PROPERTY_TWITTER]) ? $publicData[AccountManager::PROPERTY_TWITTER]['verified'] : '',
109
-				];
110
-		}
98
+        if (!empty($publicData)) {
99
+            $dataArray['name'] = isset($publicData[AccountManager::PROPERTY_DISPLAYNAME]) ? $publicData[AccountManager::PROPERTY_DISPLAYNAME]['value'] : '';
100
+            $dataArray['email'] = isset($publicData[AccountManager::PROPERTY_EMAIL]) ? $publicData[AccountManager::PROPERTY_EMAIL]['value'] : '';
101
+            $dataArray['address'] = isset($publicData[AccountManager::PROPERTY_ADDRESS]) ? $publicData[AccountManager::PROPERTY_ADDRESS]['value'] : '';
102
+            $dataArray['website'] = isset($publicData[AccountManager::PROPERTY_WEBSITE]) ? $publicData[AccountManager::PROPERTY_WEBSITE]['value'] : '';
103
+            $dataArray['twitter'] = isset($publicData[AccountManager::PROPERTY_TWITTER]) ? $publicData[AccountManager::PROPERTY_TWITTER]['value'] : '';
104
+            $dataArray['phone'] = isset($publicData[AccountManager::PROPERTY_PHONE]) ? $publicData[AccountManager::PROPERTY_PHONE]['value'] : '';
105
+            $dataArray['verificationStatus'] =
106
+                [
107
+                    AccountManager::PROPERTY_WEBSITE => isset($publicData[AccountManager::PROPERTY_WEBSITE]) ? $publicData[AccountManager::PROPERTY_WEBSITE]['verified'] : '',
108
+                    AccountManager::PROPERTY_TWITTER => isset($publicData[AccountManager::PROPERTY_TWITTER]) ? $publicData[AccountManager::PROPERTY_TWITTER]['verified'] : '',
109
+                ];
110
+        }
111 111
 
112
-		$dataArray = $this->signer->sign('lookupserver', $dataArray, $user);
113
-		$httpClient = $this->clientService->newClient();
114
-		try {
115
-			if (empty($publicData)) {
116
-				$httpClient->delete($this->lookupServer,
117
-					[
118
-						'body' => json_encode($dataArray),
119
-						'timeout' => 10,
120
-						'connect_timeout' => 3,
121
-					]
122
-				);
123
-			} else {
124
-				$httpClient->post($this->lookupServer,
125
-					[
126
-						'body' => json_encode($dataArray),
127
-						'timeout' => 10,
128
-						'connect_timeout' => 3,
129
-					]
130
-				);
131
-			}
132
-		} catch (\Exception $e) {
133
-			$this->jobList->add(RetryJob::class,
134
-				[
135
-					'dataArray' => $dataArray,
136
-					'retryNo' => 0,
137
-				]
138
-			);
139
-		}
140
-	}
112
+        $dataArray = $this->signer->sign('lookupserver', $dataArray, $user);
113
+        $httpClient = $this->clientService->newClient();
114
+        try {
115
+            if (empty($publicData)) {
116
+                $httpClient->delete($this->lookupServer,
117
+                    [
118
+                        'body' => json_encode($dataArray),
119
+                        'timeout' => 10,
120
+                        'connect_timeout' => 3,
121
+                    ]
122
+                );
123
+            } else {
124
+                $httpClient->post($this->lookupServer,
125
+                    [
126
+                        'body' => json_encode($dataArray),
127
+                        'timeout' => 10,
128
+                        'connect_timeout' => 3,
129
+                    ]
130
+                );
131
+            }
132
+        } catch (\Exception $e) {
133
+            $this->jobList->add(RetryJob::class,
134
+                [
135
+                    'dataArray' => $dataArray,
136
+                    'retryNo' => 0,
137
+                ]
138
+            );
139
+        }
140
+    }
141 141
 }
Please login to merge, or discard this patch.
apps/lookup_server_connector/appinfo/app.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -22,30 +22,30 @@
 block discarded – undo
22 22
 $dispatcher = \OC::$server->getEventDispatcher();
23 23
 
24 24
 $dispatcher->addListener('OC\AccountManager::userUpdated', function(\Symfony\Component\EventDispatcher\GenericEvent $event) {
25
-	$user = $event->getSubject();
25
+    $user = $event->getSubject();
26 26
 
27
-	$keyManager = new \OC\Security\IdentityProof\Manager(
28
-		\OC::$server->getAppDataDir('identityproof'),
29
-		\OC::$server->getCrypto()
30
-	);
27
+    $keyManager = new \OC\Security\IdentityProof\Manager(
28
+        \OC::$server->getAppDataDir('identityproof'),
29
+        \OC::$server->getCrypto()
30
+    );
31 31
 
32
-	$config = \OC::$server->getConfig();
33
-	$lookupServer = $config->getSystemValue('lookup_server', '');
32
+    $config = \OC::$server->getConfig();
33
+    $lookupServer = $config->getSystemValue('lookup_server', '');
34 34
 
35
-	$updateLookupServer = new \OCA\LookupServerConnector\UpdateLookupServer(
36
-		new \OC\Accounts\AccountManager(
37
-			\OC::$server->getDatabaseConnection(),
38
-			\OC::$server->getEventDispatcher(),
39
-			\OC::$server->getJobList()
40
-		),
41
-		\OC::$server->getHTTPClientService(),
42
-		new \OC\Security\IdentityProof\Signer(
43
-			$keyManager,
44
-			new \OC\AppFramework\Utility\TimeFactory(),
45
-			\OC::$server->getUserManager()
46
-		),
47
-		\OC::$server->getJobList(),
48
-		$lookupServer
49
-	);
50
-	$updateLookupServer->userUpdated($user);
35
+    $updateLookupServer = new \OCA\LookupServerConnector\UpdateLookupServer(
36
+        new \OC\Accounts\AccountManager(
37
+            \OC::$server->getDatabaseConnection(),
38
+            \OC::$server->getEventDispatcher(),
39
+            \OC::$server->getJobList()
40
+        ),
41
+        \OC::$server->getHTTPClientService(),
42
+        new \OC\Security\IdentityProof\Signer(
43
+            $keyManager,
44
+            new \OC\AppFramework\Utility\TimeFactory(),
45
+            \OC::$server->getUserManager()
46
+        ),
47
+        \OC::$server->getJobList(),
48
+        $lookupServer
49
+    );
50
+    $updateLookupServer->userUpdated($user);
51 51
 });
Please login to merge, or discard this patch.
settings/personal.php 1 patch
Indentation   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -41,9 +41,9 @@  discard block
 block discarded – undo
41 41
 $defaults = \OC::$server->getThemingDefaults();
42 42
 $certificateManager = \OC::$server->getCertificateManager();
43 43
 $accountManager = new \OC\Accounts\AccountManager(
44
-	\OC::$server->getDatabaseConnection(),
45
-	\OC::$server->getEventDispatcher(),
46
-	\OC::$server->getJobList()
44
+    \OC::$server->getDatabaseConnection(),
45
+    \OC::$server->getEventDispatcher(),
46
+    \OC::$server->getJobList()
47 47
 );
48 48
 $config = \OC::$server->getConfig();
49 49
 $urlGenerator = \OC::$server->getURLGenerator();
@@ -78,72 +78,72 @@  discard block
 block discarded – undo
78 78
 
79 79
 // array of common languages
80 80
 $commonLangCodes = array(
81
-	'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it', 'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
81
+    'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it', 'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
82 82
 );
83 83
 
84 84
 $languages=array();
85 85
 $commonLanguages = array();
86 86
 foreach($languageCodes as $lang) {
87
-	$l = \OC::$server->getL10N('settings', $lang);
88
-	// TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
89
-	$potentialName = (string) $l->t('__language_name__');
90
-	if($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
91
-		$ln = array('code' => $lang, 'name' => $potentialName);
92
-	} elseif ($lang === 'en') {
93
-		$ln = ['code' => $lang, 'name' => 'English (US)'];
94
-	}else{//fallback to language code
95
-		$ln=array('code'=>$lang, 'name'=>$lang);
96
-	}
97
-
98
-	// put appropriate languages into appropriate arrays, to print them sorted
99
-	// used language -> common languages -> divider -> other languages
100
-	if ($lang === $userLang) {
101
-		$userLang = $ln;
102
-	} elseif (in_array($lang, $commonLangCodes)) {
103
-		$commonLanguages[array_search($lang, $commonLangCodes)]=$ln;
104
-	} else {
105
-		$languages[]=$ln;
106
-	}
87
+    $l = \OC::$server->getL10N('settings', $lang);
88
+    // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
89
+    $potentialName = (string) $l->t('__language_name__');
90
+    if($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
91
+        $ln = array('code' => $lang, 'name' => $potentialName);
92
+    } elseif ($lang === 'en') {
93
+        $ln = ['code' => $lang, 'name' => 'English (US)'];
94
+    }else{//fallback to language code
95
+        $ln=array('code'=>$lang, 'name'=>$lang);
96
+    }
97
+
98
+    // put appropriate languages into appropriate arrays, to print them sorted
99
+    // used language -> common languages -> divider -> other languages
100
+    if ($lang === $userLang) {
101
+        $userLang = $ln;
102
+    } elseif (in_array($lang, $commonLangCodes)) {
103
+        $commonLanguages[array_search($lang, $commonLangCodes)]=$ln;
104
+    } else {
105
+        $languages[]=$ln;
106
+    }
107 107
 }
108 108
 
109 109
 // if user language is not available but set somehow: show the actual code as name
110 110
 if (!is_array($userLang)) {
111
-	$userLang = [
112
-		'code' => $userLang,
113
-		'name' => $userLang,
114
-	];
111
+    $userLang = [
112
+        'code' => $userLang,
113
+        'name' => $userLang,
114
+    ];
115 115
 }
116 116
 
117 117
 ksort($commonLanguages);
118 118
 
119 119
 // sort now by displayed language not the iso-code
120 120
 usort( $languages, function ($a, $b) {
121
-	if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
122
-		// If a doesn't have a name, but b does, list b before a
123
-		return 1;
124
-	}
125
-	if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
126
-		// If a does have a name, but b doesn't, list a before b
127
-		return -1;
128
-	}
129
-	// Otherwise compare the names
130
-	return strcmp($a['name'], $b['name']);
121
+    if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
122
+        // If a doesn't have a name, but b does, list b before a
123
+        return 1;
124
+    }
125
+    if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
126
+        // If a does have a name, but b doesn't, list a before b
127
+        return -1;
128
+    }
129
+    // Otherwise compare the names
130
+    return strcmp($a['name'], $b['name']);
131 131
 });
132 132
 
133 133
 //links to clients
134 134
 $clients = array(
135
-	'desktop' => $config->getSystemValue('customclient_desktop', $defaults->getSyncClientUrl()),
136
-	'android' => $config->getSystemValue('customclient_android', $defaults->getAndroidClientUrl()),
137
-	'ios'     => $config->getSystemValue('customclient_ios', $defaults->getiOSClientUrl())
135
+    'desktop' => $config->getSystemValue('customclient_desktop', $defaults->getSyncClientUrl()),
136
+    'android' => $config->getSystemValue('customclient_android', $defaults->getAndroidClientUrl()),
137
+    'ios'     => $config->getSystemValue('customclient_ios', $defaults->getiOSClientUrl())
138 138
 );
139 139
 
140 140
 // only show root certificate import if external storages are enabled
141 141
 $enableCertImport = false;
142 142
 $externalStorageEnabled = \OC::$server->getAppManager()->isEnabledForUser('files_external');
143 143
 if ($externalStorageEnabled) {
144
-	/** @var \OCA\Files_External\Service\BackendService $backendService */
145
-	$backendService = \OC_Mount_Config::$app->getContainer()->query('\OCA\Files_External\Service\BackendService');
146
-	$enableCertImport = $backendService->isUserMountingAllowed();
144
+    /** @var \OCA\Files_External\Service\BackendService $backendService */
145
+    $backendService = \OC_Mount_Config::$app->getContainer()->query('\OCA\Files_External\Service\BackendService');
146
+    $enableCertImport = $backendService->isUserMountingAllowed();
147 147
 }
148 148
 
149 149
 
@@ -152,9 +152,9 @@  discard block
 block discarded – undo
152 152
 $tmpl = new OC_Template( 'settings', 'personal', 'user');
153 153
 $tmpl->assign('usage', OC_Helper::humanFileSize($storageInfo['used']));
154 154
 if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
155
-	$totalSpace = $l->t('Unlimited');
155
+    $totalSpace = $l->t('Unlimited');
156 156
 } else {
157
-	$totalSpace = OC_Helper::humanFileSize($storageInfo['total']);
157
+    $totalSpace = OC_Helper::humanFileSize($storageInfo['total']);
158 158
 }
159 159
 
160 160
 $uid = $user->getUID();
@@ -212,30 +212,30 @@  discard block
 block discarded – undo
212 212
 
213 213
 // add bottom hardcoded forms from the template
214 214
 if ($enableCertImport) {
215
-	$certificatesTemplate = new OC_Template('settings', 'certificates');
216
-	$certificatesTemplate->assign('type', 'personal');
217
-	$certificatesTemplate->assign('uploadRoute', 'settings.Certificate.addPersonalRootCertificate');
218
-	$certificatesTemplate->assign('certs', $certificateManager->listCertificates());
219
-	$certificatesTemplate->assign('urlGenerator', $urlGenerator);
220
-	$forms[] = $certificatesTemplate->fetchPage();
215
+    $certificatesTemplate = new OC_Template('settings', 'certificates');
216
+    $certificatesTemplate->assign('type', 'personal');
217
+    $certificatesTemplate->assign('uploadRoute', 'settings.Certificate.addPersonalRootCertificate');
218
+    $certificatesTemplate->assign('certs', $certificateManager->listCertificates());
219
+    $certificatesTemplate->assign('urlGenerator', $urlGenerator);
220
+    $forms[] = $certificatesTemplate->fetchPage();
221 221
 }
222 222
 
223 223
 $formsMap = array_map(function($form){
224
-	if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
225
-		$sectionName = str_replace('<h2'.$regs['class'].'>', '', $regs[0]);
226
-		$sectionName = str_replace('</h2>', '', $sectionName);
227
-		$anchor = strtolower($sectionName);
228
-		$anchor = str_replace(' ', '-', $anchor);
229
-
230
-		return array(
231
-			'anchor' => $anchor,
232
-			'section-name' => $sectionName,
233
-			'form' => $form
234
-		);
235
-	}
236
-	return array(
237
-		'form' => $form
238
-	);
224
+    if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
225
+        $sectionName = str_replace('<h2'.$regs['class'].'>', '', $regs[0]);
226
+        $sectionName = str_replace('</h2>', '', $sectionName);
227
+        $anchor = strtolower($sectionName);
228
+        $anchor = str_replace(' ', '-', $anchor);
229
+
230
+        return array(
231
+            'anchor' => $anchor,
232
+            'section-name' => $sectionName,
233
+            'form' => $form
234
+        );
235
+    }
236
+    return array(
237
+        'form' => $form
238
+    );
239 239
 }, $forms);
240 240
 
241 241
 $formsAndMore = array_merge($formsAndMore, $formsMap);
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareesAPIController.php 1 patch
Indentation   +670 added lines, -670 removed lines patch added patch discarded remove patch
@@ -43,674 +43,674 @@
 block discarded – undo
43 43
 
44 44
 class ShareesAPIController extends OCSController {
45 45
 
46
-	/** @var IGroupManager */
47
-	protected $groupManager;
48
-
49
-	/** @var IUserManager */
50
-	protected $userManager;
51
-
52
-	/** @var IManager */
53
-	protected $contactsManager;
54
-
55
-	/** @var IConfig */
56
-	protected $config;
57
-
58
-	/** @var IUserSession */
59
-	protected $userSession;
60
-
61
-	/** @var IURLGenerator */
62
-	protected $urlGenerator;
63
-
64
-	/** @var ILogger */
65
-	protected $logger;
66
-
67
-	/** @var \OCP\Share\IManager */
68
-	protected $shareManager;
69
-
70
-	/** @var IClientService */
71
-	protected $clientService;
72
-
73
-	/** @var ICloudIdManager  */
74
-	protected $cloudIdManager;
75
-
76
-	/** @var bool */
77
-	protected $shareWithGroupOnly = false;
78
-
79
-	/** @var bool */
80
-	protected $shareeEnumeration = true;
81
-
82
-	/** @var int */
83
-	protected $offset = 0;
84
-
85
-	/** @var int */
86
-	protected $limit = 10;
87
-
88
-	/** @var array */
89
-	protected $result = [
90
-		'exact' => [
91
-			'users' => [],
92
-			'groups' => [],
93
-			'remotes' => [],
94
-			'emails' => [],
95
-			'circles' => [],
96
-		],
97
-		'users' => [],
98
-		'groups' => [],
99
-		'remotes' => [],
100
-		'emails' => [],
101
-		'lookup' => [],
102
-		'circles' => [],
103
-	];
104
-
105
-	protected $reachedEndFor = [];
106
-
107
-	/**
108
-	 * @param string $appName
109
-	 * @param IRequest $request
110
-	 * @param IGroupManager $groupManager
111
-	 * @param IUserManager $userManager
112
-	 * @param IManager $contactsManager
113
-	 * @param IConfig $config
114
-	 * @param IUserSession $userSession
115
-	 * @param IURLGenerator $urlGenerator
116
-	 * @param ILogger $logger
117
-	 * @param \OCP\Share\IManager $shareManager
118
-	 * @param IClientService $clientService
119
-	 * @param ICloudIdManager $cloudIdManager
120
-	 */
121
-	public function __construct($appName,
122
-								IRequest $request,
123
-								IGroupManager $groupManager,
124
-								IUserManager $userManager,
125
-								IManager $contactsManager,
126
-								IConfig $config,
127
-								IUserSession $userSession,
128
-								IURLGenerator $urlGenerator,
129
-								ILogger $logger,
130
-								\OCP\Share\IManager $shareManager,
131
-								IClientService $clientService,
132
-								ICloudIdManager $cloudIdManager
133
-	) {
134
-		parent::__construct($appName, $request);
135
-
136
-		$this->groupManager = $groupManager;
137
-		$this->userManager = $userManager;
138
-		$this->contactsManager = $contactsManager;
139
-		$this->config = $config;
140
-		$this->userSession = $userSession;
141
-		$this->urlGenerator = $urlGenerator;
142
-		$this->logger = $logger;
143
-		$this->shareManager = $shareManager;
144
-		$this->clientService = $clientService;
145
-		$this->cloudIdManager = $cloudIdManager;
146
-	}
147
-
148
-	/**
149
-	 * @param string $search
150
-	 */
151
-	protected function getUsers($search) {
152
-		$this->result['users'] = $this->result['exact']['users'] = $users = [];
153
-
154
-		$userGroups = [];
155
-		if ($this->shareWithGroupOnly) {
156
-			// Search in all the groups this user is part of
157
-			$userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
158
-			foreach ($userGroups as $userGroup) {
159
-				$usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset);
160
-				foreach ($usersTmp as $uid => $userDisplayName) {
161
-					$users[$uid] = $userDisplayName;
162
-				}
163
-			}
164
-		} else {
165
-			// Search in all users
166
-			$usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
167
-
168
-			foreach ($usersTmp as $user) {
169
-				$users[$user->getUID()] = $user->getDisplayName();
170
-			}
171
-		}
172
-
173
-		if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
174
-			$this->reachedEndFor[] = 'users';
175
-		}
176
-
177
-		$foundUserById = false;
178
-		$lowerSearch = strtolower($search);
179
-		foreach ($users as $uid => $userDisplayName) {
180
-			if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) {
181
-				if (strtolower($uid) === $lowerSearch) {
182
-					$foundUserById = true;
183
-				}
184
-				$this->result['exact']['users'][] = [
185
-					'label' => $userDisplayName,
186
-					'value' => [
187
-						'shareType' => Share::SHARE_TYPE_USER,
188
-						'shareWith' => $uid,
189
-					],
190
-				];
191
-			} else {
192
-				$this->result['users'][] = [
193
-					'label' => $userDisplayName,
194
-					'value' => [
195
-						'shareType' => Share::SHARE_TYPE_USER,
196
-						'shareWith' => $uid,
197
-					],
198
-				];
199
-			}
200
-		}
201
-
202
-		if ($this->offset === 0 && !$foundUserById) {
203
-			// On page one we try if the search result has a direct hit on the
204
-			// user id and if so, we add that to the exact match list
205
-			$user = $this->userManager->get($search);
206
-			if ($user instanceof IUser) {
207
-				$addUser = true;
208
-
209
-				if ($this->shareWithGroupOnly) {
210
-					// Only add, if we have a common group
211
-					$commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
212
-					$addUser = !empty($commonGroups);
213
-				}
214
-
215
-				if ($addUser) {
216
-					array_push($this->result['exact']['users'], [
217
-						'label' => $user->getDisplayName(),
218
-						'value' => [
219
-							'shareType' => Share::SHARE_TYPE_USER,
220
-							'shareWith' => $user->getUID(),
221
-						],
222
-					]);
223
-				}
224
-			}
225
-		}
226
-
227
-		if (!$this->shareeEnumeration) {
228
-			$this->result['users'] = [];
229
-		}
230
-	}
231
-
232
-	/**
233
-	 * @param string $search
234
-	 */
235
-	protected function getGroups($search) {
236
-		$this->result['groups'] = $this->result['exact']['groups'] = [];
237
-
238
-		$groups = $this->groupManager->search($search, $this->limit, $this->offset);
239
-		$groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
240
-
241
-		if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
242
-			$this->reachedEndFor[] = 'groups';
243
-		}
244
-
245
-		$userGroups =  [];
246
-		if (!empty($groups) && $this->shareWithGroupOnly) {
247
-			// Intersect all the groups that match with the groups this user is a member of
248
-			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
249
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
250
-			$groupIds = array_intersect($groupIds, $userGroups);
251
-		}
252
-
253
-		$lowerSearch = strtolower($search);
254
-		foreach ($groups as $group) {
255
-			// FIXME: use a more efficient approach
256
-			$gid = $group->getGID();
257
-			if (!in_array($gid, $groupIds)) {
258
-				continue;
259
-			}
260
-			if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
261
-				$this->result['exact']['groups'][] = [
262
-					'label' => $group->getDisplayName(),
263
-					'value' => [
264
-						'shareType' => Share::SHARE_TYPE_GROUP,
265
-						'shareWith' => $gid,
266
-					],
267
-				];
268
-			} else {
269
-				$this->result['groups'][] = [
270
-					'label' => $group->getDisplayName(),
271
-					'value' => [
272
-						'shareType' => Share::SHARE_TYPE_GROUP,
273
-						'shareWith' => $gid,
274
-					],
275
-				];
276
-			}
277
-		}
278
-
279
-		if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
280
-			// On page one we try if the search result has a direct hit on the
281
-			// user id and if so, we add that to the exact match list
282
-			$group = $this->groupManager->get($search);
283
-			if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
284
-				array_push($this->result['exact']['groups'], [
285
-					'label' => $group->getDisplayName(),
286
-					'value' => [
287
-						'shareType' => Share::SHARE_TYPE_GROUP,
288
-						'shareWith' => $group->getGID(),
289
-					],
290
-				]);
291
-			}
292
-		}
293
-
294
-		if (!$this->shareeEnumeration) {
295
-			$this->result['groups'] = [];
296
-		}
297
-	}
298
-
299
-
300
-	/**
301
-	 * @param string $search
302
-	 */
303
-	protected function getCircles($search) {
304
-		$this->result['circles'] = $this->result['exact']['circles'] = [];
305
-
306
-		$result = \OCA\Circles\Api\Sharees::search($search, $this->limit, $this->offset);
307
-		if (array_key_exists('circles', $result['exact'])) {
308
-			$this->result['exact']['circles'] = $result['exact']['circles'];
309
-		}
310
-		if (array_key_exists('circles', $result)) {
311
-			$this->result['circles'] = $result['circles'];
312
-		}
313
-	}
314
-
315
-
316
-	/**
317
-	 * @param string $search
318
-	 * @return array
319
-	 */
320
-	protected function getRemote($search) {
321
-		$result = ['results' => [], 'exact' => []];
322
-
323
-		// Search in contacts
324
-		//@todo Pagination missing
325
-		$addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
326
-		$result['exactIdMatch'] = false;
327
-		foreach ($addressBookContacts as $contact) {
328
-			if (isset($contact['isLocalSystemBook'])) {
329
-				continue;
330
-			}
331
-			if (isset($contact['CLOUD'])) {
332
-				$cloudIds = $contact['CLOUD'];
333
-				if (!is_array($cloudIds)) {
334
-					$cloudIds = [$cloudIds];
335
-				}
336
-				$lowerSearch = strtolower($search);
337
-				foreach ($cloudIds as $cloudId) {
338
-					list(, $serverUrl) = $this->splitUserRemote($cloudId);
339
-					if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
340
-						if (strtolower($cloudId) === $lowerSearch) {
341
-							$result['exactIdMatch'] = true;
342
-						}
343
-						$result['exact'][] = [
344
-							'label' => $contact['FN'] . " ($cloudId)",
345
-							'value' => [
346
-								'shareType' => Share::SHARE_TYPE_REMOTE,
347
-								'shareWith' => $cloudId,
348
-								'server' => $serverUrl,
349
-							],
350
-						];
351
-					} else {
352
-						$result['results'][] = [
353
-							'label' => $contact['FN'] . " ($cloudId)",
354
-							'value' => [
355
-								'shareType' => Share::SHARE_TYPE_REMOTE,
356
-								'shareWith' => $cloudId,
357
-								'server' => $serverUrl,
358
-							],
359
-						];
360
-					}
361
-				}
362
-			}
363
-		}
364
-
365
-		if (!$this->shareeEnumeration) {
366
-			$result['results'] = [];
367
-		}
368
-
369
-		if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) {
370
-			$result['exact'][] = [
371
-				'label' => $search,
372
-				'value' => [
373
-					'shareType' => Share::SHARE_TYPE_REMOTE,
374
-					'shareWith' => $search,
375
-				],
376
-			];
377
-		}
378
-
379
-		$this->reachedEndFor[] = 'remotes';
380
-
381
-		return $result;
382
-	}
383
-
384
-	/**
385
-	 * split user and remote from federated cloud id
386
-	 *
387
-	 * @param string $address federated share address
388
-	 * @return array [user, remoteURL]
389
-	 * @throws \Exception
390
-	 */
391
-	public function splitUserRemote($address) {
392
-		try {
393
-			$cloudId = $this->cloudIdManager->resolveCloudId($address);
394
-			return [$cloudId->getUser(), $cloudId->getRemote()];
395
-		} catch (\InvalidArgumentException $e) {
396
-			throw new \Exception('Invalid Federated Cloud ID', 0, $e);
397
-		}
398
-	}
399
-
400
-	/**
401
-	 * Strips away a potential file names and trailing slashes:
402
-	 * - http://localhost
403
-	 * - http://localhost/
404
-	 * - http://localhost/index.php
405
-	 * - http://localhost/index.php/s/{shareToken}
406
-	 *
407
-	 * all return: http://localhost
408
-	 *
409
-	 * @param string $remote
410
-	 * @return string
411
-	 */
412
-	protected function fixRemoteURL($remote) {
413
-		$remote = str_replace('\\', '/', $remote);
414
-		if ($fileNamePosition = strpos($remote, '/index.php')) {
415
-			$remote = substr($remote, 0, $fileNamePosition);
416
-		}
417
-		$remote = rtrim($remote, '/');
418
-
419
-		return $remote;
420
-	}
421
-
422
-	/**
423
-	 * @NoAdminRequired
424
-	 *
425
-	 * @param string $search
426
-	 * @param string $itemType
427
-	 * @param int $page
428
-	 * @param int $perPage
429
-	 * @param int|int[] $shareType
430
-	 * @param bool $lookup
431
-	 * @return DataResponse
432
-	 * @throws OCSBadRequestException
433
-	 */
434
-	public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
435
-
436
-		// only search for string larger than a given threshold
437
-		$threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
438
-		if (strlen($search) < $threshold) {
439
-			return new DataResponse($this->result);
440
-		}
441
-
442
-		// never return more than the max. number of results configured in the config.php
443
-		$maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
444
-		if ($maxResults > 0) {
445
-			$perPage = min($perPage, $maxResults);
446
-		}
447
-		if ($perPage <= 0) {
448
-			throw new OCSBadRequestException('Invalid perPage argument');
449
-		}
450
-		if ($page <= 0) {
451
-			throw new OCSBadRequestException('Invalid page');
452
-		}
453
-
454
-		$shareTypes = [
455
-			Share::SHARE_TYPE_USER,
456
-		];
457
-
458
-		if ($itemType === 'file' || $itemType === 'folder') {
459
-			if ($this->shareManager->allowGroupSharing()) {
460
-				$shareTypes[] = Share::SHARE_TYPE_GROUP;
461
-			}
462
-
463
-			if ($this->isRemoteSharingAllowed($itemType)) {
464
-				$shareTypes[] = Share::SHARE_TYPE_REMOTE;
465
-			}
466
-
467
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
468
-				$shareTypes[] = Share::SHARE_TYPE_EMAIL;
469
-			}
470
-		} else {
471
-			$shareTypes[] = Share::SHARE_TYPE_GROUP;
472
-			$shareTypes[] = Share::SHARE_TYPE_EMAIL;
473
-		}
474
-
475
-		if (\OCP\App::isEnabled('circles')) {
476
-			$shareTypes[] = Share::SHARE_TYPE_CIRCLE;
477
-		}
478
-
479
-		if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
480
-			$shareTypes = array_intersect($shareTypes, $_GET['shareType']);
481
-			sort($shareTypes);
482
-		} else if (is_numeric($shareType)) {
483
-			$shareTypes = array_intersect($shareTypes, [(int) $shareType]);
484
-			sort($shareTypes);
485
-		}
486
-
487
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
488
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
489
-		$this->limit = (int) $perPage;
490
-		$this->offset = $perPage * ($page - 1);
491
-
492
-		return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup);
493
-	}
494
-
495
-	/**
496
-	 * Method to get out the static call for better testing
497
-	 *
498
-	 * @param string $itemType
499
-	 * @return bool
500
-	 */
501
-	protected function isRemoteSharingAllowed($itemType) {
502
-		try {
503
-			$backend = Share::getBackend($itemType);
504
-			return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
505
-		} catch (\Exception $e) {
506
-			return false;
507
-		}
508
-	}
509
-
510
-	/**
511
-	 * Testable search function that does not need globals
512
-	 *
513
-	 * @param string $search
514
-	 * @param string $itemType
515
-	 * @param array $shareTypes
516
-	 * @param int $page
517
-	 * @param int $perPage
518
-	 * @param bool $lookup
519
-	 * @return DataResponse
520
-	 * @throws OCSBadRequestException
521
-	 */
522
-	protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) {
523
-		// Verify arguments
524
-		if ($itemType === null) {
525
-			throw new OCSBadRequestException('Missing itemType');
526
-		}
527
-
528
-		// Get users
529
-		if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
530
-			$this->getUsers($search);
531
-		}
532
-
533
-		// Get groups
534
-		if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
535
-			$this->getGroups($search);
536
-		}
537
-
538
-		// Get circles
539
-		if (in_array(Share::SHARE_TYPE_CIRCLE, $shareTypes)) {
540
-			$this->getCircles($search);
541
-		}
542
-
543
-
544
-		// Get remote
545
-		$remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
546
-		if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
547
-			$remoteResults = $this->getRemote($search);
548
-		}
549
-
550
-		// Get emails
551
-		$mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
552
-		if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) {
553
-			$mailResults = $this->getEmail($search);
554
-		}
555
-
556
-		// Get from lookup server
557
-		if ($lookup) {
558
-			$this->getLookup($search);
559
-		}
560
-
561
-		// if we have a exact match, either for the federated cloud id or for the
562
-		// email address we only return the exact match. It is highly unlikely
563
-		// that the exact same email address and federated cloud id exists
564
-		if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) {
565
-			$this->result['emails'] = $mailResults['results'];
566
-			$this->result['exact']['emails'] = $mailResults['exact'];
567
-		} else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) {
568
-			$this->result['remotes'] = $remoteResults['results'];
569
-			$this->result['exact']['remotes'] = $remoteResults['exact'];
570
-		} else {
571
-			$this->result['remotes'] = $remoteResults['results'];
572
-			$this->result['exact']['remotes'] = $remoteResults['exact'];
573
-			$this->result['emails'] = $mailResults['results'];
574
-			$this->result['exact']['emails'] = $mailResults['exact'];
575
-		}
576
-
577
-		$response = new DataResponse($this->result);
578
-
579
-		if (sizeof($this->reachedEndFor) < 3) {
580
-			$response->addHeader('Link', $this->getPaginationLink($page, [
581
-				'search' => $search,
582
-				'itemType' => $itemType,
583
-				'shareType' => $shareTypes,
584
-				'perPage' => $perPage,
585
-			]));
586
-		}
587
-
588
-		return $response;
589
-	}
590
-
591
-	/**
592
-	 * @param string $search
593
-	 * @return array
594
-	 */
595
-	protected function getEmail($search) {
596
-		$result = ['results' => [], 'exact' => []];
597
-
598
-		// Search in contacts
599
-		//@todo Pagination missing
600
-		$addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
601
-		$result['exactIdMatch'] = false;
602
-		foreach ($addressBookContacts as $contact) {
603
-			if (isset($contact['isLocalSystemBook'])) {
604
-				continue;
605
-			}
606
-			if (isset($contact['EMAIL'])) {
607
-				$emailAddresses = $contact['EMAIL'];
608
-				if (!is_array($emailAddresses)) {
609
-					$emailAddresses = [$emailAddresses];
610
-				}
611
-				foreach ($emailAddresses as $emailAddress) {
612
-					if (strtolower($contact['FN']) === strtolower($search) || strtolower($emailAddress) === strtolower($search)) {
613
-						if (strtolower($emailAddress) === strtolower($search)) {
614
-							$result['exactIdMatch'] = true;
615
-						}
616
-						$result['exact'][] = [
617
-							'label' => $contact['FN'] . " ($emailAddress)",
618
-							'value' => [
619
-								'shareType' => Share::SHARE_TYPE_EMAIL,
620
-								'shareWith' => $emailAddress,
621
-							],
622
-						];
623
-					} else {
624
-						$result['results'][] = [
625
-							'label' => $contact['FN'] . " ($emailAddress)",
626
-							'value' => [
627
-								'shareType' => Share::SHARE_TYPE_EMAIL,
628
-								'shareWith' => $emailAddress,
629
-							],
630
-						];
631
-					}
632
-				}
633
-			}
634
-		}
635
-
636
-		if (!$this->shareeEnumeration) {
637
-			$result['results'] = [];
638
-		}
639
-
640
-		if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) {
641
-			$result['exact'][] = [
642
-				'label' => $search,
643
-				'value' => [
644
-					'shareType' => Share::SHARE_TYPE_EMAIL,
645
-					'shareWith' => $search,
646
-				],
647
-			];
648
-		}
649
-
650
-		$this->reachedEndFor[] = 'emails';
651
-
652
-		return $result;
653
-	}
654
-
655
-	protected function getLookup($search) {
656
-		$isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
657
-		$lookupServerUrl = $this->config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
658
-		$lookupServerUrl = rtrim($lookupServerUrl, '/');
659
-		$result = [];
660
-
661
-		if($isEnabled === 'yes') {
662
-			try {
663
-				$client = $this->clientService->newClient();
664
-				$response = $client->get(
665
-					$lookupServerUrl . '/users?search=' . urlencode($search),
666
-					[
667
-						'timeout' => 10,
668
-						'connect_timeout' => 3,
669
-					]
670
-				);
671
-
672
-				$body = json_decode($response->getBody(), true);
673
-
674
-				$result = [];
675
-				foreach ($body as $lookup) {
676
-					$result[] = [
677
-						'label' => $lookup['federationId'],
678
-						'value' => [
679
-							'shareType' => Share::SHARE_TYPE_REMOTE,
680
-							'shareWith' => $lookup['federationId'],
681
-						],
682
-						'extra' => $lookup,
683
-					];
684
-				}
685
-			} catch (\Exception $e) {}
686
-		}
687
-
688
-		$this->result['lookup'] = $result;
689
-	}
690
-
691
-	/**
692
-	 * Generates a bunch of pagination links for the current page
693
-	 *
694
-	 * @param int $page Current page
695
-	 * @param array $params Parameters for the URL
696
-	 * @return string
697
-	 */
698
-	protected function getPaginationLink($page, array $params) {
699
-		if ($this->isV2()) {
700
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
701
-		} else {
702
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
703
-		}
704
-		$params['page'] = $page + 1;
705
-		$link = '<' . $url . http_build_query($params) . '>; rel="next"';
706
-
707
-		return $link;
708
-	}
709
-
710
-	/**
711
-	 * @return bool
712
-	 */
713
-	protected function isV2() {
714
-		return $this->request->getScriptName() === '/ocs/v2.php';
715
-	}
46
+    /** @var IGroupManager */
47
+    protected $groupManager;
48
+
49
+    /** @var IUserManager */
50
+    protected $userManager;
51
+
52
+    /** @var IManager */
53
+    protected $contactsManager;
54
+
55
+    /** @var IConfig */
56
+    protected $config;
57
+
58
+    /** @var IUserSession */
59
+    protected $userSession;
60
+
61
+    /** @var IURLGenerator */
62
+    protected $urlGenerator;
63
+
64
+    /** @var ILogger */
65
+    protected $logger;
66
+
67
+    /** @var \OCP\Share\IManager */
68
+    protected $shareManager;
69
+
70
+    /** @var IClientService */
71
+    protected $clientService;
72
+
73
+    /** @var ICloudIdManager  */
74
+    protected $cloudIdManager;
75
+
76
+    /** @var bool */
77
+    protected $shareWithGroupOnly = false;
78
+
79
+    /** @var bool */
80
+    protected $shareeEnumeration = true;
81
+
82
+    /** @var int */
83
+    protected $offset = 0;
84
+
85
+    /** @var int */
86
+    protected $limit = 10;
87
+
88
+    /** @var array */
89
+    protected $result = [
90
+        'exact' => [
91
+            'users' => [],
92
+            'groups' => [],
93
+            'remotes' => [],
94
+            'emails' => [],
95
+            'circles' => [],
96
+        ],
97
+        'users' => [],
98
+        'groups' => [],
99
+        'remotes' => [],
100
+        'emails' => [],
101
+        'lookup' => [],
102
+        'circles' => [],
103
+    ];
104
+
105
+    protected $reachedEndFor = [];
106
+
107
+    /**
108
+     * @param string $appName
109
+     * @param IRequest $request
110
+     * @param IGroupManager $groupManager
111
+     * @param IUserManager $userManager
112
+     * @param IManager $contactsManager
113
+     * @param IConfig $config
114
+     * @param IUserSession $userSession
115
+     * @param IURLGenerator $urlGenerator
116
+     * @param ILogger $logger
117
+     * @param \OCP\Share\IManager $shareManager
118
+     * @param IClientService $clientService
119
+     * @param ICloudIdManager $cloudIdManager
120
+     */
121
+    public function __construct($appName,
122
+                                IRequest $request,
123
+                                IGroupManager $groupManager,
124
+                                IUserManager $userManager,
125
+                                IManager $contactsManager,
126
+                                IConfig $config,
127
+                                IUserSession $userSession,
128
+                                IURLGenerator $urlGenerator,
129
+                                ILogger $logger,
130
+                                \OCP\Share\IManager $shareManager,
131
+                                IClientService $clientService,
132
+                                ICloudIdManager $cloudIdManager
133
+    ) {
134
+        parent::__construct($appName, $request);
135
+
136
+        $this->groupManager = $groupManager;
137
+        $this->userManager = $userManager;
138
+        $this->contactsManager = $contactsManager;
139
+        $this->config = $config;
140
+        $this->userSession = $userSession;
141
+        $this->urlGenerator = $urlGenerator;
142
+        $this->logger = $logger;
143
+        $this->shareManager = $shareManager;
144
+        $this->clientService = $clientService;
145
+        $this->cloudIdManager = $cloudIdManager;
146
+    }
147
+
148
+    /**
149
+     * @param string $search
150
+     */
151
+    protected function getUsers($search) {
152
+        $this->result['users'] = $this->result['exact']['users'] = $users = [];
153
+
154
+        $userGroups = [];
155
+        if ($this->shareWithGroupOnly) {
156
+            // Search in all the groups this user is part of
157
+            $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
158
+            foreach ($userGroups as $userGroup) {
159
+                $usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset);
160
+                foreach ($usersTmp as $uid => $userDisplayName) {
161
+                    $users[$uid] = $userDisplayName;
162
+                }
163
+            }
164
+        } else {
165
+            // Search in all users
166
+            $usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
167
+
168
+            foreach ($usersTmp as $user) {
169
+                $users[$user->getUID()] = $user->getDisplayName();
170
+            }
171
+        }
172
+
173
+        if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
174
+            $this->reachedEndFor[] = 'users';
175
+        }
176
+
177
+        $foundUserById = false;
178
+        $lowerSearch = strtolower($search);
179
+        foreach ($users as $uid => $userDisplayName) {
180
+            if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) {
181
+                if (strtolower($uid) === $lowerSearch) {
182
+                    $foundUserById = true;
183
+                }
184
+                $this->result['exact']['users'][] = [
185
+                    'label' => $userDisplayName,
186
+                    'value' => [
187
+                        'shareType' => Share::SHARE_TYPE_USER,
188
+                        'shareWith' => $uid,
189
+                    ],
190
+                ];
191
+            } else {
192
+                $this->result['users'][] = [
193
+                    'label' => $userDisplayName,
194
+                    'value' => [
195
+                        'shareType' => Share::SHARE_TYPE_USER,
196
+                        'shareWith' => $uid,
197
+                    ],
198
+                ];
199
+            }
200
+        }
201
+
202
+        if ($this->offset === 0 && !$foundUserById) {
203
+            // On page one we try if the search result has a direct hit on the
204
+            // user id and if so, we add that to the exact match list
205
+            $user = $this->userManager->get($search);
206
+            if ($user instanceof IUser) {
207
+                $addUser = true;
208
+
209
+                if ($this->shareWithGroupOnly) {
210
+                    // Only add, if we have a common group
211
+                    $commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
212
+                    $addUser = !empty($commonGroups);
213
+                }
214
+
215
+                if ($addUser) {
216
+                    array_push($this->result['exact']['users'], [
217
+                        'label' => $user->getDisplayName(),
218
+                        'value' => [
219
+                            'shareType' => Share::SHARE_TYPE_USER,
220
+                            'shareWith' => $user->getUID(),
221
+                        ],
222
+                    ]);
223
+                }
224
+            }
225
+        }
226
+
227
+        if (!$this->shareeEnumeration) {
228
+            $this->result['users'] = [];
229
+        }
230
+    }
231
+
232
+    /**
233
+     * @param string $search
234
+     */
235
+    protected function getGroups($search) {
236
+        $this->result['groups'] = $this->result['exact']['groups'] = [];
237
+
238
+        $groups = $this->groupManager->search($search, $this->limit, $this->offset);
239
+        $groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
240
+
241
+        if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
242
+            $this->reachedEndFor[] = 'groups';
243
+        }
244
+
245
+        $userGroups =  [];
246
+        if (!empty($groups) && $this->shareWithGroupOnly) {
247
+            // Intersect all the groups that match with the groups this user is a member of
248
+            $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
249
+            $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
250
+            $groupIds = array_intersect($groupIds, $userGroups);
251
+        }
252
+
253
+        $lowerSearch = strtolower($search);
254
+        foreach ($groups as $group) {
255
+            // FIXME: use a more efficient approach
256
+            $gid = $group->getGID();
257
+            if (!in_array($gid, $groupIds)) {
258
+                continue;
259
+            }
260
+            if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
261
+                $this->result['exact']['groups'][] = [
262
+                    'label' => $group->getDisplayName(),
263
+                    'value' => [
264
+                        'shareType' => Share::SHARE_TYPE_GROUP,
265
+                        'shareWith' => $gid,
266
+                    ],
267
+                ];
268
+            } else {
269
+                $this->result['groups'][] = [
270
+                    'label' => $group->getDisplayName(),
271
+                    'value' => [
272
+                        'shareType' => Share::SHARE_TYPE_GROUP,
273
+                        'shareWith' => $gid,
274
+                    ],
275
+                ];
276
+            }
277
+        }
278
+
279
+        if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
280
+            // On page one we try if the search result has a direct hit on the
281
+            // user id and if so, we add that to the exact match list
282
+            $group = $this->groupManager->get($search);
283
+            if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
284
+                array_push($this->result['exact']['groups'], [
285
+                    'label' => $group->getDisplayName(),
286
+                    'value' => [
287
+                        'shareType' => Share::SHARE_TYPE_GROUP,
288
+                        'shareWith' => $group->getGID(),
289
+                    ],
290
+                ]);
291
+            }
292
+        }
293
+
294
+        if (!$this->shareeEnumeration) {
295
+            $this->result['groups'] = [];
296
+        }
297
+    }
298
+
299
+
300
+    /**
301
+     * @param string $search
302
+     */
303
+    protected function getCircles($search) {
304
+        $this->result['circles'] = $this->result['exact']['circles'] = [];
305
+
306
+        $result = \OCA\Circles\Api\Sharees::search($search, $this->limit, $this->offset);
307
+        if (array_key_exists('circles', $result['exact'])) {
308
+            $this->result['exact']['circles'] = $result['exact']['circles'];
309
+        }
310
+        if (array_key_exists('circles', $result)) {
311
+            $this->result['circles'] = $result['circles'];
312
+        }
313
+    }
314
+
315
+
316
+    /**
317
+     * @param string $search
318
+     * @return array
319
+     */
320
+    protected function getRemote($search) {
321
+        $result = ['results' => [], 'exact' => []];
322
+
323
+        // Search in contacts
324
+        //@todo Pagination missing
325
+        $addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
326
+        $result['exactIdMatch'] = false;
327
+        foreach ($addressBookContacts as $contact) {
328
+            if (isset($contact['isLocalSystemBook'])) {
329
+                continue;
330
+            }
331
+            if (isset($contact['CLOUD'])) {
332
+                $cloudIds = $contact['CLOUD'];
333
+                if (!is_array($cloudIds)) {
334
+                    $cloudIds = [$cloudIds];
335
+                }
336
+                $lowerSearch = strtolower($search);
337
+                foreach ($cloudIds as $cloudId) {
338
+                    list(, $serverUrl) = $this->splitUserRemote($cloudId);
339
+                    if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
340
+                        if (strtolower($cloudId) === $lowerSearch) {
341
+                            $result['exactIdMatch'] = true;
342
+                        }
343
+                        $result['exact'][] = [
344
+                            'label' => $contact['FN'] . " ($cloudId)",
345
+                            'value' => [
346
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
347
+                                'shareWith' => $cloudId,
348
+                                'server' => $serverUrl,
349
+                            ],
350
+                        ];
351
+                    } else {
352
+                        $result['results'][] = [
353
+                            'label' => $contact['FN'] . " ($cloudId)",
354
+                            'value' => [
355
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
356
+                                'shareWith' => $cloudId,
357
+                                'server' => $serverUrl,
358
+                            ],
359
+                        ];
360
+                    }
361
+                }
362
+            }
363
+        }
364
+
365
+        if (!$this->shareeEnumeration) {
366
+            $result['results'] = [];
367
+        }
368
+
369
+        if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) {
370
+            $result['exact'][] = [
371
+                'label' => $search,
372
+                'value' => [
373
+                    'shareType' => Share::SHARE_TYPE_REMOTE,
374
+                    'shareWith' => $search,
375
+                ],
376
+            ];
377
+        }
378
+
379
+        $this->reachedEndFor[] = 'remotes';
380
+
381
+        return $result;
382
+    }
383
+
384
+    /**
385
+     * split user and remote from federated cloud id
386
+     *
387
+     * @param string $address federated share address
388
+     * @return array [user, remoteURL]
389
+     * @throws \Exception
390
+     */
391
+    public function splitUserRemote($address) {
392
+        try {
393
+            $cloudId = $this->cloudIdManager->resolveCloudId($address);
394
+            return [$cloudId->getUser(), $cloudId->getRemote()];
395
+        } catch (\InvalidArgumentException $e) {
396
+            throw new \Exception('Invalid Federated Cloud ID', 0, $e);
397
+        }
398
+    }
399
+
400
+    /**
401
+     * Strips away a potential file names and trailing slashes:
402
+     * - http://localhost
403
+     * - http://localhost/
404
+     * - http://localhost/index.php
405
+     * - http://localhost/index.php/s/{shareToken}
406
+     *
407
+     * all return: http://localhost
408
+     *
409
+     * @param string $remote
410
+     * @return string
411
+     */
412
+    protected function fixRemoteURL($remote) {
413
+        $remote = str_replace('\\', '/', $remote);
414
+        if ($fileNamePosition = strpos($remote, '/index.php')) {
415
+            $remote = substr($remote, 0, $fileNamePosition);
416
+        }
417
+        $remote = rtrim($remote, '/');
418
+
419
+        return $remote;
420
+    }
421
+
422
+    /**
423
+     * @NoAdminRequired
424
+     *
425
+     * @param string $search
426
+     * @param string $itemType
427
+     * @param int $page
428
+     * @param int $perPage
429
+     * @param int|int[] $shareType
430
+     * @param bool $lookup
431
+     * @return DataResponse
432
+     * @throws OCSBadRequestException
433
+     */
434
+    public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
435
+
436
+        // only search for string larger than a given threshold
437
+        $threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
438
+        if (strlen($search) < $threshold) {
439
+            return new DataResponse($this->result);
440
+        }
441
+
442
+        // never return more than the max. number of results configured in the config.php
443
+        $maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
444
+        if ($maxResults > 0) {
445
+            $perPage = min($perPage, $maxResults);
446
+        }
447
+        if ($perPage <= 0) {
448
+            throw new OCSBadRequestException('Invalid perPage argument');
449
+        }
450
+        if ($page <= 0) {
451
+            throw new OCSBadRequestException('Invalid page');
452
+        }
453
+
454
+        $shareTypes = [
455
+            Share::SHARE_TYPE_USER,
456
+        ];
457
+
458
+        if ($itemType === 'file' || $itemType === 'folder') {
459
+            if ($this->shareManager->allowGroupSharing()) {
460
+                $shareTypes[] = Share::SHARE_TYPE_GROUP;
461
+            }
462
+
463
+            if ($this->isRemoteSharingAllowed($itemType)) {
464
+                $shareTypes[] = Share::SHARE_TYPE_REMOTE;
465
+            }
466
+
467
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
468
+                $shareTypes[] = Share::SHARE_TYPE_EMAIL;
469
+            }
470
+        } else {
471
+            $shareTypes[] = Share::SHARE_TYPE_GROUP;
472
+            $shareTypes[] = Share::SHARE_TYPE_EMAIL;
473
+        }
474
+
475
+        if (\OCP\App::isEnabled('circles')) {
476
+            $shareTypes[] = Share::SHARE_TYPE_CIRCLE;
477
+        }
478
+
479
+        if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
480
+            $shareTypes = array_intersect($shareTypes, $_GET['shareType']);
481
+            sort($shareTypes);
482
+        } else if (is_numeric($shareType)) {
483
+            $shareTypes = array_intersect($shareTypes, [(int) $shareType]);
484
+            sort($shareTypes);
485
+        }
486
+
487
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
488
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
489
+        $this->limit = (int) $perPage;
490
+        $this->offset = $perPage * ($page - 1);
491
+
492
+        return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup);
493
+    }
494
+
495
+    /**
496
+     * Method to get out the static call for better testing
497
+     *
498
+     * @param string $itemType
499
+     * @return bool
500
+     */
501
+    protected function isRemoteSharingAllowed($itemType) {
502
+        try {
503
+            $backend = Share::getBackend($itemType);
504
+            return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
505
+        } catch (\Exception $e) {
506
+            return false;
507
+        }
508
+    }
509
+
510
+    /**
511
+     * Testable search function that does not need globals
512
+     *
513
+     * @param string $search
514
+     * @param string $itemType
515
+     * @param array $shareTypes
516
+     * @param int $page
517
+     * @param int $perPage
518
+     * @param bool $lookup
519
+     * @return DataResponse
520
+     * @throws OCSBadRequestException
521
+     */
522
+    protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) {
523
+        // Verify arguments
524
+        if ($itemType === null) {
525
+            throw new OCSBadRequestException('Missing itemType');
526
+        }
527
+
528
+        // Get users
529
+        if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
530
+            $this->getUsers($search);
531
+        }
532
+
533
+        // Get groups
534
+        if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
535
+            $this->getGroups($search);
536
+        }
537
+
538
+        // Get circles
539
+        if (in_array(Share::SHARE_TYPE_CIRCLE, $shareTypes)) {
540
+            $this->getCircles($search);
541
+        }
542
+
543
+
544
+        // Get remote
545
+        $remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
546
+        if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
547
+            $remoteResults = $this->getRemote($search);
548
+        }
549
+
550
+        // Get emails
551
+        $mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
552
+        if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) {
553
+            $mailResults = $this->getEmail($search);
554
+        }
555
+
556
+        // Get from lookup server
557
+        if ($lookup) {
558
+            $this->getLookup($search);
559
+        }
560
+
561
+        // if we have a exact match, either for the federated cloud id or for the
562
+        // email address we only return the exact match. It is highly unlikely
563
+        // that the exact same email address and federated cloud id exists
564
+        if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) {
565
+            $this->result['emails'] = $mailResults['results'];
566
+            $this->result['exact']['emails'] = $mailResults['exact'];
567
+        } else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) {
568
+            $this->result['remotes'] = $remoteResults['results'];
569
+            $this->result['exact']['remotes'] = $remoteResults['exact'];
570
+        } else {
571
+            $this->result['remotes'] = $remoteResults['results'];
572
+            $this->result['exact']['remotes'] = $remoteResults['exact'];
573
+            $this->result['emails'] = $mailResults['results'];
574
+            $this->result['exact']['emails'] = $mailResults['exact'];
575
+        }
576
+
577
+        $response = new DataResponse($this->result);
578
+
579
+        if (sizeof($this->reachedEndFor) < 3) {
580
+            $response->addHeader('Link', $this->getPaginationLink($page, [
581
+                'search' => $search,
582
+                'itemType' => $itemType,
583
+                'shareType' => $shareTypes,
584
+                'perPage' => $perPage,
585
+            ]));
586
+        }
587
+
588
+        return $response;
589
+    }
590
+
591
+    /**
592
+     * @param string $search
593
+     * @return array
594
+     */
595
+    protected function getEmail($search) {
596
+        $result = ['results' => [], 'exact' => []];
597
+
598
+        // Search in contacts
599
+        //@todo Pagination missing
600
+        $addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
601
+        $result['exactIdMatch'] = false;
602
+        foreach ($addressBookContacts as $contact) {
603
+            if (isset($contact['isLocalSystemBook'])) {
604
+                continue;
605
+            }
606
+            if (isset($contact['EMAIL'])) {
607
+                $emailAddresses = $contact['EMAIL'];
608
+                if (!is_array($emailAddresses)) {
609
+                    $emailAddresses = [$emailAddresses];
610
+                }
611
+                foreach ($emailAddresses as $emailAddress) {
612
+                    if (strtolower($contact['FN']) === strtolower($search) || strtolower($emailAddress) === strtolower($search)) {
613
+                        if (strtolower($emailAddress) === strtolower($search)) {
614
+                            $result['exactIdMatch'] = true;
615
+                        }
616
+                        $result['exact'][] = [
617
+                            'label' => $contact['FN'] . " ($emailAddress)",
618
+                            'value' => [
619
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
620
+                                'shareWith' => $emailAddress,
621
+                            ],
622
+                        ];
623
+                    } else {
624
+                        $result['results'][] = [
625
+                            'label' => $contact['FN'] . " ($emailAddress)",
626
+                            'value' => [
627
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
628
+                                'shareWith' => $emailAddress,
629
+                            ],
630
+                        ];
631
+                    }
632
+                }
633
+            }
634
+        }
635
+
636
+        if (!$this->shareeEnumeration) {
637
+            $result['results'] = [];
638
+        }
639
+
640
+        if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) {
641
+            $result['exact'][] = [
642
+                'label' => $search,
643
+                'value' => [
644
+                    'shareType' => Share::SHARE_TYPE_EMAIL,
645
+                    'shareWith' => $search,
646
+                ],
647
+            ];
648
+        }
649
+
650
+        $this->reachedEndFor[] = 'emails';
651
+
652
+        return $result;
653
+    }
654
+
655
+    protected function getLookup($search) {
656
+        $isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
657
+        $lookupServerUrl = $this->config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
658
+        $lookupServerUrl = rtrim($lookupServerUrl, '/');
659
+        $result = [];
660
+
661
+        if($isEnabled === 'yes') {
662
+            try {
663
+                $client = $this->clientService->newClient();
664
+                $response = $client->get(
665
+                    $lookupServerUrl . '/users?search=' . urlencode($search),
666
+                    [
667
+                        'timeout' => 10,
668
+                        'connect_timeout' => 3,
669
+                    ]
670
+                );
671
+
672
+                $body = json_decode($response->getBody(), true);
673
+
674
+                $result = [];
675
+                foreach ($body as $lookup) {
676
+                    $result[] = [
677
+                        'label' => $lookup['federationId'],
678
+                        'value' => [
679
+                            'shareType' => Share::SHARE_TYPE_REMOTE,
680
+                            'shareWith' => $lookup['federationId'],
681
+                        ],
682
+                        'extra' => $lookup,
683
+                    ];
684
+                }
685
+            } catch (\Exception $e) {}
686
+        }
687
+
688
+        $this->result['lookup'] = $result;
689
+    }
690
+
691
+    /**
692
+     * Generates a bunch of pagination links for the current page
693
+     *
694
+     * @param int $page Current page
695
+     * @param array $params Parameters for the URL
696
+     * @return string
697
+     */
698
+    protected function getPaginationLink($page, array $params) {
699
+        if ($this->isV2()) {
700
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
701
+        } else {
702
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
703
+        }
704
+        $params['page'] = $page + 1;
705
+        $link = '<' . $url . http_build_query($params) . '>; rel="next"';
706
+
707
+        return $link;
708
+    }
709
+
710
+    /**
711
+     * @return bool
712
+     */
713
+    protected function isV2() {
714
+        return $this->request->getScriptName() === '/ocs/v2.php';
715
+    }
716 716
 }
Please login to merge, or discard this patch.
settings/BackgroundJobs/VerifyUserData.php 1 patch
Indentation   +234 added lines, -234 removed lines patch added patch discarded remove patch
@@ -35,239 +35,239 @@
 block discarded – undo
35 35
 
36 36
 class VerifyUserData extends Job {
37 37
 
38
-	/** @var  bool */
39
-	private $retainJob = true;
40
-
41
-	/** @var int max number of attempts to send the request */
42
-	private $maxTry = 24;
43
-
44
-	/** @var int how much time should be between two tries (1 hour) */
45
-	private $interval = 3600;
46
-
47
-	/** @var AccountManager */
48
-	private $accountManager;
49
-
50
-	/** @var IUserManager */
51
-	private $userManager;
52
-
53
-	/** @var IClientService */
54
-	private $httpClientService;
55
-
56
-	/** @var ILogger */
57
-	private $logger;
58
-
59
-	/** @var string */
60
-	private $lookupServerUrl;
61
-
62
-	/**
63
-	 * VerifyUserData constructor.
64
-	 *
65
-	 * @param AccountManager $accountManager
66
-	 * @param IUserManager $userManager
67
-	 * @param IClientService $clientService
68
-	 * @param ILogger $logger
69
-	 * @param IConfig $config
70
-	 */
71
-	public function __construct(AccountManager $accountManager,
72
-								IUserManager $userManager,
73
-								IClientService $clientService,
74
-								ILogger $logger,
75
-								IConfig $config
76
-	) {
77
-		$this->accountManager = $accountManager;
78
-		$this->userManager = $userManager;
79
-		$this->httpClientService = $clientService;
80
-		$this->logger = $logger;
81
-
82
-		$lookupServerUrl = $config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
83
-		$this->lookupServerUrl = rtrim($lookupServerUrl, '/');
84
-	}
85
-
86
-	/**
87
-	 * run the job, then remove it from the jobList
88
-	 *
89
-	 * @param JobList $jobList
90
-	 * @param ILogger $logger
91
-	 */
92
-	public function execute($jobList, ILogger $logger = null) {
93
-
94
-		if ($this->shouldRun($this->argument)) {
95
-			parent::execute($jobList, $logger);
96
-			$jobList->remove($this, $this->argument);
97
-			if ($this->retainJob) {
98
-				$this->reAddJob($jobList, $this->argument);
99
-			}
100
-		}
101
-
102
-	}
103
-
104
-	protected function run($argument) {
105
-
106
-		$try = (int)$argument['try'] + 1;
107
-
108
-		switch($argument['type']) {
109
-			case AccountManager::PROPERTY_WEBSITE:
110
-				$result = $this->verifyWebsite($argument);
111
-				break;
112
-			case AccountManager::PROPERTY_TWITTER:
113
-			case AccountManager::PROPERTY_EMAIL:
114
-				$result = $this->verifyViaLookupServer($argument, $argument['type']);
115
-				break;
116
-			default:
117
-				// no valid type given, no need to retry
118
-				$this->logger->error($argument['type'] . ' is no valid type for user account data.');
119
-				$result = true;
120
-		}
121
-
122
-		if ($result === true || $try > $this->maxTry) {
123
-			$this->retainJob = false;
124
-		}
125
-	}
126
-
127
-	/**
128
-	 * verify web page
129
-	 *
130
-	 * @param array $argument
131
-	 * @return bool true if we could check the verification code, otherwise false
132
-	 */
133
-	protected function verifyWebsite(array $argument) {
134
-
135
-		$result = false;
136
-
137
-		$url = rtrim($argument['data'], '/') . '/well-known/' . 'CloudIdVerificationCode.txt';
138
-
139
-		$client = $this->httpClientService->newClient();
140
-		try {
141
-			$response = $client->get($url);
142
-		} catch (\Exception $e) {
143
-			return false;
144
-		}
145
-
146
-		if ($response->getStatusCode() === Http::STATUS_OK) {
147
-			$result = true;
148
-			$publishedCode = $response->getBody();
149
-			// remove new lines and spaces
150
-			$publishedCodeSanitized = trim(preg_replace('/\s\s+/', ' ', $publishedCode));
151
-			$user = $this->userManager->get($argument['uid']);
152
-			// we don't check a valid user -> give up
153
-			if ($user === null) {
154
-				$this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
155
-				return $result;
156
-			}
157
-			$userData = $this->accountManager->getUser($user);
158
-
159
-			if ($publishedCodeSanitized === $argument['verificationCode']) {
160
-				$userData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFIED;
161
-			} else {
162
-				$userData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::NOT_VERIFIED;
163
-			}
164
-
165
-			$this->accountManager->updateUser($user, $userData);
166
-		}
167
-
168
-		return $result;
169
-	}
170
-
171
-	/**
172
-	 * verify email address
173
-	 *
174
-	 * @param array $argument
175
-	 * @param string $dataType
176
-	 * @return bool true if we could check the verification code, otherwise false
177
-	 */
178
-	protected function verifyViaLookupServer(array $argument, $dataType) {
179
-
180
-		$user = $this->userManager->get($argument['uid']);
181
-
182
-		// we don't check a valid user -> give up
183
-		if ($user === null) {
184
-			$this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
185
-			return true;
186
-		}
187
-
188
-		$localUserData = $this->accountManager->getUser($user);
189
-		$cloudId = $user->getCloudId();
190
-
191
-		// ask lookup-server for user data
192
-		$lookupServerData = $this->queryLookupServer($cloudId);
193
-
194
-		// for some reasons we couldn't read any data from the lookup server, try again later
195
-		if (empty($lookupServerData)) {
196
-			return false;
197
-		}
198
-
199
-		// lookup server has verification data for wrong user data (e.g. email address), try again later
200
-		if ($lookupServerData[$dataType]['value'] !== $argument['data']) {
201
-			return false;
202
-		}
203
-
204
-		// lookup server hasn't verified the email address so far, try again later
205
-		if ($lookupServerData[$dataType]['verified'] === AccountManager::NOT_VERIFIED) {
206
-			return false;
207
-		}
208
-
209
-		$localUserData[$dataType]['verified'] = AccountManager::VERIFIED;
210
-		$this->accountManager->updateUser($user, $localUserData);
211
-
212
-		return true;
213
-	}
214
-
215
-	/**
216
-	 * @param string $cloudId
217
-	 * @return array
218
-	 */
219
-	protected function queryLookupServer($cloudId) {
220
-		try {
221
-			$client = $this->httpClientService->newClient();
222
-			$response = $client->get(
223
-				$this->lookupServerUrl . '/users?search=' . urlencode($cloudId) . '&exactCloudId=1',
224
-				[
225
-					'timeout' => 10,
226
-					'connect_timeout' => 3,
227
-				]
228
-			);
229
-
230
-			$body = json_decode($response->getBody(), true);
231
-
232
-			if ($body['federationId'] === $cloudId) {
233
-				return $body;
234
-			}
235
-
236
-		} catch (\Exception $e) {
237
-			// do nothing, we will just re-try later
238
-		}
239
-
240
-		return [];
241
-	}
242
-
243
-	/**
244
-	 * re-add background job with new arguments
245
-	 *
246
-	 * @param IJobList $jobList
247
-	 * @param array $argument
248
-	 */
249
-	protected function reAddJob(IJobList $jobList, array $argument) {
250
-		$jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
251
-			[
252
-				'verificationCode' => $argument['verificationCode'],
253
-				'data' => $argument['data'],
254
-				'type' => $argument['type'],
255
-				'uid' => $argument['uid'],
256
-				'try' => (int)$argument['try'] + 1,
257
-				'lastRun' => time()
258
-			]
259
-		);
260
-	}
261
-
262
-	/**
263
-	 * test if it is time for the next run
264
-	 *
265
-	 * @param array $argument
266
-	 * @return bool
267
-	 */
268
-	protected function shouldRun(array $argument) {
269
-		$lastRun = (int)$argument['lastRun'];
270
-		return ((time() - $lastRun) > $this->interval);
271
-	}
38
+    /** @var  bool */
39
+    private $retainJob = true;
40
+
41
+    /** @var int max number of attempts to send the request */
42
+    private $maxTry = 24;
43
+
44
+    /** @var int how much time should be between two tries (1 hour) */
45
+    private $interval = 3600;
46
+
47
+    /** @var AccountManager */
48
+    private $accountManager;
49
+
50
+    /** @var IUserManager */
51
+    private $userManager;
52
+
53
+    /** @var IClientService */
54
+    private $httpClientService;
55
+
56
+    /** @var ILogger */
57
+    private $logger;
58
+
59
+    /** @var string */
60
+    private $lookupServerUrl;
61
+
62
+    /**
63
+     * VerifyUserData constructor.
64
+     *
65
+     * @param AccountManager $accountManager
66
+     * @param IUserManager $userManager
67
+     * @param IClientService $clientService
68
+     * @param ILogger $logger
69
+     * @param IConfig $config
70
+     */
71
+    public function __construct(AccountManager $accountManager,
72
+                                IUserManager $userManager,
73
+                                IClientService $clientService,
74
+                                ILogger $logger,
75
+                                IConfig $config
76
+    ) {
77
+        $this->accountManager = $accountManager;
78
+        $this->userManager = $userManager;
79
+        $this->httpClientService = $clientService;
80
+        $this->logger = $logger;
81
+
82
+        $lookupServerUrl = $config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
83
+        $this->lookupServerUrl = rtrim($lookupServerUrl, '/');
84
+    }
85
+
86
+    /**
87
+     * run the job, then remove it from the jobList
88
+     *
89
+     * @param JobList $jobList
90
+     * @param ILogger $logger
91
+     */
92
+    public function execute($jobList, ILogger $logger = null) {
93
+
94
+        if ($this->shouldRun($this->argument)) {
95
+            parent::execute($jobList, $logger);
96
+            $jobList->remove($this, $this->argument);
97
+            if ($this->retainJob) {
98
+                $this->reAddJob($jobList, $this->argument);
99
+            }
100
+        }
101
+
102
+    }
103
+
104
+    protected function run($argument) {
105
+
106
+        $try = (int)$argument['try'] + 1;
107
+
108
+        switch($argument['type']) {
109
+            case AccountManager::PROPERTY_WEBSITE:
110
+                $result = $this->verifyWebsite($argument);
111
+                break;
112
+            case AccountManager::PROPERTY_TWITTER:
113
+            case AccountManager::PROPERTY_EMAIL:
114
+                $result = $this->verifyViaLookupServer($argument, $argument['type']);
115
+                break;
116
+            default:
117
+                // no valid type given, no need to retry
118
+                $this->logger->error($argument['type'] . ' is no valid type for user account data.');
119
+                $result = true;
120
+        }
121
+
122
+        if ($result === true || $try > $this->maxTry) {
123
+            $this->retainJob = false;
124
+        }
125
+    }
126
+
127
+    /**
128
+     * verify web page
129
+     *
130
+     * @param array $argument
131
+     * @return bool true if we could check the verification code, otherwise false
132
+     */
133
+    protected function verifyWebsite(array $argument) {
134
+
135
+        $result = false;
136
+
137
+        $url = rtrim($argument['data'], '/') . '/well-known/' . 'CloudIdVerificationCode.txt';
138
+
139
+        $client = $this->httpClientService->newClient();
140
+        try {
141
+            $response = $client->get($url);
142
+        } catch (\Exception $e) {
143
+            return false;
144
+        }
145
+
146
+        if ($response->getStatusCode() === Http::STATUS_OK) {
147
+            $result = true;
148
+            $publishedCode = $response->getBody();
149
+            // remove new lines and spaces
150
+            $publishedCodeSanitized = trim(preg_replace('/\s\s+/', ' ', $publishedCode));
151
+            $user = $this->userManager->get($argument['uid']);
152
+            // we don't check a valid user -> give up
153
+            if ($user === null) {
154
+                $this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
155
+                return $result;
156
+            }
157
+            $userData = $this->accountManager->getUser($user);
158
+
159
+            if ($publishedCodeSanitized === $argument['verificationCode']) {
160
+                $userData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFIED;
161
+            } else {
162
+                $userData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::NOT_VERIFIED;
163
+            }
164
+
165
+            $this->accountManager->updateUser($user, $userData);
166
+        }
167
+
168
+        return $result;
169
+    }
170
+
171
+    /**
172
+     * verify email address
173
+     *
174
+     * @param array $argument
175
+     * @param string $dataType
176
+     * @return bool true if we could check the verification code, otherwise false
177
+     */
178
+    protected function verifyViaLookupServer(array $argument, $dataType) {
179
+
180
+        $user = $this->userManager->get($argument['uid']);
181
+
182
+        // we don't check a valid user -> give up
183
+        if ($user === null) {
184
+            $this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
185
+            return true;
186
+        }
187
+
188
+        $localUserData = $this->accountManager->getUser($user);
189
+        $cloudId = $user->getCloudId();
190
+
191
+        // ask lookup-server for user data
192
+        $lookupServerData = $this->queryLookupServer($cloudId);
193
+
194
+        // for some reasons we couldn't read any data from the lookup server, try again later
195
+        if (empty($lookupServerData)) {
196
+            return false;
197
+        }
198
+
199
+        // lookup server has verification data for wrong user data (e.g. email address), try again later
200
+        if ($lookupServerData[$dataType]['value'] !== $argument['data']) {
201
+            return false;
202
+        }
203
+
204
+        // lookup server hasn't verified the email address so far, try again later
205
+        if ($lookupServerData[$dataType]['verified'] === AccountManager::NOT_VERIFIED) {
206
+            return false;
207
+        }
208
+
209
+        $localUserData[$dataType]['verified'] = AccountManager::VERIFIED;
210
+        $this->accountManager->updateUser($user, $localUserData);
211
+
212
+        return true;
213
+    }
214
+
215
+    /**
216
+     * @param string $cloudId
217
+     * @return array
218
+     */
219
+    protected function queryLookupServer($cloudId) {
220
+        try {
221
+            $client = $this->httpClientService->newClient();
222
+            $response = $client->get(
223
+                $this->lookupServerUrl . '/users?search=' . urlencode($cloudId) . '&exactCloudId=1',
224
+                [
225
+                    'timeout' => 10,
226
+                    'connect_timeout' => 3,
227
+                ]
228
+            );
229
+
230
+            $body = json_decode($response->getBody(), true);
231
+
232
+            if ($body['federationId'] === $cloudId) {
233
+                return $body;
234
+            }
235
+
236
+        } catch (\Exception $e) {
237
+            // do nothing, we will just re-try later
238
+        }
239
+
240
+        return [];
241
+    }
242
+
243
+    /**
244
+     * re-add background job with new arguments
245
+     *
246
+     * @param IJobList $jobList
247
+     * @param array $argument
248
+     */
249
+    protected function reAddJob(IJobList $jobList, array $argument) {
250
+        $jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
251
+            [
252
+                'verificationCode' => $argument['verificationCode'],
253
+                'data' => $argument['data'],
254
+                'type' => $argument['type'],
255
+                'uid' => $argument['uid'],
256
+                'try' => (int)$argument['try'] + 1,
257
+                'lastRun' => time()
258
+            ]
259
+        );
260
+    }
261
+
262
+    /**
263
+     * test if it is time for the next run
264
+     *
265
+     * @param array $argument
266
+     * @return bool
267
+     */
268
+    protected function shouldRun(array $argument) {
269
+        $lastRun = (int)$argument['lastRun'];
270
+        return ((time() - $lastRun) > $this->interval);
271
+    }
272 272
 
273 273
 }
Please login to merge, or discard this patch.
lib/private/Accounts/AccountManager.php 1 patch
Indentation   +287 added lines, -287 removed lines patch added patch discarded remove patch
@@ -39,292 +39,292 @@
 block discarded – undo
39 39
  */
40 40
 class AccountManager {
41 41
 
42
-	/** nobody can see my account details */
43
-	const VISIBILITY_PRIVATE = 'private';
44
-	/** only contacts, especially trusted servers can see my contact details */
45
-	const VISIBILITY_CONTACTS_ONLY = 'contacts';
46
-	/** every body ca see my contact detail, will be published to the lookup server */
47
-	const VISIBILITY_PUBLIC = 'public';
48
-
49
-	const PROPERTY_AVATAR = 'avatar';
50
-	const PROPERTY_DISPLAYNAME = 'displayname';
51
-	const PROPERTY_PHONE = 'phone';
52
-	const PROPERTY_EMAIL = 'email';
53
-	const PROPERTY_WEBSITE = 'website';
54
-	const PROPERTY_ADDRESS = 'address';
55
-	const PROPERTY_TWITTER = 'twitter';
56
-
57
-	const NOT_VERIFIED = '0';
58
-	const VERIFICATION_IN_PROGRESS = '1';
59
-	const VERIFIED = '2';
60
-
61
-	/** @var  IDBConnection database connection */
62
-	private $connection;
63
-
64
-	/** @var string table name */
65
-	private $table = 'accounts';
66
-
67
-	/** @var EventDispatcherInterface */
68
-	private $eventDispatcher;
69
-
70
-	/** @var IJobList */
71
-	private $jobList;
72
-
73
-	/**
74
-	 * AccountManager constructor.
75
-	 *
76
-	 * @param IDBConnection $connection
77
-	 * @param EventDispatcherInterface $eventDispatcher
78
-	 * @param IJobList $jobList
79
-	 */
80
-	public function __construct(IDBConnection $connection,
81
-								EventDispatcherInterface $eventDispatcher,
82
-								IJobList $jobList) {
83
-		$this->connection = $connection;
84
-		$this->eventDispatcher = $eventDispatcher;
85
-		$this->jobList = $jobList;
86
-	}
87
-
88
-	/**
89
-	 * update user record
90
-	 *
91
-	 * @param IUser $user
92
-	 * @param $data
93
-	 */
94
-	public function updateUser(IUser $user, $data) {
95
-		$userData = $this->getUser($user);
96
-		$updated = true;
97
-		if (empty($userData)) {
98
-			$this->insertNewUser($user, $data);
99
-		} elseif ($userData !== $data) {
100
-			$data = $this->checkEmailVerification($userData, $data, $user);
101
-			$data = $this->updateVerifyStatus($userData, $data);
102
-			$this->updateExistingUser($user, $data);
103
-		} else {
104
-			// nothing needs to be done if new and old data set are the same
105
-			$updated = false;
106
-		}
107
-
108
-		if ($updated) {
109
-			$this->eventDispatcher->dispatch(
110
-				'OC\AccountManager::userUpdated',
111
-				new GenericEvent($user, $data)
112
-			);
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * get stored data from a given user
118
-	 *
119
-	 * @param IUser $user
120
-	 * @return array
121
-	 */
122
-	public function getUser(IUser $user) {
123
-		$uid = $user->getUID();
124
-		$query = $this->connection->getQueryBuilder();
125
-		$query->select('data')->from($this->table)
126
-			->where($query->expr()->eq('uid', $query->createParameter('uid')))
127
-			->setParameter('uid', $uid);
128
-		$query->execute();
129
-		$result = $query->execute()->fetchAll();
130
-
131
-		if (empty($result)) {
132
-			$userData = $this->buildDefaultUserRecord($user);
133
-			$this->insertNewUser($user, $userData);
134
-			return $userData;
135
-		}
136
-
137
-		$userDataArray = json_decode($result[0]['data'], true);
138
-
139
-		$userDataArray = $this->addMissingDefaultValues($userDataArray);
140
-
141
-		return $userDataArray;
142
-	}
143
-
144
-	/**
145
-	 * check if we need to ask the server for email verification, if yes we create a cronjob
146
-	 *
147
-	 * @param $oldData
148
-	 * @param $newData
149
-	 * @param IUser $user
150
-	 * @return array
151
-	 */
152
-	protected function checkEmailVerification($oldData, $newData, IUser $user) {
153
-		if ($oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']) {
154
-			$this->jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
155
-				[
156
-					'verificationCode' => '',
157
-					'data' => $newData[self::PROPERTY_EMAIL]['value'],
158
-					'type' => self::PROPERTY_EMAIL,
159
-					'uid' => $user->getUID(),
160
-					'try' => 0,
161
-					'lastRun' => time()
162
-				]
163
-			);
164
-			$newData[AccountManager::PROPERTY_EMAIL]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
165
-		}
166
-
167
-		return $newData;
168
-	}
169
-
170
-	/**
171
-	 * make sure that all expected data are set
172
-	 *
173
-	 * @param array $userData
174
-	 * @return array
175
-	 */
176
-	protected function addMissingDefaultValues(array $userData) {
177
-
178
-		foreach ($userData as $key => $value) {
179
-			if (!isset($userData[$key]['verified'])) {
180
-				$userData[$key]['verified'] = self::NOT_VERIFIED;
181
-			}
182
-		}
183
-
184
-		return $userData;
185
-	}
186
-
187
-	/**
188
-	 * reset verification status if personal data changed
189
-	 *
190
-	 * @param array $oldData
191
-	 * @param array $newData
192
-	 * @return array
193
-	 */
194
-	protected function updateVerifyStatus($oldData, $newData) {
195
-
196
-		// which account was already verified successfully?
197
-		$twitterVerified = isset($oldData[self::PROPERTY_TWITTER]['verified']) && $oldData[self::PROPERTY_TWITTER]['verified'] === self::VERIFIED;
198
-		$websiteVerified = isset($oldData[self::PROPERTY_WEBSITE]['verified']) && $oldData[self::PROPERTY_WEBSITE]['verified'] === self::VERIFIED;
199
-		$emailVerified = isset($oldData[self::PROPERTY_EMAIL]['verified']) && $oldData[self::PROPERTY_EMAIL]['verified'] === self::VERIFIED;
200
-
201
-		// keep old verification status if we don't have a new one
202
-		if(!isset($newData[self::PROPERTY_TWITTER]['verified'])) {
203
-			// keep old verification status if value didn't changed and an old value exists
204
-			$keepOldStatus = $newData[self::PROPERTY_TWITTER]['value'] === $oldData[self::PROPERTY_TWITTER]['value'] && isset($oldData[self::PROPERTY_TWITTER]['verified']);
205
-			$newData[self::PROPERTY_TWITTER]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_TWITTER]['verified'] : self::NOT_VERIFIED;
206
-		}
207
-
208
-		if(!isset($newData[self::PROPERTY_WEBSITE]['verified'])) {
209
-			// keep old verification status if value didn't changed and an old value exists
210
-			$keepOldStatus = $newData[self::PROPERTY_WEBSITE]['value'] === $oldData[self::PROPERTY_WEBSITE]['value'] && isset($oldData[self::PROPERTY_WEBSITE]['verified']);
211
-			$newData[self::PROPERTY_WEBSITE]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_WEBSITE]['verified'] : self::NOT_VERIFIED;
212
-		}
213
-
214
-		if(!isset($newData[self::PROPERTY_EMAIL]['verified'])) {
215
-			// keep old verification status if value didn't changed and an old value exists
216
-			$keepOldStatus = $newData[self::PROPERTY_EMAIL]['value'] === $oldData[self::PROPERTY_EMAIL]['value'] && isset($oldData[self::PROPERTY_EMAIL]['verified']);
217
-			$newData[self::PROPERTY_EMAIL]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_EMAIL]['verified'] : self::VERIFICATION_IN_PROGRESS;
218
-		}
219
-
220
-		// reset verification status if a value from a previously verified data was changed
221
-		if($twitterVerified &&
222
-			$oldData[self::PROPERTY_TWITTER]['value'] !== $newData[self::PROPERTY_TWITTER]['value']
223
-		) {
224
-			$newData[self::PROPERTY_TWITTER]['verified'] = self::NOT_VERIFIED;
225
-		}
226
-
227
-		if($websiteVerified &&
228
-			$oldData[self::PROPERTY_WEBSITE]['value'] !== $newData[self::PROPERTY_WEBSITE]['value']
229
-		) {
230
-			$newData[self::PROPERTY_WEBSITE]['verified'] = self::NOT_VERIFIED;
231
-		}
232
-
233
-		if($emailVerified &&
234
-			$oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']
235
-		) {
236
-			$newData[self::PROPERTY_EMAIL]['verified'] = self::NOT_VERIFIED;
237
-		}
238
-
239
-		return $newData;
240
-
241
-	}
242
-
243
-	/**
244
-	 * add new user to accounts table
245
-	 *
246
-	 * @param IUser $user
247
-	 * @param array $data
248
-	 */
249
-	protected function insertNewUser(IUser $user, $data) {
250
-		$uid = $user->getUID();
251
-		$jsonEncodedData = json_encode($data);
252
-		$query = $this->connection->getQueryBuilder();
253
-		$query->insert($this->table)
254
-			->values(
255
-				[
256
-					'uid' => $query->createNamedParameter($uid),
257
-					'data' => $query->createNamedParameter($jsonEncodedData),
258
-				]
259
-			)
260
-			->execute();
261
-	}
262
-
263
-	/**
264
-	 * update existing user in accounts table
265
-	 *
266
-	 * @param IUser $user
267
-	 * @param array $data
268
-	 */
269
-	protected function updateExistingUser(IUser $user, $data) {
270
-		$uid = $user->getUID();
271
-		$jsonEncodedData = json_encode($data);
272
-		$query = $this->connection->getQueryBuilder();
273
-		$query->update($this->table)
274
-			->set('data', $query->createNamedParameter($jsonEncodedData))
275
-			->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
276
-			->execute();
277
-	}
278
-
279
-	/**
280
-	 * build default user record in case not data set exists yet
281
-	 *
282
-	 * @param IUser $user
283
-	 * @return array
284
-	 */
285
-	protected function buildDefaultUserRecord(IUser $user) {
286
-		return [
287
-			self::PROPERTY_DISPLAYNAME =>
288
-				[
289
-					'value' => $user->getDisplayName(),
290
-					'scope' => self::VISIBILITY_CONTACTS_ONLY,
291
-					'verified' => self::NOT_VERIFIED,
292
-				],
293
-			self::PROPERTY_ADDRESS =>
294
-				[
295
-					'value' => '',
296
-					'scope' => self::VISIBILITY_PRIVATE,
297
-					'verified' => self::NOT_VERIFIED,
298
-				],
299
-			self::PROPERTY_WEBSITE =>
300
-				[
301
-					'value' => '',
302
-					'scope' => self::VISIBILITY_PRIVATE,
303
-					'verified' => self::NOT_VERIFIED,
304
-				],
305
-			self::PROPERTY_EMAIL =>
306
-				[
307
-					'value' => $user->getEMailAddress(),
308
-					'scope' => self::VISIBILITY_CONTACTS_ONLY,
309
-					'verified' => self::NOT_VERIFIED,
310
-				],
311
-			self::PROPERTY_AVATAR =>
312
-				[
313
-					'scope' => self::VISIBILITY_CONTACTS_ONLY
314
-				],
315
-			self::PROPERTY_PHONE =>
316
-				[
317
-					'value' => '',
318
-					'scope' => self::VISIBILITY_PRIVATE,
319
-					'verified' => self::NOT_VERIFIED,
320
-				],
321
-			self::PROPERTY_TWITTER =>
322
-				[
323
-					'value' => '',
324
-					'scope' => self::VISIBILITY_PRIVATE,
325
-					'verified' => self::NOT_VERIFIED,
326
-				],
327
-		];
328
-	}
42
+    /** nobody can see my account details */
43
+    const VISIBILITY_PRIVATE = 'private';
44
+    /** only contacts, especially trusted servers can see my contact details */
45
+    const VISIBILITY_CONTACTS_ONLY = 'contacts';
46
+    /** every body ca see my contact detail, will be published to the lookup server */
47
+    const VISIBILITY_PUBLIC = 'public';
48
+
49
+    const PROPERTY_AVATAR = 'avatar';
50
+    const PROPERTY_DISPLAYNAME = 'displayname';
51
+    const PROPERTY_PHONE = 'phone';
52
+    const PROPERTY_EMAIL = 'email';
53
+    const PROPERTY_WEBSITE = 'website';
54
+    const PROPERTY_ADDRESS = 'address';
55
+    const PROPERTY_TWITTER = 'twitter';
56
+
57
+    const NOT_VERIFIED = '0';
58
+    const VERIFICATION_IN_PROGRESS = '1';
59
+    const VERIFIED = '2';
60
+
61
+    /** @var  IDBConnection database connection */
62
+    private $connection;
63
+
64
+    /** @var string table name */
65
+    private $table = 'accounts';
66
+
67
+    /** @var EventDispatcherInterface */
68
+    private $eventDispatcher;
69
+
70
+    /** @var IJobList */
71
+    private $jobList;
72
+
73
+    /**
74
+     * AccountManager constructor.
75
+     *
76
+     * @param IDBConnection $connection
77
+     * @param EventDispatcherInterface $eventDispatcher
78
+     * @param IJobList $jobList
79
+     */
80
+    public function __construct(IDBConnection $connection,
81
+                                EventDispatcherInterface $eventDispatcher,
82
+                                IJobList $jobList) {
83
+        $this->connection = $connection;
84
+        $this->eventDispatcher = $eventDispatcher;
85
+        $this->jobList = $jobList;
86
+    }
87
+
88
+    /**
89
+     * update user record
90
+     *
91
+     * @param IUser $user
92
+     * @param $data
93
+     */
94
+    public function updateUser(IUser $user, $data) {
95
+        $userData = $this->getUser($user);
96
+        $updated = true;
97
+        if (empty($userData)) {
98
+            $this->insertNewUser($user, $data);
99
+        } elseif ($userData !== $data) {
100
+            $data = $this->checkEmailVerification($userData, $data, $user);
101
+            $data = $this->updateVerifyStatus($userData, $data);
102
+            $this->updateExistingUser($user, $data);
103
+        } else {
104
+            // nothing needs to be done if new and old data set are the same
105
+            $updated = false;
106
+        }
107
+
108
+        if ($updated) {
109
+            $this->eventDispatcher->dispatch(
110
+                'OC\AccountManager::userUpdated',
111
+                new GenericEvent($user, $data)
112
+            );
113
+        }
114
+    }
115
+
116
+    /**
117
+     * get stored data from a given user
118
+     *
119
+     * @param IUser $user
120
+     * @return array
121
+     */
122
+    public function getUser(IUser $user) {
123
+        $uid = $user->getUID();
124
+        $query = $this->connection->getQueryBuilder();
125
+        $query->select('data')->from($this->table)
126
+            ->where($query->expr()->eq('uid', $query->createParameter('uid')))
127
+            ->setParameter('uid', $uid);
128
+        $query->execute();
129
+        $result = $query->execute()->fetchAll();
130
+
131
+        if (empty($result)) {
132
+            $userData = $this->buildDefaultUserRecord($user);
133
+            $this->insertNewUser($user, $userData);
134
+            return $userData;
135
+        }
136
+
137
+        $userDataArray = json_decode($result[0]['data'], true);
138
+
139
+        $userDataArray = $this->addMissingDefaultValues($userDataArray);
140
+
141
+        return $userDataArray;
142
+    }
143
+
144
+    /**
145
+     * check if we need to ask the server for email verification, if yes we create a cronjob
146
+     *
147
+     * @param $oldData
148
+     * @param $newData
149
+     * @param IUser $user
150
+     * @return array
151
+     */
152
+    protected function checkEmailVerification($oldData, $newData, IUser $user) {
153
+        if ($oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']) {
154
+            $this->jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
155
+                [
156
+                    'verificationCode' => '',
157
+                    'data' => $newData[self::PROPERTY_EMAIL]['value'],
158
+                    'type' => self::PROPERTY_EMAIL,
159
+                    'uid' => $user->getUID(),
160
+                    'try' => 0,
161
+                    'lastRun' => time()
162
+                ]
163
+            );
164
+            $newData[AccountManager::PROPERTY_EMAIL]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
165
+        }
166
+
167
+        return $newData;
168
+    }
169
+
170
+    /**
171
+     * make sure that all expected data are set
172
+     *
173
+     * @param array $userData
174
+     * @return array
175
+     */
176
+    protected function addMissingDefaultValues(array $userData) {
177
+
178
+        foreach ($userData as $key => $value) {
179
+            if (!isset($userData[$key]['verified'])) {
180
+                $userData[$key]['verified'] = self::NOT_VERIFIED;
181
+            }
182
+        }
183
+
184
+        return $userData;
185
+    }
186
+
187
+    /**
188
+     * reset verification status if personal data changed
189
+     *
190
+     * @param array $oldData
191
+     * @param array $newData
192
+     * @return array
193
+     */
194
+    protected function updateVerifyStatus($oldData, $newData) {
195
+
196
+        // which account was already verified successfully?
197
+        $twitterVerified = isset($oldData[self::PROPERTY_TWITTER]['verified']) && $oldData[self::PROPERTY_TWITTER]['verified'] === self::VERIFIED;
198
+        $websiteVerified = isset($oldData[self::PROPERTY_WEBSITE]['verified']) && $oldData[self::PROPERTY_WEBSITE]['verified'] === self::VERIFIED;
199
+        $emailVerified = isset($oldData[self::PROPERTY_EMAIL]['verified']) && $oldData[self::PROPERTY_EMAIL]['verified'] === self::VERIFIED;
200
+
201
+        // keep old verification status if we don't have a new one
202
+        if(!isset($newData[self::PROPERTY_TWITTER]['verified'])) {
203
+            // keep old verification status if value didn't changed and an old value exists
204
+            $keepOldStatus = $newData[self::PROPERTY_TWITTER]['value'] === $oldData[self::PROPERTY_TWITTER]['value'] && isset($oldData[self::PROPERTY_TWITTER]['verified']);
205
+            $newData[self::PROPERTY_TWITTER]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_TWITTER]['verified'] : self::NOT_VERIFIED;
206
+        }
207
+
208
+        if(!isset($newData[self::PROPERTY_WEBSITE]['verified'])) {
209
+            // keep old verification status if value didn't changed and an old value exists
210
+            $keepOldStatus = $newData[self::PROPERTY_WEBSITE]['value'] === $oldData[self::PROPERTY_WEBSITE]['value'] && isset($oldData[self::PROPERTY_WEBSITE]['verified']);
211
+            $newData[self::PROPERTY_WEBSITE]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_WEBSITE]['verified'] : self::NOT_VERIFIED;
212
+        }
213
+
214
+        if(!isset($newData[self::PROPERTY_EMAIL]['verified'])) {
215
+            // keep old verification status if value didn't changed and an old value exists
216
+            $keepOldStatus = $newData[self::PROPERTY_EMAIL]['value'] === $oldData[self::PROPERTY_EMAIL]['value'] && isset($oldData[self::PROPERTY_EMAIL]['verified']);
217
+            $newData[self::PROPERTY_EMAIL]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_EMAIL]['verified'] : self::VERIFICATION_IN_PROGRESS;
218
+        }
219
+
220
+        // reset verification status if a value from a previously verified data was changed
221
+        if($twitterVerified &&
222
+            $oldData[self::PROPERTY_TWITTER]['value'] !== $newData[self::PROPERTY_TWITTER]['value']
223
+        ) {
224
+            $newData[self::PROPERTY_TWITTER]['verified'] = self::NOT_VERIFIED;
225
+        }
226
+
227
+        if($websiteVerified &&
228
+            $oldData[self::PROPERTY_WEBSITE]['value'] !== $newData[self::PROPERTY_WEBSITE]['value']
229
+        ) {
230
+            $newData[self::PROPERTY_WEBSITE]['verified'] = self::NOT_VERIFIED;
231
+        }
232
+
233
+        if($emailVerified &&
234
+            $oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']
235
+        ) {
236
+            $newData[self::PROPERTY_EMAIL]['verified'] = self::NOT_VERIFIED;
237
+        }
238
+
239
+        return $newData;
240
+
241
+    }
242
+
243
+    /**
244
+     * add new user to accounts table
245
+     *
246
+     * @param IUser $user
247
+     * @param array $data
248
+     */
249
+    protected function insertNewUser(IUser $user, $data) {
250
+        $uid = $user->getUID();
251
+        $jsonEncodedData = json_encode($data);
252
+        $query = $this->connection->getQueryBuilder();
253
+        $query->insert($this->table)
254
+            ->values(
255
+                [
256
+                    'uid' => $query->createNamedParameter($uid),
257
+                    'data' => $query->createNamedParameter($jsonEncodedData),
258
+                ]
259
+            )
260
+            ->execute();
261
+    }
262
+
263
+    /**
264
+     * update existing user in accounts table
265
+     *
266
+     * @param IUser $user
267
+     * @param array $data
268
+     */
269
+    protected function updateExistingUser(IUser $user, $data) {
270
+        $uid = $user->getUID();
271
+        $jsonEncodedData = json_encode($data);
272
+        $query = $this->connection->getQueryBuilder();
273
+        $query->update($this->table)
274
+            ->set('data', $query->createNamedParameter($jsonEncodedData))
275
+            ->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
276
+            ->execute();
277
+    }
278
+
279
+    /**
280
+     * build default user record in case not data set exists yet
281
+     *
282
+     * @param IUser $user
283
+     * @return array
284
+     */
285
+    protected function buildDefaultUserRecord(IUser $user) {
286
+        return [
287
+            self::PROPERTY_DISPLAYNAME =>
288
+                [
289
+                    'value' => $user->getDisplayName(),
290
+                    'scope' => self::VISIBILITY_CONTACTS_ONLY,
291
+                    'verified' => self::NOT_VERIFIED,
292
+                ],
293
+            self::PROPERTY_ADDRESS =>
294
+                [
295
+                    'value' => '',
296
+                    'scope' => self::VISIBILITY_PRIVATE,
297
+                    'verified' => self::NOT_VERIFIED,
298
+                ],
299
+            self::PROPERTY_WEBSITE =>
300
+                [
301
+                    'value' => '',
302
+                    'scope' => self::VISIBILITY_PRIVATE,
303
+                    'verified' => self::NOT_VERIFIED,
304
+                ],
305
+            self::PROPERTY_EMAIL =>
306
+                [
307
+                    'value' => $user->getEMailAddress(),
308
+                    'scope' => self::VISIBILITY_CONTACTS_ONLY,
309
+                    'verified' => self::NOT_VERIFIED,
310
+                ],
311
+            self::PROPERTY_AVATAR =>
312
+                [
313
+                    'scope' => self::VISIBILITY_CONTACTS_ONLY
314
+                ],
315
+            self::PROPERTY_PHONE =>
316
+                [
317
+                    'value' => '',
318
+                    'scope' => self::VISIBILITY_PRIVATE,
319
+                    'verified' => self::NOT_VERIFIED,
320
+                ],
321
+            self::PROPERTY_TWITTER =>
322
+                [
323
+                    'value' => '',
324
+                    'scope' => self::VISIBILITY_PRIVATE,
325
+                    'verified' => self::NOT_VERIFIED,
326
+                ],
327
+        ];
328
+    }
329 329
 
330 330
 }
Please login to merge, or discard this patch.
settings/templates/personal.php 1 patch
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -11,14 +11,14 @@  discard block
 block discarded – undo
11 11
 <div id="app-navigation">
12 12
 	<ul class="with-icon">
13 13
 	<?php foreach($_['forms'] as $form) {
14
-		if (isset($form['anchor'])) {
15
-			$anchor = '#' . $form['anchor'];
16
-			$class = 'nav-icon-' . $form['anchor'];
17
-			$sectionName = $form['section-name'];
18
-			print_unescaped(sprintf("<li><a href='%s' class='%s'>%s</a></li>", \OCP\Util::sanitizeHTML($anchor),
19
-			\OCP\Util::sanitizeHTML($class), \OCP\Util::sanitizeHTML($sectionName)));
20
-		}
21
-	}?>
14
+        if (isset($form['anchor'])) {
15
+            $anchor = '#' . $form['anchor'];
16
+            $class = 'nav-icon-' . $form['anchor'];
17
+            $sectionName = $form['section-name'];
18
+            print_unescaped(sprintf("<li><a href='%s' class='%s'>%s</a></li>", \OCP\Util::sanitizeHTML($anchor),
19
+            \OCP\Util::sanitizeHTML($class), \OCP\Util::sanitizeHTML($sectionName)));
20
+        }
21
+    }?>
22 22
 	</ul>
23 23
 </div>
24 24
 
@@ -30,10 +30,10 @@  discard block
 block discarded – undo
30 30
 		<p id="quotatext">
31 31
 			<?php if ($_['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED): ?>
32 32
 				<?php print_unescaped($l->t('You are using <strong>%s</strong> of <strong>%s</strong>',
33
-					[$_['usage'], $_['total_space']]));?>
33
+                    [$_['usage'], $_['total_space']]));?>
34 34
 			<?php else: ?>
35 35
 				<?php print_unescaped($l->t('You are using <strong>%s</strong> of <strong>%s</strong> (<strong>%s %%</strong>)',
36
-					[$_['usage'], $_['total_space'],  $_['usage_relative']]));?>
36
+                    [$_['usage'], $_['total_space'],  $_['usage_relative']]));?>
37 37
 			<?php endif ?>
38 38
 		</p>
39 39
 	</div>
@@ -101,17 +101,17 @@  discard block
 block discarded – undo
101 101
 			</h2>
102 102
 			<div class="verify <?php if ($_['email'] === ''  || $_['emailScope'] !== 'public') p('hidden'); ?>">
103 103
 				<img id="verify-email" <?php
104
-				switch($_['emailVerification']) {
105
-					case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
106
-						print_unescaped('src="' . image_path('core', 'actions/verifying.svg') . '" title="' . \OC::$server->getL10N()->t('Verifying …') . '"');
107
-						break;
108
-					case \OC\Accounts\AccountManager::VERIFIED:
109
-						print_unescaped('src="' . image_path('core', 'actions/verified.svg') . '"' . \OC::$server->getL10N()->t('Verified') . '"');
110
-						break;
111
-					default:
112
-						print_unescaped('src="' . image_path('core', 'actions/verify.svg') . '" title="' . \OC::$server->getL10N()->t('Verify') . '"');
113
-				}
114
-				?>>
104
+                switch($_['emailVerification']) {
105
+                    case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
106
+                        print_unescaped('src="' . image_path('core', 'actions/verifying.svg') . '" title="' . \OC::$server->getL10N()->t('Verifying …') . '"');
107
+                        break;
108
+                    case \OC\Accounts\AccountManager::VERIFIED:
109
+                        print_unescaped('src="' . image_path('core', 'actions/verified.svg') . '"' . \OC::$server->getL10N()->t('Verified') . '"');
110
+                        break;
111
+                    default:
112
+                        print_unescaped('src="' . image_path('core', 'actions/verify.svg') . '" title="' . \OC::$server->getL10N()->t('Verify') . '"');
113
+                }
114
+                ?>>
115 115
 			</div>
116 116
 			<input type="email" name="email" id="email" value="<?php p($_['email']); ?>"
117 117
 				<?php if(!$_['displayNameChangeSupported']) { print_unescaped('class="hidden"'); } ?>
@@ -167,17 +167,17 @@  discard block
 block discarded – undo
167 167
 			</h2>
168 168
 			<div class="verify <?php if ($_['website'] === ''  || $_['websiteScope'] !== 'public') p('hidden'); ?>">
169 169
 				<img id="verify-website" <?php
170
-				switch($_['websiteVerification']) {
171
-					case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
172
-						print_unescaped('src="' . image_path('core', 'actions/verifying.svg') . '" title="' . \OC::$server->getL10N()->t('Verifying …') . '"');
173
-						break;
174
-					case \OC\Accounts\AccountManager::VERIFIED:
175
-						print_unescaped('src="' . image_path('core', 'actions/verified.svg') . '"' . \OC::$server->getL10N()->t('Verified') . '"');
176
-						break;
177
-					default:
178
-						print_unescaped('src="' . image_path('core', 'actions/verify.svg') . '" title="' . \OC::$server->getL10N()->t('Verify') . '" class="verify-action"');
179
-				}
180
-				?>>
170
+                switch($_['websiteVerification']) {
171
+                    case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
172
+                        print_unescaped('src="' . image_path('core', 'actions/verifying.svg') . '" title="' . \OC::$server->getL10N()->t('Verifying …') . '"');
173
+                        break;
174
+                    case \OC\Accounts\AccountManager::VERIFIED:
175
+                        print_unescaped('src="' . image_path('core', 'actions/verified.svg') . '"' . \OC::$server->getL10N()->t('Verified') . '"');
176
+                        break;
177
+                    default:
178
+                        print_unescaped('src="' . image_path('core', 'actions/verify.svg') . '" title="' . \OC::$server->getL10N()->t('Verify') . '" class="verify-action"');
179
+                }
180
+                ?>>
181 181
 				<div class="verification-dialog popovermenu bubble menu">
182 182
 					<div class="verification-dialog-content">
183 183
 						<p class="explainVerification"></p>
@@ -201,17 +201,17 @@  discard block
 block discarded – undo
201 201
 			</h2>
202 202
 			<div class="verify <?php if ($_['twitter'] === ''  || $_['twitterScope'] !== 'public') p('hidden'); ?>">
203 203
 				<img id="verify-twitter" <?php
204
-				switch($_['twitterVerification']) {
205
-					case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
206
-						print_unescaped('src="' . image_path('core', 'actions/verifying.svg') . '" title="' . \OC::$server->getL10N()->t('Verifying …') . '"');
207
-						break;
208
-					case \OC\Accounts\AccountManager::VERIFIED:
209
-						print_unescaped('src="' . image_path('core', 'actions/verified.svg') . '"' . \OC::$server->getL10N()->t('Verified') . '"');
210
-						break;
211
-					default:
212
-						print_unescaped('src="' . image_path('core', 'actions/verify.svg') . '" title="' . \OC::$server->getL10N()->t('Verify') . '" class="verify-action"');
213
-				}
214
-				?>>
204
+                switch($_['twitterVerification']) {
205
+                    case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
206
+                        print_unescaped('src="' . image_path('core', 'actions/verifying.svg') . '" title="' . \OC::$server->getL10N()->t('Verifying …') . '"');
207
+                        break;
208
+                    case \OC\Accounts\AccountManager::VERIFIED:
209
+                        print_unescaped('src="' . image_path('core', 'actions/verified.svg') . '"' . \OC::$server->getL10N()->t('Verified') . '"');
210
+                        break;
211
+                    default:
212
+                        print_unescaped('src="' . image_path('core', 'actions/verify.svg') . '" title="' . \OC::$server->getL10N()->t('Verify') . '" class="verify-action"');
213
+                }
214
+                ?>>
215 215
 				<div class="verification-dialog popovermenu bubble menu">
216 216
 					<div class="verification-dialog-content">
217 217
 						<p class="explainVerification"></p>
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
 
243 243
 <?php
244 244
 if($_['passwordChangeSupported']) {
245
-	script('jquery-showpassword');
245
+    script('jquery-showpassword');
246 246
 ?>
247 247
 <form id="passwordform" class="section">
248 248
 	<h2 class="inlineblock"><?php p($l->t('Password'));?></h2>
@@ -311,15 +311,15 @@  discard block
 block discarded – undo
311 311
 
312 312
 		<p>
313 313
 			<?php print_unescaped(str_replace(
314
-				[
315
-					'{contributeopen}',
316
-					'{linkclose}',
317
-				],
318
-				[
319
-					'<a href="https://nextcloud.com/contribute" target="_blank" rel="noreferrer">',
320
-					'</a>',
321
-				],
322
-				$l->t('If you want to support the project {contributeopen}join development{linkclose} or {contributeopen}spread the word{linkclose}!'))); ?>
314
+                [
315
+                    '{contributeopen}',
316
+                    '{linkclose}',
317
+                ],
318
+                [
319
+                    '<a href="https://nextcloud.com/contribute" target="_blank" rel="noreferrer">',
320
+                    '</a>',
321
+                ],
322
+                $l->t('If you want to support the project {contributeopen}join development{linkclose} or {contributeopen}spread the word{linkclose}!'))); ?>
323 323
 		</p>
324 324
 
325 325
 	<?php if(OC_APP::isEnabled('firstrunwizard')) {?>
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 </div>
381 381
 
382 382
 <?php foreach($_['forms'] as $form) {
383
-	if (isset($form['form'])) {?>
383
+    if (isset($form['form'])) {?>
384 384
 	<div id="<?php isset($form['anchor']) ? p($form['anchor']) : p('');?>"><?php print_unescaped($form['form']);?></div>
385 385
 	<?php }
386 386
 };?>
Please login to merge, or discard this patch.