athena: Re-add ui_chromeos resources in athena_resources.pak.
[chromium-blink-merge.git] / extensions / browser / extension_prefs.cc
blobefe3ba419ecf4e82d62b4b8ff5ac80204abbf91b
1 // Copyright 2014 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 "extensions/browser/extension_prefs.h"
7 #include <iterator>
9 #include "base/command_line.h"
10 #include "base/prefs/pref_notifier.h"
11 #include "base/prefs/pref_service.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_util.h"
14 #include "base/value_conversions.h"
15 #include "components/pref_registry/pref_registry_syncable.h"
16 #include "extensions/browser/admin_policy.h"
17 #include "extensions/browser/app_sorting.h"
18 #include "extensions/browser/event_router.h"
19 #include "extensions/browser/extension_pref_store.h"
20 #include "extensions/browser/extension_prefs_factory.h"
21 #include "extensions/browser/extension_prefs_observer.h"
22 #include "extensions/browser/install_flag.h"
23 #include "extensions/browser/pref_names.h"
24 #include "extensions/common/feature_switch.h"
25 #include "extensions/common/manifest.h"
26 #include "extensions/common/permissions/permission_set.h"
27 #include "extensions/common/permissions/permissions_info.h"
28 #include "extensions/common/url_pattern.h"
29 #include "extensions/common/user_script.h"
30 #include "ui/base/l10n/l10n_util.h"
32 using base::Value;
33 using base::DictionaryValue;
34 using base::ListValue;
36 namespace extensions {
38 namespace {
40 // Additional preferences keys, which are not needed by external clients.
42 // True if this extension is running. Note this preference stops getting updated
43 // during Chrome shutdown (and won't be updated on a browser crash) and so can
44 // be used at startup to determine whether the extension was running when Chrome
45 // was last terminated.
46 const char kPrefRunning[] = "running";
48 // Whether this extension had windows when it was last running.
49 const char kIsActive[] = "is_active";
51 // Where an extension was installed from. (see Manifest::Location)
52 const char kPrefLocation[] = "location";
54 // Enabled, disabled, killed, etc. (see Extension::State)
55 const char kPrefState[] = "state";
57 // The path to the current version's manifest file.
58 const char kPrefPath[] = "path";
60 // The dictionary containing the extension's manifest.
61 const char kPrefManifest[] = "manifest";
63 // The version number.
64 const char kPrefVersion[] = "manifest.version";
66 // Indicates whether an extension is blacklisted.
67 const char kPrefBlacklist[] = "blacklist";
69 // If extension is greylisted.
70 const char kPrefBlacklistState[] = "blacklist_state";
72 // The count of how many times we prompted the user to acknowledge an
73 // extension.
74 const char kPrefAcknowledgePromptCount[] = "ack_prompt_count";
76 // Indicates whether the user has acknowledged various types of extensions.
77 const char kPrefExternalAcknowledged[] = "ack_external";
78 const char kPrefBlacklistAcknowledged[] = "ack_blacklist";
79 const char kPrefWipeoutAcknowledged[] = "ack_wiped";
80 const char kPrefSettingsBubbleAcknowledged[] = "ack_settings_bubble";
81 const char kPrefNtpBubbleAcknowledged[] = "ack_ntp_bubble";
82 const char kPrefProxyBubbleAcknowledged[] = "ack_proxy_bubble";
84 // Indicates whether the external extension was installed during the first
85 // run of this profile.
86 const char kPrefExternalInstallFirstRun[] = "external_first_run";
88 // Indicates whether to show an install warning when the user enables.
89 const char kExtensionDidEscalatePermissions[] = "install_warning_on_enable";
91 // DO NOT USE, use kPrefDisableReasons instead.
92 // Indicates whether the extension was updated while it was disabled.
93 const char kDeprecatedPrefDisableReason[] = "disable_reason";
95 // A bitmask of all the reasons an extension is disabled.
96 const char kPrefDisableReasons[] = "disable_reasons";
98 // The key for a serialized Time value indicating the start of the day (from the
99 // server's perspective) an extension last included a "ping" parameter during
100 // its update check.
101 const char kLastPingDay[] = "lastpingday";
103 // Similar to kLastPingDay, but for "active" instead of "rollcall" pings.
104 const char kLastActivePingDay[] = "last_active_pingday";
106 // A bit we use to keep track of whether we need to do an "active" ping.
107 const char kActiveBit[] = "active_bit";
109 // Path for settings specific to blacklist update.
110 const char kExtensionsBlacklistUpdate[] = "extensions.blacklistupdate";
112 // Path for the delayed install info dictionary preference. The actual string
113 // value is a legacy artifact for when delayed installs only pertained to
114 // updates that were waiting for idle.
115 const char kDelayedInstallInfo[] = "idle_install_info";
117 // Reason why the extension's install was delayed.
118 const char kDelayedInstallReason[] = "delay_install_reason";
120 // Path for the suggested page ordinal of a delayed extension install.
121 const char kPrefSuggestedPageOrdinal[] = "suggested_page_ordinal";
123 // A preference that, if true, will allow this extension to run in incognito
124 // mode.
125 const char kPrefIncognitoEnabled[] = "incognito";
127 // A preference to control whether an extension is allowed to inject script in
128 // pages with file URLs.
129 const char kPrefAllowFileAccess[] = "newAllowFileAccess";
130 // TODO(jstritar): As part of fixing http://crbug.com/91577, we revoked all
131 // extension file access by renaming the pref. We should eventually clean up
132 // the old flag and possibly go back to that name.
133 // const char kPrefAllowFileAccessOld[] = "allowFileAccess";
135 // A preference specifying if the user dragged the app on the NTP.
136 const char kPrefUserDraggedApp[] = "user_dragged_app_ntp";
138 // Preferences that hold which permissions the user has granted the extension.
139 // We explicitly keep track of these so that extensions can contain unknown
140 // permissions, for backwards compatibility reasons, and we can still prompt
141 // the user to accept them once recognized. We store the active permission
142 // permissions because they may differ from those defined in the manifest.
143 const char kPrefActivePermissions[] = "active_permissions";
144 const char kPrefGrantedPermissions[] = "granted_permissions";
146 // The preference names for PermissionSet values.
147 const char kPrefAPIs[] = "api";
148 const char kPrefManifestPermissions[] = "manifest_permissions";
149 const char kPrefExplicitHosts[] = "explicit_host";
150 const char kPrefScriptableHosts[] = "scriptable_host";
152 // The preference names for the old granted permissions scheme.
153 const char kPrefOldGrantedFullAccess[] = "granted_permissions.full";
154 const char kPrefOldGrantedHosts[] = "granted_permissions.host";
155 const char kPrefOldGrantedAPIs[] = "granted_permissions.api";
157 // A preference that indicates when an extension was installed.
158 const char kPrefInstallTime[] = "install_time";
160 // A preference which saves the creation flags for extensions.
161 const char kPrefCreationFlags[] = "creation_flags";
163 // A preference that indicates whether the extension was installed from the
164 // Chrome Web Store.
165 const char kPrefFromWebStore[] = "from_webstore";
167 // A preference that indicates whether the extension was installed from a
168 // mock App created from a bookmark.
169 const char kPrefFromBookmark[] = "from_bookmark";
171 // A preference that indicates whether the extension was installed as a
172 // default app.
173 const char kPrefWasInstalledByDefault[] = "was_installed_by_default";
175 // A preference that indicates whether the extension was installed as an
176 // OEM app.
177 const char kPrefWasInstalledByOem[] = "was_installed_by_oem";
179 // Key for Geometry Cache preference.
180 const char kPrefGeometryCache[] = "geometry_cache";
182 // A preference that indicates when an extension is last launched.
183 const char kPrefLastLaunchTime[] = "last_launch_time";
185 // A preference indicating whether the extension is an ephemeral app.
186 const char kPrefEphemeralApp[] = "ephemeral_app";
188 // Am installation parameter bundled with an extension.
189 const char kPrefInstallParam[] = "install_parameter";
191 // A list of installed ids and a signature.
192 const char kInstallSignature[] = "extensions.install_signature";
194 // A boolean preference that indicates whether the extension should not be
195 // synced. Default value is false.
196 const char kPrefDoNotSync[] = "do_not_sync";
198 const char kCorruptedDisableCount[] = "extensions.corrupted_disable_count";
200 // Provider of write access to a dictionary storing extension prefs.
201 class ScopedExtensionPrefUpdate : public DictionaryPrefUpdate {
202 public:
203 ScopedExtensionPrefUpdate(PrefService* service,
204 const std::string& extension_id) :
205 DictionaryPrefUpdate(service, pref_names::kExtensions),
206 extension_id_(extension_id) {}
208 virtual ~ScopedExtensionPrefUpdate() {
211 // DictionaryPrefUpdate overrides:
212 virtual base::DictionaryValue* Get() OVERRIDE {
213 base::DictionaryValue* dict = DictionaryPrefUpdate::Get();
214 base::DictionaryValue* extension = NULL;
215 if (!dict->GetDictionary(extension_id_, &extension)) {
216 // Extension pref does not exist, create it.
217 extension = new base::DictionaryValue();
218 dict->SetWithoutPathExpansion(extension_id_, extension);
220 return extension;
223 private:
224 const std::string extension_id_;
226 DISALLOW_COPY_AND_ASSIGN(ScopedExtensionPrefUpdate);
229 std::string JoinPrefs(const std::string& parent, const char* child) {
230 return parent + "." + child;
233 // Checks if kPrefBlacklist is set to true in the base::DictionaryValue.
234 // Return false if the value is false or kPrefBlacklist does not exist.
235 // This is used to decide if an extension is blacklisted.
236 bool IsBlacklistBitSet(const base::DictionaryValue* ext) {
237 bool bool_value;
238 return ext->GetBoolean(kPrefBlacklist, &bool_value) && bool_value;
241 void LoadExtensionControlledPrefs(ExtensionPrefs* prefs,
242 ExtensionPrefValueMap* value_map,
243 const std::string& extension_id,
244 ExtensionPrefsScope scope) {
245 std::string scope_string;
246 if (!pref_names::ScopeToPrefName(scope, &scope_string))
247 return;
248 std::string key = extension_id + "." + scope_string;
250 const base::DictionaryValue* source_dict =
251 prefs->pref_service()->GetDictionary(pref_names::kExtensions);
252 const base::DictionaryValue* preferences = NULL;
253 if (!source_dict->GetDictionary(key, &preferences))
254 return;
256 for (base::DictionaryValue::Iterator iter(*preferences); !iter.IsAtEnd();
257 iter.Advance()) {
258 value_map->SetExtensionPref(
259 extension_id, iter.key(), scope, iter.value().DeepCopy());
263 } // namespace
266 // TimeProvider
269 ExtensionPrefs::TimeProvider::TimeProvider() {
272 ExtensionPrefs::TimeProvider::~TimeProvider() {
275 base::Time ExtensionPrefs::TimeProvider::GetCurrentTime() const {
276 return base::Time::Now();
280 // ScopedUpdate
282 template <typename T, base::Value::Type type_enum_value>
283 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::ScopedUpdate(
284 ExtensionPrefs* prefs,
285 const std::string& extension_id,
286 const std::string& key)
287 : update_(prefs->pref_service(), pref_names::kExtensions),
288 extension_id_(extension_id),
289 key_(key) {
290 DCHECK(Extension::IdIsValid(extension_id_));
293 template <typename T, base::Value::Type type_enum_value>
294 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::~ScopedUpdate() {
297 template <typename T, base::Value::Type type_enum_value>
298 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Get() {
299 base::DictionaryValue* dict = update_.Get();
300 base::DictionaryValue* extension = NULL;
301 base::Value* key_value = NULL;
302 if (!dict->GetDictionary(extension_id_, &extension) ||
303 !extension->Get(key_, &key_value)) {
304 return NULL;
306 return key_value->GetType() == type_enum_value ?
307 static_cast<T*>(key_value) :
308 NULL;
311 template <typename T, base::Value::Type type_enum_value>
312 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Create() {
313 base::DictionaryValue* dict = update_.Get();
314 base::DictionaryValue* extension = NULL;
315 base::Value* key_value = NULL;
316 T* value_as_t = NULL;
317 if (!dict->GetDictionary(extension_id_, &extension)) {
318 extension = new base::DictionaryValue;
319 dict->SetWithoutPathExpansion(extension_id_, extension);
321 if (!extension->Get(key_, &key_value)) {
322 value_as_t = new T;
323 extension->SetWithoutPathExpansion(key_, value_as_t);
324 } else {
325 CHECK(key_value->GetType() == type_enum_value);
326 value_as_t = static_cast<T*>(key_value);
328 return value_as_t;
331 // Explicit instantiations for Dictionary and List value types.
332 template class ExtensionPrefs::ScopedUpdate<base::DictionaryValue,
333 base::Value::TYPE_DICTIONARY>;
334 template class ExtensionPrefs::ScopedUpdate<base::ListValue,
335 base::Value::TYPE_LIST>;
338 // ExtensionPrefs
341 // static
342 ExtensionPrefs* ExtensionPrefs::Create(
343 PrefService* prefs,
344 const base::FilePath& root_dir,
345 ExtensionPrefValueMap* extension_pref_value_map,
346 scoped_ptr<AppSorting> app_sorting,
347 bool extensions_disabled,
348 const std::vector<ExtensionPrefsObserver*>& early_observers) {
349 return ExtensionPrefs::Create(prefs,
350 root_dir,
351 extension_pref_value_map,
352 app_sorting.Pass(),
353 extensions_disabled,
354 early_observers,
355 make_scoped_ptr(new TimeProvider()));
358 // static
359 ExtensionPrefs* ExtensionPrefs::Create(
360 PrefService* pref_service,
361 const base::FilePath& root_dir,
362 ExtensionPrefValueMap* extension_pref_value_map,
363 scoped_ptr<AppSorting> app_sorting,
364 bool extensions_disabled,
365 const std::vector<ExtensionPrefsObserver*>& early_observers,
366 scoped_ptr<TimeProvider> time_provider) {
367 return new ExtensionPrefs(pref_service,
368 root_dir,
369 extension_pref_value_map,
370 app_sorting.Pass(),
371 time_provider.Pass(),
372 extensions_disabled,
373 early_observers);
376 ExtensionPrefs::~ExtensionPrefs() {
379 // static
380 ExtensionPrefs* ExtensionPrefs::Get(content::BrowserContext* context) {
381 return ExtensionPrefsFactory::GetInstance()->GetForBrowserContext(context);
384 static base::FilePath::StringType MakePathRelative(const base::FilePath& parent,
385 const base::FilePath& child) {
386 if (!parent.IsParent(child))
387 return child.value();
389 base::FilePath::StringType retval = child.value().substr(
390 parent.value().length());
391 if (base::FilePath::IsSeparator(retval[0]))
392 return retval.substr(1);
393 else
394 return retval;
397 void ExtensionPrefs::MakePathsRelative() {
398 const base::DictionaryValue* dict =
399 prefs_->GetDictionary(pref_names::kExtensions);
400 if (!dict || dict->empty())
401 return;
403 // Collect all extensions ids with absolute paths in |absolute_keys|.
404 std::set<std::string> absolute_keys;
405 for (base::DictionaryValue::Iterator i(*dict); !i.IsAtEnd(); i.Advance()) {
406 const base::DictionaryValue* extension_dict = NULL;
407 if (!i.value().GetAsDictionary(&extension_dict))
408 continue;
409 int location_value;
410 if (extension_dict->GetInteger(kPrefLocation, &location_value) &&
411 Manifest::IsUnpackedLocation(
412 static_cast<Manifest::Location>(location_value))) {
413 // Unpacked extensions can have absolute paths.
414 continue;
416 base::FilePath::StringType path_string;
417 if (!extension_dict->GetString(kPrefPath, &path_string))
418 continue;
419 base::FilePath path(path_string);
420 if (path.IsAbsolute())
421 absolute_keys.insert(i.key());
423 if (absolute_keys.empty())
424 return;
426 // Fix these paths.
427 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
428 base::DictionaryValue* update_dict = update.Get();
429 for (std::set<std::string>::iterator i = absolute_keys.begin();
430 i != absolute_keys.end(); ++i) {
431 base::DictionaryValue* extension_dict = NULL;
432 if (!update_dict->GetDictionaryWithoutPathExpansion(*i, &extension_dict)) {
433 NOTREACHED() << "Control should never reach here for extension " << *i;
434 continue;
436 base::FilePath::StringType path_string;
437 extension_dict->GetString(kPrefPath, &path_string);
438 base::FilePath path(path_string);
439 extension_dict->SetString(kPrefPath,
440 MakePathRelative(install_directory_, path));
444 const base::DictionaryValue* ExtensionPrefs::GetExtensionPref(
445 const std::string& extension_id) const {
446 const base::DictionaryValue* extensions =
447 prefs_->GetDictionary(pref_names::kExtensions);
448 const base::DictionaryValue* extension_dict = NULL;
449 if (!extensions ||
450 !extensions->GetDictionary(extension_id, &extension_dict)) {
451 return NULL;
453 return extension_dict;
456 void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id,
457 const std::string& key,
458 base::Value* data_value) {
459 if (!Extension::IdIsValid(extension_id)) {
460 NOTREACHED() << "Invalid extension_id " << extension_id;
461 return;
463 ScopedExtensionPrefUpdate update(prefs_, extension_id);
464 if (data_value)
465 update->Set(key, data_value);
466 else
467 update->Remove(key, NULL);
470 void ExtensionPrefs::DeleteExtensionPrefs(const std::string& extension_id) {
471 extension_pref_value_map_->UnregisterExtension(extension_id);
472 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
473 observer_list_,
474 OnExtensionPrefsDeleted(extension_id));
475 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
476 base::DictionaryValue* dict = update.Get();
477 dict->Remove(extension_id, NULL);
480 bool ExtensionPrefs::ReadPrefAsBoolean(const std::string& extension_id,
481 const std::string& pref_key,
482 bool* out_value) const {
483 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
484 if (!ext || !ext->GetBoolean(pref_key, out_value))
485 return false;
487 return true;
490 bool ExtensionPrefs::ReadPrefAsInteger(const std::string& extension_id,
491 const std::string& pref_key,
492 int* out_value) const {
493 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
494 if (!ext || !ext->GetInteger(pref_key, out_value))
495 return false;
497 return true;
500 bool ExtensionPrefs::ReadPrefAsString(const std::string& extension_id,
501 const std::string& pref_key,
502 std::string* out_value) const {
503 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
504 if (!ext || !ext->GetString(pref_key, out_value))
505 return false;
507 return true;
510 bool ExtensionPrefs::ReadPrefAsList(const std::string& extension_id,
511 const std::string& pref_key,
512 const base::ListValue** out_value) const {
513 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
514 const base::ListValue* out = NULL;
515 if (!ext || !ext->GetList(pref_key, &out))
516 return false;
517 if (out_value)
518 *out_value = out;
520 return true;
523 bool ExtensionPrefs::ReadPrefAsDictionary(
524 const std::string& extension_id,
525 const std::string& pref_key,
526 const base::DictionaryValue** out_value) const {
527 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
528 const base::DictionaryValue* out = NULL;
529 if (!ext || !ext->GetDictionary(pref_key, &out))
530 return false;
531 if (out_value)
532 *out_value = out;
534 return true;
537 bool ExtensionPrefs::HasPrefForExtension(
538 const std::string& extension_id) const {
539 return GetExtensionPref(extension_id) != NULL;
542 bool ExtensionPrefs::ReadPrefAsURLPatternSet(const std::string& extension_id,
543 const std::string& pref_key,
544 URLPatternSet* result,
545 int valid_schemes) {
546 const base::ListValue* value = NULL;
547 if (!ReadPrefAsList(extension_id, pref_key, &value))
548 return false;
550 bool allow_file_access = AllowFileAccess(extension_id);
551 return result->Populate(*value, valid_schemes, allow_file_access, NULL);
554 void ExtensionPrefs::SetExtensionPrefURLPatternSet(
555 const std::string& extension_id,
556 const std::string& pref_key,
557 const URLPatternSet& new_value) {
558 UpdateExtensionPref(extension_id, pref_key, new_value.ToValue().release());
561 bool ExtensionPrefs::ReadPrefAsBooleanAndReturn(
562 const std::string& extension_id,
563 const std::string& pref_key) const {
564 bool out_value = false;
565 return ReadPrefAsBoolean(extension_id, pref_key, &out_value) && out_value;
568 PermissionSet* ExtensionPrefs::ReadPrefAsPermissionSet(
569 const std::string& extension_id,
570 const std::string& pref_key) {
571 if (!GetExtensionPref(extension_id))
572 return NULL;
574 // Retrieve the API permissions. Please refer SetExtensionPrefPermissionSet()
575 // for api_values format.
576 APIPermissionSet apis;
577 const base::ListValue* api_values = NULL;
578 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
579 if (ReadPrefAsList(extension_id, api_pref, &api_values)) {
580 APIPermissionSet::ParseFromJSON(api_values,
581 APIPermissionSet::kAllowInternalPermissions,
582 &apis, NULL, NULL);
585 // Retrieve the Manifest Keys permissions. Please refer to
586 // |SetExtensionPrefPermissionSet| for manifest_permissions_values format.
587 ManifestPermissionSet manifest_permissions;
588 const base::ListValue* manifest_permissions_values = NULL;
589 std::string manifest_permission_pref =
590 JoinPrefs(pref_key, kPrefManifestPermissions);
591 if (ReadPrefAsList(extension_id, manifest_permission_pref,
592 &manifest_permissions_values)) {
593 ManifestPermissionSet::ParseFromJSON(
594 manifest_permissions_values, &manifest_permissions, NULL, NULL);
597 // Retrieve the explicit host permissions.
598 URLPatternSet explicit_hosts;
599 ReadPrefAsURLPatternSet(
600 extension_id, JoinPrefs(pref_key, kPrefExplicitHosts),
601 &explicit_hosts, Extension::kValidHostPermissionSchemes);
603 // Retrieve the scriptable host permissions.
604 URLPatternSet scriptable_hosts;
605 ReadPrefAsURLPatternSet(
606 extension_id, JoinPrefs(pref_key, kPrefScriptableHosts),
607 &scriptable_hosts, UserScript::ValidUserScriptSchemes());
609 return new PermissionSet(
610 apis, manifest_permissions, explicit_hosts, scriptable_hosts);
613 // Set the API or Manifest permissions.
614 // The format of api_values is:
615 // [ "permission_name1", // permissions do not support detail.
616 // "permission_name2",
617 // {"permission_name3": value },
618 // // permission supports detail, permission detail will be stored in value.
619 // ...
620 // ]
621 template<typename T>
622 static base::ListValue* CreatePermissionList(const T& permissions) {
623 base::ListValue* values = new base::ListValue();
624 for (typename T::const_iterator i = permissions.begin();
625 i != permissions.end(); ++i) {
626 scoped_ptr<base::Value> detail(i->ToValue());
627 if (detail) {
628 base::DictionaryValue* tmp = new base::DictionaryValue();
629 tmp->Set(i->name(), detail.release());
630 values->Append(tmp);
631 } else {
632 values->Append(new base::StringValue(i->name()));
635 return values;
638 void ExtensionPrefs::SetExtensionPrefPermissionSet(
639 const std::string& extension_id,
640 const std::string& pref_key,
641 const PermissionSet* new_value) {
642 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
643 base::ListValue* api_values = CreatePermissionList(new_value->apis());
644 UpdateExtensionPref(extension_id, api_pref, api_values);
646 std::string manifest_permissions_pref =
647 JoinPrefs(pref_key, kPrefManifestPermissions);
648 base::ListValue* manifest_permissions_values = CreatePermissionList(
649 new_value->manifest_permissions());
650 UpdateExtensionPref(extension_id,
651 manifest_permissions_pref,
652 manifest_permissions_values);
654 // Set the explicit host permissions.
655 if (!new_value->explicit_hosts().is_empty()) {
656 SetExtensionPrefURLPatternSet(extension_id,
657 JoinPrefs(pref_key, kPrefExplicitHosts),
658 new_value->explicit_hosts());
661 // Set the scriptable host permissions.
662 if (!new_value->scriptable_hosts().is_empty()) {
663 SetExtensionPrefURLPatternSet(extension_id,
664 JoinPrefs(pref_key, kPrefScriptableHosts),
665 new_value->scriptable_hosts());
669 int ExtensionPrefs::IncrementAcknowledgePromptCount(
670 const std::string& extension_id) {
671 int count = 0;
672 ReadPrefAsInteger(extension_id, kPrefAcknowledgePromptCount, &count);
673 ++count;
674 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount,
675 new base::FundamentalValue(count));
676 return count;
679 bool ExtensionPrefs::IsExternalExtensionAcknowledged(
680 const std::string& extension_id) {
681 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalAcknowledged);
684 void ExtensionPrefs::AcknowledgeExternalExtension(
685 const std::string& extension_id) {
686 DCHECK(Extension::IdIsValid(extension_id));
687 UpdateExtensionPref(extension_id, kPrefExternalAcknowledged,
688 new base::FundamentalValue(true));
689 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
692 bool ExtensionPrefs::IsBlacklistedExtensionAcknowledged(
693 const std::string& extension_id) {
694 return ReadPrefAsBooleanAndReturn(extension_id, kPrefBlacklistAcknowledged);
697 void ExtensionPrefs::AcknowledgeBlacklistedExtension(
698 const std::string& extension_id) {
699 DCHECK(Extension::IdIsValid(extension_id));
700 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged,
701 new base::FundamentalValue(true));
702 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
705 bool ExtensionPrefs::IsExternalInstallFirstRun(
706 const std::string& extension_id) {
707 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalInstallFirstRun);
710 void ExtensionPrefs::SetExternalInstallFirstRun(
711 const std::string& extension_id) {
712 DCHECK(Extension::IdIsValid(extension_id));
713 UpdateExtensionPref(extension_id, kPrefExternalInstallFirstRun,
714 new base::FundamentalValue(true));
717 bool ExtensionPrefs::HasWipeoutBeenAcknowledged(
718 const std::string& extension_id) {
719 return ReadPrefAsBooleanAndReturn(extension_id, kPrefWipeoutAcknowledged);
722 void ExtensionPrefs::SetWipeoutAcknowledged(
723 const std::string& extension_id,
724 bool value) {
725 UpdateExtensionPref(extension_id,
726 kPrefWipeoutAcknowledged,
727 value ? new base::FundamentalValue(value) : NULL);
730 bool ExtensionPrefs::HasSettingsApiBubbleBeenAcknowledged(
731 const std::string& extension_id) {
732 return ReadPrefAsBooleanAndReturn(extension_id,
733 kPrefSettingsBubbleAcknowledged);
736 void ExtensionPrefs::SetSettingsApiBubbleBeenAcknowledged(
737 const std::string& extension_id,
738 bool value) {
739 UpdateExtensionPref(extension_id,
740 kPrefSettingsBubbleAcknowledged,
741 value ? new base::FundamentalValue(value) : NULL);
744 bool ExtensionPrefs::HasNtpOverriddenBubbleBeenAcknowledged(
745 const std::string& extension_id) {
746 return ReadPrefAsBooleanAndReturn(extension_id, kPrefNtpBubbleAcknowledged);
749 void ExtensionPrefs::SetNtpOverriddenBubbleBeenAcknowledged(
750 const std::string& extension_id,
751 bool value) {
752 UpdateExtensionPref(extension_id,
753 kPrefNtpBubbleAcknowledged,
754 value ? new base::FundamentalValue(value) : NULL);
757 bool ExtensionPrefs::HasProxyOverriddenBubbleBeenAcknowledged(
758 const std::string& extension_id) {
759 return ReadPrefAsBooleanAndReturn(extension_id, kPrefProxyBubbleAcknowledged);
762 void ExtensionPrefs::SetProxyOverriddenBubbleBeenAcknowledged(
763 const std::string& extension_id,
764 bool value) {
765 UpdateExtensionPref(extension_id,
766 kPrefProxyBubbleAcknowledged,
767 value ? new base::FundamentalValue(value) : NULL);
770 bool ExtensionPrefs::SetAlertSystemFirstRun() {
771 if (prefs_->GetBoolean(pref_names::kAlertsInitialized)) {
772 return true;
774 prefs_->SetBoolean(pref_names::kAlertsInitialized, true);
775 return false;
778 bool ExtensionPrefs::ExtensionsBlacklistedByDefault() const {
779 return admin_policy::BlacklistedByDefault(
780 prefs_->GetList(pref_names::kInstallDenyList));
783 bool ExtensionPrefs::DidExtensionEscalatePermissions(
784 const std::string& extension_id) {
785 return ReadPrefAsBooleanAndReturn(extension_id,
786 kExtensionDidEscalatePermissions);
789 void ExtensionPrefs::SetDidExtensionEscalatePermissions(
790 const Extension* extension, bool did_escalate) {
791 UpdateExtensionPref(extension->id(), kExtensionDidEscalatePermissions,
792 new base::FundamentalValue(did_escalate));
795 int ExtensionPrefs::GetDisableReasons(const std::string& extension_id) const {
796 int value = -1;
797 if (ReadPrefAsInteger(extension_id, kPrefDisableReasons, &value) &&
798 value >= 0) {
799 return value;
801 return Extension::DISABLE_NONE;
804 bool ExtensionPrefs::HasDisableReason(
805 const std::string& extension_id,
806 Extension::DisableReason disable_reason) const {
807 return (GetDisableReasons(extension_id) & disable_reason) != 0;
810 void ExtensionPrefs::AddDisableReason(const std::string& extension_id,
811 Extension::DisableReason disable_reason) {
812 ModifyDisableReason(extension_id, disable_reason, DISABLE_REASON_ADD);
815 void ExtensionPrefs::RemoveDisableReason(
816 const std::string& extension_id,
817 Extension::DisableReason disable_reason) {
818 ModifyDisableReason(extension_id, disable_reason, DISABLE_REASON_REMOVE);
821 void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) {
822 ModifyDisableReason(
823 extension_id, Extension::DISABLE_NONE, DISABLE_REASON_CLEAR);
826 void ExtensionPrefs::ModifyDisableReason(const std::string& extension_id,
827 Extension::DisableReason reason,
828 DisableReasonChange change) {
829 int old_value = GetDisableReasons(extension_id);
830 int new_value = old_value;
831 switch (change) {
832 case DISABLE_REASON_ADD:
833 new_value |= static_cast<int>(reason);
834 break;
835 case DISABLE_REASON_REMOVE:
836 new_value &= ~static_cast<int>(reason);
837 break;
838 case DISABLE_REASON_CLEAR:
839 new_value = Extension::DISABLE_NONE;
840 break;
843 if (old_value == new_value) // no change, return.
844 return;
846 if (new_value == Extension::DISABLE_NONE) {
847 UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
848 } else {
849 UpdateExtensionPref(extension_id,
850 kPrefDisableReasons,
851 new base::FundamentalValue(new_value));
854 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
855 observer_list_,
856 OnExtensionDisableReasonsChanged(extension_id, new_value));
859 std::set<std::string> ExtensionPrefs::GetBlacklistedExtensions() {
860 std::set<std::string> ids;
862 const base::DictionaryValue* extensions =
863 prefs_->GetDictionary(pref_names::kExtensions);
864 if (!extensions)
865 return ids;
867 for (base::DictionaryValue::Iterator it(*extensions);
868 !it.IsAtEnd(); it.Advance()) {
869 if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) {
870 NOTREACHED() << "Invalid pref for extension " << it.key();
871 continue;
873 if (IsBlacklistBitSet(
874 static_cast<const base::DictionaryValue*>(&it.value()))) {
875 ids.insert(it.key());
879 return ids;
882 void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id,
883 bool is_blacklisted) {
884 bool currently_blacklisted = IsExtensionBlacklisted(extension_id);
885 if (is_blacklisted == currently_blacklisted)
886 return;
888 // Always make sure the "acknowledged" bit is cleared since the blacklist bit
889 // is changing.
890 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL);
892 if (is_blacklisted) {
893 UpdateExtensionPref(extension_id,
894 kPrefBlacklist,
895 new base::FundamentalValue(true));
896 } else {
897 UpdateExtensionPref(extension_id, kPrefBlacklist, NULL);
898 const base::DictionaryValue* dict = GetExtensionPref(extension_id);
899 if (dict && dict->empty())
900 DeleteExtensionPrefs(extension_id);
904 bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const {
905 const base::DictionaryValue* ext_prefs = GetExtensionPref(id);
906 return ext_prefs && IsBlacklistBitSet(ext_prefs);
909 namespace {
911 // Serializes a 64bit integer as a string value.
912 void SaveInt64(base::DictionaryValue* dictionary,
913 const char* key,
914 const int64 value) {
915 if (!dictionary)
916 return;
918 std::string string_value = base::Int64ToString(value);
919 dictionary->SetString(key, string_value);
922 // Deserializes a 64bit integer stored as a string value.
923 bool ReadInt64(const base::DictionaryValue* dictionary,
924 const char* key,
925 int64* value) {
926 if (!dictionary)
927 return false;
929 std::string string_value;
930 if (!dictionary->GetString(key, &string_value))
931 return false;
933 return base::StringToInt64(string_value, value);
936 // Serializes |time| as a string value mapped to |key| in |dictionary|.
937 void SaveTime(base::DictionaryValue* dictionary,
938 const char* key,
939 const base::Time& time) {
940 SaveInt64(dictionary, key, time.ToInternalValue());
943 // The opposite of SaveTime. If |key| is not found, this returns an empty Time
944 // (is_null() will return true).
945 base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) {
946 int64 value;
947 if (ReadInt64(dictionary, key, &value))
948 return base::Time::FromInternalValue(value);
950 return base::Time();
953 } // namespace
955 base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const {
956 DCHECK(Extension::IdIsValid(extension_id));
957 return ReadTime(GetExtensionPref(extension_id), kLastPingDay);
960 void ExtensionPrefs::SetLastPingDay(const std::string& extension_id,
961 const base::Time& time) {
962 DCHECK(Extension::IdIsValid(extension_id));
963 ScopedExtensionPrefUpdate update(prefs_, extension_id);
964 SaveTime(update.Get(), kLastPingDay, time);
967 base::Time ExtensionPrefs::BlacklistLastPingDay() const {
968 return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate),
969 kLastPingDay);
972 void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) {
973 DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate);
974 SaveTime(update.Get(), kLastPingDay, time);
977 base::Time ExtensionPrefs::LastActivePingDay(const std::string& extension_id) {
978 DCHECK(Extension::IdIsValid(extension_id));
979 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
982 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
983 const base::Time& time) {
984 DCHECK(Extension::IdIsValid(extension_id));
985 ScopedExtensionPrefUpdate update(prefs_, extension_id);
986 SaveTime(update.Get(), kLastActivePingDay, time);
989 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) {
990 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
991 bool result = false;
992 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
993 return result;
994 return false;
997 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
998 bool active) {
999 UpdateExtensionPref(extension_id, kActiveBit,
1000 new base::FundamentalValue(active));
1003 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
1004 PermissionsInfo* info = PermissionsInfo::GetInstance();
1005 for (ExtensionIdList::const_iterator ext_id =
1006 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
1007 // An extension's granted permissions need to be migrated if the
1008 // full_access bit is present. This bit was always present in the previous
1009 // scheme and is never present now.
1010 bool full_access = false;
1011 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
1012 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
1013 continue;
1015 // Remove the full access bit (empty list will get trimmed).
1016 UpdateExtensionPref(
1017 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
1019 // Add the plugin permission if the full access bit was set.
1020 if (full_access) {
1021 const base::ListValue* apis = NULL;
1022 base::ListValue* new_apis = NULL;
1024 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
1025 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
1026 new_apis = apis->DeepCopy();
1027 else
1028 new_apis = new base::ListValue();
1030 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
1031 new_apis->Append(new base::StringValue(plugin_name));
1032 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
1035 // The granted permissions originally only held the effective hosts,
1036 // which are a combination of host and user script host permissions.
1037 // We now maintain these lists separately. For migration purposes, it
1038 // does not matter how we treat the old effective hosts as long as the
1039 // new effective hosts will be the same, so we move them to explicit
1040 // host permissions.
1041 const base::ListValue* hosts = NULL;
1042 std::string explicit_hosts =
1043 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
1044 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
1045 UpdateExtensionPref(
1046 *ext_id, explicit_hosts, hosts->DeepCopy());
1048 // We can get rid of the old one by setting it to an empty list.
1049 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
1054 void ExtensionPrefs::MigrateDisableReasons(
1055 const ExtensionIdList& extension_ids) {
1056 for (ExtensionIdList::const_iterator ext_id =
1057 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
1058 int value = -1;
1059 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
1060 int new_value = Extension::DISABLE_NONE;
1061 switch (value) {
1062 case Extension::DEPRECATED_DISABLE_USER_ACTION:
1063 new_value = Extension::DISABLE_USER_ACTION;
1064 break;
1065 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
1066 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
1067 break;
1068 case Extension::DEPRECATED_DISABLE_RELOAD:
1069 new_value = Extension::DISABLE_RELOAD;
1070 break;
1073 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
1074 new base::FundamentalValue(new_value));
1075 // Remove the old disable reason.
1076 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
1081 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
1082 const std::string& extension_id) {
1083 CHECK(Extension::IdIsValid(extension_id));
1084 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
1087 void ExtensionPrefs::AddGrantedPermissions(
1088 const std::string& extension_id,
1089 const PermissionSet* permissions) {
1090 CHECK(Extension::IdIsValid(extension_id));
1092 scoped_refptr<PermissionSet> granted_permissions(
1093 GetGrantedPermissions(extension_id));
1095 // The new granted permissions are the union of the already granted
1096 // permissions and the newly granted permissions.
1097 scoped_refptr<PermissionSet> new_perms(
1098 PermissionSet::CreateUnion(
1099 permissions, granted_permissions.get()));
1101 SetExtensionPrefPermissionSet(
1102 extension_id, kPrefGrantedPermissions, new_perms.get());
1105 void ExtensionPrefs::RemoveGrantedPermissions(
1106 const std::string& extension_id,
1107 const PermissionSet* permissions) {
1108 CHECK(Extension::IdIsValid(extension_id));
1110 scoped_refptr<PermissionSet> granted_permissions(
1111 GetGrantedPermissions(extension_id));
1113 // The new granted permissions are the difference of the already granted
1114 // permissions and the newly ungranted permissions.
1115 scoped_refptr<PermissionSet> new_perms(
1116 PermissionSet::CreateDifference(
1117 granted_permissions.get(), permissions));
1119 SetExtensionPrefPermissionSet(
1120 extension_id, kPrefGrantedPermissions, new_perms.get());
1123 PermissionSet* ExtensionPrefs::GetActivePermissions(
1124 const std::string& extension_id) {
1125 CHECK(Extension::IdIsValid(extension_id));
1126 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
1129 void ExtensionPrefs::SetActivePermissions(
1130 const std::string& extension_id,
1131 const PermissionSet* permissions) {
1132 SetExtensionPrefPermissionSet(
1133 extension_id, kPrefActivePermissions, permissions);
1136 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1137 bool is_running) {
1138 base::Value* value = new base::FundamentalValue(is_running);
1139 UpdateExtensionPref(extension_id, kPrefRunning, value);
1142 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) {
1143 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1144 if (!extension)
1145 return false;
1146 bool running = false;
1147 extension->GetBoolean(kPrefRunning, &running);
1148 return running;
1151 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1152 bool is_active) {
1153 base::Value* value = new base::FundamentalValue(is_active);
1154 UpdateExtensionPref(extension_id, kIsActive, value);
1157 bool ExtensionPrefs::IsActive(const std::string& extension_id) {
1158 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1159 if (!extension)
1160 return false;
1161 bool is_active = false;
1162 extension->GetBoolean(kIsActive, &is_active);
1163 return is_active;
1166 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1167 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1170 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1171 bool enabled) {
1172 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1173 new base::FundamentalValue(enabled));
1174 extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled);
1177 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1178 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1181 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1182 bool allow) {
1183 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1184 new base::FundamentalValue(allow));
1187 bool ExtensionPrefs::HasAllowFileAccessSetting(
1188 const std::string& extension_id) const {
1189 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1190 return ext && ext->HasKey(kPrefAllowFileAccess);
1193 bool ExtensionPrefs::DoesExtensionHaveState(
1194 const std::string& id, Extension::State check_state) const {
1195 const base::DictionaryValue* extension = GetExtensionPref(id);
1196 int state = -1;
1197 if (!extension || !extension->GetInteger(kPrefState, &state))
1198 return false;
1200 if (state < 0 || state >= Extension::NUM_STATES) {
1201 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1202 return false;
1205 return state == check_state;
1208 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1209 const std::string& id) const {
1210 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1213 bool ExtensionPrefs::IsExtensionDisabled(
1214 const std::string& id) const {
1215 return DoesExtensionHaveState(id, Extension::DISABLED);
1218 ExtensionIdList ExtensionPrefs::GetToolbarOrder() {
1219 ExtensionIdList id_list_out;
1220 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1221 return id_list_out;
1224 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1225 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1228 void ExtensionPrefs::OnExtensionInstalled(
1229 const Extension* extension,
1230 Extension::State initial_state,
1231 const syncer::StringOrdinal& page_ordinal,
1232 int install_flags,
1233 const std::string& install_parameter) {
1234 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1235 base::DictionaryValue* extension_dict = update.Get();
1236 const base::Time install_time = time_provider_->GetCurrentTime();
1237 PopulateExtensionInfoPrefs(extension,
1238 install_time,
1239 initial_state,
1240 install_flags,
1241 install_parameter,
1242 extension_dict);
1244 bool requires_sort_ordinal = extension->RequiresSortOrdinal() &&
1245 (install_flags & kInstallFlagIsEphemeral) == 0;
1246 FinishExtensionInfoPrefs(extension->id(),
1247 install_time,
1248 requires_sort_ordinal,
1249 page_ordinal,
1250 extension_dict);
1253 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1254 const Manifest::Location& location,
1255 bool external_uninstall) {
1256 app_sorting_->ClearOrdinals(extension_id);
1258 // For external extensions, we save a preference reminding ourself not to try
1259 // and install the extension anymore (except when |external_uninstall| is
1260 // true, which signifies that the registry key was deleted or the pref file
1261 // no longer lists the extension).
1262 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1263 UpdateExtensionPref(extension_id, kPrefState,
1264 new base::FundamentalValue(
1265 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1266 extension_pref_value_map_->SetExtensionState(extension_id, false);
1267 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1268 observer_list_,
1269 OnExtensionStateChanged(extension_id, false));
1270 } else {
1271 DeleteExtensionPrefs(extension_id);
1275 void ExtensionPrefs::SetExtensionState(const std::string& extension_id,
1276 Extension::State state) {
1277 UpdateExtensionPref(extension_id, kPrefState,
1278 new base::FundamentalValue(state));
1279 bool enabled = (state == Extension::ENABLED);
1280 extension_pref_value_map_->SetExtensionState(extension_id, enabled);
1281 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1282 observer_list_,
1283 OnExtensionStateChanged(extension_id, enabled));
1286 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1287 BlacklistState state) {
1288 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1289 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1290 new base::FundamentalValue(state));
1293 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1294 const std::string& extension_id) {
1295 if (IsExtensionBlacklisted(extension_id))
1296 return BLACKLISTED_MALWARE;
1297 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1298 int int_value = 0;
1299 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1300 return static_cast<BlacklistState>(int_value);
1302 return NOT_BLACKLISTED;
1305 std::string ExtensionPrefs::GetVersionString(const std::string& extension_id) {
1306 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1307 if (!extension)
1308 return std::string();
1310 std::string version;
1311 extension->GetString(kPrefVersion, &version);
1313 return version;
1316 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1317 if (!Manifest::IsUnpackedLocation(extension->location())) {
1318 const base::DictionaryValue* extension_dict =
1319 GetExtensionPref(extension->id());
1320 if (!extension_dict)
1321 return;
1322 const base::DictionaryValue* old_manifest = NULL;
1323 bool update_required =
1324 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1325 !extension->manifest()->value()->Equals(old_manifest);
1326 if (update_required) {
1327 UpdateExtensionPref(extension->id(), kPrefManifest,
1328 extension->manifest()->value()->DeepCopy());
1333 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1334 const std::string& extension_id,
1335 const base::DictionaryValue* extension) const {
1336 int location_value;
1337 if (!extension->GetInteger(kPrefLocation, &location_value))
1338 return scoped_ptr<ExtensionInfo>();
1340 base::FilePath::StringType path;
1341 if (!extension->GetString(kPrefPath, &path))
1342 return scoped_ptr<ExtensionInfo>();
1344 // Make path absolute. Unpacked extensions will already have absolute paths,
1345 // otherwise make it so.
1346 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1347 #if !defined(OS_CHROMEOS)
1348 if (!Manifest::IsUnpackedLocation(location)) {
1349 DCHECK(location == Manifest::COMPONENT ||
1350 !base::FilePath(path).IsAbsolute());
1351 #else
1352 // On Chrome OS some extensions can be installed to shared location and
1353 // thus use absolute paths in prefs.
1354 if (!base::FilePath(path).IsAbsolute()) {
1355 #endif // !defined(OS_CHROMEOS)
1356 path = install_directory_.Append(path).value();
1359 // Only the following extension types have data saved in the preferences.
1360 if (location != Manifest::INTERNAL &&
1361 !Manifest::IsUnpackedLocation(location) &&
1362 !Manifest::IsExternalLocation(location)) {
1363 NOTREACHED();
1364 return scoped_ptr<ExtensionInfo>();
1367 const base::DictionaryValue* manifest = NULL;
1368 if (!Manifest::IsUnpackedLocation(location) &&
1369 !extension->GetDictionary(kPrefManifest, &manifest)) {
1370 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1371 // Just a warning for now.
1374 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1375 manifest, extension_id, base::FilePath(path), location));
1378 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1379 const std::string& extension_id) const {
1380 const base::DictionaryValue* ext = NULL;
1381 const base::DictionaryValue* extensions =
1382 prefs_->GetDictionary(pref_names::kExtensions);
1383 if (!extensions ||
1384 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1385 return scoped_ptr<ExtensionInfo>();
1386 int state_value;
1387 if (!ext->GetInteger(kPrefState, &state_value) ||
1388 state_value == Extension::ENABLED_COMPONENT) {
1389 // Old preferences files may not have kPrefState for component extensions.
1390 return scoped_ptr<ExtensionInfo>();
1393 if (state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1394 LOG(WARNING) << "External extension with id " << extension_id
1395 << " has been uninstalled by the user";
1396 return scoped_ptr<ExtensionInfo>();
1399 return GetInstalledInfoHelper(extension_id, ext);
1402 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1403 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1404 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1406 const base::DictionaryValue* extensions =
1407 prefs_->GetDictionary(pref_names::kExtensions);
1408 for (base::DictionaryValue::Iterator extension_id(*extensions);
1409 !extension_id.IsAtEnd(); extension_id.Advance()) {
1410 if (!Extension::IdIsValid(extension_id.key()))
1411 continue;
1413 scoped_ptr<ExtensionInfo> info =
1414 GetInstalledExtensionInfo(extension_id.key());
1415 if (info)
1416 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1419 return extensions_info.Pass();
1422 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1423 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1424 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1426 const base::DictionaryValue* extensions =
1427 prefs_->GetDictionary(pref_names::kExtensions);
1428 for (base::DictionaryValue::Iterator extension_id(*extensions);
1429 !extension_id.IsAtEnd(); extension_id.Advance()) {
1430 const base::DictionaryValue* ext = NULL;
1431 if (!Extension::IdIsValid(extension_id.key()) ||
1432 !IsExternalExtensionUninstalled(extension_id.key()) ||
1433 !extension_id.value().GetAsDictionary(&ext))
1434 continue;
1436 scoped_ptr<ExtensionInfo> info =
1437 GetInstalledInfoHelper(extension_id.key(), ext);
1438 if (info)
1439 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1442 return extensions_info.Pass();
1445 void ExtensionPrefs::SetDelayedInstallInfo(
1446 const Extension* extension,
1447 Extension::State initial_state,
1448 int install_flags,
1449 DelayReason delay_reason,
1450 const syncer::StringOrdinal& page_ordinal,
1451 const std::string& install_parameter) {
1452 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1453 PopulateExtensionInfoPrefs(extension,
1454 time_provider_->GetCurrentTime(),
1455 initial_state,
1456 install_flags,
1457 install_parameter,
1458 extension_dict);
1460 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1461 // should not be in the final extension prefs. All entries here should have
1462 // a corresponding Remove() call in FinishDelayedInstallInfo().
1463 if (extension->RequiresSortOrdinal() &&
1464 (install_flags & kInstallFlagIsEphemeral) == 0) {
1465 extension_dict->SetString(
1466 kPrefSuggestedPageOrdinal,
1467 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1468 : std::string());
1470 extension_dict->SetInteger(kDelayedInstallReason,
1471 static_cast<int>(delay_reason));
1473 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1476 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1477 const std::string& extension_id) {
1478 if (!GetExtensionPref(extension_id))
1479 return false;
1480 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1481 bool result = update->Remove(kDelayedInstallInfo, NULL);
1482 return result;
1485 bool ExtensionPrefs::FinishDelayedInstallInfo(
1486 const std::string& extension_id) {
1487 CHECK(Extension::IdIsValid(extension_id));
1488 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1489 base::DictionaryValue* extension_dict = update.Get();
1490 base::DictionaryValue* pending_install_dict = NULL;
1491 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1492 &pending_install_dict)) {
1493 return false;
1496 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1497 // Also do any other data cleanup that makes sense.
1498 std::string serialized_ordinal;
1499 syncer::StringOrdinal suggested_page_ordinal;
1500 bool needs_sort_ordinal = false;
1501 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1502 &serialized_ordinal)) {
1503 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1504 needs_sort_ordinal = true;
1505 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1507 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1509 const base::Time install_time = time_provider_->GetCurrentTime();
1510 pending_install_dict->Set(
1511 kPrefInstallTime,
1512 new base::StringValue(
1513 base::Int64ToString(install_time.ToInternalValue())));
1515 // Some extension pref values are written conditionally. If they are not
1516 // present in the delayed install data, they should be removed when the
1517 // delayed install is committed.
1518 extension_dict->Remove(kPrefEphemeralApp, NULL);
1520 // Commit the delayed install data.
1521 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1522 it.Advance()) {
1523 extension_dict->Set(it.key(), it.value().DeepCopy());
1525 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1526 suggested_page_ordinal, extension_dict);
1527 return true;
1530 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1531 const std::string& extension_id) const {
1532 const base::DictionaryValue* extension_prefs =
1533 GetExtensionPref(extension_id);
1534 if (!extension_prefs)
1535 return scoped_ptr<ExtensionInfo>();
1537 const base::DictionaryValue* ext = NULL;
1538 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1539 return scoped_ptr<ExtensionInfo>();
1541 return GetInstalledInfoHelper(extension_id, ext);
1544 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1545 const std::string& extension_id) const {
1546 const base::DictionaryValue* extension_prefs =
1547 GetExtensionPref(extension_id);
1548 if (!extension_prefs)
1549 return DELAY_REASON_NONE;
1551 const base::DictionaryValue* ext = NULL;
1552 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1553 return DELAY_REASON_NONE;
1555 int delay_reason;
1556 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1557 return DELAY_REASON_NONE;
1559 return static_cast<DelayReason>(delay_reason);
1562 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1563 GetAllDelayedInstallInfo() const {
1564 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1566 const base::DictionaryValue* extensions =
1567 prefs_->GetDictionary(pref_names::kExtensions);
1568 for (base::DictionaryValue::Iterator extension_id(*extensions);
1569 !extension_id.IsAtEnd(); extension_id.Advance()) {
1570 if (!Extension::IdIsValid(extension_id.key()))
1571 continue;
1573 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1574 if (info)
1575 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1578 return extensions_info.Pass();
1581 bool ExtensionPrefs::IsEphemeralApp(const std::string& extension_id) const {
1582 if (ReadPrefAsBooleanAndReturn(extension_id, kPrefEphemeralApp))
1583 return true;
1585 // Ephemerality was previously stored in the creation flags, so we must also
1586 // check it for backcompatibility.
1587 return (GetCreationFlags(extension_id) & Extension::IS_EPHEMERAL) != 0;
1590 void ExtensionPrefs::OnEphemeralAppPromoted(const std::string& extension_id) {
1591 DCHECK(IsEphemeralApp(extension_id));
1593 UpdateExtensionPref(extension_id, kPrefEphemeralApp, NULL);
1595 // Ephemerality was previously stored in the creation flags, so ensure the bit
1596 // is cleared.
1597 int creation_flags = Extension::NO_FLAGS;
1598 if (ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1599 if (creation_flags & Extension::IS_EPHEMERAL) {
1600 creation_flags &= ~static_cast<int>(Extension::IS_EPHEMERAL);
1601 UpdateExtensionPref(extension_id,
1602 kPrefCreationFlags,
1603 new base::FundamentalValue(creation_flags));
1608 bool ExtensionPrefs::WasAppDraggedByUser(const std::string& extension_id) {
1609 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1612 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1613 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1614 new base::FundamentalValue(true));
1617 bool ExtensionPrefs::IsFromWebStore(
1618 const std::string& extension_id) const {
1619 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1620 bool result = false;
1621 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1622 return result;
1623 return false;
1626 bool ExtensionPrefs::IsFromBookmark(
1627 const std::string& extension_id) const {
1628 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1629 bool result = false;
1630 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1631 return result;
1632 return false;
1635 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1636 int creation_flags = Extension::NO_FLAGS;
1637 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1638 // Since kPrefCreationFlags was added later, it will be missing for
1639 // previously installed extensions.
1640 if (IsFromBookmark(extension_id))
1641 creation_flags |= Extension::FROM_BOOKMARK;
1642 if (IsFromWebStore(extension_id))
1643 creation_flags |= Extension::FROM_WEBSTORE;
1644 if (WasInstalledByDefault(extension_id))
1645 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1646 if (WasInstalledByOem(extension_id))
1647 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
1649 return creation_flags;
1652 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1653 const std::string& extension_id) const {
1654 int creation_flags = Extension::NO_FLAGS;
1655 const base::DictionaryValue* delayed_info = NULL;
1656 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1657 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1659 return creation_flags;
1662 bool ExtensionPrefs::WasInstalledByDefault(
1663 const std::string& extension_id) const {
1664 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1665 bool result = false;
1666 if (dictionary &&
1667 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1668 return result;
1669 return false;
1672 bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const {
1673 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1674 bool result = false;
1675 if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result))
1676 return result;
1677 return false;
1680 base::Time ExtensionPrefs::GetInstallTime(
1681 const std::string& extension_id) const {
1682 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1683 if (!extension) {
1684 NOTREACHED();
1685 return base::Time();
1687 std::string install_time_str;
1688 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1689 return base::Time();
1690 int64 install_time_i64 = 0;
1691 if (!base::StringToInt64(install_time_str, &install_time_i64))
1692 return base::Time();
1693 return base::Time::FromInternalValue(install_time_i64);
1696 bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const {
1697 bool do_not_sync;
1698 if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync))
1699 return false;
1701 return do_not_sync;
1704 base::Time ExtensionPrefs::GetLastLaunchTime(
1705 const std::string& extension_id) const {
1706 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1707 if (!extension)
1708 return base::Time();
1710 std::string launch_time_str;
1711 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1712 return base::Time();
1713 int64 launch_time_i64 = 0;
1714 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1715 return base::Time();
1716 return base::Time::FromInternalValue(launch_time_i64);
1719 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1720 const base::Time& time) {
1721 DCHECK(Extension::IdIsValid(extension_id));
1722 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1723 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1726 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) {
1727 CHECK(out);
1729 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1731 for (size_t i = 0; i < extensions_info->size(); ++i) {
1732 ExtensionInfo* info = extensions_info->at(i).get();
1733 out->push_back(info->extension_id);
1737 // static
1738 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1739 const PrefService* pref_service) {
1740 ExtensionIdList result;
1742 const base::DictionaryValue* extension_prefs = NULL;
1743 const base::Value* extension_prefs_value =
1744 pref_service->GetUserPrefValue(pref_names::kExtensions);
1745 if (!extension_prefs_value ||
1746 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1747 return result; // Empty set
1750 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1751 it.Advance()) {
1752 const base::DictionaryValue* ext = NULL;
1753 if (!it.value().GetAsDictionary(&ext)) {
1754 NOTREACHED() << "Invalid pref for extension " << it.key();
1755 continue;
1757 if (!IsBlacklistBitSet(ext))
1758 result.push_back(it.key());
1760 return result;
1763 void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) {
1764 observer_list_.AddObserver(observer);
1767 void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) {
1768 observer_list_.RemoveObserver(observer);
1771 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1772 // Fix old entries that did not get an installation time entry when they
1773 // were installed or don't have a preferences field.
1774 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1775 ext_id != extension_ids.end(); ++ext_id) {
1776 if (GetInstallTime(*ext_id) == base::Time()) {
1777 VLOG(1) << "Could not parse installation time of extension "
1778 << *ext_id << ". It was probably installed before setting "
1779 << kPrefInstallTime << " was introduced. Updating "
1780 << kPrefInstallTime << " to the current time.";
1781 const base::Time install_time = time_provider_->GetCurrentTime();
1782 UpdateExtensionPref(*ext_id,
1783 kPrefInstallTime,
1784 new base::StringValue(base::Int64ToString(
1785 install_time.ToInternalValue())));
1790 void ExtensionPrefs::InitPrefStore() {
1791 if (extensions_disabled_) {
1792 extension_pref_value_map_->NotifyInitializationCompleted();
1793 return;
1796 // When this is called, the PrefService is initialized and provides access
1797 // to the user preferences stored in a JSON file.
1798 ExtensionIdList extension_ids;
1799 GetExtensions(&extension_ids);
1800 // Create empty preferences dictionary for each extension (these dictionaries
1801 // are pruned when persisting the preferences to disk).
1802 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1803 ext_id != extension_ids.end(); ++ext_id) {
1804 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1805 // This creates an empty dictionary if none is stored.
1806 update.Get();
1809 FixMissingPrefs(extension_ids);
1810 MigratePermissions(extension_ids);
1811 MigrateDisableReasons(extension_ids);
1812 app_sorting_->Initialize(extension_ids);
1814 InitExtensionControlledPrefs(extension_pref_value_map_);
1816 extension_pref_value_map_->NotifyInitializationCompleted();
1819 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) {
1820 bool has_incognito_pref_value = false;
1821 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1822 true,
1823 &has_incognito_pref_value);
1824 return has_incognito_pref_value;
1827 URLPatternSet ExtensionPrefs::GetAllowedInstallSites() {
1828 URLPatternSet result;
1829 const base::ListValue* list =
1830 prefs_->GetList(pref_names::kAllowedInstallSites);
1831 CHECK(list);
1833 for (size_t i = 0; i < list->GetSize(); ++i) {
1834 std::string entry_string;
1835 URLPattern entry(URLPattern::SCHEME_ALL);
1836 if (!list->GetString(i, &entry_string) ||
1837 entry.Parse(entry_string) != URLPattern::PARSE_SUCCESS) {
1838 LOG(ERROR) << "Invalid value for preference: "
1839 << pref_names::kAllowedInstallSites << "." << i;
1840 continue;
1842 result.AddPattern(entry);
1845 return result;
1848 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1849 const std::string& extension_id) const {
1850 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1851 if (!extension_prefs)
1852 return NULL;
1854 const base::DictionaryValue* ext = NULL;
1855 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1856 return NULL;
1858 return ext;
1861 void ExtensionPrefs::SetGeometryCache(
1862 const std::string& extension_id,
1863 scoped_ptr<base::DictionaryValue> cache) {
1864 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1867 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() {
1868 return prefs_->GetDictionary(kInstallSignature);
1871 void ExtensionPrefs::SetInstallSignature(
1872 const base::DictionaryValue* signature) {
1873 if (signature) {
1874 prefs_->Set(kInstallSignature, *signature);
1875 DVLOG(1) << "SetInstallSignature - saving";
1876 } else {
1877 DVLOG(1) << "SetInstallSignature - clearing";
1878 prefs_->ClearPref(kInstallSignature);
1882 std::string ExtensionPrefs::GetInstallParam(
1883 const std::string& extension_id) const {
1884 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1885 if (!extension) // Expected during unit testing.
1886 return std::string();
1887 std::string install_parameter;
1888 if (!extension->GetString(kPrefInstallParam, &install_parameter))
1889 return std::string();
1890 return install_parameter;
1893 void ExtensionPrefs::SetInstallParam(const std::string& extension_id,
1894 const std::string& install_parameter) {
1895 UpdateExtensionPref(extension_id,
1896 kPrefInstallParam,
1897 new base::StringValue(install_parameter));
1900 int ExtensionPrefs::GetCorruptedDisableCount() {
1901 return prefs_->GetInteger(kCorruptedDisableCount);
1904 void ExtensionPrefs::IncrementCorruptedDisableCount() {
1905 int count = prefs_->GetInteger(kCorruptedDisableCount);
1906 prefs_->SetInteger(kCorruptedDisableCount, count + 1);
1909 ExtensionPrefs::ExtensionPrefs(
1910 PrefService* prefs,
1911 const base::FilePath& root_dir,
1912 ExtensionPrefValueMap* extension_pref_value_map,
1913 scoped_ptr<AppSorting> app_sorting,
1914 scoped_ptr<TimeProvider> time_provider,
1915 bool extensions_disabled,
1916 const std::vector<ExtensionPrefsObserver*>& early_observers)
1917 : prefs_(prefs),
1918 install_directory_(root_dir),
1919 extension_pref_value_map_(extension_pref_value_map),
1920 app_sorting_(app_sorting.Pass()),
1921 time_provider_(time_provider.Pass()),
1922 extensions_disabled_(extensions_disabled) {
1923 // Remove this deprecated pref.
1924 // TODO(gab): Remove the pref's name from the code base altogether in M40.
1925 prefs_->ClearPref(pref_names::kKnownDisabled);
1927 app_sorting_->SetExtensionScopedPrefs(this);
1928 MakePathsRelative();
1930 // Ensure that any early observers are watching before prefs are initialized.
1931 for (std::vector<ExtensionPrefsObserver*>::const_iterator iter =
1932 early_observers.begin();
1933 iter != early_observers.end();
1934 ++iter) {
1935 AddObserver(*iter);
1938 InitPrefStore();
1941 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1942 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1945 bool ExtensionPrefs::NeedsStorageGarbageCollection() {
1946 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1949 // static
1950 void ExtensionPrefs::RegisterProfilePrefs(
1951 user_prefs::PrefRegistrySyncable* registry) {
1952 registry->RegisterDictionaryPref(
1953 pref_names::kExtensions,
1954 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1955 registry->RegisterListPref(pref_names::kToolbar,
1956 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1957 registry->RegisterIntegerPref(
1958 pref_names::kToolbarSize,
1959 -1, // default value
1960 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1961 registry->RegisterDictionaryPref(
1962 kExtensionsBlacklistUpdate,
1963 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1964 registry->RegisterListPref(pref_names::kInstallAllowList,
1965 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1966 registry->RegisterListPref(pref_names::kInstallDenyList,
1967 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1968 registry->RegisterDictionaryPref(
1969 pref_names::kInstallForceList,
1970 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1971 registry->RegisterListPref(pref_names::kAllowedTypes,
1972 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1973 registry->RegisterBooleanPref(
1974 pref_names::kStorageGarbageCollect,
1975 false, // default value
1976 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1977 registry->RegisterInt64Pref(
1978 pref_names::kLastUpdateCheck,
1979 0, // default value
1980 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1981 registry->RegisterInt64Pref(
1982 pref_names::kNextUpdateCheck,
1983 0, // default value
1984 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1985 registry->RegisterListPref(pref_names::kAllowedInstallSites,
1986 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1987 registry->RegisterStringPref(
1988 pref_names::kLastChromeVersion,
1989 std::string(), // default value
1990 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1991 registry->RegisterListPref(pref_names::kKnownDisabled,
1992 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1993 #if defined(OS_MACOSX)
1994 registry->RegisterDoublePref(
1995 pref_names::kBrowserActionContainerWidth,
1997 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1998 #else
1999 registry->RegisterIntegerPref(
2000 pref_names::kBrowserActionContainerWidth,
2002 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
2003 #endif
2004 registry->RegisterDictionaryPref(
2005 kInstallSignature,
2006 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
2008 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist,
2009 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
2010 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist,
2011 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
2012 registry->RegisterBooleanPref(
2013 pref_names::kNativeMessagingUserLevelHosts,
2014 true, // default value
2015 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
2016 registry->RegisterIntegerPref(
2017 kCorruptedDisableCount,
2018 0, // default value
2019 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
2022 template <class ExtensionIdContainer>
2023 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
2024 const char* pref,
2025 ExtensionIdContainer* id_container_out) {
2026 DCHECK(id_container_out->empty());
2028 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
2029 const base::ListValue* user_pref_as_list;
2030 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
2031 return false;
2033 std::insert_iterator<ExtensionIdContainer> insert_iterator(
2034 *id_container_out, id_container_out->end());
2035 std::string extension_id;
2036 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
2037 value_it != user_pref_as_list->end(); ++value_it) {
2038 if (!(*value_it)->GetAsString(&extension_id)) {
2039 NOTREACHED();
2040 continue;
2042 insert_iterator = extension_id;
2044 return true;
2047 template <class ExtensionIdContainer>
2048 void ExtensionPrefs::SetExtensionPrefFromContainer(
2049 const char* pref,
2050 const ExtensionIdContainer& strings) {
2051 ListPrefUpdate update(prefs_, pref);
2052 base::ListValue* list_of_values = update.Get();
2053 list_of_values->Clear();
2054 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
2055 iter != strings.end(); ++iter) {
2056 list_of_values->Append(new base::StringValue(*iter));
2060 void ExtensionPrefs::PopulateExtensionInfoPrefs(
2061 const Extension* extension,
2062 const base::Time install_time,
2063 Extension::State initial_state,
2064 int install_flags,
2065 const std::string& install_parameter,
2066 base::DictionaryValue* extension_dict) {
2067 // Leave the state blank for component extensions so that old chrome versions
2068 // loading new profiles do not fail in GetInstalledExtensionInfo. Older
2069 // Chrome versions would only check for an omitted state.
2070 if (initial_state != Extension::ENABLED_COMPONENT)
2071 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
2073 extension_dict->Set(kPrefLocation,
2074 new base::FundamentalValue(extension->location()));
2075 extension_dict->Set(kPrefCreationFlags,
2076 new base::FundamentalValue(extension->creation_flags()));
2077 extension_dict->Set(kPrefFromWebStore,
2078 new base::FundamentalValue(extension->from_webstore()));
2079 extension_dict->Set(kPrefFromBookmark,
2080 new base::FundamentalValue(extension->from_bookmark()));
2081 extension_dict->Set(
2082 kPrefWasInstalledByDefault,
2083 new base::FundamentalValue(extension->was_installed_by_default()));
2084 extension_dict->Set(
2085 kPrefWasInstalledByOem,
2086 new base::FundamentalValue(extension->was_installed_by_oem()));
2087 extension_dict->Set(kPrefInstallTime,
2088 new base::StringValue(
2089 base::Int64ToString(install_time.ToInternalValue())));
2090 if (install_flags & kInstallFlagIsBlacklistedForMalware)
2091 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
2093 if (install_flags & kInstallFlagIsEphemeral)
2094 extension_dict->Set(kPrefEphemeralApp, new base::FundamentalValue(true));
2095 else
2096 extension_dict->Remove(kPrefEphemeralApp, NULL);
2098 base::FilePath::StringType path = MakePathRelative(install_directory_,
2099 extension->path());
2100 extension_dict->Set(kPrefPath, new base::StringValue(path));
2101 if (!install_parameter.empty()) {
2102 extension_dict->Set(kPrefInstallParam,
2103 new base::StringValue(install_parameter));
2105 // We store prefs about LOAD extensions, but don't cache their manifest
2106 // since it may change on disk.
2107 if (!Manifest::IsUnpackedLocation(extension->location())) {
2108 extension_dict->Set(kPrefManifest,
2109 extension->manifest()->value()->DeepCopy());
2112 // Only writes kPrefDoNotSync when it is not the default.
2113 if (install_flags & kInstallFlagDoNotSync)
2114 extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true));
2115 else
2116 extension_dict->Remove(kPrefDoNotSync, NULL);
2119 void ExtensionPrefs::InitExtensionControlledPrefs(
2120 ExtensionPrefValueMap* value_map) {
2121 ExtensionIdList extension_ids;
2122 GetExtensions(&extension_ids);
2124 for (ExtensionIdList::iterator extension_id = extension_ids.begin();
2125 extension_id != extension_ids.end();
2126 ++extension_id) {
2127 base::Time install_time = GetInstallTime(*extension_id);
2128 bool is_enabled = !IsExtensionDisabled(*extension_id);
2129 bool is_incognito_enabled = IsIncognitoEnabled(*extension_id);
2130 value_map->RegisterExtension(
2131 *extension_id, install_time, is_enabled, is_incognito_enabled);
2133 FOR_EACH_OBSERVER(
2134 ExtensionPrefsObserver,
2135 observer_list_,
2136 OnExtensionRegistered(*extension_id, install_time, is_enabled));
2138 // Set regular extension controlled prefs.
2139 LoadExtensionControlledPrefs(
2140 this, value_map, *extension_id, kExtensionPrefsScopeRegular);
2141 // Set incognito extension controlled prefs.
2142 LoadExtensionControlledPrefs(this,
2143 value_map,
2144 *extension_id,
2145 kExtensionPrefsScopeIncognitoPersistent);
2146 // Set regular-only extension controlled prefs.
2147 LoadExtensionControlledPrefs(
2148 this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly);
2150 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
2151 observer_list_,
2152 OnExtensionPrefsLoaded(*extension_id, this));
2156 void ExtensionPrefs::FinishExtensionInfoPrefs(
2157 const std::string& extension_id,
2158 const base::Time install_time,
2159 bool needs_sort_ordinal,
2160 const syncer::StringOrdinal& suggested_page_ordinal,
2161 base::DictionaryValue* extension_dict) {
2162 // Reinitializes various preferences with empty dictionaries.
2163 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
2164 extension_dict->Set(pref_names::kPrefPreferences,
2165 new base::DictionaryValue);
2168 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
2169 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
2170 new base::DictionaryValue);
2173 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
2174 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
2175 new base::DictionaryValue);
2178 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
2179 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
2181 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
2182 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
2183 new base::ListValue);
2186 // If this point has been reached, any pending installs should be considered
2187 // out of date.
2188 extension_dict->Remove(kDelayedInstallInfo, NULL);
2190 // Clear state that may be registered from a previous install.
2191 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
2193 // FYI, all code below here races on sudden shutdown because |extension_dict|,
2194 // |app_sorting_|, |extension_pref_value_map_|, and (potentially) observers
2195 // are updated non-transactionally. This is probably not fixable without
2196 // nested transactional updates to pref dictionaries.
2197 if (needs_sort_ordinal)
2198 app_sorting_->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
2200 bool is_enabled = false;
2201 int initial_state;
2202 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
2203 is_enabled = initial_state == Extension::ENABLED;
2205 bool is_incognito_enabled = IsIncognitoEnabled(extension_id);
2207 extension_pref_value_map_->RegisterExtension(
2208 extension_id, install_time, is_enabled, is_incognito_enabled);
2210 FOR_EACH_OBSERVER(
2211 ExtensionPrefsObserver,
2212 observer_list_,
2213 OnExtensionRegistered(extension_id, install_time, is_enabled));
2216 } // namespace extensions