Code Cleanup for extension_prefs, as AddDisableReasons() is not required same behavio...
[chromium-blink-merge.git] / extensions / browser / extension_prefs.cc
blobc4f7da2e79013c6ba7d1be3ff6de6c4d5903cb70
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/metrics/histogram_macros.h"
11 #include "base/prefs/pref_notifier.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_util.h"
15 #include "base/trace_event/trace_event.h"
16 #include "base/value_conversions.h"
17 #include "components/crx_file/id_util.h"
18 #include "components/pref_registry/pref_registry_syncable.h"
19 #include "extensions/browser/app_sorting.h"
20 #include "extensions/browser/event_router.h"
21 #include "extensions/browser/extension_pref_store.h"
22 #include "extensions/browser/extension_prefs_factory.h"
23 #include "extensions/browser/extension_prefs_observer.h"
24 #include "extensions/browser/install_flag.h"
25 #include "extensions/browser/pref_names.h"
26 #include "extensions/common/feature_switch.h"
27 #include "extensions/common/manifest.h"
28 #include "extensions/common/permissions/permission_set.h"
29 #include "extensions/common/permissions/permissions_info.h"
30 #include "extensions/common/url_pattern.h"
31 #include "extensions/common/user_script.h"
32 #include "ui/base/l10n/l10n_util.h"
34 using base::Value;
35 using base::DictionaryValue;
36 using base::ListValue;
38 namespace extensions {
40 namespace {
42 // Additional preferences keys, which are not needed by external clients.
44 // True if this extension is running. Note this preference stops getting updated
45 // during Chrome shutdown (and won't be updated on a browser crash) and so can
46 // be used at startup to determine whether the extension was running when Chrome
47 // was last terminated.
48 const char kPrefRunning[] = "running";
50 // Whether this extension had windows when it was last running.
51 const char kIsActive[] = "is_active";
53 // Where an extension was installed from. (see Manifest::Location)
54 const char kPrefLocation[] = "location";
56 // Enabled, disabled, killed, etc. (see Extension::State)
57 const char kPrefState[] = "state";
59 // The path to the current version's manifest file.
60 const char kPrefPath[] = "path";
62 // The dictionary containing the extension's manifest.
63 const char kPrefManifest[] = "manifest";
65 // The version number.
66 const char kPrefVersion[] = "manifest.version";
68 // Indicates whether an extension is blacklisted.
69 const char kPrefBlacklist[] = "blacklist";
71 // If extension is greylisted.
72 const char kPrefBlacklistState[] = "blacklist_state";
74 // The count of how many times we prompted the user to acknowledge an
75 // extension.
76 const char kPrefAcknowledgePromptCount[] = "ack_prompt_count";
78 // Indicates whether the user has acknowledged various types of extensions.
79 const char kPrefExternalAcknowledged[] = "ack_external";
80 const char kPrefBlacklistAcknowledged[] = "ack_blacklist";
82 // Indicates whether the external extension was installed during the first
83 // run of this profile.
84 const char kPrefExternalInstallFirstRun[] = "external_first_run";
86 // Indicates whether to show an install warning when the user enables.
87 const char kExtensionDidEscalatePermissions[] = "install_warning_on_enable";
89 // DO NOT USE, use kPrefDisableReasons instead.
90 // Indicates whether the extension was updated while it was disabled.
91 const char kDeprecatedPrefDisableReason[] = "disable_reason";
93 // A bitmask of all the reasons an extension is disabled.
94 const char kPrefDisableReasons[] = "disable_reasons";
96 // The key for a serialized Time value indicating the start of the day (from the
97 // server's perspective) an extension last included a "ping" parameter during
98 // its update check.
99 const char kLastPingDay[] = "lastpingday";
101 // Similar to kLastPingDay, but for "active" instead of "rollcall" pings.
102 const char kLastActivePingDay[] = "last_active_pingday";
104 // A bit we use to keep track of whether we need to do an "active" ping.
105 const char kActiveBit[] = "active_bit";
107 // Path for settings specific to blacklist update.
108 const char kExtensionsBlacklistUpdate[] = "extensions.blacklistupdate";
110 // Path for the delayed install info dictionary preference. The actual string
111 // value is a legacy artifact for when delayed installs only pertained to
112 // updates that were waiting for idle.
113 const char kDelayedInstallInfo[] = "idle_install_info";
115 // Reason why the extension's install was delayed.
116 const char kDelayedInstallReason[] = "delay_install_reason";
118 // Path for the suggested page ordinal of a delayed extension install.
119 const char kPrefSuggestedPageOrdinal[] = "suggested_page_ordinal";
121 // A preference that, if true, will allow this extension to run in incognito
122 // mode.
123 const char kPrefIncognitoEnabled[] = "incognito";
125 // A preference to control whether an extension is allowed to inject script in
126 // pages with file URLs.
127 const char kPrefAllowFileAccess[] = "newAllowFileAccess";
128 // TODO(jstritar): As part of fixing http://crbug.com/91577, we revoked all
129 // extension file access by renaming the pref. We should eventually clean up
130 // the old flag and possibly go back to that name.
131 // const char kPrefAllowFileAccessOld[] = "allowFileAccess";
133 // A preference specifying if the user dragged the app on the NTP.
134 const char kPrefUserDraggedApp[] = "user_dragged_app_ntp";
136 // Preferences that hold which permissions the user has granted the extension.
137 // We explicitly keep track of these so that extensions can contain unknown
138 // permissions, for backwards compatibility reasons, and we can still prompt
139 // the user to accept them once recognized. We store the active permission
140 // permissions because they may differ from those defined in the manifest.
141 const char kPrefActivePermissions[] = "active_permissions";
142 const char kPrefGrantedPermissions[] = "granted_permissions";
144 // The preference names for PermissionSet values.
145 const char kPrefAPIs[] = "api";
146 const char kPrefManifestPermissions[] = "manifest_permissions";
147 const char kPrefExplicitHosts[] = "explicit_host";
148 const char kPrefScriptableHosts[] = "scriptable_host";
150 // The preference names for the old granted permissions scheme.
151 const char kPrefOldGrantedFullAccess[] = "granted_permissions.full";
152 const char kPrefOldGrantedHosts[] = "granted_permissions.host";
153 const char kPrefOldGrantedAPIs[] = "granted_permissions.api";
155 // A preference that indicates when an extension was installed.
156 const char kPrefInstallTime[] = "install_time";
158 // A preference which saves the creation flags for extensions.
159 const char kPrefCreationFlags[] = "creation_flags";
161 // A preference that indicates whether the extension was installed from the
162 // Chrome Web Store.
163 const char kPrefFromWebStore[] = "from_webstore";
165 // A preference that indicates whether the extension was installed from a
166 // mock App created from a bookmark.
167 const char kPrefFromBookmark[] = "from_bookmark";
169 // A preference that indicates whether the extension was installed as a
170 // default app.
171 const char kPrefWasInstalledByDefault[] = "was_installed_by_default";
173 // A preference that indicates whether the extension was installed as an
174 // OEM app.
175 const char kPrefWasInstalledByOem[] = "was_installed_by_oem";
177 // Key for Geometry Cache preference.
178 const char kPrefGeometryCache[] = "geometry_cache";
180 // A preference that indicates when an extension is last launched.
181 const char kPrefLastLaunchTime[] = "last_launch_time";
183 // A preference indicating whether the extension is an ephemeral app.
184 const char kPrefEphemeralApp[] = "ephemeral_app";
186 // Am installation parameter bundled with an extension.
187 const char kPrefInstallParam[] = "install_parameter";
189 // A list of installed ids and a signature.
190 const char kInstallSignature[] = "extensions.install_signature";
192 // A boolean preference that indicates whether the extension should not be
193 // synced. Default value is false.
194 const char kPrefDoNotSync[] = "do_not_sync";
196 const char kCorruptedDisableCount[] = "extensions.corrupted_disable_count";
198 // Provider of write access to a dictionary storing extension prefs.
199 class ScopedExtensionPrefUpdate : public DictionaryPrefUpdate {
200 public:
201 ScopedExtensionPrefUpdate(PrefService* service,
202 const std::string& extension_id) :
203 DictionaryPrefUpdate(service, pref_names::kExtensions),
204 extension_id_(extension_id) {}
206 ~ScopedExtensionPrefUpdate() override {}
208 // DictionaryPrefUpdate overrides:
209 base::DictionaryValue* Get() override {
210 base::DictionaryValue* dict = DictionaryPrefUpdate::Get();
211 base::DictionaryValue* extension = NULL;
212 if (!dict->GetDictionary(extension_id_, &extension)) {
213 // Extension pref does not exist, create it.
214 extension = new base::DictionaryValue();
215 dict->SetWithoutPathExpansion(extension_id_, extension);
217 return extension;
220 private:
221 const std::string extension_id_;
223 DISALLOW_COPY_AND_ASSIGN(ScopedExtensionPrefUpdate);
226 std::string JoinPrefs(const std::string& parent, const char* child) {
227 return parent + "." + child;
230 // Checks if kPrefBlacklist is set to true in the base::DictionaryValue.
231 // Return false if the value is false or kPrefBlacklist does not exist.
232 // This is used to decide if an extension is blacklisted.
233 bool IsBlacklistBitSet(const base::DictionaryValue* ext) {
234 bool bool_value;
235 return ext->GetBoolean(kPrefBlacklist, &bool_value) && bool_value;
238 void LoadExtensionControlledPrefs(ExtensionPrefs* prefs,
239 ExtensionPrefValueMap* value_map,
240 const std::string& extension_id,
241 ExtensionPrefsScope scope) {
242 std::string scope_string;
243 if (!pref_names::ScopeToPrefName(scope, &scope_string))
244 return;
245 std::string key = extension_id + "." + scope_string;
247 const base::DictionaryValue* source_dict =
248 prefs->pref_service()->GetDictionary(pref_names::kExtensions);
249 const base::DictionaryValue* preferences = NULL;
250 if (!source_dict->GetDictionary(key, &preferences))
251 return;
253 for (base::DictionaryValue::Iterator iter(*preferences); !iter.IsAtEnd();
254 iter.Advance()) {
255 value_map->SetExtensionPref(
256 extension_id, iter.key(), scope, iter.value().DeepCopy());
260 } // namespace
263 // TimeProvider
266 ExtensionPrefs::TimeProvider::TimeProvider() {
269 ExtensionPrefs::TimeProvider::~TimeProvider() {
272 base::Time ExtensionPrefs::TimeProvider::GetCurrentTime() const {
273 return base::Time::Now();
277 // ScopedUpdate
279 template <typename T, base::Value::Type type_enum_value>
280 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::ScopedUpdate(
281 ExtensionPrefs* prefs,
282 const std::string& extension_id,
283 const std::string& key)
284 : update_(prefs->pref_service(), pref_names::kExtensions),
285 extension_id_(extension_id),
286 key_(key) {
287 DCHECK(crx_file::id_util::IdIsValid(extension_id_));
290 template <typename T, base::Value::Type type_enum_value>
291 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::~ScopedUpdate() {
294 template <typename T, base::Value::Type type_enum_value>
295 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Get() {
296 base::DictionaryValue* dict = update_.Get();
297 base::DictionaryValue* extension = NULL;
298 base::Value* key_value = NULL;
299 if (!dict->GetDictionary(extension_id_, &extension) ||
300 !extension->Get(key_, &key_value)) {
301 return NULL;
303 return key_value->GetType() == type_enum_value ?
304 static_cast<T*>(key_value) :
305 NULL;
308 template <typename T, base::Value::Type type_enum_value>
309 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Create() {
310 base::DictionaryValue* dict = update_.Get();
311 base::DictionaryValue* extension = NULL;
312 base::Value* key_value = NULL;
313 T* value_as_t = NULL;
314 if (!dict->GetDictionary(extension_id_, &extension)) {
315 extension = new base::DictionaryValue;
316 dict->SetWithoutPathExpansion(extension_id_, extension);
318 if (!extension->Get(key_, &key_value)) {
319 value_as_t = new T;
320 extension->SetWithoutPathExpansion(key_, value_as_t);
321 } else {
322 CHECK(key_value->GetType() == type_enum_value);
323 value_as_t = static_cast<T*>(key_value);
325 return value_as_t;
328 // Explicit instantiations for Dictionary and List value types.
329 template class ExtensionPrefs::ScopedUpdate<base::DictionaryValue,
330 base::Value::TYPE_DICTIONARY>;
331 template class ExtensionPrefs::ScopedUpdate<base::ListValue,
332 base::Value::TYPE_LIST>;
335 // ExtensionPrefs
338 // static
339 ExtensionPrefs* ExtensionPrefs::Create(
340 PrefService* prefs,
341 const base::FilePath& root_dir,
342 ExtensionPrefValueMap* extension_pref_value_map,
343 scoped_ptr<AppSorting> app_sorting,
344 bool extensions_disabled,
345 const std::vector<ExtensionPrefsObserver*>& early_observers) {
346 return ExtensionPrefs::Create(prefs,
347 root_dir,
348 extension_pref_value_map,
349 app_sorting.Pass(),
350 extensions_disabled,
351 early_observers,
352 make_scoped_ptr(new TimeProvider()));
355 // static
356 ExtensionPrefs* ExtensionPrefs::Create(
357 PrefService* pref_service,
358 const base::FilePath& root_dir,
359 ExtensionPrefValueMap* extension_pref_value_map,
360 scoped_ptr<AppSorting> app_sorting,
361 bool extensions_disabled,
362 const std::vector<ExtensionPrefsObserver*>& early_observers,
363 scoped_ptr<TimeProvider> time_provider) {
364 return new ExtensionPrefs(pref_service,
365 root_dir,
366 extension_pref_value_map,
367 app_sorting.Pass(),
368 time_provider.Pass(),
369 extensions_disabled,
370 early_observers);
373 ExtensionPrefs::~ExtensionPrefs() {
376 // static
377 ExtensionPrefs* ExtensionPrefs::Get(content::BrowserContext* context) {
378 return ExtensionPrefsFactory::GetInstance()->GetForBrowserContext(context);
381 static base::FilePath::StringType MakePathRelative(const base::FilePath& parent,
382 const base::FilePath& child) {
383 if (!parent.IsParent(child))
384 return child.value();
386 base::FilePath::StringType retval = child.value().substr(
387 parent.value().length());
388 if (base::FilePath::IsSeparator(retval[0]))
389 return retval.substr(1);
390 else
391 return retval;
394 void ExtensionPrefs::MakePathsRelative() {
395 const base::DictionaryValue* dict =
396 prefs_->GetDictionary(pref_names::kExtensions);
397 if (!dict || dict->empty())
398 return;
400 // Collect all extensions ids with absolute paths in |absolute_keys|.
401 std::set<std::string> absolute_keys;
402 for (base::DictionaryValue::Iterator i(*dict); !i.IsAtEnd(); i.Advance()) {
403 const base::DictionaryValue* extension_dict = NULL;
404 if (!i.value().GetAsDictionary(&extension_dict))
405 continue;
406 int location_value;
407 if (extension_dict->GetInteger(kPrefLocation, &location_value) &&
408 Manifest::IsUnpackedLocation(
409 static_cast<Manifest::Location>(location_value))) {
410 // Unpacked extensions can have absolute paths.
411 continue;
413 base::FilePath::StringType path_string;
414 if (!extension_dict->GetString(kPrefPath, &path_string))
415 continue;
416 base::FilePath path(path_string);
417 if (path.IsAbsolute())
418 absolute_keys.insert(i.key());
420 if (absolute_keys.empty())
421 return;
423 // Fix these paths.
424 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
425 base::DictionaryValue* update_dict = update.Get();
426 for (std::set<std::string>::iterator i = absolute_keys.begin();
427 i != absolute_keys.end(); ++i) {
428 base::DictionaryValue* extension_dict = NULL;
429 if (!update_dict->GetDictionaryWithoutPathExpansion(*i, &extension_dict)) {
430 NOTREACHED() << "Control should never reach here for extension " << *i;
431 continue;
433 base::FilePath::StringType path_string;
434 extension_dict->GetString(kPrefPath, &path_string);
435 base::FilePath path(path_string);
436 extension_dict->SetString(kPrefPath,
437 MakePathRelative(install_directory_, path));
441 const base::DictionaryValue* ExtensionPrefs::GetExtensionPref(
442 const std::string& extension_id) const {
443 const base::DictionaryValue* extensions =
444 prefs_->GetDictionary(pref_names::kExtensions);
445 const base::DictionaryValue* extension_dict = NULL;
446 if (!extensions ||
447 !extensions->GetDictionary(extension_id, &extension_dict)) {
448 return NULL;
450 return extension_dict;
453 void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id,
454 const std::string& key,
455 base::Value* data_value) {
456 if (!crx_file::id_util::IdIsValid(extension_id)) {
457 NOTREACHED() << "Invalid extension_id " << extension_id;
458 return;
460 ScopedExtensionPrefUpdate update(prefs_, extension_id);
461 if (data_value)
462 update->Set(key, data_value);
463 else
464 update->Remove(key, NULL);
467 void ExtensionPrefs::DeleteExtensionPrefs(const std::string& extension_id) {
468 extension_pref_value_map_->UnregisterExtension(extension_id);
469 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
470 observer_list_,
471 OnExtensionPrefsDeleted(extension_id));
472 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
473 base::DictionaryValue* dict = update.Get();
474 dict->Remove(extension_id, NULL);
477 bool ExtensionPrefs::ReadPrefAsBoolean(const std::string& extension_id,
478 const std::string& pref_key,
479 bool* out_value) const {
480 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
481 if (!ext || !ext->GetBoolean(pref_key, out_value))
482 return false;
484 return true;
487 bool ExtensionPrefs::ReadPrefAsInteger(const std::string& extension_id,
488 const std::string& pref_key,
489 int* out_value) const {
490 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
491 if (!ext || !ext->GetInteger(pref_key, out_value))
492 return false;
494 return true;
497 bool ExtensionPrefs::ReadPrefAsString(const std::string& extension_id,
498 const std::string& pref_key,
499 std::string* out_value) const {
500 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
501 if (!ext || !ext->GetString(pref_key, out_value))
502 return false;
504 return true;
507 bool ExtensionPrefs::ReadPrefAsList(const std::string& extension_id,
508 const std::string& pref_key,
509 const base::ListValue** out_value) const {
510 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
511 const base::ListValue* out = NULL;
512 if (!ext || !ext->GetList(pref_key, &out))
513 return false;
514 if (out_value)
515 *out_value = out;
517 return true;
520 bool ExtensionPrefs::ReadPrefAsDictionary(
521 const std::string& extension_id,
522 const std::string& pref_key,
523 const base::DictionaryValue** out_value) const {
524 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
525 const base::DictionaryValue* out = NULL;
526 if (!ext || !ext->GetDictionary(pref_key, &out))
527 return false;
528 if (out_value)
529 *out_value = out;
531 return true;
534 bool ExtensionPrefs::HasPrefForExtension(
535 const std::string& extension_id) const {
536 return GetExtensionPref(extension_id) != NULL;
539 bool ExtensionPrefs::ReadPrefAsURLPatternSet(const std::string& extension_id,
540 const std::string& pref_key,
541 URLPatternSet* result,
542 int valid_schemes) {
543 const base::ListValue* value = NULL;
544 if (!ReadPrefAsList(extension_id, pref_key, &value))
545 return false;
546 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
547 if (!extension)
548 return false;
549 int location;
550 if (extension->GetInteger(kPrefLocation, &location) &&
551 static_cast<Manifest::Location>(location) == Manifest::COMPONENT) {
552 valid_schemes |= URLPattern::SCHEME_CHROMEUI;
555 bool allow_file_access = AllowFileAccess(extension_id);
556 return result->Populate(*value, valid_schemes, allow_file_access, NULL);
559 void ExtensionPrefs::SetExtensionPrefURLPatternSet(
560 const std::string& extension_id,
561 const std::string& pref_key,
562 const URLPatternSet& new_value) {
563 UpdateExtensionPref(extension_id, pref_key, new_value.ToValue().release());
566 bool ExtensionPrefs::ReadPrefAsBooleanAndReturn(
567 const std::string& extension_id,
568 const std::string& pref_key) const {
569 bool out_value = false;
570 return ReadPrefAsBoolean(extension_id, pref_key, &out_value) && out_value;
573 PermissionSet* ExtensionPrefs::ReadPrefAsPermissionSet(
574 const std::string& extension_id,
575 const std::string& pref_key) {
576 if (!GetExtensionPref(extension_id))
577 return NULL;
579 // Retrieve the API permissions. Please refer SetExtensionPrefPermissionSet()
580 // for api_values format.
581 APIPermissionSet apis;
582 const base::ListValue* api_values = NULL;
583 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
584 if (ReadPrefAsList(extension_id, api_pref, &api_values)) {
585 APIPermissionSet::ParseFromJSON(api_values,
586 APIPermissionSet::kAllowInternalPermissions,
587 &apis, NULL, NULL);
590 // Retrieve the Manifest Keys permissions. Please refer to
591 // |SetExtensionPrefPermissionSet| for manifest_permissions_values format.
592 ManifestPermissionSet manifest_permissions;
593 const base::ListValue* manifest_permissions_values = NULL;
594 std::string manifest_permission_pref =
595 JoinPrefs(pref_key, kPrefManifestPermissions);
596 if (ReadPrefAsList(extension_id, manifest_permission_pref,
597 &manifest_permissions_values)) {
598 ManifestPermissionSet::ParseFromJSON(
599 manifest_permissions_values, &manifest_permissions, NULL, NULL);
602 // Retrieve the explicit host permissions.
603 URLPatternSet explicit_hosts;
604 ReadPrefAsURLPatternSet(
605 extension_id, JoinPrefs(pref_key, kPrefExplicitHosts),
606 &explicit_hosts, Extension::kValidHostPermissionSchemes);
608 // Retrieve the scriptable host permissions.
609 URLPatternSet scriptable_hosts;
610 ReadPrefAsURLPatternSet(
611 extension_id, JoinPrefs(pref_key, kPrefScriptableHosts),
612 &scriptable_hosts, UserScript::ValidUserScriptSchemes());
614 return new PermissionSet(
615 apis, manifest_permissions, explicit_hosts, scriptable_hosts);
618 // Set the API or Manifest permissions.
619 // The format of api_values is:
620 // [ "permission_name1", // permissions do not support detail.
621 // "permission_name2",
622 // {"permission_name3": value },
623 // // permission supports detail, permission detail will be stored in value.
624 // ...
625 // ]
626 template<typename T>
627 static base::ListValue* CreatePermissionList(const T& permissions) {
628 base::ListValue* values = new base::ListValue();
629 for (typename T::const_iterator i = permissions.begin();
630 i != permissions.end(); ++i) {
631 scoped_ptr<base::Value> detail(i->ToValue());
632 if (detail) {
633 base::DictionaryValue* tmp = new base::DictionaryValue();
634 tmp->Set(i->name(), detail.release());
635 values->Append(tmp);
636 } else {
637 values->Append(new base::StringValue(i->name()));
640 return values;
643 void ExtensionPrefs::SetExtensionPrefPermissionSet(
644 const std::string& extension_id,
645 const std::string& pref_key,
646 const PermissionSet* new_value) {
647 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
648 base::ListValue* api_values = CreatePermissionList(new_value->apis());
649 UpdateExtensionPref(extension_id, api_pref, api_values);
651 std::string manifest_permissions_pref =
652 JoinPrefs(pref_key, kPrefManifestPermissions);
653 base::ListValue* manifest_permissions_values = CreatePermissionList(
654 new_value->manifest_permissions());
655 UpdateExtensionPref(extension_id,
656 manifest_permissions_pref,
657 manifest_permissions_values);
659 // Set the explicit host permissions.
660 if (!new_value->explicit_hosts().is_empty()) {
661 SetExtensionPrefURLPatternSet(extension_id,
662 JoinPrefs(pref_key, kPrefExplicitHosts),
663 new_value->explicit_hosts());
666 // Set the scriptable host permissions.
667 if (!new_value->scriptable_hosts().is_empty()) {
668 SetExtensionPrefURLPatternSet(extension_id,
669 JoinPrefs(pref_key, kPrefScriptableHosts),
670 new_value->scriptable_hosts());
674 int ExtensionPrefs::IncrementAcknowledgePromptCount(
675 const std::string& extension_id) {
676 int count = 0;
677 ReadPrefAsInteger(extension_id, kPrefAcknowledgePromptCount, &count);
678 ++count;
679 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount,
680 new base::FundamentalValue(count));
681 return count;
684 bool ExtensionPrefs::IsExternalExtensionAcknowledged(
685 const std::string& extension_id) {
686 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalAcknowledged);
689 void ExtensionPrefs::AcknowledgeExternalExtension(
690 const std::string& extension_id) {
691 DCHECK(crx_file::id_util::IdIsValid(extension_id));
692 UpdateExtensionPref(extension_id, kPrefExternalAcknowledged,
693 new base::FundamentalValue(true));
694 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
697 bool ExtensionPrefs::IsBlacklistedExtensionAcknowledged(
698 const std::string& extension_id) {
699 return ReadPrefAsBooleanAndReturn(extension_id, kPrefBlacklistAcknowledged);
702 void ExtensionPrefs::AcknowledgeBlacklistedExtension(
703 const std::string& extension_id) {
704 DCHECK(crx_file::id_util::IdIsValid(extension_id));
705 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged,
706 new base::FundamentalValue(true));
707 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
710 bool ExtensionPrefs::IsExternalInstallFirstRun(
711 const std::string& extension_id) {
712 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalInstallFirstRun);
715 void ExtensionPrefs::SetExternalInstallFirstRun(
716 const std::string& extension_id) {
717 DCHECK(crx_file::id_util::IdIsValid(extension_id));
718 UpdateExtensionPref(extension_id, kPrefExternalInstallFirstRun,
719 new base::FundamentalValue(true));
722 bool ExtensionPrefs::SetAlertSystemFirstRun() {
723 if (prefs_->GetBoolean(pref_names::kAlertsInitialized)) {
724 return true;
726 prefs_->SetBoolean(pref_names::kAlertsInitialized, true);
727 return false;
730 bool ExtensionPrefs::DidExtensionEscalatePermissions(
731 const std::string& extension_id) {
732 return ReadPrefAsBooleanAndReturn(extension_id,
733 kExtensionDidEscalatePermissions);
736 void ExtensionPrefs::SetDidExtensionEscalatePermissions(
737 const Extension* extension, bool did_escalate) {
738 UpdateExtensionPref(extension->id(), kExtensionDidEscalatePermissions,
739 new base::FundamentalValue(did_escalate));
742 int ExtensionPrefs::GetDisableReasons(const std::string& extension_id) const {
743 int value = -1;
744 if (ReadPrefAsInteger(extension_id, kPrefDisableReasons, &value) &&
745 value >= 0) {
746 return value;
748 return Extension::DISABLE_NONE;
751 bool ExtensionPrefs::HasDisableReason(
752 const std::string& extension_id,
753 Extension::DisableReason disable_reason) const {
754 return (GetDisableReasons(extension_id) & disable_reason) != 0;
757 void ExtensionPrefs::AddDisableReason(const std::string& extension_id,
758 Extension::DisableReason disable_reason) {
759 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_ADD);
762 void ExtensionPrefs::RemoveDisableReason(
763 const std::string& extension_id,
764 Extension::DisableReason disable_reason) {
765 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_REMOVE);
768 void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) {
769 ModifyDisableReasons(extension_id, Extension::DISABLE_NONE,
770 DISABLE_REASON_CLEAR);
773 void ExtensionPrefs::ModifyDisableReasons(const std::string& extension_id,
774 int reasons,
775 DisableReasonChange change) {
776 int old_value = GetDisableReasons(extension_id);
777 int new_value = old_value;
778 switch (change) {
779 case DISABLE_REASON_ADD:
780 new_value |= reasons;
781 break;
782 case DISABLE_REASON_REMOVE:
783 new_value &= ~reasons;
784 break;
785 case DISABLE_REASON_CLEAR:
786 new_value = Extension::DISABLE_NONE;
787 break;
790 if (old_value == new_value) // no change, return.
791 return;
793 if (new_value == Extension::DISABLE_NONE) {
794 UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
795 } else {
796 UpdateExtensionPref(extension_id,
797 kPrefDisableReasons,
798 new base::FundamentalValue(new_value));
801 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
802 observer_list_,
803 OnExtensionDisableReasonsChanged(extension_id, new_value));
806 std::set<std::string> ExtensionPrefs::GetBlacklistedExtensions() {
807 std::set<std::string> ids;
809 const base::DictionaryValue* extensions =
810 prefs_->GetDictionary(pref_names::kExtensions);
811 if (!extensions)
812 return ids;
814 for (base::DictionaryValue::Iterator it(*extensions);
815 !it.IsAtEnd(); it.Advance()) {
816 if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) {
817 NOTREACHED() << "Invalid pref for extension " << it.key();
818 continue;
820 if (IsBlacklistBitSet(
821 static_cast<const base::DictionaryValue*>(&it.value()))) {
822 ids.insert(it.key());
826 return ids;
829 void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id,
830 bool is_blacklisted) {
831 bool currently_blacklisted = IsExtensionBlacklisted(extension_id);
832 if (is_blacklisted == currently_blacklisted)
833 return;
835 // Always make sure the "acknowledged" bit is cleared since the blacklist bit
836 // is changing.
837 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL);
839 if (is_blacklisted) {
840 UpdateExtensionPref(extension_id,
841 kPrefBlacklist,
842 new base::FundamentalValue(true));
843 } else {
844 UpdateExtensionPref(extension_id, kPrefBlacklist, NULL);
845 const base::DictionaryValue* dict = GetExtensionPref(extension_id);
846 if (dict && dict->empty())
847 DeleteExtensionPrefs(extension_id);
851 bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const {
852 const base::DictionaryValue* ext_prefs = GetExtensionPref(id);
853 return ext_prefs && IsBlacklistBitSet(ext_prefs);
856 namespace {
858 // Serializes a 64bit integer as a string value.
859 void SaveInt64(base::DictionaryValue* dictionary,
860 const char* key,
861 const int64 value) {
862 if (!dictionary)
863 return;
865 std::string string_value = base::Int64ToString(value);
866 dictionary->SetString(key, string_value);
869 // Deserializes a 64bit integer stored as a string value.
870 bool ReadInt64(const base::DictionaryValue* dictionary,
871 const char* key,
872 int64* value) {
873 if (!dictionary)
874 return false;
876 std::string string_value;
877 if (!dictionary->GetString(key, &string_value))
878 return false;
880 return base::StringToInt64(string_value, value);
883 // Serializes |time| as a string value mapped to |key| in |dictionary|.
884 void SaveTime(base::DictionaryValue* dictionary,
885 const char* key,
886 const base::Time& time) {
887 SaveInt64(dictionary, key, time.ToInternalValue());
890 // The opposite of SaveTime. If |key| is not found, this returns an empty Time
891 // (is_null() will return true).
892 base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) {
893 int64 value;
894 if (ReadInt64(dictionary, key, &value))
895 return base::Time::FromInternalValue(value);
897 return base::Time();
900 } // namespace
902 base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const {
903 DCHECK(crx_file::id_util::IdIsValid(extension_id));
904 return ReadTime(GetExtensionPref(extension_id), kLastPingDay);
907 void ExtensionPrefs::SetLastPingDay(const std::string& extension_id,
908 const base::Time& time) {
909 DCHECK(crx_file::id_util::IdIsValid(extension_id));
910 ScopedExtensionPrefUpdate update(prefs_, extension_id);
911 SaveTime(update.Get(), kLastPingDay, time);
914 base::Time ExtensionPrefs::BlacklistLastPingDay() const {
915 return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate),
916 kLastPingDay);
919 void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) {
920 DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate);
921 SaveTime(update.Get(), kLastPingDay, time);
924 base::Time ExtensionPrefs::LastActivePingDay(const std::string& extension_id) {
925 DCHECK(crx_file::id_util::IdIsValid(extension_id));
926 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
929 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
930 const base::Time& time) {
931 DCHECK(crx_file::id_util::IdIsValid(extension_id));
932 ScopedExtensionPrefUpdate update(prefs_, extension_id);
933 SaveTime(update.Get(), kLastActivePingDay, time);
936 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) {
937 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
938 bool result = false;
939 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
940 return result;
941 return false;
944 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
945 bool active) {
946 UpdateExtensionPref(extension_id, kActiveBit,
947 new base::FundamentalValue(active));
950 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
951 PermissionsInfo* info = PermissionsInfo::GetInstance();
952 for (ExtensionIdList::const_iterator ext_id =
953 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
954 // An extension's granted permissions need to be migrated if the
955 // full_access bit is present. This bit was always present in the previous
956 // scheme and is never present now.
957 bool full_access = false;
958 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
959 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
960 continue;
962 // Remove the full access bit (empty list will get trimmed).
963 UpdateExtensionPref(
964 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
966 // Add the plugin permission if the full access bit was set.
967 if (full_access) {
968 const base::ListValue* apis = NULL;
969 base::ListValue* new_apis = NULL;
971 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
972 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
973 new_apis = apis->DeepCopy();
974 else
975 new_apis = new base::ListValue();
977 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
978 new_apis->Append(new base::StringValue(plugin_name));
979 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
982 // The granted permissions originally only held the effective hosts,
983 // which are a combination of host and user script host permissions.
984 // We now maintain these lists separately. For migration purposes, it
985 // does not matter how we treat the old effective hosts as long as the
986 // new effective hosts will be the same, so we move them to explicit
987 // host permissions.
988 const base::ListValue* hosts = NULL;
989 std::string explicit_hosts =
990 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
991 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
992 UpdateExtensionPref(
993 *ext_id, explicit_hosts, hosts->DeepCopy());
995 // We can get rid of the old one by setting it to an empty list.
996 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
1001 void ExtensionPrefs::MigrateDisableReasons(
1002 const ExtensionIdList& extension_ids) {
1003 for (ExtensionIdList::const_iterator ext_id =
1004 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
1005 int value = -1;
1006 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
1007 int new_value = Extension::DISABLE_NONE;
1008 switch (value) {
1009 case Extension::DEPRECATED_DISABLE_USER_ACTION:
1010 new_value = Extension::DISABLE_USER_ACTION;
1011 break;
1012 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
1013 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
1014 break;
1015 case Extension::DEPRECATED_DISABLE_RELOAD:
1016 new_value = Extension::DISABLE_RELOAD;
1017 break;
1020 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
1021 new base::FundamentalValue(new_value));
1022 // Remove the old disable reason.
1023 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
1028 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
1029 const std::string& extension_id) {
1030 CHECK(crx_file::id_util::IdIsValid(extension_id));
1031 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
1034 void ExtensionPrefs::AddGrantedPermissions(
1035 const std::string& extension_id,
1036 const PermissionSet* permissions) {
1037 CHECK(crx_file::id_util::IdIsValid(extension_id));
1039 scoped_refptr<PermissionSet> granted_permissions(
1040 GetGrantedPermissions(extension_id));
1042 // The new granted permissions are the union of the already granted
1043 // permissions and the newly granted permissions.
1044 scoped_refptr<PermissionSet> new_perms(
1045 PermissionSet::CreateUnion(
1046 permissions, granted_permissions.get()));
1048 SetExtensionPrefPermissionSet(
1049 extension_id, kPrefGrantedPermissions, new_perms.get());
1052 void ExtensionPrefs::RemoveGrantedPermissions(
1053 const std::string& extension_id,
1054 const PermissionSet* permissions) {
1055 CHECK(crx_file::id_util::IdIsValid(extension_id));
1057 scoped_refptr<PermissionSet> granted_permissions(
1058 GetGrantedPermissions(extension_id));
1060 // The new granted permissions are the difference of the already granted
1061 // permissions and the newly ungranted permissions.
1062 scoped_refptr<PermissionSet> new_perms(
1063 PermissionSet::CreateDifference(
1064 granted_permissions.get(), permissions));
1066 SetExtensionPrefPermissionSet(
1067 extension_id, kPrefGrantedPermissions, new_perms.get());
1070 PermissionSet* ExtensionPrefs::GetActivePermissions(
1071 const std::string& extension_id) {
1072 CHECK(crx_file::id_util::IdIsValid(extension_id));
1073 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
1076 void ExtensionPrefs::SetActivePermissions(
1077 const std::string& extension_id,
1078 const PermissionSet* permissions) {
1079 SetExtensionPrefPermissionSet(
1080 extension_id, kPrefActivePermissions, permissions);
1083 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1084 bool is_running) {
1085 base::Value* value = new base::FundamentalValue(is_running);
1086 UpdateExtensionPref(extension_id, kPrefRunning, value);
1089 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) {
1090 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1091 if (!extension)
1092 return false;
1093 bool running = false;
1094 extension->GetBoolean(kPrefRunning, &running);
1095 return running;
1098 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1099 bool is_active) {
1100 base::Value* value = new base::FundamentalValue(is_active);
1101 UpdateExtensionPref(extension_id, kIsActive, value);
1104 bool ExtensionPrefs::IsActive(const std::string& extension_id) {
1105 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1106 if (!extension)
1107 return false;
1108 bool is_active = false;
1109 extension->GetBoolean(kIsActive, &is_active);
1110 return is_active;
1113 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1114 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1117 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1118 bool enabled) {
1119 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1120 new base::FundamentalValue(enabled));
1121 extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled);
1124 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1125 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1128 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1129 bool allow) {
1130 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1131 new base::FundamentalValue(allow));
1134 bool ExtensionPrefs::HasAllowFileAccessSetting(
1135 const std::string& extension_id) const {
1136 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1137 return ext && ext->HasKey(kPrefAllowFileAccess);
1140 bool ExtensionPrefs::DoesExtensionHaveState(
1141 const std::string& id, Extension::State check_state) const {
1142 const base::DictionaryValue* extension = GetExtensionPref(id);
1143 int state = -1;
1144 if (!extension || !extension->GetInteger(kPrefState, &state))
1145 return false;
1147 if (state < 0 || state >= Extension::NUM_STATES) {
1148 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1149 return false;
1152 return state == check_state;
1155 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1156 const std::string& id) const {
1157 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1160 bool ExtensionPrefs::IsExtensionDisabled(
1161 const std::string& id) const {
1162 return DoesExtensionHaveState(id, Extension::DISABLED);
1165 ExtensionIdList ExtensionPrefs::GetToolbarOrder() {
1166 ExtensionIdList id_list_out;
1167 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1168 return id_list_out;
1171 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1172 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1175 void ExtensionPrefs::OnExtensionInstalled(
1176 const Extension* extension,
1177 Extension::State initial_state,
1178 const syncer::StringOrdinal& page_ordinal,
1179 int install_flags,
1180 const std::string& install_parameter) {
1181 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1182 base::DictionaryValue* extension_dict = update.Get();
1183 const base::Time install_time = time_provider_->GetCurrentTime();
1184 PopulateExtensionInfoPrefs(extension,
1185 install_time,
1186 initial_state,
1187 install_flags,
1188 install_parameter,
1189 extension_dict);
1191 bool requires_sort_ordinal = extension->RequiresSortOrdinal() &&
1192 (install_flags & kInstallFlagIsEphemeral) == 0;
1193 FinishExtensionInfoPrefs(extension->id(),
1194 install_time,
1195 requires_sort_ordinal,
1196 page_ordinal,
1197 extension_dict);
1200 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1201 const Manifest::Location& location,
1202 bool external_uninstall) {
1203 app_sorting_->ClearOrdinals(extension_id);
1205 // For external extensions, we save a preference reminding ourself not to try
1206 // and install the extension anymore (except when |external_uninstall| is
1207 // true, which signifies that the registry key was deleted or the pref file
1208 // no longer lists the extension).
1209 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1210 UpdateExtensionPref(extension_id, kPrefState,
1211 new base::FundamentalValue(
1212 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1213 extension_pref_value_map_->SetExtensionState(extension_id, false);
1214 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1215 observer_list_,
1216 OnExtensionStateChanged(extension_id, false));
1217 } else {
1218 DeleteExtensionPrefs(extension_id);
1222 void ExtensionPrefs::SetExtensionState(const std::string& extension_id,
1223 Extension::State state) {
1224 UpdateExtensionPref(extension_id, kPrefState,
1225 new base::FundamentalValue(state));
1226 bool enabled = (state == Extension::ENABLED);
1227 extension_pref_value_map_->SetExtensionState(extension_id, enabled);
1228 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1229 observer_list_,
1230 OnExtensionStateChanged(extension_id, enabled));
1233 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1234 BlacklistState state) {
1235 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1236 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1237 new base::FundamentalValue(state));
1240 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1241 const std::string& extension_id) {
1242 if (IsExtensionBlacklisted(extension_id))
1243 return BLACKLISTED_MALWARE;
1244 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1245 int int_value = 0;
1246 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1247 return static_cast<BlacklistState>(int_value);
1249 return NOT_BLACKLISTED;
1252 std::string ExtensionPrefs::GetVersionString(const std::string& extension_id) {
1253 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1254 if (!extension)
1255 return std::string();
1257 std::string version;
1258 extension->GetString(kPrefVersion, &version);
1260 return version;
1263 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1264 if (!Manifest::IsUnpackedLocation(extension->location())) {
1265 const base::DictionaryValue* extension_dict =
1266 GetExtensionPref(extension->id());
1267 if (!extension_dict)
1268 return;
1269 const base::DictionaryValue* old_manifest = NULL;
1270 bool update_required =
1271 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1272 !extension->manifest()->value()->Equals(old_manifest);
1273 if (update_required) {
1274 UpdateExtensionPref(extension->id(), kPrefManifest,
1275 extension->manifest()->value()->DeepCopy());
1280 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1281 const std::string& extension_id,
1282 const base::DictionaryValue* extension) const {
1283 int location_value;
1284 if (!extension->GetInteger(kPrefLocation, &location_value))
1285 return scoped_ptr<ExtensionInfo>();
1287 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1288 if (location == Manifest::COMPONENT) {
1289 // Component extensions are ignored. Component extensions may have data
1290 // saved in preferences, but they are already loaded at this point (by
1291 // ComponentLoader) and shouldn't be populated into the result of
1292 // GetInstalledExtensionsInfo, otherwise InstalledLoader would also want to
1293 // load them.
1294 return scoped_ptr<ExtensionInfo>();
1297 // Only the following extension types have data saved in the preferences.
1298 if (location != Manifest::INTERNAL &&
1299 !Manifest::IsUnpackedLocation(location) &&
1300 !Manifest::IsExternalLocation(location)) {
1301 NOTREACHED();
1302 return scoped_ptr<ExtensionInfo>();
1305 const base::DictionaryValue* manifest = NULL;
1306 if (!Manifest::IsUnpackedLocation(location) &&
1307 !extension->GetDictionary(kPrefManifest, &manifest)) {
1308 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1309 // Just a warning for now.
1312 base::FilePath::StringType path;
1313 if (!extension->GetString(kPrefPath, &path))
1314 return scoped_ptr<ExtensionInfo>();
1316 // Make path absolute. Most (but not all) extension types have relative paths.
1317 if (!base::FilePath(path).IsAbsolute())
1318 path = install_directory_.Append(path).value();
1320 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1321 manifest, extension_id, base::FilePath(path), location));
1324 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1325 const std::string& extension_id) const {
1326 const base::DictionaryValue* ext = NULL;
1327 const base::DictionaryValue* extensions =
1328 prefs_->GetDictionary(pref_names::kExtensions);
1329 if (!extensions ||
1330 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1331 return scoped_ptr<ExtensionInfo>();
1332 int state_value;
1333 if (ext->GetInteger(kPrefState, &state_value) &&
1334 state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1335 LOG(WARNING) << "External extension with id " << extension_id
1336 << " has been uninstalled by the user";
1337 return scoped_ptr<ExtensionInfo>();
1340 return GetInstalledInfoHelper(extension_id, ext);
1343 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1344 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1345 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1347 const base::DictionaryValue* extensions =
1348 prefs_->GetDictionary(pref_names::kExtensions);
1349 for (base::DictionaryValue::Iterator extension_id(*extensions);
1350 !extension_id.IsAtEnd(); extension_id.Advance()) {
1351 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1352 continue;
1354 scoped_ptr<ExtensionInfo> info =
1355 GetInstalledExtensionInfo(extension_id.key());
1356 if (info)
1357 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1360 return extensions_info.Pass();
1363 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1364 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1365 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1367 const base::DictionaryValue* extensions =
1368 prefs_->GetDictionary(pref_names::kExtensions);
1369 for (base::DictionaryValue::Iterator extension_id(*extensions);
1370 !extension_id.IsAtEnd(); extension_id.Advance()) {
1371 const base::DictionaryValue* ext = NULL;
1372 if (!crx_file::id_util::IdIsValid(extension_id.key()) ||
1373 !IsExternalExtensionUninstalled(extension_id.key()) ||
1374 !extension_id.value().GetAsDictionary(&ext))
1375 continue;
1377 scoped_ptr<ExtensionInfo> info =
1378 GetInstalledInfoHelper(extension_id.key(), ext);
1379 if (info)
1380 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1383 return extensions_info.Pass();
1386 void ExtensionPrefs::SetDelayedInstallInfo(
1387 const Extension* extension,
1388 Extension::State initial_state,
1389 int install_flags,
1390 DelayReason delay_reason,
1391 const syncer::StringOrdinal& page_ordinal,
1392 const std::string& install_parameter) {
1393 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1394 PopulateExtensionInfoPrefs(extension,
1395 time_provider_->GetCurrentTime(),
1396 initial_state,
1397 install_flags,
1398 install_parameter,
1399 extension_dict);
1401 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1402 // should not be in the final extension prefs. All entries here should have
1403 // a corresponding Remove() call in FinishDelayedInstallInfo().
1404 if (extension->RequiresSortOrdinal() &&
1405 (install_flags & kInstallFlagIsEphemeral) == 0) {
1406 extension_dict->SetString(
1407 kPrefSuggestedPageOrdinal,
1408 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1409 : std::string());
1411 extension_dict->SetInteger(kDelayedInstallReason,
1412 static_cast<int>(delay_reason));
1414 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1417 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1418 const std::string& extension_id) {
1419 if (!GetExtensionPref(extension_id))
1420 return false;
1421 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1422 bool result = update->Remove(kDelayedInstallInfo, NULL);
1423 return result;
1426 bool ExtensionPrefs::FinishDelayedInstallInfo(
1427 const std::string& extension_id) {
1428 CHECK(crx_file::id_util::IdIsValid(extension_id));
1429 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1430 base::DictionaryValue* extension_dict = update.Get();
1431 base::DictionaryValue* pending_install_dict = NULL;
1432 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1433 &pending_install_dict)) {
1434 return false;
1437 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1438 // Also do any other data cleanup that makes sense.
1439 std::string serialized_ordinal;
1440 syncer::StringOrdinal suggested_page_ordinal;
1441 bool needs_sort_ordinal = false;
1442 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1443 &serialized_ordinal)) {
1444 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1445 needs_sort_ordinal = true;
1446 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1448 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1450 const base::Time install_time = time_provider_->GetCurrentTime();
1451 pending_install_dict->Set(
1452 kPrefInstallTime,
1453 new base::StringValue(
1454 base::Int64ToString(install_time.ToInternalValue())));
1456 // Some extension pref values are written conditionally. If they are not
1457 // present in the delayed install data, they should be removed when the
1458 // delayed install is committed.
1459 extension_dict->Remove(kPrefEphemeralApp, NULL);
1461 // Commit the delayed install data.
1462 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1463 it.Advance()) {
1464 extension_dict->Set(it.key(), it.value().DeepCopy());
1466 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1467 suggested_page_ordinal, extension_dict);
1468 return true;
1471 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1472 const std::string& extension_id) const {
1473 const base::DictionaryValue* extension_prefs =
1474 GetExtensionPref(extension_id);
1475 if (!extension_prefs)
1476 return scoped_ptr<ExtensionInfo>();
1478 const base::DictionaryValue* ext = NULL;
1479 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1480 return scoped_ptr<ExtensionInfo>();
1482 return GetInstalledInfoHelper(extension_id, ext);
1485 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1486 const std::string& extension_id) const {
1487 const base::DictionaryValue* extension_prefs =
1488 GetExtensionPref(extension_id);
1489 if (!extension_prefs)
1490 return DELAY_REASON_NONE;
1492 const base::DictionaryValue* ext = NULL;
1493 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1494 return DELAY_REASON_NONE;
1496 int delay_reason;
1497 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1498 return DELAY_REASON_NONE;
1500 return static_cast<DelayReason>(delay_reason);
1503 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1504 GetAllDelayedInstallInfo() const {
1505 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1507 const base::DictionaryValue* extensions =
1508 prefs_->GetDictionary(pref_names::kExtensions);
1509 for (base::DictionaryValue::Iterator extension_id(*extensions);
1510 !extension_id.IsAtEnd(); extension_id.Advance()) {
1511 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1512 continue;
1514 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1515 if (info)
1516 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1519 return extensions_info.Pass();
1522 bool ExtensionPrefs::IsEphemeralApp(const std::string& extension_id) const {
1523 if (ReadPrefAsBooleanAndReturn(extension_id, kPrefEphemeralApp))
1524 return true;
1526 // Ephemerality was previously stored in the creation flags, so we must also
1527 // check it for backcompatibility.
1528 return (GetCreationFlags(extension_id) & Extension::IS_EPHEMERAL) != 0;
1531 void ExtensionPrefs::OnEphemeralAppPromoted(const std::string& extension_id) {
1532 DCHECK(IsEphemeralApp(extension_id));
1534 UpdateExtensionPref(extension_id, kPrefEphemeralApp, NULL);
1536 // Ephemerality was previously stored in the creation flags, so ensure the bit
1537 // is cleared.
1538 int creation_flags = Extension::NO_FLAGS;
1539 if (ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1540 if (creation_flags & Extension::IS_EPHEMERAL) {
1541 creation_flags &= ~static_cast<int>(Extension::IS_EPHEMERAL);
1542 UpdateExtensionPref(extension_id,
1543 kPrefCreationFlags,
1544 new base::FundamentalValue(creation_flags));
1549 bool ExtensionPrefs::WasAppDraggedByUser(const std::string& extension_id) {
1550 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1553 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1554 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1555 new base::FundamentalValue(true));
1558 bool ExtensionPrefs::IsFromWebStore(
1559 const std::string& extension_id) const {
1560 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1561 bool result = false;
1562 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1563 return result;
1564 return false;
1567 bool ExtensionPrefs::IsFromBookmark(
1568 const std::string& extension_id) const {
1569 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1570 bool result = false;
1571 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1572 return result;
1573 return false;
1576 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1577 int creation_flags = Extension::NO_FLAGS;
1578 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1579 // Since kPrefCreationFlags was added later, it will be missing for
1580 // previously installed extensions.
1581 if (IsFromBookmark(extension_id))
1582 creation_flags |= Extension::FROM_BOOKMARK;
1583 if (IsFromWebStore(extension_id))
1584 creation_flags |= Extension::FROM_WEBSTORE;
1585 if (WasInstalledByDefault(extension_id))
1586 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1587 if (WasInstalledByOem(extension_id))
1588 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
1590 return creation_flags;
1593 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1594 const std::string& extension_id) const {
1595 int creation_flags = Extension::NO_FLAGS;
1596 const base::DictionaryValue* delayed_info = NULL;
1597 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1598 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1600 return creation_flags;
1603 bool ExtensionPrefs::WasInstalledByDefault(
1604 const std::string& extension_id) const {
1605 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1606 bool result = false;
1607 if (dictionary &&
1608 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1609 return result;
1610 return false;
1613 bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const {
1614 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1615 bool result = false;
1616 if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result))
1617 return result;
1618 return false;
1621 base::Time ExtensionPrefs::GetInstallTime(
1622 const std::string& extension_id) const {
1623 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1624 if (!extension) {
1625 NOTREACHED();
1626 return base::Time();
1628 std::string install_time_str;
1629 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1630 return base::Time();
1631 int64 install_time_i64 = 0;
1632 if (!base::StringToInt64(install_time_str, &install_time_i64))
1633 return base::Time();
1634 return base::Time::FromInternalValue(install_time_i64);
1637 bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const {
1638 bool do_not_sync;
1639 if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync))
1640 return false;
1642 return do_not_sync;
1645 base::Time ExtensionPrefs::GetLastLaunchTime(
1646 const std::string& extension_id) const {
1647 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1648 if (!extension)
1649 return base::Time();
1651 std::string launch_time_str;
1652 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1653 return base::Time();
1654 int64 launch_time_i64 = 0;
1655 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1656 return base::Time();
1657 return base::Time::FromInternalValue(launch_time_i64);
1660 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1661 const base::Time& time) {
1662 DCHECK(crx_file::id_util::IdIsValid(extension_id));
1663 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1664 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1667 void ExtensionPrefs::ClearLastLaunchTimes() {
1668 const base::DictionaryValue* dict =
1669 prefs_->GetDictionary(pref_names::kExtensions);
1670 if (!dict || dict->empty())
1671 return;
1673 // Collect all the keys to remove the last launched preference from.
1674 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
1675 base::DictionaryValue* update_dict = update.Get();
1676 for (base::DictionaryValue::Iterator i(*update_dict); !i.IsAtEnd();
1677 i.Advance()) {
1678 base::DictionaryValue* extension_dict = NULL;
1679 if (!update_dict->GetDictionary(i.key(), &extension_dict))
1680 continue;
1682 if (extension_dict->HasKey(kPrefLastLaunchTime))
1683 extension_dict->Remove(kPrefLastLaunchTime, NULL);
1687 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) {
1688 CHECK(out);
1690 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1692 for (size_t i = 0; i < extensions_info->size(); ++i) {
1693 ExtensionInfo* info = extensions_info->at(i).get();
1694 out->push_back(info->extension_id);
1698 // static
1699 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1700 const PrefService* pref_service) {
1701 ExtensionIdList result;
1703 const base::DictionaryValue* extension_prefs = NULL;
1704 const base::Value* extension_prefs_value =
1705 pref_service->GetUserPrefValue(pref_names::kExtensions);
1706 if (!extension_prefs_value ||
1707 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1708 return result; // Empty set
1711 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1712 it.Advance()) {
1713 const base::DictionaryValue* ext = NULL;
1714 if (!it.value().GetAsDictionary(&ext)) {
1715 NOTREACHED() << "Invalid pref for extension " << it.key();
1716 continue;
1718 if (!IsBlacklistBitSet(ext))
1719 result.push_back(it.key());
1721 return result;
1724 void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) {
1725 observer_list_.AddObserver(observer);
1728 void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) {
1729 observer_list_.RemoveObserver(observer);
1732 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1733 // Fix old entries that did not get an installation time entry when they
1734 // were installed or don't have a preferences field.
1735 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1736 ext_id != extension_ids.end(); ++ext_id) {
1737 if (GetInstallTime(*ext_id) == base::Time()) {
1738 VLOG(1) << "Could not parse installation time of extension "
1739 << *ext_id << ". It was probably installed before setting "
1740 << kPrefInstallTime << " was introduced. Updating "
1741 << kPrefInstallTime << " to the current time.";
1742 const base::Time install_time = time_provider_->GetCurrentTime();
1743 UpdateExtensionPref(*ext_id,
1744 kPrefInstallTime,
1745 new base::StringValue(base::Int64ToString(
1746 install_time.ToInternalValue())));
1751 void ExtensionPrefs::InitPrefStore() {
1752 TRACE_EVENT0("browser,startup", "ExtensionPrefs::InitPrefStore")
1753 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefStoreTime");
1755 if (extensions_disabled_) {
1756 extension_pref_value_map_->NotifyInitializationCompleted();
1757 return;
1760 // When this is called, the PrefService is initialized and provides access
1761 // to the user preferences stored in a JSON file.
1762 ExtensionIdList extension_ids;
1764 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefGetExtensionsTime");
1765 GetExtensions(&extension_ids);
1767 // Create empty preferences dictionary for each extension (these dictionaries
1768 // are pruned when persisting the preferences to disk).
1769 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1770 ext_id != extension_ids.end(); ++ext_id) {
1771 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1772 // This creates an empty dictionary if none is stored.
1773 update.Get();
1776 FixMissingPrefs(extension_ids);
1777 MigratePermissions(extension_ids);
1778 MigrateDisableReasons(extension_ids);
1779 app_sorting_->Initialize(extension_ids);
1781 InitExtensionControlledPrefs(extension_pref_value_map_);
1783 extension_pref_value_map_->NotifyInitializationCompleted();
1786 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) {
1787 bool has_incognito_pref_value = false;
1788 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1789 true,
1790 &has_incognito_pref_value);
1791 return has_incognito_pref_value;
1794 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1795 const std::string& extension_id) const {
1796 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1797 if (!extension_prefs)
1798 return NULL;
1800 const base::DictionaryValue* ext = NULL;
1801 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1802 return NULL;
1804 return ext;
1807 void ExtensionPrefs::SetGeometryCache(
1808 const std::string& extension_id,
1809 scoped_ptr<base::DictionaryValue> cache) {
1810 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1813 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() {
1814 return prefs_->GetDictionary(kInstallSignature);
1817 void ExtensionPrefs::SetInstallSignature(
1818 const base::DictionaryValue* signature) {
1819 if (signature) {
1820 prefs_->Set(kInstallSignature, *signature);
1821 DVLOG(1) << "SetInstallSignature - saving";
1822 } else {
1823 DVLOG(1) << "SetInstallSignature - clearing";
1824 prefs_->ClearPref(kInstallSignature);
1828 std::string ExtensionPrefs::GetInstallParam(
1829 const std::string& extension_id) const {
1830 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1831 if (!extension) // Expected during unit testing.
1832 return std::string();
1833 std::string install_parameter;
1834 if (!extension->GetString(kPrefInstallParam, &install_parameter))
1835 return std::string();
1836 return install_parameter;
1839 void ExtensionPrefs::SetInstallParam(const std::string& extension_id,
1840 const std::string& install_parameter) {
1841 UpdateExtensionPref(extension_id,
1842 kPrefInstallParam,
1843 new base::StringValue(install_parameter));
1846 int ExtensionPrefs::GetCorruptedDisableCount() {
1847 return prefs_->GetInteger(kCorruptedDisableCount);
1850 void ExtensionPrefs::IncrementCorruptedDisableCount() {
1851 int count = prefs_->GetInteger(kCorruptedDisableCount);
1852 prefs_->SetInteger(kCorruptedDisableCount, count + 1);
1855 ExtensionPrefs::ExtensionPrefs(
1856 PrefService* prefs,
1857 const base::FilePath& root_dir,
1858 ExtensionPrefValueMap* extension_pref_value_map,
1859 scoped_ptr<AppSorting> app_sorting,
1860 scoped_ptr<TimeProvider> time_provider,
1861 bool extensions_disabled,
1862 const std::vector<ExtensionPrefsObserver*>& early_observers)
1863 : prefs_(prefs),
1864 install_directory_(root_dir),
1865 extension_pref_value_map_(extension_pref_value_map),
1866 app_sorting_(app_sorting.Pass()),
1867 time_provider_(time_provider.Pass()),
1868 extensions_disabled_(extensions_disabled) {
1869 app_sorting_->SetExtensionScopedPrefs(this);
1870 MakePathsRelative();
1872 // Ensure that any early observers are watching before prefs are initialized.
1873 for (std::vector<ExtensionPrefsObserver*>::const_iterator iter =
1874 early_observers.begin();
1875 iter != early_observers.end();
1876 ++iter) {
1877 AddObserver(*iter);
1880 InitPrefStore();
1883 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1884 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1887 bool ExtensionPrefs::NeedsStorageGarbageCollection() {
1888 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1891 // static
1892 void ExtensionPrefs::RegisterProfilePrefs(
1893 user_prefs::PrefRegistrySyncable* registry) {
1894 registry->RegisterDictionaryPref(
1895 pref_names::kExtensions,
1896 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1897 registry->RegisterListPref(pref_names::kToolbar,
1898 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1899 registry->RegisterIntegerPref(
1900 pref_names::kToolbarSize,
1901 -1, // default value
1902 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1903 registry->RegisterDictionaryPref(
1904 kExtensionsBlacklistUpdate,
1905 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1906 registry->RegisterListPref(pref_names::kInstallAllowList,
1907 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1908 registry->RegisterListPref(pref_names::kInstallDenyList,
1909 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1910 registry->RegisterDictionaryPref(
1911 pref_names::kInstallForceList,
1912 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1913 registry->RegisterListPref(pref_names::kAllowedTypes,
1914 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1915 registry->RegisterBooleanPref(
1916 pref_names::kStorageGarbageCollect,
1917 false, // default value
1918 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1919 registry->RegisterInt64Pref(
1920 pref_names::kLastUpdateCheck,
1921 0, // default value
1922 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1923 registry->RegisterInt64Pref(
1924 pref_names::kNextUpdateCheck,
1925 0, // default value
1926 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1927 registry->RegisterListPref(pref_names::kAllowedInstallSites,
1928 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1929 registry->RegisterStringPref(
1930 pref_names::kLastChromeVersion,
1931 std::string(), // default value
1932 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1933 registry->RegisterDictionaryPref(
1934 kInstallSignature,
1935 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1937 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist,
1938 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1939 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist,
1940 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1941 registry->RegisterBooleanPref(
1942 pref_names::kNativeMessagingUserLevelHosts,
1943 true, // default value
1944 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1945 registry->RegisterIntegerPref(
1946 kCorruptedDisableCount,
1947 0, // default value
1948 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1950 #if !defined(OS_MACOSX)
1951 registry->RegisterBooleanPref(
1952 pref_names::kAppFullscreenAllowed, true,
1953 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1954 #endif
1957 template <class ExtensionIdContainer>
1958 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
1959 const char* pref,
1960 ExtensionIdContainer* id_container_out) {
1961 DCHECK(id_container_out->empty());
1963 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
1964 const base::ListValue* user_pref_as_list;
1965 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
1966 return false;
1968 std::insert_iterator<ExtensionIdContainer> insert_iterator(
1969 *id_container_out, id_container_out->end());
1970 std::string extension_id;
1971 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
1972 value_it != user_pref_as_list->end(); ++value_it) {
1973 if (!(*value_it)->GetAsString(&extension_id)) {
1974 NOTREACHED();
1975 continue;
1977 insert_iterator = extension_id;
1979 return true;
1982 template <class ExtensionIdContainer>
1983 void ExtensionPrefs::SetExtensionPrefFromContainer(
1984 const char* pref,
1985 const ExtensionIdContainer& strings) {
1986 ListPrefUpdate update(prefs_, pref);
1987 base::ListValue* list_of_values = update.Get();
1988 list_of_values->Clear();
1989 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
1990 iter != strings.end(); ++iter) {
1991 list_of_values->Append(new base::StringValue(*iter));
1995 void ExtensionPrefs::PopulateExtensionInfoPrefs(
1996 const Extension* extension,
1997 const base::Time install_time,
1998 Extension::State initial_state,
1999 int install_flags,
2000 const std::string& install_parameter,
2001 base::DictionaryValue* extension_dict) {
2002 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
2003 extension_dict->Set(kPrefLocation,
2004 new base::FundamentalValue(extension->location()));
2005 extension_dict->Set(kPrefCreationFlags,
2006 new base::FundamentalValue(extension->creation_flags()));
2007 extension_dict->Set(kPrefFromWebStore,
2008 new base::FundamentalValue(extension->from_webstore()));
2009 extension_dict->Set(kPrefFromBookmark,
2010 new base::FundamentalValue(extension->from_bookmark()));
2011 extension_dict->Set(
2012 kPrefWasInstalledByDefault,
2013 new base::FundamentalValue(extension->was_installed_by_default()));
2014 extension_dict->Set(
2015 kPrefWasInstalledByOem,
2016 new base::FundamentalValue(extension->was_installed_by_oem()));
2017 extension_dict->Set(kPrefInstallTime,
2018 new base::StringValue(
2019 base::Int64ToString(install_time.ToInternalValue())));
2020 if (install_flags & kInstallFlagIsBlacklistedForMalware)
2021 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
2023 if (install_flags & kInstallFlagIsEphemeral)
2024 extension_dict->Set(kPrefEphemeralApp, new base::FundamentalValue(true));
2025 else
2026 extension_dict->Remove(kPrefEphemeralApp, NULL);
2028 base::FilePath::StringType path = MakePathRelative(install_directory_,
2029 extension->path());
2030 extension_dict->Set(kPrefPath, new base::StringValue(path));
2031 if (!install_parameter.empty()) {
2032 extension_dict->Set(kPrefInstallParam,
2033 new base::StringValue(install_parameter));
2035 // We store prefs about LOAD extensions, but don't cache their manifest
2036 // since it may change on disk.
2037 if (!Manifest::IsUnpackedLocation(extension->location())) {
2038 extension_dict->Set(kPrefManifest,
2039 extension->manifest()->value()->DeepCopy());
2042 // Only writes kPrefDoNotSync when it is not the default.
2043 if (install_flags & kInstallFlagDoNotSync)
2044 extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true));
2045 else
2046 extension_dict->Remove(kPrefDoNotSync, NULL);
2049 void ExtensionPrefs::InitExtensionControlledPrefs(
2050 ExtensionPrefValueMap* value_map) {
2051 TRACE_EVENT0("browser,startup",
2052 "ExtensionPrefs::InitExtensionControlledPrefs")
2053 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitExtensionControlledPrefsTime");
2055 ExtensionIdList extension_ids;
2056 GetExtensions(&extension_ids);
2058 for (ExtensionIdList::iterator extension_id = extension_ids.begin();
2059 extension_id != extension_ids.end();
2060 ++extension_id) {
2061 base::Time install_time = GetInstallTime(*extension_id);
2062 bool is_enabled = !IsExtensionDisabled(*extension_id);
2063 bool is_incognito_enabled = IsIncognitoEnabled(*extension_id);
2064 value_map->RegisterExtension(
2065 *extension_id, install_time, is_enabled, is_incognito_enabled);
2067 FOR_EACH_OBSERVER(
2068 ExtensionPrefsObserver,
2069 observer_list_,
2070 OnExtensionRegistered(*extension_id, install_time, is_enabled));
2072 // Set regular extension controlled prefs.
2073 LoadExtensionControlledPrefs(
2074 this, value_map, *extension_id, kExtensionPrefsScopeRegular);
2075 // Set incognito extension controlled prefs.
2076 LoadExtensionControlledPrefs(this,
2077 value_map,
2078 *extension_id,
2079 kExtensionPrefsScopeIncognitoPersistent);
2080 // Set regular-only extension controlled prefs.
2081 LoadExtensionControlledPrefs(
2082 this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly);
2084 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
2085 observer_list_,
2086 OnExtensionPrefsLoaded(*extension_id, this));
2090 void ExtensionPrefs::FinishExtensionInfoPrefs(
2091 const std::string& extension_id,
2092 const base::Time install_time,
2093 bool needs_sort_ordinal,
2094 const syncer::StringOrdinal& suggested_page_ordinal,
2095 base::DictionaryValue* extension_dict) {
2096 // Reinitializes various preferences with empty dictionaries.
2097 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
2098 extension_dict->Set(pref_names::kPrefPreferences,
2099 new base::DictionaryValue);
2102 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
2103 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
2104 new base::DictionaryValue);
2107 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
2108 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
2109 new base::DictionaryValue);
2112 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
2113 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
2115 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
2116 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
2117 new base::ListValue);
2120 // If this point has been reached, any pending installs should be considered
2121 // out of date.
2122 extension_dict->Remove(kDelayedInstallInfo, NULL);
2124 // Clear state that may be registered from a previous install.
2125 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
2127 // FYI, all code below here races on sudden shutdown because |extension_dict|,
2128 // |app_sorting_|, |extension_pref_value_map_|, and (potentially) observers
2129 // are updated non-transactionally. This is probably not fixable without
2130 // nested transactional updates to pref dictionaries.
2131 if (needs_sort_ordinal)
2132 app_sorting_->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
2134 bool is_enabled = false;
2135 int initial_state;
2136 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
2137 is_enabled = initial_state == Extension::ENABLED;
2139 bool is_incognito_enabled = IsIncognitoEnabled(extension_id);
2141 extension_pref_value_map_->RegisterExtension(
2142 extension_id, install_time, is_enabled, is_incognito_enabled);
2144 FOR_EACH_OBSERVER(
2145 ExtensionPrefsObserver,
2146 observer_list_,
2147 OnExtensionRegistered(extension_id, install_time, is_enabled));
2150 } // namespace extensions