Fix for ERROR:url_pattern_set.cc(240)] Invalid url pattern: chrome://print/*
[chromium-blink-merge.git] / extensions / browser / extension_prefs.cc
blobff708121dfd0c36584c5caa9b1d055649c2098ea
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::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() {
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(const std::string& extension_id) {
930 DCHECK(crx_file::id_util::IdIsValid(extension_id));
931 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
934 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
935 const base::Time& time) {
936 DCHECK(crx_file::id_util::IdIsValid(extension_id));
937 ScopedExtensionPrefUpdate update(prefs_, extension_id);
938 SaveTime(update.Get(), kLastActivePingDay, time);
941 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) {
942 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
943 bool result = false;
944 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
945 return result;
946 return false;
949 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
950 bool active) {
951 UpdateExtensionPref(extension_id, kActiveBit,
952 new base::FundamentalValue(active));
955 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
956 PermissionsInfo* info = PermissionsInfo::GetInstance();
957 for (ExtensionIdList::const_iterator ext_id =
958 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
959 // An extension's granted permissions need to be migrated if the
960 // full_access bit is present. This bit was always present in the previous
961 // scheme and is never present now.
962 bool full_access = false;
963 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
964 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
965 continue;
967 // Remove the full access bit (empty list will get trimmed).
968 UpdateExtensionPref(
969 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
971 // Add the plugin permission if the full access bit was set.
972 if (full_access) {
973 const base::ListValue* apis = NULL;
974 base::ListValue* new_apis = NULL;
976 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
977 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
978 new_apis = apis->DeepCopy();
979 else
980 new_apis = new base::ListValue();
982 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
983 new_apis->Append(new base::StringValue(plugin_name));
984 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
987 // The granted permissions originally only held the effective hosts,
988 // which are a combination of host and user script host permissions.
989 // We now maintain these lists separately. For migration purposes, it
990 // does not matter how we treat the old effective hosts as long as the
991 // new effective hosts will be the same, so we move them to explicit
992 // host permissions.
993 const base::ListValue* hosts = NULL;
994 std::string explicit_hosts =
995 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
996 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
997 UpdateExtensionPref(
998 *ext_id, explicit_hosts, hosts->DeepCopy());
1000 // We can get rid of the old one by setting it to an empty list.
1001 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
1006 void ExtensionPrefs::MigrateDisableReasons(
1007 const ExtensionIdList& extension_ids) {
1008 for (ExtensionIdList::const_iterator ext_id =
1009 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
1010 int value = -1;
1011 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
1012 int new_value = Extension::DISABLE_NONE;
1013 switch (value) {
1014 case Extension::DEPRECATED_DISABLE_USER_ACTION:
1015 new_value = Extension::DISABLE_USER_ACTION;
1016 break;
1017 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
1018 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
1019 break;
1020 case Extension::DEPRECATED_DISABLE_RELOAD:
1021 new_value = Extension::DISABLE_RELOAD;
1022 break;
1025 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
1026 new base::FundamentalValue(new_value));
1027 // Remove the old disable reason.
1028 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
1033 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
1034 const std::string& extension_id) {
1035 CHECK(crx_file::id_util::IdIsValid(extension_id));
1036 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
1039 void ExtensionPrefs::AddGrantedPermissions(
1040 const std::string& extension_id,
1041 const PermissionSet* permissions) {
1042 CHECK(crx_file::id_util::IdIsValid(extension_id));
1044 scoped_refptr<PermissionSet> granted_permissions(
1045 GetGrantedPermissions(extension_id));
1047 // The new granted permissions are the union of the already granted
1048 // permissions and the newly granted permissions.
1049 scoped_refptr<PermissionSet> new_perms(
1050 PermissionSet::CreateUnion(
1051 permissions, granted_permissions.get()));
1053 SetExtensionPrefPermissionSet(
1054 extension_id, kPrefGrantedPermissions, new_perms.get());
1057 void ExtensionPrefs::RemoveGrantedPermissions(
1058 const std::string& extension_id,
1059 const PermissionSet* permissions) {
1060 CHECK(crx_file::id_util::IdIsValid(extension_id));
1062 scoped_refptr<PermissionSet> granted_permissions(
1063 GetGrantedPermissions(extension_id));
1065 // The new granted permissions are the difference of the already granted
1066 // permissions and the newly ungranted permissions.
1067 scoped_refptr<PermissionSet> new_perms(
1068 PermissionSet::CreateDifference(
1069 granted_permissions.get(), permissions));
1071 SetExtensionPrefPermissionSet(
1072 extension_id, kPrefGrantedPermissions, new_perms.get());
1075 PermissionSet* ExtensionPrefs::GetActivePermissions(
1076 const std::string& extension_id) {
1077 CHECK(crx_file::id_util::IdIsValid(extension_id));
1078 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
1081 void ExtensionPrefs::SetActivePermissions(
1082 const std::string& extension_id,
1083 const PermissionSet* permissions) {
1084 SetExtensionPrefPermissionSet(
1085 extension_id, kPrefActivePermissions, permissions);
1088 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1089 bool is_running) {
1090 base::Value* value = new base::FundamentalValue(is_running);
1091 UpdateExtensionPref(extension_id, kPrefRunning, value);
1094 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) {
1095 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1096 if (!extension)
1097 return false;
1098 bool running = false;
1099 extension->GetBoolean(kPrefRunning, &running);
1100 return running;
1103 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1104 bool is_active) {
1105 base::Value* value = new base::FundamentalValue(is_active);
1106 UpdateExtensionPref(extension_id, kIsActive, value);
1109 bool ExtensionPrefs::IsActive(const std::string& extension_id) {
1110 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1111 if (!extension)
1112 return false;
1113 bool is_active = false;
1114 extension->GetBoolean(kIsActive, &is_active);
1115 return is_active;
1118 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1119 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1122 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1123 bool enabled) {
1124 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1125 new base::FundamentalValue(enabled));
1126 extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled);
1129 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1130 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1133 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1134 bool allow) {
1135 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1136 new base::FundamentalValue(allow));
1139 bool ExtensionPrefs::HasAllowFileAccessSetting(
1140 const std::string& extension_id) const {
1141 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1142 return ext && ext->HasKey(kPrefAllowFileAccess);
1145 bool ExtensionPrefs::DoesExtensionHaveState(
1146 const std::string& id, Extension::State check_state) const {
1147 const base::DictionaryValue* extension = GetExtensionPref(id);
1148 int state = -1;
1149 if (!extension || !extension->GetInteger(kPrefState, &state))
1150 return false;
1152 if (state < 0 || state >= Extension::NUM_STATES) {
1153 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1154 return false;
1157 return state == check_state;
1160 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1161 const std::string& id) const {
1162 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1165 bool ExtensionPrefs::IsExtensionDisabled(
1166 const std::string& id) const {
1167 return DoesExtensionHaveState(id, Extension::DISABLED);
1170 ExtensionIdList ExtensionPrefs::GetToolbarOrder() {
1171 ExtensionIdList id_list_out;
1172 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1173 return id_list_out;
1176 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1177 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1180 void ExtensionPrefs::OnExtensionInstalled(
1181 const Extension* extension,
1182 Extension::State initial_state,
1183 const syncer::StringOrdinal& page_ordinal,
1184 int install_flags,
1185 const std::string& install_parameter) {
1186 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1187 base::DictionaryValue* extension_dict = update.Get();
1188 const base::Time install_time = time_provider_->GetCurrentTime();
1189 PopulateExtensionInfoPrefs(extension,
1190 install_time,
1191 initial_state,
1192 install_flags,
1193 install_parameter,
1194 extension_dict);
1196 bool requires_sort_ordinal = extension->RequiresSortOrdinal() &&
1197 (install_flags & kInstallFlagIsEphemeral) == 0;
1198 FinishExtensionInfoPrefs(extension->id(),
1199 install_time,
1200 requires_sort_ordinal,
1201 page_ordinal,
1202 extension_dict);
1205 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1206 const Manifest::Location& location,
1207 bool external_uninstall) {
1208 app_sorting_->ClearOrdinals(extension_id);
1210 // For external extensions, we save a preference reminding ourself not to try
1211 // and install the extension anymore (except when |external_uninstall| is
1212 // true, which signifies that the registry key was deleted or the pref file
1213 // no longer lists the extension).
1214 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1215 UpdateExtensionPref(extension_id, kPrefState,
1216 new base::FundamentalValue(
1217 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1218 extension_pref_value_map_->SetExtensionState(extension_id, false);
1219 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1220 observer_list_,
1221 OnExtensionStateChanged(extension_id, false));
1222 } else {
1223 DeleteExtensionPrefs(extension_id);
1227 void ExtensionPrefs::SetExtensionState(const std::string& extension_id,
1228 Extension::State state) {
1229 UpdateExtensionPref(extension_id, kPrefState,
1230 new base::FundamentalValue(state));
1231 bool enabled = (state == Extension::ENABLED);
1232 extension_pref_value_map_->SetExtensionState(extension_id, enabled);
1233 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1234 observer_list_,
1235 OnExtensionStateChanged(extension_id, enabled));
1238 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1239 BlacklistState state) {
1240 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1241 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1242 new base::FundamentalValue(state));
1245 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1246 const std::string& extension_id) {
1247 if (IsExtensionBlacklisted(extension_id))
1248 return BLACKLISTED_MALWARE;
1249 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1250 int int_value = 0;
1251 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1252 return static_cast<BlacklistState>(int_value);
1254 return NOT_BLACKLISTED;
1257 std::string ExtensionPrefs::GetVersionString(const std::string& extension_id) {
1258 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1259 if (!extension)
1260 return std::string();
1262 std::string version;
1263 extension->GetString(kPrefVersion, &version);
1265 return version;
1268 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1269 if (!Manifest::IsUnpackedLocation(extension->location())) {
1270 const base::DictionaryValue* extension_dict =
1271 GetExtensionPref(extension->id());
1272 if (!extension_dict)
1273 return;
1274 const base::DictionaryValue* old_manifest = NULL;
1275 bool update_required =
1276 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1277 !extension->manifest()->value()->Equals(old_manifest);
1278 if (update_required) {
1279 UpdateExtensionPref(extension->id(), kPrefManifest,
1280 extension->manifest()->value()->DeepCopy());
1285 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1286 const std::string& extension_id,
1287 const base::DictionaryValue* extension) const {
1288 int location_value;
1289 if (!extension->GetInteger(kPrefLocation, &location_value))
1290 return scoped_ptr<ExtensionInfo>();
1292 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1293 if (location == Manifest::COMPONENT) {
1294 // Component extensions are ignored. Component extensions may have data
1295 // saved in preferences, but they are already loaded at this point (by
1296 // ComponentLoader) and shouldn't be populated into the result of
1297 // GetInstalledExtensionsInfo, otherwise InstalledLoader would also want to
1298 // load them.
1299 return scoped_ptr<ExtensionInfo>();
1302 // Only the following extension types have data saved in the preferences.
1303 if (location != Manifest::INTERNAL &&
1304 !Manifest::IsUnpackedLocation(location) &&
1305 !Manifest::IsExternalLocation(location)) {
1306 NOTREACHED();
1307 return scoped_ptr<ExtensionInfo>();
1310 const base::DictionaryValue* manifest = NULL;
1311 if (!Manifest::IsUnpackedLocation(location) &&
1312 !extension->GetDictionary(kPrefManifest, &manifest)) {
1313 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1314 // Just a warning for now.
1317 base::FilePath::StringType path;
1318 if (!extension->GetString(kPrefPath, &path))
1319 return scoped_ptr<ExtensionInfo>();
1321 // Make path absolute. Most (but not all) extension types have relative paths.
1322 if (!base::FilePath(path).IsAbsolute())
1323 path = install_directory_.Append(path).value();
1325 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1326 manifest, extension_id, base::FilePath(path), location));
1329 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1330 const std::string& extension_id) const {
1331 const base::DictionaryValue* ext = NULL;
1332 const base::DictionaryValue* extensions =
1333 prefs_->GetDictionary(pref_names::kExtensions);
1334 if (!extensions ||
1335 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1336 return scoped_ptr<ExtensionInfo>();
1337 int state_value;
1338 if (ext->GetInteger(kPrefState, &state_value) &&
1339 state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1340 LOG(WARNING) << "External extension with id " << extension_id
1341 << " has been uninstalled by the user";
1342 return scoped_ptr<ExtensionInfo>();
1345 return GetInstalledInfoHelper(extension_id, ext);
1348 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1349 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1350 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1352 const base::DictionaryValue* extensions =
1353 prefs_->GetDictionary(pref_names::kExtensions);
1354 for (base::DictionaryValue::Iterator extension_id(*extensions);
1355 !extension_id.IsAtEnd(); extension_id.Advance()) {
1356 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1357 continue;
1359 scoped_ptr<ExtensionInfo> info =
1360 GetInstalledExtensionInfo(extension_id.key());
1361 if (info)
1362 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1365 return extensions_info.Pass();
1368 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1369 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1370 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1372 const base::DictionaryValue* extensions =
1373 prefs_->GetDictionary(pref_names::kExtensions);
1374 for (base::DictionaryValue::Iterator extension_id(*extensions);
1375 !extension_id.IsAtEnd(); extension_id.Advance()) {
1376 const base::DictionaryValue* ext = NULL;
1377 if (!crx_file::id_util::IdIsValid(extension_id.key()) ||
1378 !IsExternalExtensionUninstalled(extension_id.key()) ||
1379 !extension_id.value().GetAsDictionary(&ext))
1380 continue;
1382 scoped_ptr<ExtensionInfo> info =
1383 GetInstalledInfoHelper(extension_id.key(), ext);
1384 if (info)
1385 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1388 return extensions_info.Pass();
1391 void ExtensionPrefs::SetDelayedInstallInfo(
1392 const Extension* extension,
1393 Extension::State initial_state,
1394 int install_flags,
1395 DelayReason delay_reason,
1396 const syncer::StringOrdinal& page_ordinal,
1397 const std::string& install_parameter) {
1398 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1399 PopulateExtensionInfoPrefs(extension,
1400 time_provider_->GetCurrentTime(),
1401 initial_state,
1402 install_flags,
1403 install_parameter,
1404 extension_dict);
1406 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1407 // should not be in the final extension prefs. All entries here should have
1408 // a corresponding Remove() call in FinishDelayedInstallInfo().
1409 if (extension->RequiresSortOrdinal() &&
1410 (install_flags & kInstallFlagIsEphemeral) == 0) {
1411 extension_dict->SetString(
1412 kPrefSuggestedPageOrdinal,
1413 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1414 : std::string());
1416 extension_dict->SetInteger(kDelayedInstallReason,
1417 static_cast<int>(delay_reason));
1419 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1422 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1423 const std::string& extension_id) {
1424 if (!GetExtensionPref(extension_id))
1425 return false;
1426 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1427 bool result = update->Remove(kDelayedInstallInfo, NULL);
1428 return result;
1431 bool ExtensionPrefs::FinishDelayedInstallInfo(
1432 const std::string& extension_id) {
1433 CHECK(crx_file::id_util::IdIsValid(extension_id));
1434 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1435 base::DictionaryValue* extension_dict = update.Get();
1436 base::DictionaryValue* pending_install_dict = NULL;
1437 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1438 &pending_install_dict)) {
1439 return false;
1442 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1443 // Also do any other data cleanup that makes sense.
1444 std::string serialized_ordinal;
1445 syncer::StringOrdinal suggested_page_ordinal;
1446 bool needs_sort_ordinal = false;
1447 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1448 &serialized_ordinal)) {
1449 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1450 needs_sort_ordinal = true;
1451 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1453 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1455 const base::Time install_time = time_provider_->GetCurrentTime();
1456 pending_install_dict->Set(
1457 kPrefInstallTime,
1458 new base::StringValue(
1459 base::Int64ToString(install_time.ToInternalValue())));
1461 // Some extension pref values are written conditionally. If they are not
1462 // present in the delayed install data, they should be removed when the
1463 // delayed install is committed.
1464 extension_dict->Remove(kPrefEphemeralApp, NULL);
1466 // Commit the delayed install data.
1467 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1468 it.Advance()) {
1469 extension_dict->Set(it.key(), it.value().DeepCopy());
1471 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1472 suggested_page_ordinal, extension_dict);
1473 return true;
1476 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1477 const std::string& extension_id) const {
1478 const base::DictionaryValue* extension_prefs =
1479 GetExtensionPref(extension_id);
1480 if (!extension_prefs)
1481 return scoped_ptr<ExtensionInfo>();
1483 const base::DictionaryValue* ext = NULL;
1484 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1485 return scoped_ptr<ExtensionInfo>();
1487 return GetInstalledInfoHelper(extension_id, ext);
1490 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1491 const std::string& extension_id) const {
1492 const base::DictionaryValue* extension_prefs =
1493 GetExtensionPref(extension_id);
1494 if (!extension_prefs)
1495 return DELAY_REASON_NONE;
1497 const base::DictionaryValue* ext = NULL;
1498 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1499 return DELAY_REASON_NONE;
1501 int delay_reason;
1502 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1503 return DELAY_REASON_NONE;
1505 return static_cast<DelayReason>(delay_reason);
1508 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1509 GetAllDelayedInstallInfo() const {
1510 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1512 const base::DictionaryValue* extensions =
1513 prefs_->GetDictionary(pref_names::kExtensions);
1514 for (base::DictionaryValue::Iterator extension_id(*extensions);
1515 !extension_id.IsAtEnd(); extension_id.Advance()) {
1516 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1517 continue;
1519 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1520 if (info)
1521 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1524 return extensions_info.Pass();
1527 bool ExtensionPrefs::IsEphemeralApp(const std::string& extension_id) const {
1528 if (ReadPrefAsBooleanAndReturn(extension_id, kPrefEphemeralApp))
1529 return true;
1531 // Ephemerality was previously stored in the creation flags, so we must also
1532 // check it for backcompatibility.
1533 return (GetCreationFlags(extension_id) & Extension::IS_EPHEMERAL) != 0;
1536 void ExtensionPrefs::OnEphemeralAppPromoted(const std::string& extension_id) {
1537 DCHECK(IsEphemeralApp(extension_id));
1539 UpdateExtensionPref(extension_id, kPrefEphemeralApp, NULL);
1541 // Ephemerality was previously stored in the creation flags, so ensure the bit
1542 // is cleared.
1543 int creation_flags = Extension::NO_FLAGS;
1544 if (ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1545 if (creation_flags & Extension::IS_EPHEMERAL) {
1546 creation_flags &= ~static_cast<int>(Extension::IS_EPHEMERAL);
1547 UpdateExtensionPref(extension_id,
1548 kPrefCreationFlags,
1549 new base::FundamentalValue(creation_flags));
1554 bool ExtensionPrefs::WasAppDraggedByUser(const std::string& extension_id) {
1555 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1558 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1559 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1560 new base::FundamentalValue(true));
1563 bool ExtensionPrefs::IsFromWebStore(
1564 const std::string& extension_id) const {
1565 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1566 bool result = false;
1567 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1568 return result;
1569 return false;
1572 bool ExtensionPrefs::IsFromBookmark(
1573 const std::string& extension_id) const {
1574 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1575 bool result = false;
1576 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1577 return result;
1578 return false;
1581 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1582 int creation_flags = Extension::NO_FLAGS;
1583 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1584 // Since kPrefCreationFlags was added later, it will be missing for
1585 // previously installed extensions.
1586 if (IsFromBookmark(extension_id))
1587 creation_flags |= Extension::FROM_BOOKMARK;
1588 if (IsFromWebStore(extension_id))
1589 creation_flags |= Extension::FROM_WEBSTORE;
1590 if (WasInstalledByDefault(extension_id))
1591 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1592 if (WasInstalledByOem(extension_id))
1593 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
1595 return creation_flags;
1598 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1599 const std::string& extension_id) const {
1600 int creation_flags = Extension::NO_FLAGS;
1601 const base::DictionaryValue* delayed_info = NULL;
1602 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1603 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1605 return creation_flags;
1608 bool ExtensionPrefs::WasInstalledByDefault(
1609 const std::string& extension_id) const {
1610 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1611 bool result = false;
1612 if (dictionary &&
1613 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1614 return result;
1615 return false;
1618 bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const {
1619 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1620 bool result = false;
1621 if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result))
1622 return result;
1623 return false;
1626 base::Time ExtensionPrefs::GetInstallTime(
1627 const std::string& extension_id) const {
1628 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1629 if (!extension) {
1630 NOTREACHED();
1631 return base::Time();
1633 std::string install_time_str;
1634 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1635 return base::Time();
1636 int64 install_time_i64 = 0;
1637 if (!base::StringToInt64(install_time_str, &install_time_i64))
1638 return base::Time();
1639 return base::Time::FromInternalValue(install_time_i64);
1642 bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const {
1643 bool do_not_sync;
1644 if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync))
1645 return false;
1647 return do_not_sync;
1650 base::Time ExtensionPrefs::GetLastLaunchTime(
1651 const std::string& extension_id) const {
1652 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1653 if (!extension)
1654 return base::Time();
1656 std::string launch_time_str;
1657 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1658 return base::Time();
1659 int64 launch_time_i64 = 0;
1660 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1661 return base::Time();
1662 return base::Time::FromInternalValue(launch_time_i64);
1665 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1666 const base::Time& time) {
1667 DCHECK(crx_file::id_util::IdIsValid(extension_id));
1668 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1669 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1672 void ExtensionPrefs::ClearLastLaunchTimes() {
1673 const base::DictionaryValue* dict =
1674 prefs_->GetDictionary(pref_names::kExtensions);
1675 if (!dict || dict->empty())
1676 return;
1678 // Collect all the keys to remove the last launched preference from.
1679 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
1680 base::DictionaryValue* update_dict = update.Get();
1681 for (base::DictionaryValue::Iterator i(*update_dict); !i.IsAtEnd();
1682 i.Advance()) {
1683 base::DictionaryValue* extension_dict = NULL;
1684 if (!update_dict->GetDictionary(i.key(), &extension_dict))
1685 continue;
1687 if (extension_dict->HasKey(kPrefLastLaunchTime))
1688 extension_dict->Remove(kPrefLastLaunchTime, NULL);
1692 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) {
1693 CHECK(out);
1695 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1697 for (size_t i = 0; i < extensions_info->size(); ++i) {
1698 ExtensionInfo* info = extensions_info->at(i).get();
1699 out->push_back(info->extension_id);
1703 // static
1704 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1705 const PrefService* pref_service) {
1706 ExtensionIdList result;
1708 const base::DictionaryValue* extension_prefs = NULL;
1709 const base::Value* extension_prefs_value =
1710 pref_service->GetUserPrefValue(pref_names::kExtensions);
1711 if (!extension_prefs_value ||
1712 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1713 return result; // Empty set
1716 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1717 it.Advance()) {
1718 const base::DictionaryValue* ext = NULL;
1719 if (!it.value().GetAsDictionary(&ext)) {
1720 NOTREACHED() << "Invalid pref for extension " << it.key();
1721 continue;
1723 if (!IsBlacklistBitSet(ext))
1724 result.push_back(it.key());
1726 return result;
1729 void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) {
1730 observer_list_.AddObserver(observer);
1733 void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) {
1734 observer_list_.RemoveObserver(observer);
1737 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1738 // Fix old entries that did not get an installation time entry when they
1739 // were installed or don't have a preferences field.
1740 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1741 ext_id != extension_ids.end(); ++ext_id) {
1742 if (GetInstallTime(*ext_id) == base::Time()) {
1743 VLOG(1) << "Could not parse installation time of extension "
1744 << *ext_id << ". It was probably installed before setting "
1745 << kPrefInstallTime << " was introduced. Updating "
1746 << kPrefInstallTime << " to the current time.";
1747 const base::Time install_time = time_provider_->GetCurrentTime();
1748 UpdateExtensionPref(*ext_id,
1749 kPrefInstallTime,
1750 new base::StringValue(base::Int64ToString(
1751 install_time.ToInternalValue())));
1756 void ExtensionPrefs::InitPrefStore() {
1757 TRACE_EVENT0("browser,startup", "ExtensionPrefs::InitPrefStore")
1758 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefStoreTime");
1760 if (extensions_disabled_) {
1761 extension_pref_value_map_->NotifyInitializationCompleted();
1762 return;
1765 // When this is called, the PrefService is initialized and provides access
1766 // to the user preferences stored in a JSON file.
1767 ExtensionIdList extension_ids;
1769 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefGetExtensionsTime");
1770 GetExtensions(&extension_ids);
1772 // Create empty preferences dictionary for each extension (these dictionaries
1773 // are pruned when persisting the preferences to disk).
1774 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1775 ext_id != extension_ids.end(); ++ext_id) {
1776 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1777 // This creates an empty dictionary if none is stored.
1778 update.Get();
1781 FixMissingPrefs(extension_ids);
1782 MigratePermissions(extension_ids);
1783 MigrateDisableReasons(extension_ids);
1784 app_sorting_->Initialize(extension_ids);
1786 InitExtensionControlledPrefs(extension_pref_value_map_);
1788 extension_pref_value_map_->NotifyInitializationCompleted();
1791 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) {
1792 bool has_incognito_pref_value = false;
1793 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1794 true,
1795 &has_incognito_pref_value);
1796 return has_incognito_pref_value;
1799 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1800 const std::string& extension_id) const {
1801 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1802 if (!extension_prefs)
1803 return NULL;
1805 const base::DictionaryValue* ext = NULL;
1806 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1807 return NULL;
1809 return ext;
1812 void ExtensionPrefs::SetGeometryCache(
1813 const std::string& extension_id,
1814 scoped_ptr<base::DictionaryValue> cache) {
1815 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1818 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() {
1819 return prefs_->GetDictionary(kInstallSignature);
1822 void ExtensionPrefs::SetInstallSignature(
1823 const base::DictionaryValue* signature) {
1824 if (signature) {
1825 prefs_->Set(kInstallSignature, *signature);
1826 DVLOG(1) << "SetInstallSignature - saving";
1827 } else {
1828 DVLOG(1) << "SetInstallSignature - clearing";
1829 prefs_->ClearPref(kInstallSignature);
1833 std::string ExtensionPrefs::GetInstallParam(
1834 const std::string& extension_id) const {
1835 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1836 if (!extension) // Expected during unit testing.
1837 return std::string();
1838 std::string install_parameter;
1839 if (!extension->GetString(kPrefInstallParam, &install_parameter))
1840 return std::string();
1841 return install_parameter;
1844 void ExtensionPrefs::SetInstallParam(const std::string& extension_id,
1845 const std::string& install_parameter) {
1846 UpdateExtensionPref(extension_id,
1847 kPrefInstallParam,
1848 new base::StringValue(install_parameter));
1851 int ExtensionPrefs::GetCorruptedDisableCount() {
1852 return prefs_->GetInteger(kCorruptedDisableCount);
1855 void ExtensionPrefs::IncrementCorruptedDisableCount() {
1856 int count = prefs_->GetInteger(kCorruptedDisableCount);
1857 prefs_->SetInteger(kCorruptedDisableCount, count + 1);
1860 ExtensionPrefs::ExtensionPrefs(
1861 PrefService* prefs,
1862 const base::FilePath& root_dir,
1863 ExtensionPrefValueMap* extension_pref_value_map,
1864 scoped_ptr<AppSorting> app_sorting,
1865 scoped_ptr<TimeProvider> time_provider,
1866 bool extensions_disabled,
1867 const std::vector<ExtensionPrefsObserver*>& early_observers)
1868 : prefs_(prefs),
1869 install_directory_(root_dir),
1870 extension_pref_value_map_(extension_pref_value_map),
1871 app_sorting_(app_sorting.Pass()),
1872 time_provider_(time_provider.Pass()),
1873 extensions_disabled_(extensions_disabled) {
1874 app_sorting_->SetExtensionScopedPrefs(this);
1875 MakePathsRelative();
1877 // Ensure that any early observers are watching before prefs are initialized.
1878 for (std::vector<ExtensionPrefsObserver*>::const_iterator iter =
1879 early_observers.begin();
1880 iter != early_observers.end();
1881 ++iter) {
1882 AddObserver(*iter);
1885 InitPrefStore();
1888 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1889 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1892 bool ExtensionPrefs::NeedsStorageGarbageCollection() {
1893 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1896 // static
1897 void ExtensionPrefs::RegisterProfilePrefs(
1898 user_prefs::PrefRegistrySyncable* registry) {
1899 registry->RegisterDictionaryPref(
1900 pref_names::kExtensions,
1901 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1902 registry->RegisterListPref(pref_names::kToolbar,
1903 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1904 registry->RegisterIntegerPref(
1905 pref_names::kToolbarSize,
1906 -1, // default value
1907 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1908 registry->RegisterDictionaryPref(
1909 kExtensionsBlacklistUpdate,
1910 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1911 registry->RegisterListPref(pref_names::kInstallAllowList,
1912 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1913 registry->RegisterListPref(pref_names::kInstallDenyList,
1914 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1915 registry->RegisterDictionaryPref(
1916 pref_names::kInstallForceList,
1917 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1918 registry->RegisterListPref(pref_names::kAllowedTypes,
1919 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1920 registry->RegisterBooleanPref(
1921 pref_names::kStorageGarbageCollect,
1922 false, // default value
1923 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1924 registry->RegisterInt64Pref(
1925 pref_names::kLastUpdateCheck,
1926 0, // default value
1927 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1928 registry->RegisterInt64Pref(
1929 pref_names::kNextUpdateCheck,
1930 0, // default value
1931 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1932 registry->RegisterListPref(pref_names::kAllowedInstallSites,
1933 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1934 registry->RegisterStringPref(
1935 pref_names::kLastChromeVersion,
1936 std::string(), // default value
1937 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1938 registry->RegisterDictionaryPref(
1939 kInstallSignature,
1940 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1942 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist,
1943 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1944 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist,
1945 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1946 registry->RegisterBooleanPref(
1947 pref_names::kNativeMessagingUserLevelHosts,
1948 true, // default value
1949 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1950 registry->RegisterIntegerPref(
1951 kCorruptedDisableCount,
1952 0, // default value
1953 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1955 #if !defined(OS_MACOSX)
1956 registry->RegisterBooleanPref(
1957 pref_names::kAppFullscreenAllowed, true,
1958 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1959 #endif
1962 template <class ExtensionIdContainer>
1963 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
1964 const char* pref,
1965 ExtensionIdContainer* id_container_out) {
1966 DCHECK(id_container_out->empty());
1968 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
1969 const base::ListValue* user_pref_as_list;
1970 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
1971 return false;
1973 std::insert_iterator<ExtensionIdContainer> insert_iterator(
1974 *id_container_out, id_container_out->end());
1975 std::string extension_id;
1976 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
1977 value_it != user_pref_as_list->end(); ++value_it) {
1978 if (!(*value_it)->GetAsString(&extension_id)) {
1979 NOTREACHED();
1980 continue;
1982 insert_iterator = extension_id;
1984 return true;
1987 template <class ExtensionIdContainer>
1988 void ExtensionPrefs::SetExtensionPrefFromContainer(
1989 const char* pref,
1990 const ExtensionIdContainer& strings) {
1991 ListPrefUpdate update(prefs_, pref);
1992 base::ListValue* list_of_values = update.Get();
1993 list_of_values->Clear();
1994 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
1995 iter != strings.end(); ++iter) {
1996 list_of_values->Append(new base::StringValue(*iter));
2000 void ExtensionPrefs::PopulateExtensionInfoPrefs(
2001 const Extension* extension,
2002 const base::Time install_time,
2003 Extension::State initial_state,
2004 int install_flags,
2005 const std::string& install_parameter,
2006 base::DictionaryValue* extension_dict) {
2007 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
2008 extension_dict->Set(kPrefLocation,
2009 new base::FundamentalValue(extension->location()));
2010 extension_dict->Set(kPrefCreationFlags,
2011 new base::FundamentalValue(extension->creation_flags()));
2012 extension_dict->Set(kPrefFromWebStore,
2013 new base::FundamentalValue(extension->from_webstore()));
2014 extension_dict->Set(kPrefFromBookmark,
2015 new base::FundamentalValue(extension->from_bookmark()));
2016 extension_dict->Set(
2017 kPrefWasInstalledByDefault,
2018 new base::FundamentalValue(extension->was_installed_by_default()));
2019 extension_dict->Set(
2020 kPrefWasInstalledByOem,
2021 new base::FundamentalValue(extension->was_installed_by_oem()));
2022 extension_dict->Set(kPrefInstallTime,
2023 new base::StringValue(
2024 base::Int64ToString(install_time.ToInternalValue())));
2025 if (install_flags & kInstallFlagIsBlacklistedForMalware)
2026 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
2028 if (install_flags & kInstallFlagIsEphemeral)
2029 extension_dict->Set(kPrefEphemeralApp, new base::FundamentalValue(true));
2030 else
2031 extension_dict->Remove(kPrefEphemeralApp, NULL);
2033 base::FilePath::StringType path = MakePathRelative(install_directory_,
2034 extension->path());
2035 extension_dict->Set(kPrefPath, new base::StringValue(path));
2036 if (!install_parameter.empty()) {
2037 extension_dict->Set(kPrefInstallParam,
2038 new base::StringValue(install_parameter));
2040 // We store prefs about LOAD extensions, but don't cache their manifest
2041 // since it may change on disk.
2042 if (!Manifest::IsUnpackedLocation(extension->location())) {
2043 extension_dict->Set(kPrefManifest,
2044 extension->manifest()->value()->DeepCopy());
2047 // Only writes kPrefDoNotSync when it is not the default.
2048 if (install_flags & kInstallFlagDoNotSync)
2049 extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true));
2050 else
2051 extension_dict->Remove(kPrefDoNotSync, NULL);
2054 void ExtensionPrefs::InitExtensionControlledPrefs(
2055 ExtensionPrefValueMap* value_map) {
2056 TRACE_EVENT0("browser,startup",
2057 "ExtensionPrefs::InitExtensionControlledPrefs")
2058 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitExtensionControlledPrefsTime");
2060 ExtensionIdList extension_ids;
2061 GetExtensions(&extension_ids);
2063 for (ExtensionIdList::iterator extension_id = extension_ids.begin();
2064 extension_id != extension_ids.end();
2065 ++extension_id) {
2066 base::Time install_time = GetInstallTime(*extension_id);
2067 bool is_enabled = !IsExtensionDisabled(*extension_id);
2068 bool is_incognito_enabled = IsIncognitoEnabled(*extension_id);
2069 value_map->RegisterExtension(
2070 *extension_id, install_time, is_enabled, is_incognito_enabled);
2072 FOR_EACH_OBSERVER(
2073 ExtensionPrefsObserver,
2074 observer_list_,
2075 OnExtensionRegistered(*extension_id, install_time, is_enabled));
2077 // Set regular extension controlled prefs.
2078 LoadExtensionControlledPrefs(
2079 this, value_map, *extension_id, kExtensionPrefsScopeRegular);
2080 // Set incognito extension controlled prefs.
2081 LoadExtensionControlledPrefs(this,
2082 value_map,
2083 *extension_id,
2084 kExtensionPrefsScopeIncognitoPersistent);
2085 // Set regular-only extension controlled prefs.
2086 LoadExtensionControlledPrefs(
2087 this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly);
2089 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
2090 observer_list_,
2091 OnExtensionPrefsLoaded(*extension_id, this));
2095 void ExtensionPrefs::FinishExtensionInfoPrefs(
2096 const std::string& extension_id,
2097 const base::Time install_time,
2098 bool needs_sort_ordinal,
2099 const syncer::StringOrdinal& suggested_page_ordinal,
2100 base::DictionaryValue* extension_dict) {
2101 // Reinitializes various preferences with empty dictionaries.
2102 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
2103 extension_dict->Set(pref_names::kPrefPreferences,
2104 new base::DictionaryValue);
2107 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
2108 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
2109 new base::DictionaryValue);
2112 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
2113 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
2114 new base::DictionaryValue);
2117 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
2118 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
2120 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
2121 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
2122 new base::ListValue);
2125 // If this point has been reached, any pending installs should be considered
2126 // out of date.
2127 extension_dict->Remove(kDelayedInstallInfo, NULL);
2129 // Clear state that may be registered from a previous install.
2130 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
2132 // FYI, all code below here races on sudden shutdown because |extension_dict|,
2133 // |app_sorting_|, |extension_pref_value_map_|, and (potentially) observers
2134 // are updated non-transactionally. This is probably not fixable without
2135 // nested transactional updates to pref dictionaries.
2136 if (needs_sort_ordinal)
2137 app_sorting_->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
2139 bool is_enabled = false;
2140 int initial_state;
2141 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
2142 is_enabled = initial_state == Extension::ENABLED;
2144 bool is_incognito_enabled = IsIncognitoEnabled(extension_id);
2146 extension_pref_value_map_->RegisterExtension(
2147 extension_id, install_time, is_enabled, is_incognito_enabled);
2149 FOR_EACH_OBSERVER(
2150 ExtensionPrefsObserver,
2151 observer_list_,
2152 OnExtensionRegistered(extension_id, install_time, is_enabled));
2155 } // namespace extensions