Extensions: Store disable reasons in Sync
[chromium-blink-merge.git] / extensions / browser / extension_prefs.cc
blob460e0de7297f1e97470323c7a97f2e69406a2f5d
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) const {
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) const {
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) const {
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) const {
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) const {
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) const {
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::AddDisableReasons(const std::string& extension_id,
763 int disable_reasons) {
764 ModifyDisableReasons(extension_id, disable_reasons, DISABLE_REASON_ADD);
767 void ExtensionPrefs::RemoveDisableReason(
768 const std::string& extension_id,
769 Extension::DisableReason disable_reason) {
770 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_REMOVE);
773 void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) {
774 ModifyDisableReasons(extension_id, Extension::DISABLE_NONE,
775 DISABLE_REASON_CLEAR);
778 void ExtensionPrefs::ModifyDisableReasons(const std::string& extension_id,
779 int reasons,
780 DisableReasonChange change) {
781 int old_value = GetDisableReasons(extension_id);
782 int new_value = old_value;
783 switch (change) {
784 case DISABLE_REASON_ADD:
785 new_value |= reasons;
786 break;
787 case DISABLE_REASON_REMOVE:
788 new_value &= ~reasons;
789 break;
790 case DISABLE_REASON_CLEAR:
791 new_value = Extension::DISABLE_NONE;
792 break;
795 if (old_value == new_value) // no change, return.
796 return;
798 if (new_value == Extension::DISABLE_NONE) {
799 UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
800 } else {
801 UpdateExtensionPref(extension_id,
802 kPrefDisableReasons,
803 new base::FundamentalValue(new_value));
806 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
807 observer_list_,
808 OnExtensionDisableReasonsChanged(extension_id, new_value));
811 std::set<std::string> ExtensionPrefs::GetBlacklistedExtensions() const {
812 std::set<std::string> ids;
814 const base::DictionaryValue* extensions =
815 prefs_->GetDictionary(pref_names::kExtensions);
816 if (!extensions)
817 return ids;
819 for (base::DictionaryValue::Iterator it(*extensions);
820 !it.IsAtEnd(); it.Advance()) {
821 if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) {
822 NOTREACHED() << "Invalid pref for extension " << it.key();
823 continue;
825 if (IsBlacklistBitSet(
826 static_cast<const base::DictionaryValue*>(&it.value()))) {
827 ids.insert(it.key());
831 return ids;
834 void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id,
835 bool is_blacklisted) {
836 bool currently_blacklisted = IsExtensionBlacklisted(extension_id);
837 if (is_blacklisted == currently_blacklisted)
838 return;
840 // Always make sure the "acknowledged" bit is cleared since the blacklist bit
841 // is changing.
842 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL);
844 if (is_blacklisted) {
845 UpdateExtensionPref(extension_id,
846 kPrefBlacklist,
847 new base::FundamentalValue(true));
848 } else {
849 UpdateExtensionPref(extension_id, kPrefBlacklist, NULL);
850 const base::DictionaryValue* dict = GetExtensionPref(extension_id);
851 if (dict && dict->empty())
852 DeleteExtensionPrefs(extension_id);
856 bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const {
857 const base::DictionaryValue* ext_prefs = GetExtensionPref(id);
858 return ext_prefs && IsBlacklistBitSet(ext_prefs);
861 namespace {
863 // Serializes a 64bit integer as a string value.
864 void SaveInt64(base::DictionaryValue* dictionary,
865 const char* key,
866 const int64 value) {
867 if (!dictionary)
868 return;
870 std::string string_value = base::Int64ToString(value);
871 dictionary->SetString(key, string_value);
874 // Deserializes a 64bit integer stored as a string value.
875 bool ReadInt64(const base::DictionaryValue* dictionary,
876 const char* key,
877 int64* value) {
878 if (!dictionary)
879 return false;
881 std::string string_value;
882 if (!dictionary->GetString(key, &string_value))
883 return false;
885 return base::StringToInt64(string_value, value);
888 // Serializes |time| as a string value mapped to |key| in |dictionary|.
889 void SaveTime(base::DictionaryValue* dictionary,
890 const char* key,
891 const base::Time& time) {
892 SaveInt64(dictionary, key, time.ToInternalValue());
895 // The opposite of SaveTime. If |key| is not found, this returns an empty Time
896 // (is_null() will return true).
897 base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) {
898 int64 value;
899 if (ReadInt64(dictionary, key, &value))
900 return base::Time::FromInternalValue(value);
902 return base::Time();
905 } // namespace
907 base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const {
908 DCHECK(crx_file::id_util::IdIsValid(extension_id));
909 return ReadTime(GetExtensionPref(extension_id), kLastPingDay);
912 void ExtensionPrefs::SetLastPingDay(const std::string& extension_id,
913 const base::Time& time) {
914 DCHECK(crx_file::id_util::IdIsValid(extension_id));
915 ScopedExtensionPrefUpdate update(prefs_, extension_id);
916 SaveTime(update.Get(), kLastPingDay, time);
919 base::Time ExtensionPrefs::BlacklistLastPingDay() const {
920 return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate),
921 kLastPingDay);
924 void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) {
925 DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate);
926 SaveTime(update.Get(), kLastPingDay, time);
929 base::Time ExtensionPrefs::LastActivePingDay(
930 const std::string& extension_id) const {
931 DCHECK(crx_file::id_util::IdIsValid(extension_id));
932 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
935 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
936 const base::Time& time) {
937 DCHECK(crx_file::id_util::IdIsValid(extension_id));
938 ScopedExtensionPrefUpdate update(prefs_, extension_id);
939 SaveTime(update.Get(), kLastActivePingDay, time);
942 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) const {
943 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
944 bool result = false;
945 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
946 return result;
947 return false;
950 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
951 bool active) {
952 UpdateExtensionPref(extension_id, kActiveBit,
953 new base::FundamentalValue(active));
956 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
957 PermissionsInfo* info = PermissionsInfo::GetInstance();
958 for (ExtensionIdList::const_iterator ext_id =
959 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
960 // An extension's granted permissions need to be migrated if the
961 // full_access bit is present. This bit was always present in the previous
962 // scheme and is never present now.
963 bool full_access = false;
964 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
965 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
966 continue;
968 // Remove the full access bit (empty list will get trimmed).
969 UpdateExtensionPref(
970 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
972 // Add the plugin permission if the full access bit was set.
973 if (full_access) {
974 const base::ListValue* apis = NULL;
975 base::ListValue* new_apis = NULL;
977 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
978 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
979 new_apis = apis->DeepCopy();
980 else
981 new_apis = new base::ListValue();
983 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
984 new_apis->Append(new base::StringValue(plugin_name));
985 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
988 // The granted permissions originally only held the effective hosts,
989 // which are a combination of host and user script host permissions.
990 // We now maintain these lists separately. For migration purposes, it
991 // does not matter how we treat the old effective hosts as long as the
992 // new effective hosts will be the same, so we move them to explicit
993 // host permissions.
994 const base::ListValue* hosts = NULL;
995 std::string explicit_hosts =
996 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
997 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
998 UpdateExtensionPref(
999 *ext_id, explicit_hosts, hosts->DeepCopy());
1001 // We can get rid of the old one by setting it to an empty list.
1002 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
1007 void ExtensionPrefs::MigrateDisableReasons(
1008 const ExtensionIdList& extension_ids) {
1009 for (ExtensionIdList::const_iterator ext_id =
1010 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
1011 int value = -1;
1012 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
1013 int new_value = Extension::DISABLE_NONE;
1014 switch (value) {
1015 case Extension::DEPRECATED_DISABLE_USER_ACTION:
1016 new_value = Extension::DISABLE_USER_ACTION;
1017 break;
1018 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
1019 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
1020 break;
1021 case Extension::DEPRECATED_DISABLE_RELOAD:
1022 new_value = Extension::DISABLE_RELOAD;
1023 break;
1026 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
1027 new base::FundamentalValue(new_value));
1028 // Remove the old disable reason.
1029 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
1034 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
1035 const std::string& extension_id) const {
1036 CHECK(crx_file::id_util::IdIsValid(extension_id));
1037 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
1040 void ExtensionPrefs::AddGrantedPermissions(
1041 const std::string& extension_id,
1042 const PermissionSet* permissions) {
1043 CHECK(crx_file::id_util::IdIsValid(extension_id));
1045 scoped_refptr<PermissionSet> granted_permissions(
1046 GetGrantedPermissions(extension_id));
1048 // The new granted permissions are the union of the already granted
1049 // permissions and the newly granted permissions.
1050 scoped_refptr<PermissionSet> new_perms(
1051 PermissionSet::CreateUnion(
1052 permissions, granted_permissions.get()));
1054 SetExtensionPrefPermissionSet(
1055 extension_id, kPrefGrantedPermissions, new_perms.get());
1058 void ExtensionPrefs::RemoveGrantedPermissions(
1059 const std::string& extension_id,
1060 const PermissionSet* permissions) {
1061 CHECK(crx_file::id_util::IdIsValid(extension_id));
1063 scoped_refptr<PermissionSet> granted_permissions(
1064 GetGrantedPermissions(extension_id));
1066 // The new granted permissions are the difference of the already granted
1067 // permissions and the newly ungranted permissions.
1068 scoped_refptr<PermissionSet> new_perms(
1069 PermissionSet::CreateDifference(
1070 granted_permissions.get(), permissions));
1072 SetExtensionPrefPermissionSet(
1073 extension_id, kPrefGrantedPermissions, new_perms.get());
1076 PermissionSet* ExtensionPrefs::GetActivePermissions(
1077 const std::string& extension_id) const {
1078 CHECK(crx_file::id_util::IdIsValid(extension_id));
1079 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
1082 void ExtensionPrefs::SetActivePermissions(
1083 const std::string& extension_id,
1084 const PermissionSet* permissions) {
1085 SetExtensionPrefPermissionSet(
1086 extension_id, kPrefActivePermissions, permissions);
1089 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1090 bool is_running) {
1091 base::Value* value = new base::FundamentalValue(is_running);
1092 UpdateExtensionPref(extension_id, kPrefRunning, value);
1095 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) const {
1096 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1097 if (!extension)
1098 return false;
1099 bool running = false;
1100 extension->GetBoolean(kPrefRunning, &running);
1101 return running;
1104 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1105 bool is_active) {
1106 base::Value* value = new base::FundamentalValue(is_active);
1107 UpdateExtensionPref(extension_id, kIsActive, value);
1110 bool ExtensionPrefs::IsActive(const std::string& extension_id) const {
1111 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1112 if (!extension)
1113 return false;
1114 bool is_active = false;
1115 extension->GetBoolean(kIsActive, &is_active);
1116 return is_active;
1119 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1120 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1123 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1124 bool enabled) {
1125 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1126 new base::FundamentalValue(enabled));
1127 extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled);
1130 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1131 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1134 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1135 bool allow) {
1136 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1137 new base::FundamentalValue(allow));
1140 bool ExtensionPrefs::HasAllowFileAccessSetting(
1141 const std::string& extension_id) const {
1142 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1143 return ext && ext->HasKey(kPrefAllowFileAccess);
1146 bool ExtensionPrefs::DoesExtensionHaveState(
1147 const std::string& id, Extension::State check_state) const {
1148 const base::DictionaryValue* extension = GetExtensionPref(id);
1149 int state = -1;
1150 if (!extension || !extension->GetInteger(kPrefState, &state))
1151 return false;
1153 if (state < 0 || state >= Extension::NUM_STATES) {
1154 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1155 return false;
1158 return state == check_state;
1161 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1162 const std::string& id) const {
1163 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1166 bool ExtensionPrefs::IsExtensionDisabled(
1167 const std::string& id) const {
1168 return DoesExtensionHaveState(id, Extension::DISABLED);
1171 ExtensionIdList ExtensionPrefs::GetToolbarOrder() const {
1172 ExtensionIdList id_list_out;
1173 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1174 return id_list_out;
1177 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1178 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1181 void ExtensionPrefs::OnExtensionInstalled(
1182 const Extension* extension,
1183 Extension::State initial_state,
1184 const syncer::StringOrdinal& page_ordinal,
1185 int install_flags,
1186 const std::string& install_parameter) {
1187 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1188 base::DictionaryValue* extension_dict = update.Get();
1189 const base::Time install_time = time_provider_->GetCurrentTime();
1190 PopulateExtensionInfoPrefs(extension,
1191 install_time,
1192 initial_state,
1193 install_flags,
1194 install_parameter,
1195 extension_dict);
1197 bool requires_sort_ordinal = extension->RequiresSortOrdinal() &&
1198 (install_flags & kInstallFlagIsEphemeral) == 0;
1199 FinishExtensionInfoPrefs(extension->id(),
1200 install_time,
1201 requires_sort_ordinal,
1202 page_ordinal,
1203 extension_dict);
1206 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1207 const Manifest::Location& location,
1208 bool external_uninstall) {
1209 app_sorting_->ClearOrdinals(extension_id);
1211 // For external extensions, we save a preference reminding ourself not to try
1212 // and install the extension anymore (except when |external_uninstall| is
1213 // true, which signifies that the registry key was deleted or the pref file
1214 // no longer lists the extension).
1215 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1216 UpdateExtensionPref(extension_id, kPrefState,
1217 new base::FundamentalValue(
1218 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1219 extension_pref_value_map_->SetExtensionState(extension_id, false);
1220 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1221 observer_list_,
1222 OnExtensionStateChanged(extension_id, false));
1223 } else {
1224 DeleteExtensionPrefs(extension_id);
1228 void ExtensionPrefs::SetExtensionState(const std::string& extension_id,
1229 Extension::State state) {
1230 UpdateExtensionPref(extension_id, kPrefState,
1231 new base::FundamentalValue(state));
1232 bool enabled = (state == Extension::ENABLED);
1233 extension_pref_value_map_->SetExtensionState(extension_id, enabled);
1234 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1235 observer_list_,
1236 OnExtensionStateChanged(extension_id, enabled));
1239 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1240 BlacklistState state) {
1241 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1242 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1243 new base::FundamentalValue(state));
1246 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1247 const std::string& extension_id) const {
1248 if (IsExtensionBlacklisted(extension_id))
1249 return BLACKLISTED_MALWARE;
1250 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1251 int int_value = 0;
1252 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1253 return static_cast<BlacklistState>(int_value);
1255 return NOT_BLACKLISTED;
1258 std::string ExtensionPrefs::GetVersionString(
1259 const std::string& extension_id) const {
1260 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1261 if (!extension)
1262 return std::string();
1264 std::string version;
1265 extension->GetString(kPrefVersion, &version);
1267 return version;
1270 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1271 if (!Manifest::IsUnpackedLocation(extension->location())) {
1272 const base::DictionaryValue* extension_dict =
1273 GetExtensionPref(extension->id());
1274 if (!extension_dict)
1275 return;
1276 const base::DictionaryValue* old_manifest = NULL;
1277 bool update_required =
1278 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1279 !extension->manifest()->value()->Equals(old_manifest);
1280 if (update_required) {
1281 UpdateExtensionPref(extension->id(), kPrefManifest,
1282 extension->manifest()->value()->DeepCopy());
1287 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1288 const std::string& extension_id,
1289 const base::DictionaryValue* extension) const {
1290 int location_value;
1291 if (!extension->GetInteger(kPrefLocation, &location_value))
1292 return scoped_ptr<ExtensionInfo>();
1294 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1295 if (location == Manifest::COMPONENT) {
1296 // Component extensions are ignored. Component extensions may have data
1297 // saved in preferences, but they are already loaded at this point (by
1298 // ComponentLoader) and shouldn't be populated into the result of
1299 // GetInstalledExtensionsInfo, otherwise InstalledLoader would also want to
1300 // load them.
1301 return scoped_ptr<ExtensionInfo>();
1304 // Only the following extension types have data saved in the preferences.
1305 if (location != Manifest::INTERNAL &&
1306 !Manifest::IsUnpackedLocation(location) &&
1307 !Manifest::IsExternalLocation(location)) {
1308 NOTREACHED();
1309 return scoped_ptr<ExtensionInfo>();
1312 const base::DictionaryValue* manifest = NULL;
1313 if (!Manifest::IsUnpackedLocation(location) &&
1314 !extension->GetDictionary(kPrefManifest, &manifest)) {
1315 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1316 // Just a warning for now.
1319 base::FilePath::StringType path;
1320 if (!extension->GetString(kPrefPath, &path))
1321 return scoped_ptr<ExtensionInfo>();
1323 // Make path absolute. Most (but not all) extension types have relative paths.
1324 if (!base::FilePath(path).IsAbsolute())
1325 path = install_directory_.Append(path).value();
1327 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1328 manifest, extension_id, base::FilePath(path), location));
1331 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1332 const std::string& extension_id) const {
1333 const base::DictionaryValue* ext = NULL;
1334 const base::DictionaryValue* extensions =
1335 prefs_->GetDictionary(pref_names::kExtensions);
1336 if (!extensions ||
1337 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1338 return scoped_ptr<ExtensionInfo>();
1339 int state_value;
1340 if (ext->GetInteger(kPrefState, &state_value) &&
1341 state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1342 LOG(WARNING) << "External extension with id " << extension_id
1343 << " has been uninstalled by the user";
1344 return scoped_ptr<ExtensionInfo>();
1347 return GetInstalledInfoHelper(extension_id, ext);
1350 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1351 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1352 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1354 const base::DictionaryValue* extensions =
1355 prefs_->GetDictionary(pref_names::kExtensions);
1356 for (base::DictionaryValue::Iterator extension_id(*extensions);
1357 !extension_id.IsAtEnd(); extension_id.Advance()) {
1358 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1359 continue;
1361 scoped_ptr<ExtensionInfo> info =
1362 GetInstalledExtensionInfo(extension_id.key());
1363 if (info)
1364 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1367 return extensions_info.Pass();
1370 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1371 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1372 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1374 const base::DictionaryValue* extensions =
1375 prefs_->GetDictionary(pref_names::kExtensions);
1376 for (base::DictionaryValue::Iterator extension_id(*extensions);
1377 !extension_id.IsAtEnd(); extension_id.Advance()) {
1378 const base::DictionaryValue* ext = NULL;
1379 if (!crx_file::id_util::IdIsValid(extension_id.key()) ||
1380 !IsExternalExtensionUninstalled(extension_id.key()) ||
1381 !extension_id.value().GetAsDictionary(&ext))
1382 continue;
1384 scoped_ptr<ExtensionInfo> info =
1385 GetInstalledInfoHelper(extension_id.key(), ext);
1386 if (info)
1387 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1390 return extensions_info.Pass();
1393 void ExtensionPrefs::SetDelayedInstallInfo(
1394 const Extension* extension,
1395 Extension::State initial_state,
1396 int install_flags,
1397 DelayReason delay_reason,
1398 const syncer::StringOrdinal& page_ordinal,
1399 const std::string& install_parameter) {
1400 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1401 PopulateExtensionInfoPrefs(extension,
1402 time_provider_->GetCurrentTime(),
1403 initial_state,
1404 install_flags,
1405 install_parameter,
1406 extension_dict);
1408 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1409 // should not be in the final extension prefs. All entries here should have
1410 // a corresponding Remove() call in FinishDelayedInstallInfo().
1411 if (extension->RequiresSortOrdinal() &&
1412 (install_flags & kInstallFlagIsEphemeral) == 0) {
1413 extension_dict->SetString(
1414 kPrefSuggestedPageOrdinal,
1415 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1416 : std::string());
1418 extension_dict->SetInteger(kDelayedInstallReason,
1419 static_cast<int>(delay_reason));
1421 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1424 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1425 const std::string& extension_id) {
1426 if (!GetExtensionPref(extension_id))
1427 return false;
1428 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1429 bool result = update->Remove(kDelayedInstallInfo, NULL);
1430 return result;
1433 bool ExtensionPrefs::FinishDelayedInstallInfo(
1434 const std::string& extension_id) {
1435 CHECK(crx_file::id_util::IdIsValid(extension_id));
1436 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1437 base::DictionaryValue* extension_dict = update.Get();
1438 base::DictionaryValue* pending_install_dict = NULL;
1439 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1440 &pending_install_dict)) {
1441 return false;
1444 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1445 // Also do any other data cleanup that makes sense.
1446 std::string serialized_ordinal;
1447 syncer::StringOrdinal suggested_page_ordinal;
1448 bool needs_sort_ordinal = false;
1449 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1450 &serialized_ordinal)) {
1451 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1452 needs_sort_ordinal = true;
1453 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1455 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1457 const base::Time install_time = time_provider_->GetCurrentTime();
1458 pending_install_dict->Set(
1459 kPrefInstallTime,
1460 new base::StringValue(
1461 base::Int64ToString(install_time.ToInternalValue())));
1463 // Some extension pref values are written conditionally. If they are not
1464 // present in the delayed install data, they should be removed when the
1465 // delayed install is committed.
1466 extension_dict->Remove(kPrefEphemeralApp, NULL);
1468 // Commit the delayed install data.
1469 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1470 it.Advance()) {
1471 extension_dict->Set(it.key(), it.value().DeepCopy());
1473 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1474 suggested_page_ordinal, extension_dict);
1475 return true;
1478 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1479 const std::string& extension_id) const {
1480 const base::DictionaryValue* extension_prefs =
1481 GetExtensionPref(extension_id);
1482 if (!extension_prefs)
1483 return scoped_ptr<ExtensionInfo>();
1485 const base::DictionaryValue* ext = NULL;
1486 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1487 return scoped_ptr<ExtensionInfo>();
1489 return GetInstalledInfoHelper(extension_id, ext);
1492 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1493 const std::string& extension_id) const {
1494 const base::DictionaryValue* extension_prefs =
1495 GetExtensionPref(extension_id);
1496 if (!extension_prefs)
1497 return DELAY_REASON_NONE;
1499 const base::DictionaryValue* ext = NULL;
1500 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1501 return DELAY_REASON_NONE;
1503 int delay_reason;
1504 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1505 return DELAY_REASON_NONE;
1507 return static_cast<DelayReason>(delay_reason);
1510 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1511 GetAllDelayedInstallInfo() const {
1512 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1514 const base::DictionaryValue* extensions =
1515 prefs_->GetDictionary(pref_names::kExtensions);
1516 for (base::DictionaryValue::Iterator extension_id(*extensions);
1517 !extension_id.IsAtEnd(); extension_id.Advance()) {
1518 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1519 continue;
1521 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1522 if (info)
1523 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1526 return extensions_info.Pass();
1529 bool ExtensionPrefs::IsEphemeralApp(const std::string& extension_id) const {
1530 if (ReadPrefAsBooleanAndReturn(extension_id, kPrefEphemeralApp))
1531 return true;
1533 // Ephemerality was previously stored in the creation flags, so we must also
1534 // check it for backcompatibility.
1535 return (GetCreationFlags(extension_id) & Extension::IS_EPHEMERAL) != 0;
1538 void ExtensionPrefs::OnEphemeralAppPromoted(const std::string& extension_id) {
1539 DCHECK(IsEphemeralApp(extension_id));
1541 UpdateExtensionPref(extension_id, kPrefEphemeralApp, NULL);
1543 // Ephemerality was previously stored in the creation flags, so ensure the bit
1544 // is cleared.
1545 int creation_flags = Extension::NO_FLAGS;
1546 if (ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1547 if (creation_flags & Extension::IS_EPHEMERAL) {
1548 creation_flags &= ~static_cast<int>(Extension::IS_EPHEMERAL);
1549 UpdateExtensionPref(extension_id,
1550 kPrefCreationFlags,
1551 new base::FundamentalValue(creation_flags));
1556 bool ExtensionPrefs::WasAppDraggedByUser(
1557 const std::string& extension_id) const {
1558 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1561 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1562 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1563 new base::FundamentalValue(true));
1566 bool ExtensionPrefs::IsFromWebStore(
1567 const std::string& extension_id) const {
1568 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1569 bool result = false;
1570 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1571 return result;
1572 return false;
1575 bool ExtensionPrefs::IsFromBookmark(
1576 const std::string& extension_id) const {
1577 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1578 bool result = false;
1579 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1580 return result;
1581 return false;
1584 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1585 int creation_flags = Extension::NO_FLAGS;
1586 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1587 // Since kPrefCreationFlags was added later, it will be missing for
1588 // previously installed extensions.
1589 if (IsFromBookmark(extension_id))
1590 creation_flags |= Extension::FROM_BOOKMARK;
1591 if (IsFromWebStore(extension_id))
1592 creation_flags |= Extension::FROM_WEBSTORE;
1593 if (WasInstalledByDefault(extension_id))
1594 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1595 if (WasInstalledByOem(extension_id))
1596 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
1598 return creation_flags;
1601 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1602 const std::string& extension_id) const {
1603 int creation_flags = Extension::NO_FLAGS;
1604 const base::DictionaryValue* delayed_info = NULL;
1605 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1606 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1608 return creation_flags;
1611 bool ExtensionPrefs::WasInstalledByDefault(
1612 const std::string& extension_id) const {
1613 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1614 bool result = false;
1615 if (dictionary &&
1616 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1617 return result;
1618 return false;
1621 bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const {
1622 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1623 bool result = false;
1624 if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result))
1625 return result;
1626 return false;
1629 base::Time ExtensionPrefs::GetInstallTime(
1630 const std::string& extension_id) const {
1631 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1632 if (!extension) {
1633 NOTREACHED();
1634 return base::Time();
1636 std::string install_time_str;
1637 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1638 return base::Time();
1639 int64 install_time_i64 = 0;
1640 if (!base::StringToInt64(install_time_str, &install_time_i64))
1641 return base::Time();
1642 return base::Time::FromInternalValue(install_time_i64);
1645 bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const {
1646 bool do_not_sync;
1647 if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync))
1648 return false;
1650 return do_not_sync;
1653 base::Time ExtensionPrefs::GetLastLaunchTime(
1654 const std::string& extension_id) const {
1655 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1656 if (!extension)
1657 return base::Time();
1659 std::string launch_time_str;
1660 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1661 return base::Time();
1662 int64 launch_time_i64 = 0;
1663 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1664 return base::Time();
1665 return base::Time::FromInternalValue(launch_time_i64);
1668 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1669 const base::Time& time) {
1670 DCHECK(crx_file::id_util::IdIsValid(extension_id));
1671 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1672 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1675 void ExtensionPrefs::ClearLastLaunchTimes() {
1676 const base::DictionaryValue* dict =
1677 prefs_->GetDictionary(pref_names::kExtensions);
1678 if (!dict || dict->empty())
1679 return;
1681 // Collect all the keys to remove the last launched preference from.
1682 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
1683 base::DictionaryValue* update_dict = update.Get();
1684 for (base::DictionaryValue::Iterator i(*update_dict); !i.IsAtEnd();
1685 i.Advance()) {
1686 base::DictionaryValue* extension_dict = NULL;
1687 if (!update_dict->GetDictionary(i.key(), &extension_dict))
1688 continue;
1690 if (extension_dict->HasKey(kPrefLastLaunchTime))
1691 extension_dict->Remove(kPrefLastLaunchTime, NULL);
1695 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) const {
1696 CHECK(out);
1698 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1700 for (size_t i = 0; i < extensions_info->size(); ++i) {
1701 ExtensionInfo* info = extensions_info->at(i).get();
1702 out->push_back(info->extension_id);
1706 // static
1707 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1708 const PrefService* pref_service) {
1709 ExtensionIdList result;
1711 const base::DictionaryValue* extension_prefs = NULL;
1712 const base::Value* extension_prefs_value =
1713 pref_service->GetUserPrefValue(pref_names::kExtensions);
1714 if (!extension_prefs_value ||
1715 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1716 return result; // Empty set
1719 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1720 it.Advance()) {
1721 const base::DictionaryValue* ext = NULL;
1722 if (!it.value().GetAsDictionary(&ext)) {
1723 NOTREACHED() << "Invalid pref for extension " << it.key();
1724 continue;
1726 if (!IsBlacklistBitSet(ext))
1727 result.push_back(it.key());
1729 return result;
1732 void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) {
1733 observer_list_.AddObserver(observer);
1736 void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) {
1737 observer_list_.RemoveObserver(observer);
1740 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1741 // Fix old entries that did not get an installation time entry when they
1742 // were installed or don't have a preferences field.
1743 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1744 ext_id != extension_ids.end(); ++ext_id) {
1745 if (GetInstallTime(*ext_id) == base::Time()) {
1746 VLOG(1) << "Could not parse installation time of extension "
1747 << *ext_id << ". It was probably installed before setting "
1748 << kPrefInstallTime << " was introduced. Updating "
1749 << kPrefInstallTime << " to the current time.";
1750 const base::Time install_time = time_provider_->GetCurrentTime();
1751 UpdateExtensionPref(*ext_id,
1752 kPrefInstallTime,
1753 new base::StringValue(base::Int64ToString(
1754 install_time.ToInternalValue())));
1759 void ExtensionPrefs::InitPrefStore() {
1760 TRACE_EVENT0("browser,startup", "ExtensionPrefs::InitPrefStore")
1761 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefStoreTime");
1763 if (extensions_disabled_) {
1764 extension_pref_value_map_->NotifyInitializationCompleted();
1765 return;
1768 // When this is called, the PrefService is initialized and provides access
1769 // to the user preferences stored in a JSON file.
1770 ExtensionIdList extension_ids;
1772 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefGetExtensionsTime");
1773 GetExtensions(&extension_ids);
1775 // Create empty preferences dictionary for each extension (these dictionaries
1776 // are pruned when persisting the preferences to disk).
1777 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1778 ext_id != extension_ids.end(); ++ext_id) {
1779 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1780 // This creates an empty dictionary if none is stored.
1781 update.Get();
1784 FixMissingPrefs(extension_ids);
1785 MigratePermissions(extension_ids);
1786 MigrateDisableReasons(extension_ids);
1787 app_sorting_->Initialize(extension_ids);
1789 InitExtensionControlledPrefs(extension_pref_value_map_);
1791 extension_pref_value_map_->NotifyInitializationCompleted();
1794 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) const {
1795 bool has_incognito_pref_value = false;
1796 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1797 true,
1798 &has_incognito_pref_value);
1799 return has_incognito_pref_value;
1802 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1803 const std::string& extension_id) const {
1804 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1805 if (!extension_prefs)
1806 return NULL;
1808 const base::DictionaryValue* ext = NULL;
1809 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1810 return NULL;
1812 return ext;
1815 void ExtensionPrefs::SetGeometryCache(
1816 const std::string& extension_id,
1817 scoped_ptr<base::DictionaryValue> cache) {
1818 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1821 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() const {
1822 return prefs_->GetDictionary(kInstallSignature);
1825 void ExtensionPrefs::SetInstallSignature(
1826 const base::DictionaryValue* signature) {
1827 if (signature) {
1828 prefs_->Set(kInstallSignature, *signature);
1829 DVLOG(1) << "SetInstallSignature - saving";
1830 } else {
1831 DVLOG(1) << "SetInstallSignature - clearing";
1832 prefs_->ClearPref(kInstallSignature);
1836 std::string ExtensionPrefs::GetInstallParam(
1837 const std::string& extension_id) const {
1838 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1839 if (!extension) // Expected during unit testing.
1840 return std::string();
1841 std::string install_parameter;
1842 if (!extension->GetString(kPrefInstallParam, &install_parameter))
1843 return std::string();
1844 return install_parameter;
1847 void ExtensionPrefs::SetInstallParam(const std::string& extension_id,
1848 const std::string& install_parameter) {
1849 UpdateExtensionPref(extension_id,
1850 kPrefInstallParam,
1851 new base::StringValue(install_parameter));
1854 int ExtensionPrefs::GetCorruptedDisableCount() const {
1855 return prefs_->GetInteger(kCorruptedDisableCount);
1858 void ExtensionPrefs::IncrementCorruptedDisableCount() {
1859 int count = prefs_->GetInteger(kCorruptedDisableCount);
1860 prefs_->SetInteger(kCorruptedDisableCount, count + 1);
1863 ExtensionPrefs::ExtensionPrefs(
1864 PrefService* prefs,
1865 const base::FilePath& root_dir,
1866 ExtensionPrefValueMap* extension_pref_value_map,
1867 scoped_ptr<AppSorting> app_sorting,
1868 scoped_ptr<TimeProvider> time_provider,
1869 bool extensions_disabled,
1870 const std::vector<ExtensionPrefsObserver*>& early_observers)
1871 : prefs_(prefs),
1872 install_directory_(root_dir),
1873 extension_pref_value_map_(extension_pref_value_map),
1874 app_sorting_(app_sorting.Pass()),
1875 time_provider_(time_provider.Pass()),
1876 extensions_disabled_(extensions_disabled) {
1877 // TODO(mgiuca): Added these checks to try and diagnose
1878 // http://crbug.com/476648. Remove them after the investigation is concluded.
1879 CHECK(this);
1880 app_sorting_->SetExtensionScopedPrefs(this);
1881 app_sorting_->CheckExtensionScopedPrefs();
1882 MakePathsRelative();
1884 // Ensure that any early observers are watching before prefs are initialized.
1885 for (std::vector<ExtensionPrefsObserver*>::const_iterator iter =
1886 early_observers.begin();
1887 iter != early_observers.end();
1888 ++iter) {
1889 AddObserver(*iter);
1892 InitPrefStore();
1895 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1896 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1899 bool ExtensionPrefs::NeedsStorageGarbageCollection() const {
1900 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1903 // static
1904 void ExtensionPrefs::RegisterProfilePrefs(
1905 user_prefs::PrefRegistrySyncable* registry) {
1906 registry->RegisterDictionaryPref(pref_names::kExtensions);
1907 registry->RegisterListPref(pref_names::kToolbar,
1908 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1909 registry->RegisterIntegerPref(pref_names::kToolbarSize, -1);
1910 registry->RegisterDictionaryPref(kExtensionsBlacklistUpdate);
1911 registry->RegisterListPref(pref_names::kInstallAllowList);
1912 registry->RegisterListPref(pref_names::kInstallDenyList);
1913 registry->RegisterDictionaryPref(pref_names::kInstallForceList);
1914 registry->RegisterListPref(pref_names::kAllowedTypes);
1915 registry->RegisterBooleanPref(pref_names::kStorageGarbageCollect, false);
1916 registry->RegisterInt64Pref(pref_names::kLastUpdateCheck, 0);
1917 registry->RegisterInt64Pref(pref_names::kNextUpdateCheck, 0);
1918 registry->RegisterListPref(pref_names::kAllowedInstallSites);
1919 registry->RegisterStringPref(pref_names::kLastChromeVersion, std::string());
1920 registry->RegisterDictionaryPref(kInstallSignature);
1922 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist);
1923 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist);
1924 registry->RegisterBooleanPref(pref_names::kNativeMessagingUserLevelHosts,
1925 true);
1926 registry->RegisterIntegerPref(kCorruptedDisableCount, 0);
1928 #if !defined(OS_MACOSX)
1929 registry->RegisterBooleanPref(pref_names::kAppFullscreenAllowed, true);
1930 #endif
1933 template <class ExtensionIdContainer>
1934 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
1935 const char* pref,
1936 ExtensionIdContainer* id_container_out) const {
1937 DCHECK(id_container_out->empty());
1939 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
1940 const base::ListValue* user_pref_as_list;
1941 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
1942 return false;
1944 std::insert_iterator<ExtensionIdContainer> insert_iterator(
1945 *id_container_out, id_container_out->end());
1946 std::string extension_id;
1947 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
1948 value_it != user_pref_as_list->end(); ++value_it) {
1949 if (!(*value_it)->GetAsString(&extension_id)) {
1950 NOTREACHED();
1951 continue;
1953 insert_iterator = extension_id;
1955 return true;
1958 template <class ExtensionIdContainer>
1959 void ExtensionPrefs::SetExtensionPrefFromContainer(
1960 const char* pref,
1961 const ExtensionIdContainer& strings) {
1962 ListPrefUpdate update(prefs_, pref);
1963 base::ListValue* list_of_values = update.Get();
1964 list_of_values->Clear();
1965 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
1966 iter != strings.end(); ++iter) {
1967 list_of_values->Append(new base::StringValue(*iter));
1971 void ExtensionPrefs::PopulateExtensionInfoPrefs(
1972 const Extension* extension,
1973 const base::Time install_time,
1974 Extension::State initial_state,
1975 int install_flags,
1976 const std::string& install_parameter,
1977 base::DictionaryValue* extension_dict) const {
1978 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
1979 extension_dict->Set(kPrefLocation,
1980 new base::FundamentalValue(extension->location()));
1981 extension_dict->Set(kPrefCreationFlags,
1982 new base::FundamentalValue(extension->creation_flags()));
1983 extension_dict->Set(kPrefFromWebStore,
1984 new base::FundamentalValue(extension->from_webstore()));
1985 extension_dict->Set(kPrefFromBookmark,
1986 new base::FundamentalValue(extension->from_bookmark()));
1987 extension_dict->Set(
1988 kPrefWasInstalledByDefault,
1989 new base::FundamentalValue(extension->was_installed_by_default()));
1990 extension_dict->Set(
1991 kPrefWasInstalledByOem,
1992 new base::FundamentalValue(extension->was_installed_by_oem()));
1993 extension_dict->Set(kPrefInstallTime,
1994 new base::StringValue(
1995 base::Int64ToString(install_time.ToInternalValue())));
1996 if (install_flags & kInstallFlagIsBlacklistedForMalware)
1997 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
1999 if (install_flags & kInstallFlagIsEphemeral)
2000 extension_dict->Set(kPrefEphemeralApp, new base::FundamentalValue(true));
2001 else
2002 extension_dict->Remove(kPrefEphemeralApp, NULL);
2004 base::FilePath::StringType path = MakePathRelative(install_directory_,
2005 extension->path());
2006 extension_dict->Set(kPrefPath, new base::StringValue(path));
2007 if (!install_parameter.empty()) {
2008 extension_dict->Set(kPrefInstallParam,
2009 new base::StringValue(install_parameter));
2011 // We store prefs about LOAD extensions, but don't cache their manifest
2012 // since it may change on disk.
2013 if (!Manifest::IsUnpackedLocation(extension->location())) {
2014 extension_dict->Set(kPrefManifest,
2015 extension->manifest()->value()->DeepCopy());
2018 // Only writes kPrefDoNotSync when it is not the default.
2019 if (install_flags & kInstallFlagDoNotSync)
2020 extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true));
2021 else
2022 extension_dict->Remove(kPrefDoNotSync, NULL);
2025 void ExtensionPrefs::InitExtensionControlledPrefs(
2026 ExtensionPrefValueMap* value_map) {
2027 TRACE_EVENT0("browser,startup",
2028 "ExtensionPrefs::InitExtensionControlledPrefs")
2029 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitExtensionControlledPrefsTime");
2031 ExtensionIdList extension_ids;
2032 GetExtensions(&extension_ids);
2034 for (ExtensionIdList::iterator extension_id = extension_ids.begin();
2035 extension_id != extension_ids.end();
2036 ++extension_id) {
2037 base::Time install_time = GetInstallTime(*extension_id);
2038 bool is_enabled = !IsExtensionDisabled(*extension_id);
2039 bool is_incognito_enabled = IsIncognitoEnabled(*extension_id);
2040 value_map->RegisterExtension(
2041 *extension_id, install_time, is_enabled, is_incognito_enabled);
2043 FOR_EACH_OBSERVER(
2044 ExtensionPrefsObserver,
2045 observer_list_,
2046 OnExtensionRegistered(*extension_id, install_time, is_enabled));
2048 // Set regular extension controlled prefs.
2049 LoadExtensionControlledPrefs(
2050 this, value_map, *extension_id, kExtensionPrefsScopeRegular);
2051 // Set incognito extension controlled prefs.
2052 LoadExtensionControlledPrefs(this,
2053 value_map,
2054 *extension_id,
2055 kExtensionPrefsScopeIncognitoPersistent);
2056 // Set regular-only extension controlled prefs.
2057 LoadExtensionControlledPrefs(
2058 this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly);
2060 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
2061 observer_list_,
2062 OnExtensionPrefsLoaded(*extension_id, this));
2066 void ExtensionPrefs::FinishExtensionInfoPrefs(
2067 const std::string& extension_id,
2068 const base::Time install_time,
2069 bool needs_sort_ordinal,
2070 const syncer::StringOrdinal& suggested_page_ordinal,
2071 base::DictionaryValue* extension_dict) {
2072 // Reinitializes various preferences with empty dictionaries.
2073 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
2074 extension_dict->Set(pref_names::kPrefPreferences,
2075 new base::DictionaryValue);
2078 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
2079 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
2080 new base::DictionaryValue);
2083 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
2084 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
2085 new base::DictionaryValue);
2088 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
2089 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
2091 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
2092 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
2093 new base::ListValue);
2096 // If this point has been reached, any pending installs should be considered
2097 // out of date.
2098 extension_dict->Remove(kDelayedInstallInfo, NULL);
2100 // Clear state that may be registered from a previous install.
2101 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
2103 // FYI, all code below here races on sudden shutdown because |extension_dict|,
2104 // |app_sorting_|, |extension_pref_value_map_|, and (potentially) observers
2105 // are updated non-transactionally. This is probably not fixable without
2106 // nested transactional updates to pref dictionaries.
2107 if (needs_sort_ordinal)
2108 app_sorting_->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
2110 bool is_enabled = false;
2111 int initial_state;
2112 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
2113 is_enabled = initial_state == Extension::ENABLED;
2115 bool is_incognito_enabled = IsIncognitoEnabled(extension_id);
2117 extension_pref_value_map_->RegisterExtension(
2118 extension_id, install_time, is_enabled, is_incognito_enabled);
2120 FOR_EACH_OBSERVER(
2121 ExtensionPrefsObserver,
2122 observer_list_,
2123 OnExtensionRegistered(extension_id, install_time, is_enabled));
2126 } // namespace extensions