1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/webui/options/manage_profile_handler.h"
8 #include "base/bind_helpers.h"
9 #include "base/prefs/pref_service.h"
10 #include "base/prefs/scoped_user_pref_update.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/value_conversions.h"
14 #include "base/values.h"
15 #include "chrome/browser/browser_process.h"
16 #include "chrome/browser/chrome_notification_types.h"
17 #include "chrome/browser/profiles/gaia_info_update_service.h"
18 #include "chrome/browser/profiles/profile.h"
19 #include "chrome/browser/profiles/profile_avatar_icon_util.h"
20 #include "chrome/browser/profiles/profile_info_cache.h"
21 #include "chrome/browser/profiles/profile_manager.h"
22 #include "chrome/browser/profiles/profile_metrics.h"
23 #include "chrome/browser/profiles/profile_shortcut_manager.h"
24 #include "chrome/browser/profiles/profile_window.h"
25 #include "chrome/browser/profiles/profiles_state.h"
26 #include "chrome/browser/signin/signin_manager_factory.h"
27 #include "chrome/browser/sync/profile_sync_service.h"
28 #include "chrome/browser/sync/profile_sync_service_factory.h"
29 #include "chrome/browser/ui/browser_finder.h"
30 #include "chrome/browser/ui/webui/options/options_handlers_helper.h"
31 #include "chrome/common/pref_names.h"
32 #include "chrome/common/url_constants.h"
33 #include "components/signin/core/browser/signin_manager.h"
34 #include "components/signin/core/common/profile_management_switches.h"
35 #include "content/public/browser/browser_thread.h"
36 #include "content/public/browser/notification_service.h"
37 #include "content/public/browser/web_ui.h"
38 #include "google_apis/gaia/gaia_auth_util.h"
39 #include "grit/generated_resources.h"
40 #include "grit/google_chrome_strings.h"
41 #include "ui/base/l10n/l10n_util.h"
42 #include "ui/base/webui/web_ui_util.h"
44 #if defined(ENABLE_SETTINGS_APP)
45 #include "chrome/browser/ui/app_list/app_list_service.h"
46 #include "content/public/browser/web_contents.h"
53 const char kCreateProfileIdentifier[] = "create";
54 const char kManageProfileIdentifier[] = "manage";
56 // Given |args| from the WebUI, parses value 0 as a FilePath |profile_file_path|
57 // and returns true on success.
58 bool GetProfilePathFromArgs(const base::ListValue* args,
59 base::FilePath* profile_file_path) {
60 const base::Value* file_path_value;
61 if (!args->Get(0, &file_path_value))
63 return base::GetValueAsFilePath(*file_path_value, profile_file_path);
68 ManageProfileHandler::ManageProfileHandler()
69 : weak_factory_(this) {
72 ManageProfileHandler::~ManageProfileHandler() {
73 ProfileSyncService* service =
74 ProfileSyncServiceFactory::GetForProfile(Profile::FromWebUI(web_ui()));
75 // Sync may be disabled in tests.
77 service->RemoveObserver(this);
80 void ManageProfileHandler::GetLocalizedValues(
81 base::DictionaryValue* localized_strings) {
82 DCHECK(localized_strings);
84 const bool using_new_profiles_ui = switches::IsNewAvatarMenu();
86 static OptionsStringResource resources[] = {
87 { "manageProfilesNameLabel", IDS_PROFILES_MANAGE_NAME_LABEL },
88 { "manageProfilesDuplicateNameError",
89 IDS_PROFILES_MANAGE_DUPLICATE_NAME_ERROR },
90 { "manageProfilesIconLabel", IDS_PROFILES_MANAGE_ICON_LABEL },
91 { "manageProfilesExistingSupervisedUser",
92 IDS_PROFILES_CREATE_EXISTING_SUPERVISED_USER_ERROR },
93 { "manageProfilesSupervisedSignedInLabel",
94 IDS_PROFILES_CREATE_SUPERVISED_SIGNED_IN_LABEL },
95 { "manageProfilesSupervisedNotSignedIn",
96 IDS_PROFILES_CREATE_SUPERVISED_NOT_SIGNED_IN_HTML },
97 { "manageProfilesSupervisedAccountDetailsOutOfDate",
98 IDS_PROFILES_CREATE_SUPERVISED_ACCOUNT_DETAILS_OUT_OF_DATE_LABEL },
99 { "manageProfilesSupervisedSignInAgainLink",
100 IDS_PROFILES_CREATE_SUPERVISED_SIGN_IN_AGAIN_LINK },
101 { "manageProfilesConfirm", using_new_profiles_ui ? IDS_SAVE : IDS_OK },
102 { "deleteProfileTitle", using_new_profiles_ui ?
103 IDS_NEW_PROFILES_DELETE_TITLE : IDS_PROFILES_DELETE_TITLE },
104 { "deleteProfileOK", using_new_profiles_ui ?
105 IDS_NEW_PROFILES_DELETE_OK_BUTTON_LABEL :
106 IDS_PROFILES_DELETE_OK_BUTTON_LABEL },
107 { "deleteProfileMessage", using_new_profiles_ui ?
108 IDS_NEW_PROFILES_DELETE_MESSAGE : IDS_PROFILES_DELETE_MESSAGE },
109 { "deleteSupervisedProfileAddendum",
110 IDS_PROFILES_DELETE_SUPERVISED_ADDENDUM },
111 { "disconnectManagedProfileTitle",
112 IDS_PROFILES_DISCONNECT_MANAGED_PROFILE_TITLE },
113 { "disconnectManagedProfileOK",
114 IDS_PROFILES_DISCONNECT_MANAGED_PROFILE_OK_BUTTON_LABEL },
115 { "createProfileTitle", using_new_profiles_ui ?
116 IDS_NEW_PROFILES_CREATE_TITLE : IDS_PROFILES_CREATE_TITLE },
117 { "createProfileInstructions", IDS_PROFILES_CREATE_INSTRUCTIONS },
118 { "createProfileConfirm", using_new_profiles_ui ?
119 IDS_ADD : IDS_PROFILES_CREATE_CONFIRM },
120 { "createProfileShortcutCheckbox", IDS_PROFILES_CREATE_SHORTCUT_CHECKBOX },
121 { "createProfileShortcutButton", IDS_PROFILES_CREATE_SHORTCUT_BUTTON },
122 { "removeProfileShortcutButton", IDS_PROFILES_REMOVE_SHORTCUT_BUTTON },
123 { "importExistingSupervisedUserLink",
124 IDS_PROFILES_IMPORT_EXISTING_SUPERVISED_USER_LINK },
127 RegisterStrings(localized_strings, resources, arraysize(resources));
128 RegisterTitle(localized_strings, "manageProfile",
129 using_new_profiles_ui ? IDS_NEW_PROFILES_MANAGE_TITLE :
130 IDS_PROFILES_MANAGE_TITLE);
131 RegisterTitle(localized_strings, "createProfile",
132 using_new_profiles_ui ? IDS_NEW_PROFILES_CREATE_TITLE :
133 IDS_PROFILES_CREATE_TITLE);
135 localized_strings->SetBoolean("profileShortcutsEnabled",
136 ProfileShortcutManager::IsFeatureEnabled());
138 GenerateSignedinUserSpecificStrings(localized_strings);
141 void ManageProfileHandler::InitializeHandler() {
142 registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
143 content::NotificationService::AllSources());
145 Profile* profile = Profile::FromWebUI(web_ui());
146 pref_change_registrar_.Init(profile->GetPrefs());
147 pref_change_registrar_.Add(
148 prefs::kSupervisedUserCreationAllowed,
149 base::Bind(&ManageProfileHandler::OnCreateSupervisedUserPrefChange,
150 base::Unretained(this)));
151 ProfileSyncService* service =
152 ProfileSyncServiceFactory::GetForProfile(profile);
153 // Sync may be disabled for tests.
155 service->AddObserver(this);
158 void ManageProfileHandler::InitializePage() {
159 SendExistingProfileNames();
160 OnCreateSupervisedUserPrefChange();
163 void ManageProfileHandler::RegisterMessages() {
164 web_ui()->RegisterMessageCallback("setProfileIconAndName",
165 base::Bind(&ManageProfileHandler::SetProfileIconAndName,
166 base::Unretained(this)));
167 web_ui()->RegisterMessageCallback("requestDefaultProfileIcons",
168 base::Bind(&ManageProfileHandler::RequestDefaultProfileIcons,
169 base::Unretained(this)));
170 web_ui()->RegisterMessageCallback("requestNewProfileDefaults",
171 base::Bind(&ManageProfileHandler::RequestNewProfileDefaults,
172 base::Unretained(this)));
173 web_ui()->RegisterMessageCallback("requestHasProfileShortcuts",
174 base::Bind(&ManageProfileHandler::RequestHasProfileShortcuts,
175 base::Unretained(this)));
176 web_ui()->RegisterMessageCallback("requestCreateProfileUpdate",
177 base::Bind(&ManageProfileHandler::RequestCreateProfileUpdate,
178 base::Unretained(this)));
179 web_ui()->RegisterMessageCallback("profileIconSelectionChanged",
180 base::Bind(&ManageProfileHandler::ProfileIconSelectionChanged,
181 base::Unretained(this)));
182 #if defined(ENABLE_SETTINGS_APP)
183 web_ui()->RegisterMessageCallback("switchAppListProfile",
184 base::Bind(&ManageProfileHandler::SwitchAppListProfile,
185 base::Unretained(this)));
187 web_ui()->RegisterMessageCallback("addProfileShortcut",
188 base::Bind(&ManageProfileHandler::AddProfileShortcut,
189 base::Unretained(this)));
190 web_ui()->RegisterMessageCallback("removeProfileShortcut",
191 base::Bind(&ManageProfileHandler::RemoveProfileShortcut,
192 base::Unretained(this)));
193 web_ui()->RegisterMessageCallback("refreshGaiaPicture",
194 base::Bind(&ManageProfileHandler::RefreshGaiaPicture,
195 base::Unretained(this)));
196 web_ui()->RegisterMessageCallback(
197 "showDisconnectManagedProfileDialog",
198 base::Bind(&ManageProfileHandler::ShowDisconnectManagedProfileDialog,
199 base::Unretained(this)));
202 void ManageProfileHandler::Uninitialize() {
203 registrar_.RemoveAll();
206 void ManageProfileHandler::Observe(
208 const content::NotificationSource& source,
209 const content::NotificationDetails& details) {
210 if (type == chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED) {
211 SendExistingProfileNames();
212 base::StringValue value(kManageProfileIdentifier);
213 SendProfileIconsAndNames(value);
217 void ManageProfileHandler::OnStateChanged() {
218 RequestCreateProfileUpdate(NULL);
221 void ManageProfileHandler::GenerateSignedinUserSpecificStrings(
222 base::DictionaryValue* dictionary) {
223 std::string username;
224 std::string domain_name;
226 #if !defined(OS_CHROMEOS)
227 Profile* profile = Profile::FromWebUI(web_ui());
229 SigninManagerBase* manager = SigninManagerFactory::GetForProfile(profile);
231 username = manager->GetAuthenticatedUsername();
232 // If there is no one logged in or if the profile name is empty then the
233 // domain name is empty. This happens in browser tests.
234 if (!username.empty()) {
235 domain_name = "<span id=disconnect-managed-profile-domain-name>" +
236 gaia::ExtractDomainName(username) + "</span>";
241 dictionary->SetString(
242 "disconnectManagedProfileDomainInformation",
243 l10n_util::GetStringFUTF16(
244 IDS_PROFILES_DISCONNECT_MANAGED_PROFILE_DOMAIN_INFORMATION,
245 base::ASCIIToUTF16(domain_name)));
247 dictionary->SetString(
248 "disconnectManagedProfileText",
249 l10n_util::GetStringFUTF16(
250 IDS_PROFILES_DISCONNECT_MANAGED_PROFILE_TEXT,
251 base::UTF8ToUTF16(username),
252 base::UTF8ToUTF16(chrome::kSyncGoogleDashboardURL)));
255 void ManageProfileHandler::RequestDefaultProfileIcons(
256 const base::ListValue* args) {
258 bool ok = args->GetString(0, &mode);
260 DCHECK(mode == kCreateProfileIdentifier || mode == kManageProfileIdentifier);
262 base::StringValue value(mode);
263 SendProfileIconsAndNames(value);
267 void ManageProfileHandler::RequestNewProfileDefaults(
268 const base::ListValue* args) {
269 const ProfileInfoCache& cache =
270 g_browser_process->profile_manager()->GetProfileInfoCache();
271 const size_t icon_index = cache.ChooseAvatarIconIndexForNewProfile();
273 base::DictionaryValue profile_info;
274 profile_info.SetString("name", cache.ChooseNameForNewProfile(icon_index));
275 profile_info.SetString("iconURL",
276 profiles::GetDefaultAvatarIconUrl(icon_index));
278 web_ui()->CallJavascriptFunction(
279 "ManageProfileOverlay.receiveNewProfileDefaults", profile_info);
282 void ManageProfileHandler::SendProfileIconsAndNames(
283 const base::StringValue& mode) {
284 base::ListValue image_url_list;
285 base::ListValue default_name_list;
287 // First add the GAIA picture if it's available.
288 const ProfileInfoCache& cache =
289 g_browser_process->profile_manager()->GetProfileInfoCache();
290 Profile* profile = Profile::FromWebUI(web_ui());
291 size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath());
292 if (profile_index != std::string::npos) {
293 const gfx::Image* icon =
294 cache.GetGAIAPictureOfProfileAtIndex(profile_index);
296 gfx::Image icon2 = profiles::GetAvatarIconForWebUI(*icon, true);
297 gaia_picture_url_ = webui::GetBitmapDataUrl(icon2.AsBitmap());
298 image_url_list.AppendString(gaia_picture_url_);
299 default_name_list.AppendString(std::string());
303 // Next add the default avatar icons and names.
304 for (size_t i = 0; i < profiles::GetDefaultAvatarIconCount(); i++) {
305 std::string url = profiles::GetDefaultAvatarIconUrl(i);
306 image_url_list.AppendString(url);
307 default_name_list.AppendString(cache.ChooseNameForNewProfile(i));
310 web_ui()->CallJavascriptFunction(
311 "ManageProfileOverlay.receiveDefaultProfileIconsAndNames", mode,
312 image_url_list, default_name_list);
315 void ManageProfileHandler::SendExistingProfileNames() {
316 const ProfileInfoCache& cache =
317 g_browser_process->profile_manager()->GetProfileInfoCache();
318 base::DictionaryValue profile_name_dict;
319 for (size_t i = 0, e = cache.GetNumberOfProfiles(); i < e; ++i) {
320 profile_name_dict.SetBoolean(
321 base::UTF16ToUTF8(cache.GetNameOfProfileAtIndex(i)), true);
324 web_ui()->CallJavascriptFunction(
325 "ManageProfileOverlay.receiveExistingProfileNames", profile_name_dict);
328 void ManageProfileHandler::ShowDisconnectManagedProfileDialog(
329 const base::ListValue* args) {
330 base::DictionaryValue replacements;
331 GenerateSignedinUserSpecificStrings(&replacements);
332 web_ui()->CallJavascriptFunction(
333 "ManageProfileOverlay.showDisconnectManagedProfileDialog", replacements);
336 void ManageProfileHandler::SetProfileIconAndName(const base::ListValue* args) {
339 base::FilePath profile_file_path;
340 if (!GetProfilePathFromArgs(args, &profile_file_path))
344 g_browser_process->profile_manager()->GetProfile(profile_file_path);
348 std::string icon_url;
349 if (!args->GetString(1, &icon_url))
352 PrefService* pref_service = profile->GetPrefs();
353 // Updating the profile preferences will cause the cache to be updated.
355 // Metrics logging variable.
356 bool previously_using_gaia_icon =
357 pref_service->GetBoolean(prefs::kProfileUsingGAIAAvatar);
359 size_t new_icon_index;
360 if (icon_url == gaia_picture_url_) {
361 pref_service->SetBoolean(prefs::kProfileUsingDefaultAvatar, false);
362 pref_service->SetBoolean(prefs::kProfileUsingGAIAAvatar, true);
363 if (!previously_using_gaia_icon) {
364 // Only log if they changed to the GAIA photo.
365 // Selection of GAIA photo as avatar is logged as part of the function
367 ProfileMetrics::LogProfileSwitchGaia(ProfileMetrics::GAIA_OPT_IN);
369 } else if (profiles::IsDefaultAvatarIconUrl(icon_url, &new_icon_index)) {
370 ProfileMetrics::LogProfileAvatarSelection(new_icon_index);
371 pref_service->SetInteger(prefs::kProfileAvatarIndex, new_icon_index);
372 pref_service->SetBoolean(prefs::kProfileUsingDefaultAvatar, false);
373 pref_service->SetBoolean(prefs::kProfileUsingGAIAAvatar, false);
375 ProfileMetrics::LogProfileUpdate(profile_file_path);
377 if (profile->IsSupervised())
380 base::string16 new_profile_name;
381 if (!args->GetString(2, &new_profile_name))
384 profiles::UpdateProfileName(profile, new_profile_name);
387 #if defined(ENABLE_SETTINGS_APP)
388 void ManageProfileHandler::SwitchAppListProfile(const base::ListValue* args) {
390 DCHECK(profiles::IsMultipleProfilesEnabled());
392 const base::Value* file_path_value;
393 base::FilePath profile_file_path;
394 if (!args->Get(0, &file_path_value) ||
395 !base::GetValueAsFilePath(*file_path_value, &profile_file_path))
398 AppListService* app_list_service = AppListService::Get(
399 options::helper::GetDesktopType(web_ui()));
400 app_list_service->SetProfilePath(profile_file_path);
401 app_list_service->Show();
403 // Close the settings app, since it will now be for the wrong profile.
404 web_ui()->GetWebContents()->Close();
406 #endif // defined(ENABLE_SETTINGS_APP)
408 void ManageProfileHandler::ProfileIconSelectionChanged(
409 const base::ListValue* args) {
412 base::FilePath profile_file_path;
413 if (!GetProfilePathFromArgs(args, &profile_file_path))
416 // Currently this only supports editing the current profile's info.
417 if (profile_file_path != Profile::FromWebUI(web_ui())->GetPath())
420 std::string icon_url;
421 if (!args->GetString(1, &icon_url))
424 if (icon_url != gaia_picture_url_)
427 // If the selection is the GAIA picture then also show the profile name in the
428 // text field. This will display either the GAIA given name, if available,
429 // or the first name.
430 ProfileInfoCache& cache =
431 g_browser_process->profile_manager()->GetProfileInfoCache();
432 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_file_path);
433 if (profile_index == std::string::npos)
435 base::string16 gaia_name = cache.GetNameOfProfileAtIndex(profile_index);
436 if (gaia_name.empty())
439 base::StringValue gaia_name_value(gaia_name);
440 base::StringValue mode_value(kManageProfileIdentifier);
441 web_ui()->CallJavascriptFunction("ManageProfileOverlay.setProfileName",
442 gaia_name_value, mode_value);
445 void ManageProfileHandler::RequestHasProfileShortcuts(
446 const base::ListValue* args) {
447 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
448 DCHECK(ProfileShortcutManager::IsFeatureEnabled());
450 base::FilePath profile_file_path;
451 if (!GetProfilePathFromArgs(args, &profile_file_path))
454 const ProfileInfoCache& cache =
455 g_browser_process->profile_manager()->GetProfileInfoCache();
456 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_file_path);
457 if (profile_index == std::string::npos)
460 const base::FilePath profile_path =
461 cache.GetPathOfProfileAtIndex(profile_index);
462 ProfileShortcutManager* shortcut_manager =
463 g_browser_process->profile_manager()->profile_shortcut_manager();
464 shortcut_manager->HasProfileShortcuts(
465 profile_path, base::Bind(&ManageProfileHandler::OnHasProfileShortcuts,
466 weak_factory_.GetWeakPtr()));
469 void ManageProfileHandler::RequestCreateProfileUpdate(
470 const base::ListValue* args) {
471 Profile* profile = Profile::FromWebUI(web_ui());
472 SigninManagerBase* manager =
473 SigninManagerFactory::GetForProfile(profile);
474 base::string16 username =
475 base::UTF8ToUTF16(manager->GetAuthenticatedUsername());
476 ProfileSyncService* service =
477 ProfileSyncServiceFactory::GetForProfile(profile);
478 GoogleServiceAuthError::State state = service->GetAuthError().state();
479 bool has_error = (state == GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS ||
480 state == GoogleServiceAuthError::USER_NOT_SIGNED_UP ||
481 state == GoogleServiceAuthError::ACCOUNT_DELETED ||
482 state == GoogleServiceAuthError::ACCOUNT_DISABLED);
483 web_ui()->CallJavascriptFunction("CreateProfileOverlay.updateSignedInStatus",
484 base::StringValue(username),
485 base::FundamentalValue(has_error));
487 OnCreateSupervisedUserPrefChange();
490 void ManageProfileHandler::OnCreateSupervisedUserPrefChange() {
491 PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();
492 base::FundamentalValue allowed(
493 prefs->GetBoolean(prefs::kSupervisedUserCreationAllowed));
494 web_ui()->CallJavascriptFunction(
495 "CreateProfileOverlay.updateSupervisedUsersAllowed", allowed);
498 void ManageProfileHandler::OnHasProfileShortcuts(bool has_shortcuts) {
499 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
501 const base::FundamentalValue has_shortcuts_value(has_shortcuts);
502 web_ui()->CallJavascriptFunction(
503 "ManageProfileOverlay.receiveHasProfileShortcuts", has_shortcuts_value);
506 void ManageProfileHandler::AddProfileShortcut(const base::ListValue* args) {
507 base::FilePath profile_file_path;
508 if (!GetProfilePathFromArgs(args, &profile_file_path))
511 DCHECK(ProfileShortcutManager::IsFeatureEnabled());
512 ProfileShortcutManager* shortcut_manager =
513 g_browser_process->profile_manager()->profile_shortcut_manager();
514 DCHECK(shortcut_manager);
516 shortcut_manager->CreateProfileShortcut(profile_file_path);
518 // Update the UI buttons.
519 OnHasProfileShortcuts(true);
522 void ManageProfileHandler::RemoveProfileShortcut(const base::ListValue* args) {
523 base::FilePath profile_file_path;
524 if (!GetProfilePathFromArgs(args, &profile_file_path))
527 DCHECK(ProfileShortcutManager::IsFeatureEnabled());
528 ProfileShortcutManager* shortcut_manager =
529 g_browser_process->profile_manager()->profile_shortcut_manager();
530 DCHECK(shortcut_manager);
532 shortcut_manager->RemoveProfileShortcuts(profile_file_path);
534 // Update the UI buttons.
535 OnHasProfileShortcuts(false);
538 void ManageProfileHandler::RefreshGaiaPicture(const base::ListValue* args) {
539 profiles::UpdateGaiaProfilePhotoIfNeeded(Profile::FromWebUI(web_ui()));
542 } // namespace options