Add ICU message format support
[chromium-blink-merge.git] / extensions / browser / extension_prefs.cc
blobe4114d72fe3e04ab9fff89473ada0e7752168cbb
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/extension_system.h"
25 #include "extensions/browser/install_flag.h"
26 #include "extensions/browser/pref_names.h"
27 #include "extensions/common/feature_switch.h"
28 #include "extensions/common/manifest.h"
29 #include "extensions/common/permissions/permission_set.h"
30 #include "extensions/common/permissions/permissions_info.h"
31 #include "extensions/common/url_pattern.h"
32 #include "extensions/common/user_script.h"
33 #include "ui/base/l10n/l10n_util.h"
35 using base::Value;
36 using base::DictionaryValue;
37 using base::ListValue;
39 namespace extensions {
41 namespace {
43 // Additional preferences keys, which are not needed by external clients.
45 // True if this extension is running. Note this preference stops getting updated
46 // during Chrome shutdown (and won't be updated on a browser crash) and so can
47 // be used at startup to determine whether the extension was running when Chrome
48 // was last terminated.
49 const char kPrefRunning[] = "running";
51 // Whether this extension had windows when it was last running.
52 const char kIsActive[] = "is_active";
54 // Where an extension was installed from. (see Manifest::Location)
55 const char kPrefLocation[] = "location";
57 // Enabled, disabled, killed, etc. (see Extension::State)
58 const char kPrefState[] = "state";
60 // The path to the current version's manifest file.
61 const char kPrefPath[] = "path";
63 // The dictionary containing the extension's manifest.
64 const char kPrefManifest[] = "manifest";
66 // The version number.
67 const char kPrefVersion[] = "manifest.version";
69 // Indicates whether an extension is blacklisted.
70 const char kPrefBlacklist[] = "blacklist";
72 // If extension is greylisted.
73 const char kPrefBlacklistState[] = "blacklist_state";
75 // The count of how many times we prompted the user to acknowledge an
76 // extension.
77 const char kPrefAcknowledgePromptCount[] = "ack_prompt_count";
79 // Indicates whether the user has acknowledged various types of extensions.
80 const char kPrefExternalAcknowledged[] = "ack_external";
81 const char kPrefBlacklistAcknowledged[] = "ack_blacklist";
83 // Indicates whether the external extension was installed during the first
84 // run of this profile.
85 const char kPrefExternalInstallFirstRun[] = "external_first_run";
87 // DO NOT USE, use kPrefDisableReasons instead.
88 // Indicates whether the extension was updated while it was disabled.
89 const char kDeprecatedPrefDisableReason[] = "disable_reason";
91 // A bitmask of all the reasons an extension is disabled.
92 const char kPrefDisableReasons[] = "disable_reasons";
94 // The key for a serialized Time value indicating the start of the day (from the
95 // server's perspective) an extension last included a "ping" parameter during
96 // its update check.
97 const char kLastPingDay[] = "lastpingday";
99 // Similar to kLastPingDay, but for "active" instead of "rollcall" pings.
100 const char kLastActivePingDay[] = "last_active_pingday";
102 // A bit we use to keep track of whether we need to do an "active" ping.
103 const char kActiveBit[] = "active_bit";
105 // Path for settings specific to blacklist update.
106 const char kExtensionsBlacklistUpdate[] = "extensions.blacklistupdate";
108 // Path for the delayed install info dictionary preference. The actual string
109 // value is a legacy artifact for when delayed installs only pertained to
110 // updates that were waiting for idle.
111 const char kDelayedInstallInfo[] = "idle_install_info";
113 // Reason why the extension's install was delayed.
114 const char kDelayedInstallReason[] = "delay_install_reason";
116 // Path for the suggested page ordinal of a delayed extension install.
117 const char kPrefSuggestedPageOrdinal[] = "suggested_page_ordinal";
119 // A preference that, if true, will allow this extension to run in incognito
120 // mode.
121 const char kPrefIncognitoEnabled[] = "incognito";
123 // A preference to control whether an extension is allowed to inject script in
124 // pages with file URLs.
125 const char kPrefAllowFileAccess[] = "newAllowFileAccess";
126 // TODO(jstritar): As part of fixing http://crbug.com/91577, we revoked all
127 // extension file access by renaming the pref. We should eventually clean up
128 // the old flag and possibly go back to that name.
129 // const char kPrefAllowFileAccessOld[] = "allowFileAccess";
131 // A preference specifying if the user dragged the app on the NTP.
132 const char kPrefUserDraggedApp[] = "user_dragged_app_ntp";
134 // Preferences that hold which permissions the user has granted the extension.
135 // We explicitly keep track of these so that extensions can contain unknown
136 // permissions, for backwards compatibility reasons, and we can still prompt
137 // the user to accept them once recognized. We store the active permission
138 // permissions because they may differ from those defined in the manifest.
139 const char kPrefActivePermissions[] = "active_permissions";
140 const char kPrefGrantedPermissions[] = "granted_permissions";
142 // The preference names for PermissionSet values.
143 const char kPrefAPIs[] = "api";
144 const char kPrefManifestPermissions[] = "manifest_permissions";
145 const char kPrefExplicitHosts[] = "explicit_host";
146 const char kPrefScriptableHosts[] = "scriptable_host";
148 // The preference names for the old granted permissions scheme.
149 const char kPrefOldGrantedFullAccess[] = "granted_permissions.full";
150 const char kPrefOldGrantedHosts[] = "granted_permissions.host";
151 const char kPrefOldGrantedAPIs[] = "granted_permissions.api";
153 // A preference that indicates when an extension was installed.
154 const char kPrefInstallTime[] = "install_time";
156 // A preference which saves the creation flags for extensions.
157 const char kPrefCreationFlags[] = "creation_flags";
159 // A preference that indicates whether the extension was installed from the
160 // Chrome Web Store.
161 const char kPrefFromWebStore[] = "from_webstore";
163 // A preference that indicates whether the extension was installed from a
164 // mock App created from a bookmark.
165 const char kPrefFromBookmark[] = "from_bookmark";
167 // A preference that indicates whether the extension was installed as a
168 // default app.
169 const char kPrefWasInstalledByDefault[] = "was_installed_by_default";
171 // A preference that indicates whether the extension was installed as an
172 // OEM app.
173 const char kPrefWasInstalledByOem[] = "was_installed_by_oem";
175 // Key for Geometry Cache preference.
176 const char kPrefGeometryCache[] = "geometry_cache";
178 // A preference that indicates when an extension is last launched.
179 const char kPrefLastLaunchTime[] = "last_launch_time";
181 // A preference indicating whether the extension is an ephemeral app.
182 const char kPrefEphemeralApp[] = "ephemeral_app";
184 // Am installation parameter bundled with an extension.
185 const char kPrefInstallParam[] = "install_parameter";
187 // A list of installed ids and a signature.
188 const char kInstallSignature[] = "extensions.install_signature";
190 // A boolean preference that indicates whether the extension should not be
191 // synced. Default value is false.
192 const char kPrefDoNotSync[] = "do_not_sync";
194 const char kCorruptedDisableCount[] = "extensions.corrupted_disable_count";
196 // A boolean preference that indicates whether the extension has local changes
197 // that need to be synced. Default value is false.
198 const char kPrefNeedsSync[] = "needs_sync";
200 // Provider of write access to a dictionary storing extension prefs.
201 class ScopedExtensionPrefUpdate : public DictionaryPrefUpdate {
202 public:
203 ScopedExtensionPrefUpdate(PrefService* service,
204 const std::string& extension_id) :
205 DictionaryPrefUpdate(service, pref_names::kExtensions),
206 extension_id_(extension_id) {}
208 ~ScopedExtensionPrefUpdate() override {}
210 // DictionaryPrefUpdate overrides:
211 base::DictionaryValue* Get() override {
212 base::DictionaryValue* dict = DictionaryPrefUpdate::Get();
213 base::DictionaryValue* extension = NULL;
214 if (!dict->GetDictionary(extension_id_, &extension)) {
215 // Extension pref does not exist, create it.
216 extension = new base::DictionaryValue();
217 dict->SetWithoutPathExpansion(extension_id_, extension);
219 return extension;
222 private:
223 const std::string extension_id_;
225 DISALLOW_COPY_AND_ASSIGN(ScopedExtensionPrefUpdate);
228 std::string JoinPrefs(const std::string& parent, const char* child) {
229 return parent + "." + child;
232 // Checks if kPrefBlacklist is set to true in the base::DictionaryValue.
233 // Return false if the value is false or kPrefBlacklist does not exist.
234 // This is used to decide if an extension is blacklisted.
235 bool IsBlacklistBitSet(const base::DictionaryValue* ext) {
236 bool bool_value;
237 return ext->GetBoolean(kPrefBlacklist, &bool_value) && bool_value;
240 void LoadExtensionControlledPrefs(ExtensionPrefs* prefs,
241 ExtensionPrefValueMap* value_map,
242 const std::string& extension_id,
243 ExtensionPrefsScope scope) {
244 std::string scope_string;
245 if (!pref_names::ScopeToPrefName(scope, &scope_string))
246 return;
247 std::string key = extension_id + "." + scope_string;
249 const base::DictionaryValue* source_dict =
250 prefs->pref_service()->GetDictionary(pref_names::kExtensions);
251 const base::DictionaryValue* preferences = NULL;
252 if (!source_dict->GetDictionary(key, &preferences))
253 return;
255 for (base::DictionaryValue::Iterator iter(*preferences); !iter.IsAtEnd();
256 iter.Advance()) {
257 value_map->SetExtensionPref(
258 extension_id, iter.key(), scope, iter.value().DeepCopy());
262 } // namespace
265 // TimeProvider
268 ExtensionPrefs::TimeProvider::TimeProvider() {
271 ExtensionPrefs::TimeProvider::~TimeProvider() {
274 base::Time ExtensionPrefs::TimeProvider::GetCurrentTime() const {
275 return base::Time::Now();
279 // ScopedUpdate
281 template <typename T, base::Value::Type type_enum_value>
282 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::ScopedUpdate(
283 ExtensionPrefs* prefs,
284 const std::string& extension_id,
285 const std::string& key)
286 : update_(prefs->pref_service(), pref_names::kExtensions),
287 extension_id_(extension_id),
288 key_(key) {
289 DCHECK(crx_file::id_util::IdIsValid(extension_id_));
292 template <typename T, base::Value::Type type_enum_value>
293 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::~ScopedUpdate() {
296 template <typename T, base::Value::Type type_enum_value>
297 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Get() {
298 base::DictionaryValue* dict = update_.Get();
299 base::DictionaryValue* extension = NULL;
300 base::Value* key_value = NULL;
301 if (!dict->GetDictionary(extension_id_, &extension) ||
302 !extension->Get(key_, &key_value)) {
303 return NULL;
305 return key_value->GetType() == type_enum_value ?
306 static_cast<T*>(key_value) :
307 NULL;
310 template <typename T, base::Value::Type type_enum_value>
311 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Create() {
312 base::DictionaryValue* dict = update_.Get();
313 base::DictionaryValue* extension = NULL;
314 base::Value* key_value = NULL;
315 T* value_as_t = NULL;
316 if (!dict->GetDictionary(extension_id_, &extension)) {
317 extension = new base::DictionaryValue;
318 dict->SetWithoutPathExpansion(extension_id_, extension);
320 if (!extension->Get(key_, &key_value)) {
321 value_as_t = new T;
322 extension->SetWithoutPathExpansion(key_, value_as_t);
323 } else {
324 CHECK(key_value->GetType() == type_enum_value);
325 value_as_t = static_cast<T*>(key_value);
327 return value_as_t;
330 // Explicit instantiations for Dictionary and List value types.
331 template class ExtensionPrefs::ScopedUpdate<base::DictionaryValue,
332 base::Value::TYPE_DICTIONARY>;
333 template class ExtensionPrefs::ScopedUpdate<base::ListValue,
334 base::Value::TYPE_LIST>;
337 // ExtensionPrefs
340 // static
341 ExtensionPrefs* ExtensionPrefs::Create(
342 content::BrowserContext* browser_context,
343 PrefService* prefs,
344 const base::FilePath& root_dir,
345 ExtensionPrefValueMap* extension_pref_value_map,
346 bool extensions_disabled,
347 const std::vector<ExtensionPrefsObserver*>& early_observers) {
348 return ExtensionPrefs::Create(browser_context, prefs, root_dir,
349 extension_pref_value_map, extensions_disabled,
350 early_observers,
351 make_scoped_ptr(new TimeProvider()));
354 // static
355 ExtensionPrefs* ExtensionPrefs::Create(
356 content::BrowserContext* browser_context,
357 PrefService* pref_service,
358 const base::FilePath& root_dir,
359 ExtensionPrefValueMap* extension_pref_value_map,
360 bool extensions_disabled,
361 const std::vector<ExtensionPrefsObserver*>& early_observers,
362 scoped_ptr<TimeProvider> time_provider) {
363 return new ExtensionPrefs(browser_context, pref_service, root_dir,
364 extension_pref_value_map, time_provider.Pass(),
365 extensions_disabled, early_observers);
368 ExtensionPrefs::~ExtensionPrefs() {
371 // static
372 ExtensionPrefs* ExtensionPrefs::Get(content::BrowserContext* context) {
373 return ExtensionPrefsFactory::GetInstance()->GetForBrowserContext(context);
376 static base::FilePath::StringType MakePathRelative(const base::FilePath& parent,
377 const base::FilePath& child) {
378 if (!parent.IsParent(child))
379 return child.value();
381 base::FilePath::StringType retval = child.value().substr(
382 parent.value().length());
383 if (base::FilePath::IsSeparator(retval[0]))
384 return retval.substr(1);
385 else
386 return retval;
389 void ExtensionPrefs::MakePathsRelative() {
390 const base::DictionaryValue* dict =
391 prefs_->GetDictionary(pref_names::kExtensions);
392 if (!dict || dict->empty())
393 return;
395 // Collect all extensions ids with absolute paths in |absolute_keys|.
396 std::set<std::string> absolute_keys;
397 for (base::DictionaryValue::Iterator i(*dict); !i.IsAtEnd(); i.Advance()) {
398 const base::DictionaryValue* extension_dict = NULL;
399 if (!i.value().GetAsDictionary(&extension_dict))
400 continue;
401 int location_value;
402 if (extension_dict->GetInteger(kPrefLocation, &location_value) &&
403 Manifest::IsUnpackedLocation(
404 static_cast<Manifest::Location>(location_value))) {
405 // Unpacked extensions can have absolute paths.
406 continue;
408 base::FilePath::StringType path_string;
409 if (!extension_dict->GetString(kPrefPath, &path_string))
410 continue;
411 base::FilePath path(path_string);
412 if (path.IsAbsolute())
413 absolute_keys.insert(i.key());
415 if (absolute_keys.empty())
416 return;
418 // Fix these paths.
419 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
420 base::DictionaryValue* update_dict = update.Get();
421 for (std::set<std::string>::iterator i = absolute_keys.begin();
422 i != absolute_keys.end(); ++i) {
423 base::DictionaryValue* extension_dict = NULL;
424 if (!update_dict->GetDictionaryWithoutPathExpansion(*i, &extension_dict)) {
425 NOTREACHED() << "Control should never reach here for extension " << *i;
426 continue;
428 base::FilePath::StringType path_string;
429 extension_dict->GetString(kPrefPath, &path_string);
430 base::FilePath path(path_string);
431 extension_dict->SetString(kPrefPath,
432 MakePathRelative(install_directory_, path));
436 const base::DictionaryValue* ExtensionPrefs::GetExtensionPref(
437 const std::string& extension_id) const {
438 const base::DictionaryValue* extensions =
439 prefs_->GetDictionary(pref_names::kExtensions);
440 const base::DictionaryValue* extension_dict = NULL;
441 if (!extensions ||
442 !extensions->GetDictionary(extension_id, &extension_dict)) {
443 return NULL;
445 return extension_dict;
448 void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id,
449 const std::string& key,
450 base::Value* data_value) {
451 if (!crx_file::id_util::IdIsValid(extension_id)) {
452 NOTREACHED() << "Invalid extension_id " << extension_id;
453 return;
455 ScopedExtensionPrefUpdate update(prefs_, extension_id);
456 if (data_value)
457 update->Set(key, data_value);
458 else
459 update->Remove(key, NULL);
462 void ExtensionPrefs::DeleteExtensionPrefs(const std::string& extension_id) {
463 extension_pref_value_map_->UnregisterExtension(extension_id);
464 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
465 observer_list_,
466 OnExtensionPrefsDeleted(extension_id));
467 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
468 base::DictionaryValue* dict = update.Get();
469 dict->Remove(extension_id, NULL);
472 bool ExtensionPrefs::ReadPrefAsBoolean(const std::string& extension_id,
473 const std::string& pref_key,
474 bool* out_value) const {
475 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
476 if (!ext || !ext->GetBoolean(pref_key, out_value))
477 return false;
479 return true;
482 bool ExtensionPrefs::ReadPrefAsInteger(const std::string& extension_id,
483 const std::string& pref_key,
484 int* out_value) const {
485 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
486 if (!ext || !ext->GetInteger(pref_key, out_value))
487 return false;
489 return true;
492 bool ExtensionPrefs::ReadPrefAsString(const std::string& extension_id,
493 const std::string& pref_key,
494 std::string* out_value) const {
495 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
496 if (!ext || !ext->GetString(pref_key, out_value))
497 return false;
499 return true;
502 bool ExtensionPrefs::ReadPrefAsList(const std::string& extension_id,
503 const std::string& pref_key,
504 const base::ListValue** out_value) const {
505 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
506 const base::ListValue* out = NULL;
507 if (!ext || !ext->GetList(pref_key, &out))
508 return false;
509 if (out_value)
510 *out_value = out;
512 return true;
515 bool ExtensionPrefs::ReadPrefAsDictionary(
516 const std::string& extension_id,
517 const std::string& pref_key,
518 const base::DictionaryValue** out_value) const {
519 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
520 const base::DictionaryValue* out = NULL;
521 if (!ext || !ext->GetDictionary(pref_key, &out))
522 return false;
523 if (out_value)
524 *out_value = out;
526 return true;
529 bool ExtensionPrefs::HasPrefForExtension(
530 const std::string& extension_id) const {
531 return GetExtensionPref(extension_id) != NULL;
534 bool ExtensionPrefs::ReadPrefAsURLPatternSet(const std::string& extension_id,
535 const std::string& pref_key,
536 URLPatternSet* result,
537 int valid_schemes) const {
538 const base::ListValue* value = NULL;
539 if (!ReadPrefAsList(extension_id, pref_key, &value))
540 return false;
541 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
542 if (!extension)
543 return false;
544 int location;
545 if (extension->GetInteger(kPrefLocation, &location) &&
546 static_cast<Manifest::Location>(location) == Manifest::COMPONENT) {
547 valid_schemes |= URLPattern::SCHEME_CHROMEUI;
550 bool allow_file_access = AllowFileAccess(extension_id);
551 return result->Populate(*value, valid_schemes, allow_file_access, NULL);
554 void ExtensionPrefs::SetExtensionPrefURLPatternSet(
555 const std::string& extension_id,
556 const std::string& pref_key,
557 const URLPatternSet& new_value) {
558 UpdateExtensionPref(extension_id, pref_key, new_value.ToValue().release());
561 bool ExtensionPrefs::ReadPrefAsBooleanAndReturn(
562 const std::string& extension_id,
563 const std::string& pref_key) const {
564 bool out_value = false;
565 return ReadPrefAsBoolean(extension_id, pref_key, &out_value) && out_value;
568 PermissionSet* ExtensionPrefs::ReadPrefAsPermissionSet(
569 const std::string& extension_id,
570 const std::string& pref_key) const {
571 if (!GetExtensionPref(extension_id))
572 return NULL;
574 // Retrieve the API permissions. Please refer SetExtensionPrefPermissionSet()
575 // for api_values format.
576 APIPermissionSet apis;
577 const base::ListValue* api_values = NULL;
578 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
579 if (ReadPrefAsList(extension_id, api_pref, &api_values)) {
580 APIPermissionSet::ParseFromJSON(api_values,
581 APIPermissionSet::kAllowInternalPermissions,
582 &apis, NULL, NULL);
585 // Retrieve the Manifest Keys permissions. Please refer to
586 // |SetExtensionPrefPermissionSet| for manifest_permissions_values format.
587 ManifestPermissionSet manifest_permissions;
588 const base::ListValue* manifest_permissions_values = NULL;
589 std::string manifest_permission_pref =
590 JoinPrefs(pref_key, kPrefManifestPermissions);
591 if (ReadPrefAsList(extension_id, manifest_permission_pref,
592 &manifest_permissions_values)) {
593 ManifestPermissionSet::ParseFromJSON(
594 manifest_permissions_values, &manifest_permissions, NULL, NULL);
597 // Retrieve the explicit host permissions.
598 URLPatternSet explicit_hosts;
599 ReadPrefAsURLPatternSet(
600 extension_id, JoinPrefs(pref_key, kPrefExplicitHosts),
601 &explicit_hosts, Extension::kValidHostPermissionSchemes);
603 // Retrieve the scriptable host permissions.
604 URLPatternSet scriptable_hosts;
605 ReadPrefAsURLPatternSet(
606 extension_id, JoinPrefs(pref_key, kPrefScriptableHosts),
607 &scriptable_hosts, UserScript::ValidUserScriptSchemes());
609 return new PermissionSet(
610 apis, manifest_permissions, explicit_hosts, scriptable_hosts);
613 // Set the API or Manifest permissions.
614 // The format of api_values is:
615 // [ "permission_name1", // permissions do not support detail.
616 // "permission_name2",
617 // {"permission_name3": value },
618 // // permission supports detail, permission detail will be stored in value.
619 // ...
620 // ]
621 template<typename T>
622 static base::ListValue* CreatePermissionList(const T& permissions) {
623 base::ListValue* values = new base::ListValue();
624 for (typename T::const_iterator i = permissions.begin();
625 i != permissions.end(); ++i) {
626 scoped_ptr<base::Value> detail(i->ToValue());
627 if (detail) {
628 base::DictionaryValue* tmp = new base::DictionaryValue();
629 tmp->Set(i->name(), detail.release());
630 values->Append(tmp);
631 } else {
632 values->Append(new base::StringValue(i->name()));
635 return values;
638 void ExtensionPrefs::SetExtensionPrefPermissionSet(
639 const std::string& extension_id,
640 const std::string& pref_key,
641 const PermissionSet* new_value) {
642 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
643 base::ListValue* api_values = CreatePermissionList(new_value->apis());
644 UpdateExtensionPref(extension_id, api_pref, api_values);
646 std::string manifest_permissions_pref =
647 JoinPrefs(pref_key, kPrefManifestPermissions);
648 base::ListValue* manifest_permissions_values = CreatePermissionList(
649 new_value->manifest_permissions());
650 UpdateExtensionPref(extension_id,
651 manifest_permissions_pref,
652 manifest_permissions_values);
654 // Set the explicit host permissions.
655 if (!new_value->explicit_hosts().is_empty()) {
656 SetExtensionPrefURLPatternSet(extension_id,
657 JoinPrefs(pref_key, kPrefExplicitHosts),
658 new_value->explicit_hosts());
661 // Set the scriptable host permissions.
662 if (!new_value->scriptable_hosts().is_empty()) {
663 SetExtensionPrefURLPatternSet(extension_id,
664 JoinPrefs(pref_key, kPrefScriptableHosts),
665 new_value->scriptable_hosts());
669 int ExtensionPrefs::IncrementAcknowledgePromptCount(
670 const std::string& extension_id) {
671 int count = 0;
672 ReadPrefAsInteger(extension_id, kPrefAcknowledgePromptCount, &count);
673 ++count;
674 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount,
675 new base::FundamentalValue(count));
676 return count;
679 bool ExtensionPrefs::IsExternalExtensionAcknowledged(
680 const std::string& extension_id) const {
681 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalAcknowledged);
684 void ExtensionPrefs::AcknowledgeExternalExtension(
685 const std::string& extension_id) {
686 DCHECK(crx_file::id_util::IdIsValid(extension_id));
687 UpdateExtensionPref(extension_id, kPrefExternalAcknowledged,
688 new base::FundamentalValue(true));
689 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
692 bool ExtensionPrefs::IsBlacklistedExtensionAcknowledged(
693 const std::string& extension_id) const {
694 return ReadPrefAsBooleanAndReturn(extension_id, kPrefBlacklistAcknowledged);
697 void ExtensionPrefs::AcknowledgeBlacklistedExtension(
698 const std::string& extension_id) {
699 DCHECK(crx_file::id_util::IdIsValid(extension_id));
700 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged,
701 new base::FundamentalValue(true));
702 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
705 bool ExtensionPrefs::IsExternalInstallFirstRun(
706 const std::string& extension_id) const {
707 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalInstallFirstRun);
710 void ExtensionPrefs::SetExternalInstallFirstRun(
711 const std::string& extension_id) {
712 DCHECK(crx_file::id_util::IdIsValid(extension_id));
713 UpdateExtensionPref(extension_id, kPrefExternalInstallFirstRun,
714 new base::FundamentalValue(true));
717 bool ExtensionPrefs::SetAlertSystemFirstRun() {
718 if (prefs_->GetBoolean(pref_names::kAlertsInitialized)) {
719 return true;
721 prefs_->SetBoolean(pref_names::kAlertsInitialized, true);
722 return false;
725 bool ExtensionPrefs::DidExtensionEscalatePermissions(
726 const std::string& extension_id) const {
727 return HasDisableReason(extension_id,
728 Extension::DISABLE_PERMISSIONS_INCREASE) ||
729 HasDisableReason(extension_id, Extension::DISABLE_REMOTE_INSTALL);
732 int ExtensionPrefs::GetDisableReasons(const std::string& extension_id) const {
733 int value = -1;
734 if (ReadPrefAsInteger(extension_id, kPrefDisableReasons, &value) &&
735 value >= 0) {
736 return value;
738 return Extension::DISABLE_NONE;
741 bool ExtensionPrefs::HasDisableReason(
742 const std::string& extension_id,
743 Extension::DisableReason disable_reason) const {
744 return (GetDisableReasons(extension_id) & disable_reason) != 0;
747 void ExtensionPrefs::AddDisableReason(const std::string& extension_id,
748 Extension::DisableReason disable_reason) {
749 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_ADD);
752 void ExtensionPrefs::AddDisableReasons(const std::string& extension_id,
753 int disable_reasons) {
754 ModifyDisableReasons(extension_id, disable_reasons, DISABLE_REASON_ADD);
757 void ExtensionPrefs::RemoveDisableReason(
758 const std::string& extension_id,
759 Extension::DisableReason disable_reason) {
760 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_REMOVE);
763 void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) {
764 ModifyDisableReasons(extension_id, Extension::DISABLE_NONE,
765 DISABLE_REASON_CLEAR);
768 void ExtensionPrefs::ModifyDisableReasons(const std::string& extension_id,
769 int reasons,
770 DisableReasonChange change) {
771 int old_value = GetDisableReasons(extension_id);
772 int new_value = old_value;
773 switch (change) {
774 case DISABLE_REASON_ADD:
775 new_value |= reasons;
776 break;
777 case DISABLE_REASON_REMOVE:
778 new_value &= ~reasons;
779 break;
780 case DISABLE_REASON_CLEAR:
781 new_value = Extension::DISABLE_NONE;
782 break;
785 if (old_value == new_value) // no change, return.
786 return;
788 if (new_value == Extension::DISABLE_NONE) {
789 UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
790 } else {
791 UpdateExtensionPref(extension_id,
792 kPrefDisableReasons,
793 new base::FundamentalValue(new_value));
796 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
797 observer_list_,
798 OnExtensionDisableReasonsChanged(extension_id, new_value));
801 std::set<std::string> ExtensionPrefs::GetBlacklistedExtensions() const {
802 std::set<std::string> ids;
804 const base::DictionaryValue* extensions =
805 prefs_->GetDictionary(pref_names::kExtensions);
806 if (!extensions)
807 return ids;
809 for (base::DictionaryValue::Iterator it(*extensions);
810 !it.IsAtEnd(); it.Advance()) {
811 if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) {
812 NOTREACHED() << "Invalid pref for extension " << it.key();
813 continue;
815 if (IsBlacklistBitSet(
816 static_cast<const base::DictionaryValue*>(&it.value()))) {
817 ids.insert(it.key());
821 return ids;
824 void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id,
825 bool is_blacklisted) {
826 bool currently_blacklisted = IsExtensionBlacklisted(extension_id);
827 if (is_blacklisted == currently_blacklisted)
828 return;
830 // Always make sure the "acknowledged" bit is cleared since the blacklist bit
831 // is changing.
832 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL);
834 if (is_blacklisted) {
835 UpdateExtensionPref(extension_id,
836 kPrefBlacklist,
837 new base::FundamentalValue(true));
838 } else {
839 UpdateExtensionPref(extension_id, kPrefBlacklist, NULL);
840 const base::DictionaryValue* dict = GetExtensionPref(extension_id);
841 if (dict && dict->empty())
842 DeleteExtensionPrefs(extension_id);
846 bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const {
847 const base::DictionaryValue* ext_prefs = GetExtensionPref(id);
848 return ext_prefs && IsBlacklistBitSet(ext_prefs);
851 namespace {
853 // Serializes a 64bit integer as a string value.
854 void SaveInt64(base::DictionaryValue* dictionary,
855 const char* key,
856 const int64 value) {
857 if (!dictionary)
858 return;
860 std::string string_value = base::Int64ToString(value);
861 dictionary->SetString(key, string_value);
864 // Deserializes a 64bit integer stored as a string value.
865 bool ReadInt64(const base::DictionaryValue* dictionary,
866 const char* key,
867 int64* value) {
868 if (!dictionary)
869 return false;
871 std::string string_value;
872 if (!dictionary->GetString(key, &string_value))
873 return false;
875 return base::StringToInt64(string_value, value);
878 // Serializes |time| as a string value mapped to |key| in |dictionary|.
879 void SaveTime(base::DictionaryValue* dictionary,
880 const char* key,
881 const base::Time& time) {
882 SaveInt64(dictionary, key, time.ToInternalValue());
885 // The opposite of SaveTime. If |key| is not found, this returns an empty Time
886 // (is_null() will return true).
887 base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) {
888 int64 value;
889 if (ReadInt64(dictionary, key, &value))
890 return base::Time::FromInternalValue(value);
892 return base::Time();
895 } // namespace
897 base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const {
898 DCHECK(crx_file::id_util::IdIsValid(extension_id));
899 return ReadTime(GetExtensionPref(extension_id), kLastPingDay);
902 void ExtensionPrefs::SetLastPingDay(const std::string& extension_id,
903 const base::Time& time) {
904 DCHECK(crx_file::id_util::IdIsValid(extension_id));
905 ScopedExtensionPrefUpdate update(prefs_, extension_id);
906 SaveTime(update.Get(), kLastPingDay, time);
909 base::Time ExtensionPrefs::BlacklistLastPingDay() const {
910 return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate),
911 kLastPingDay);
914 void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) {
915 DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate);
916 SaveTime(update.Get(), kLastPingDay, time);
919 base::Time ExtensionPrefs::LastActivePingDay(
920 const std::string& extension_id) const {
921 DCHECK(crx_file::id_util::IdIsValid(extension_id));
922 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
925 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
926 const base::Time& time) {
927 DCHECK(crx_file::id_util::IdIsValid(extension_id));
928 ScopedExtensionPrefUpdate update(prefs_, extension_id);
929 SaveTime(update.Get(), kLastActivePingDay, time);
932 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) const {
933 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
934 bool result = false;
935 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
936 return result;
937 return false;
940 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
941 bool active) {
942 UpdateExtensionPref(extension_id, kActiveBit,
943 new base::FundamentalValue(active));
946 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
947 PermissionsInfo* info = PermissionsInfo::GetInstance();
948 for (ExtensionIdList::const_iterator ext_id =
949 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
950 // An extension's granted permissions need to be migrated if the
951 // full_access bit is present. This bit was always present in the previous
952 // scheme and is never present now.
953 bool full_access = false;
954 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
955 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
956 continue;
958 // Remove the full access bit (empty list will get trimmed).
959 UpdateExtensionPref(
960 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
962 // Add the plugin permission if the full access bit was set.
963 if (full_access) {
964 const base::ListValue* apis = NULL;
965 base::ListValue* new_apis = NULL;
967 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
968 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
969 new_apis = apis->DeepCopy();
970 else
971 new_apis = new base::ListValue();
973 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
974 new_apis->Append(new base::StringValue(plugin_name));
975 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
978 // The granted permissions originally only held the effective hosts,
979 // which are a combination of host and user script host permissions.
980 // We now maintain these lists separately. For migration purposes, it
981 // does not matter how we treat the old effective hosts as long as the
982 // new effective hosts will be the same, so we move them to explicit
983 // host permissions.
984 const base::ListValue* hosts = NULL;
985 std::string explicit_hosts =
986 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
987 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
988 UpdateExtensionPref(
989 *ext_id, explicit_hosts, hosts->DeepCopy());
991 // We can get rid of the old one by setting it to an empty list.
992 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
997 void ExtensionPrefs::MigrateDisableReasons(
998 const ExtensionIdList& extension_ids) {
999 for (ExtensionIdList::const_iterator ext_id =
1000 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
1001 int value = -1;
1002 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
1003 int new_value = Extension::DISABLE_NONE;
1004 switch (value) {
1005 case Extension::DEPRECATED_DISABLE_USER_ACTION:
1006 new_value = Extension::DISABLE_USER_ACTION;
1007 break;
1008 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
1009 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
1010 break;
1011 case Extension::DEPRECATED_DISABLE_RELOAD:
1012 new_value = Extension::DISABLE_RELOAD;
1013 break;
1016 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
1017 new base::FundamentalValue(new_value));
1018 // Remove the old disable reason.
1019 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
1024 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
1025 const std::string& extension_id) const {
1026 CHECK(crx_file::id_util::IdIsValid(extension_id));
1027 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
1030 void ExtensionPrefs::AddGrantedPermissions(
1031 const std::string& extension_id,
1032 const PermissionSet* permissions) {
1033 CHECK(crx_file::id_util::IdIsValid(extension_id));
1035 scoped_refptr<PermissionSet> granted_permissions(
1036 GetGrantedPermissions(extension_id));
1038 // The new granted permissions are the union of the already granted
1039 // permissions and the newly granted permissions.
1040 scoped_refptr<PermissionSet> new_perms(
1041 PermissionSet::CreateUnion(
1042 permissions, granted_permissions.get()));
1044 SetExtensionPrefPermissionSet(
1045 extension_id, kPrefGrantedPermissions, new_perms.get());
1048 void ExtensionPrefs::RemoveGrantedPermissions(
1049 const std::string& extension_id,
1050 const PermissionSet* permissions) {
1051 CHECK(crx_file::id_util::IdIsValid(extension_id));
1053 scoped_refptr<PermissionSet> granted_permissions(
1054 GetGrantedPermissions(extension_id));
1056 // The new granted permissions are the difference of the already granted
1057 // permissions and the newly ungranted permissions.
1058 scoped_refptr<PermissionSet> new_perms(
1059 PermissionSet::CreateDifference(
1060 granted_permissions.get(), permissions));
1062 SetExtensionPrefPermissionSet(
1063 extension_id, kPrefGrantedPermissions, new_perms.get());
1066 PermissionSet* ExtensionPrefs::GetActivePermissions(
1067 const std::string& extension_id) const {
1068 CHECK(crx_file::id_util::IdIsValid(extension_id));
1069 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
1072 void ExtensionPrefs::SetActivePermissions(
1073 const std::string& extension_id,
1074 const PermissionSet* permissions) {
1075 SetExtensionPrefPermissionSet(
1076 extension_id, kPrefActivePermissions, permissions);
1079 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1080 bool is_running) {
1081 base::Value* value = new base::FundamentalValue(is_running);
1082 UpdateExtensionPref(extension_id, kPrefRunning, value);
1085 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) const {
1086 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1087 if (!extension)
1088 return false;
1089 bool running = false;
1090 extension->GetBoolean(kPrefRunning, &running);
1091 return running;
1094 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1095 bool is_active) {
1096 base::Value* value = new base::FundamentalValue(is_active);
1097 UpdateExtensionPref(extension_id, kIsActive, value);
1100 bool ExtensionPrefs::IsActive(const std::string& extension_id) const {
1101 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1102 if (!extension)
1103 return false;
1104 bool is_active = false;
1105 extension->GetBoolean(kIsActive, &is_active);
1106 return is_active;
1109 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1110 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1113 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1114 bool enabled) {
1115 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1116 new base::FundamentalValue(enabled));
1117 extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled);
1120 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1121 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1124 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1125 bool allow) {
1126 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1127 new base::FundamentalValue(allow));
1130 bool ExtensionPrefs::HasAllowFileAccessSetting(
1131 const std::string& extension_id) const {
1132 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1133 return ext && ext->HasKey(kPrefAllowFileAccess);
1136 bool ExtensionPrefs::DoesExtensionHaveState(
1137 const std::string& id, Extension::State check_state) const {
1138 const base::DictionaryValue* extension = GetExtensionPref(id);
1139 int state = -1;
1140 if (!extension || !extension->GetInteger(kPrefState, &state))
1141 return false;
1143 if (state < 0 || state >= Extension::NUM_STATES) {
1144 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1145 return false;
1148 return state == check_state;
1151 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1152 const std::string& id) const {
1153 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1156 bool ExtensionPrefs::IsExtensionDisabled(
1157 const std::string& id) const {
1158 return DoesExtensionHaveState(id, Extension::DISABLED);
1161 ExtensionIdList ExtensionPrefs::GetToolbarOrder() const {
1162 ExtensionIdList id_list_out;
1163 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1164 return id_list_out;
1167 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1168 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1171 void ExtensionPrefs::OnExtensionInstalled(
1172 const Extension* extension,
1173 Extension::State initial_state,
1174 const syncer::StringOrdinal& page_ordinal,
1175 int install_flags,
1176 const std::string& install_parameter) {
1177 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1178 base::DictionaryValue* extension_dict = update.Get();
1179 const base::Time install_time = time_provider_->GetCurrentTime();
1180 PopulateExtensionInfoPrefs(extension,
1181 install_time,
1182 initial_state,
1183 install_flags,
1184 install_parameter,
1185 extension_dict);
1187 bool requires_sort_ordinal = extension->RequiresSortOrdinal() &&
1188 (install_flags & kInstallFlagIsEphemeral) == 0;
1189 FinishExtensionInfoPrefs(extension->id(),
1190 install_time,
1191 requires_sort_ordinal,
1192 page_ordinal,
1193 extension_dict);
1196 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1197 const Manifest::Location& location,
1198 bool external_uninstall) {
1199 app_sorting()->ClearOrdinals(extension_id);
1201 // For external extensions, we save a preference reminding ourself not to try
1202 // and install the extension anymore (except when |external_uninstall| is
1203 // true, which signifies that the registry key was deleted or the pref file
1204 // no longer lists the extension).
1205 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1206 UpdateExtensionPref(extension_id, kPrefState,
1207 new base::FundamentalValue(
1208 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1209 extension_pref_value_map_->SetExtensionState(extension_id, false);
1210 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1211 observer_list_,
1212 OnExtensionStateChanged(extension_id, false));
1213 } else {
1214 DeleteExtensionPrefs(extension_id);
1218 void ExtensionPrefs::SetExtensionState(const std::string& extension_id,
1219 Extension::State state) {
1220 UpdateExtensionPref(extension_id, kPrefState,
1221 new base::FundamentalValue(state));
1222 bool enabled = (state == Extension::ENABLED);
1223 extension_pref_value_map_->SetExtensionState(extension_id, enabled);
1224 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1225 observer_list_,
1226 OnExtensionStateChanged(extension_id, enabled));
1229 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1230 BlacklistState state) {
1231 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1232 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1233 new base::FundamentalValue(state));
1236 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1237 const std::string& extension_id) const {
1238 if (IsExtensionBlacklisted(extension_id))
1239 return BLACKLISTED_MALWARE;
1240 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1241 int int_value = 0;
1242 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1243 return static_cast<BlacklistState>(int_value);
1245 return NOT_BLACKLISTED;
1248 std::string ExtensionPrefs::GetVersionString(
1249 const std::string& extension_id) const {
1250 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1251 if (!extension)
1252 return std::string();
1254 std::string version;
1255 extension->GetString(kPrefVersion, &version);
1257 return version;
1260 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1261 if (!Manifest::IsUnpackedLocation(extension->location())) {
1262 const base::DictionaryValue* extension_dict =
1263 GetExtensionPref(extension->id());
1264 if (!extension_dict)
1265 return;
1266 const base::DictionaryValue* old_manifest = NULL;
1267 bool update_required =
1268 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1269 !extension->manifest()->value()->Equals(old_manifest);
1270 if (update_required) {
1271 UpdateExtensionPref(extension->id(), kPrefManifest,
1272 extension->manifest()->value()->DeepCopy());
1277 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1278 const std::string& extension_id,
1279 const base::DictionaryValue* extension) const {
1280 int location_value;
1281 if (!extension->GetInteger(kPrefLocation, &location_value))
1282 return scoped_ptr<ExtensionInfo>();
1284 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1285 if (location == Manifest::COMPONENT) {
1286 // Component extensions are ignored. Component extensions may have data
1287 // saved in preferences, but they are already loaded at this point (by
1288 // ComponentLoader) and shouldn't be populated into the result of
1289 // GetInstalledExtensionsInfo, otherwise InstalledLoader would also want to
1290 // load them.
1291 return scoped_ptr<ExtensionInfo>();
1294 // Only the following extension types have data saved in the preferences.
1295 if (location != Manifest::INTERNAL &&
1296 !Manifest::IsUnpackedLocation(location) &&
1297 !Manifest::IsExternalLocation(location)) {
1298 NOTREACHED();
1299 return scoped_ptr<ExtensionInfo>();
1302 const base::DictionaryValue* manifest = NULL;
1303 if (!Manifest::IsUnpackedLocation(location) &&
1304 !extension->GetDictionary(kPrefManifest, &manifest)) {
1305 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1306 // Just a warning for now.
1309 base::FilePath::StringType path;
1310 if (!extension->GetString(kPrefPath, &path))
1311 return scoped_ptr<ExtensionInfo>();
1313 // Make path absolute. Most (but not all) extension types have relative paths.
1314 if (!base::FilePath(path).IsAbsolute())
1315 path = install_directory_.Append(path).value();
1317 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1318 manifest, extension_id, base::FilePath(path), location));
1321 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1322 const std::string& extension_id) const {
1323 const base::DictionaryValue* ext = NULL;
1324 const base::DictionaryValue* extensions =
1325 prefs_->GetDictionary(pref_names::kExtensions);
1326 if (!extensions ||
1327 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1328 return scoped_ptr<ExtensionInfo>();
1329 int state_value;
1330 if (ext->GetInteger(kPrefState, &state_value) &&
1331 state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1332 LOG(WARNING) << "External extension with id " << extension_id
1333 << " has been uninstalled by the user";
1334 return scoped_ptr<ExtensionInfo>();
1337 return GetInstalledInfoHelper(extension_id, ext);
1340 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1341 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1342 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1344 const base::DictionaryValue* extensions =
1345 prefs_->GetDictionary(pref_names::kExtensions);
1346 for (base::DictionaryValue::Iterator extension_id(*extensions);
1347 !extension_id.IsAtEnd(); extension_id.Advance()) {
1348 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1349 continue;
1351 scoped_ptr<ExtensionInfo> info =
1352 GetInstalledExtensionInfo(extension_id.key());
1353 if (info)
1354 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1357 return extensions_info.Pass();
1360 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1361 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1362 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1364 const base::DictionaryValue* extensions =
1365 prefs_->GetDictionary(pref_names::kExtensions);
1366 for (base::DictionaryValue::Iterator extension_id(*extensions);
1367 !extension_id.IsAtEnd(); extension_id.Advance()) {
1368 const base::DictionaryValue* ext = NULL;
1369 if (!crx_file::id_util::IdIsValid(extension_id.key()) ||
1370 !IsExternalExtensionUninstalled(extension_id.key()) ||
1371 !extension_id.value().GetAsDictionary(&ext))
1372 continue;
1374 scoped_ptr<ExtensionInfo> info =
1375 GetInstalledInfoHelper(extension_id.key(), ext);
1376 if (info)
1377 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1380 return extensions_info.Pass();
1383 void ExtensionPrefs::SetDelayedInstallInfo(
1384 const Extension* extension,
1385 Extension::State initial_state,
1386 int install_flags,
1387 DelayReason delay_reason,
1388 const syncer::StringOrdinal& page_ordinal,
1389 const std::string& install_parameter) {
1390 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1391 PopulateExtensionInfoPrefs(extension,
1392 time_provider_->GetCurrentTime(),
1393 initial_state,
1394 install_flags,
1395 install_parameter,
1396 extension_dict);
1398 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1399 // should not be in the final extension prefs. All entries here should have
1400 // a corresponding Remove() call in FinishDelayedInstallInfo().
1401 if (extension->RequiresSortOrdinal() &&
1402 (install_flags & kInstallFlagIsEphemeral) == 0) {
1403 extension_dict->SetString(
1404 kPrefSuggestedPageOrdinal,
1405 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1406 : std::string());
1408 extension_dict->SetInteger(kDelayedInstallReason,
1409 static_cast<int>(delay_reason));
1411 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1414 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1415 const std::string& extension_id) {
1416 if (!GetExtensionPref(extension_id))
1417 return false;
1418 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1419 bool result = update->Remove(kDelayedInstallInfo, NULL);
1420 return result;
1423 bool ExtensionPrefs::FinishDelayedInstallInfo(
1424 const std::string& extension_id) {
1425 CHECK(crx_file::id_util::IdIsValid(extension_id));
1426 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1427 base::DictionaryValue* extension_dict = update.Get();
1428 base::DictionaryValue* pending_install_dict = NULL;
1429 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1430 &pending_install_dict)) {
1431 return false;
1434 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1435 // Also do any other data cleanup that makes sense.
1436 std::string serialized_ordinal;
1437 syncer::StringOrdinal suggested_page_ordinal;
1438 bool needs_sort_ordinal = false;
1439 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1440 &serialized_ordinal)) {
1441 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1442 needs_sort_ordinal = true;
1443 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1445 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1447 const base::Time install_time = time_provider_->GetCurrentTime();
1448 pending_install_dict->Set(
1449 kPrefInstallTime,
1450 new base::StringValue(
1451 base::Int64ToString(install_time.ToInternalValue())));
1453 // Some extension pref values are written conditionally. If they are not
1454 // present in the delayed install data, they should be removed when the
1455 // delayed install is committed.
1456 extension_dict->Remove(kPrefEphemeralApp, NULL);
1458 // Commit the delayed install data.
1459 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1460 it.Advance()) {
1461 extension_dict->Set(it.key(), it.value().DeepCopy());
1463 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1464 suggested_page_ordinal, extension_dict);
1465 return true;
1468 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1469 const std::string& extension_id) const {
1470 const base::DictionaryValue* extension_prefs =
1471 GetExtensionPref(extension_id);
1472 if (!extension_prefs)
1473 return scoped_ptr<ExtensionInfo>();
1475 const base::DictionaryValue* ext = NULL;
1476 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1477 return scoped_ptr<ExtensionInfo>();
1479 return GetInstalledInfoHelper(extension_id, ext);
1482 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1483 const std::string& extension_id) const {
1484 const base::DictionaryValue* extension_prefs =
1485 GetExtensionPref(extension_id);
1486 if (!extension_prefs)
1487 return DELAY_REASON_NONE;
1489 const base::DictionaryValue* ext = NULL;
1490 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1491 return DELAY_REASON_NONE;
1493 int delay_reason;
1494 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1495 return DELAY_REASON_NONE;
1497 return static_cast<DelayReason>(delay_reason);
1500 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1501 GetAllDelayedInstallInfo() const {
1502 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1504 const base::DictionaryValue* extensions =
1505 prefs_->GetDictionary(pref_names::kExtensions);
1506 for (base::DictionaryValue::Iterator extension_id(*extensions);
1507 !extension_id.IsAtEnd(); extension_id.Advance()) {
1508 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1509 continue;
1511 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1512 if (info)
1513 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1516 return extensions_info.Pass();
1519 bool ExtensionPrefs::IsEphemeralApp(const std::string& extension_id) const {
1520 if (ReadPrefAsBooleanAndReturn(extension_id, kPrefEphemeralApp))
1521 return true;
1523 // Ephemerality was previously stored in the creation flags, so we must also
1524 // check it for backcompatibility.
1525 return (GetCreationFlags(extension_id) & Extension::IS_EPHEMERAL) != 0;
1528 void ExtensionPrefs::OnEphemeralAppPromoted(const std::string& extension_id) {
1529 DCHECK(IsEphemeralApp(extension_id));
1531 UpdateExtensionPref(extension_id, kPrefEphemeralApp, NULL);
1533 // Ephemerality was previously stored in the creation flags, so ensure the bit
1534 // is cleared.
1535 int creation_flags = Extension::NO_FLAGS;
1536 if (ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1537 if (creation_flags & Extension::IS_EPHEMERAL) {
1538 creation_flags &= ~static_cast<int>(Extension::IS_EPHEMERAL);
1539 UpdateExtensionPref(extension_id,
1540 kPrefCreationFlags,
1541 new base::FundamentalValue(creation_flags));
1546 bool ExtensionPrefs::WasAppDraggedByUser(
1547 const std::string& extension_id) const {
1548 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1551 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1552 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1553 new base::FundamentalValue(true));
1556 bool ExtensionPrefs::IsFromWebStore(
1557 const std::string& extension_id) const {
1558 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1559 bool result = false;
1560 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1561 return result;
1562 return false;
1565 bool ExtensionPrefs::IsFromBookmark(
1566 const std::string& extension_id) const {
1567 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1568 bool result = false;
1569 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1570 return result;
1571 return false;
1574 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1575 int creation_flags = Extension::NO_FLAGS;
1576 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1577 // Since kPrefCreationFlags was added later, it will be missing for
1578 // previously installed extensions.
1579 if (IsFromBookmark(extension_id))
1580 creation_flags |= Extension::FROM_BOOKMARK;
1581 if (IsFromWebStore(extension_id))
1582 creation_flags |= Extension::FROM_WEBSTORE;
1583 if (WasInstalledByDefault(extension_id))
1584 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1585 if (WasInstalledByOem(extension_id))
1586 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
1588 return creation_flags;
1591 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1592 const std::string& extension_id) const {
1593 int creation_flags = Extension::NO_FLAGS;
1594 const base::DictionaryValue* delayed_info = NULL;
1595 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1596 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1598 return creation_flags;
1601 bool ExtensionPrefs::WasInstalledByDefault(
1602 const std::string& extension_id) const {
1603 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1604 bool result = false;
1605 if (dictionary &&
1606 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1607 return result;
1608 return false;
1611 bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const {
1612 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1613 bool result = false;
1614 if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result))
1615 return result;
1616 return false;
1619 base::Time ExtensionPrefs::GetInstallTime(
1620 const std::string& extension_id) const {
1621 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1622 if (!extension) {
1623 NOTREACHED();
1624 return base::Time();
1626 std::string install_time_str;
1627 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1628 return base::Time();
1629 int64 install_time_i64 = 0;
1630 if (!base::StringToInt64(install_time_str, &install_time_i64))
1631 return base::Time();
1632 return base::Time::FromInternalValue(install_time_i64);
1635 bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const {
1636 bool do_not_sync;
1637 if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync))
1638 return false;
1640 return do_not_sync;
1643 base::Time ExtensionPrefs::GetLastLaunchTime(
1644 const std::string& extension_id) const {
1645 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1646 if (!extension)
1647 return base::Time();
1649 std::string launch_time_str;
1650 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1651 return base::Time();
1652 int64 launch_time_i64 = 0;
1653 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1654 return base::Time();
1655 return base::Time::FromInternalValue(launch_time_i64);
1658 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1659 const base::Time& time) {
1660 DCHECK(crx_file::id_util::IdIsValid(extension_id));
1661 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1662 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1665 void ExtensionPrefs::ClearLastLaunchTimes() {
1666 const base::DictionaryValue* dict =
1667 prefs_->GetDictionary(pref_names::kExtensions);
1668 if (!dict || dict->empty())
1669 return;
1671 // Collect all the keys to remove the last launched preference from.
1672 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
1673 base::DictionaryValue* update_dict = update.Get();
1674 for (base::DictionaryValue::Iterator i(*update_dict); !i.IsAtEnd();
1675 i.Advance()) {
1676 base::DictionaryValue* extension_dict = NULL;
1677 if (!update_dict->GetDictionary(i.key(), &extension_dict))
1678 continue;
1680 if (extension_dict->HasKey(kPrefLastLaunchTime))
1681 extension_dict->Remove(kPrefLastLaunchTime, NULL);
1685 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) const {
1686 CHECK(out);
1688 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1690 for (size_t i = 0; i < extensions_info->size(); ++i) {
1691 ExtensionInfo* info = extensions_info->at(i).get();
1692 out->push_back(info->extension_id);
1696 // static
1697 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1698 const PrefService* pref_service) {
1699 ExtensionIdList result;
1701 const base::DictionaryValue* extension_prefs = NULL;
1702 const base::Value* extension_prefs_value =
1703 pref_service->GetUserPrefValue(pref_names::kExtensions);
1704 if (!extension_prefs_value ||
1705 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1706 return result; // Empty set
1709 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1710 it.Advance()) {
1711 const base::DictionaryValue* ext = NULL;
1712 if (!it.value().GetAsDictionary(&ext)) {
1713 NOTREACHED() << "Invalid pref for extension " << it.key();
1714 continue;
1716 if (!IsBlacklistBitSet(ext))
1717 result.push_back(it.key());
1719 return result;
1722 void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) {
1723 observer_list_.AddObserver(observer);
1726 void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) {
1727 observer_list_.RemoveObserver(observer);
1730 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1731 // Fix old entries that did not get an installation time entry when they
1732 // were installed or don't have a preferences field.
1733 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1734 ext_id != extension_ids.end(); ++ext_id) {
1735 if (GetInstallTime(*ext_id) == base::Time()) {
1736 VLOG(1) << "Could not parse installation time of extension "
1737 << *ext_id << ". It was probably installed before setting "
1738 << kPrefInstallTime << " was introduced. Updating "
1739 << kPrefInstallTime << " to the current time.";
1740 const base::Time install_time = time_provider_->GetCurrentTime();
1741 UpdateExtensionPref(*ext_id,
1742 kPrefInstallTime,
1743 new base::StringValue(base::Int64ToString(
1744 install_time.ToInternalValue())));
1749 void ExtensionPrefs::InitPrefStore() {
1750 TRACE_EVENT0("browser,startup", "ExtensionPrefs::InitPrefStore")
1751 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefStoreTime");
1753 if (extensions_disabled_) {
1754 extension_pref_value_map_->NotifyInitializationCompleted();
1755 return;
1758 // When this is called, the PrefService is initialized and provides access
1759 // to the user preferences stored in a JSON file.
1760 ExtensionIdList extension_ids;
1762 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefGetExtensionsTime");
1763 GetExtensions(&extension_ids);
1765 // Create empty preferences dictionary for each extension (these dictionaries
1766 // are pruned when persisting the preferences to disk).
1767 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1768 ext_id != extension_ids.end(); ++ext_id) {
1769 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1770 // This creates an empty dictionary if none is stored.
1771 update.Get();
1774 FixMissingPrefs(extension_ids);
1775 MigratePermissions(extension_ids);
1776 MigrateDisableReasons(extension_ids);
1778 InitExtensionControlledPrefs(extension_pref_value_map_);
1780 extension_pref_value_map_->NotifyInitializationCompleted();
1783 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) const {
1784 bool has_incognito_pref_value = false;
1785 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1786 true,
1787 &has_incognito_pref_value);
1788 return has_incognito_pref_value;
1791 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1792 const std::string& extension_id) const {
1793 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1794 if (!extension_prefs)
1795 return NULL;
1797 const base::DictionaryValue* ext = NULL;
1798 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1799 return NULL;
1801 return ext;
1804 void ExtensionPrefs::SetGeometryCache(
1805 const std::string& extension_id,
1806 scoped_ptr<base::DictionaryValue> cache) {
1807 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1810 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() const {
1811 return prefs_->GetDictionary(kInstallSignature);
1814 void ExtensionPrefs::SetInstallSignature(
1815 const base::DictionaryValue* signature) {
1816 if (signature) {
1817 prefs_->Set(kInstallSignature, *signature);
1818 DVLOG(1) << "SetInstallSignature - saving";
1819 } else {
1820 DVLOG(1) << "SetInstallSignature - clearing";
1821 prefs_->ClearPref(kInstallSignature);
1825 std::string ExtensionPrefs::GetInstallParam(
1826 const std::string& extension_id) const {
1827 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1828 if (!extension) // Expected during unit testing.
1829 return std::string();
1830 std::string install_parameter;
1831 if (!extension->GetString(kPrefInstallParam, &install_parameter))
1832 return std::string();
1833 return install_parameter;
1836 void ExtensionPrefs::SetInstallParam(const std::string& extension_id,
1837 const std::string& install_parameter) {
1838 UpdateExtensionPref(extension_id,
1839 kPrefInstallParam,
1840 new base::StringValue(install_parameter));
1843 int ExtensionPrefs::GetCorruptedDisableCount() const {
1844 return prefs_->GetInteger(kCorruptedDisableCount);
1847 void ExtensionPrefs::IncrementCorruptedDisableCount() {
1848 int count = prefs_->GetInteger(kCorruptedDisableCount);
1849 prefs_->SetInteger(kCorruptedDisableCount, count + 1);
1852 bool ExtensionPrefs::NeedsSync(const std::string& extension_id) const {
1853 return ReadPrefAsBooleanAndReturn(extension_id, kPrefNeedsSync);
1856 void ExtensionPrefs::SetNeedsSync(const std::string& extension_id,
1857 bool needs_sync) {
1858 UpdateExtensionPref(extension_id, kPrefNeedsSync,
1859 needs_sync ? new base::FundamentalValue(true) : nullptr);
1862 ExtensionPrefs::ExtensionPrefs(
1863 content::BrowserContext* browser_context,
1864 PrefService* prefs,
1865 const base::FilePath& root_dir,
1866 ExtensionPrefValueMap* extension_pref_value_map,
1867 scoped_ptr<TimeProvider> time_provider,
1868 bool extensions_disabled,
1869 const std::vector<ExtensionPrefsObserver*>& early_observers)
1870 : browser_context_(browser_context),
1871 prefs_(prefs),
1872 install_directory_(root_dir),
1873 extension_pref_value_map_(extension_pref_value_map),
1874 time_provider_(time_provider.Pass()),
1875 extensions_disabled_(extensions_disabled) {
1876 MakePathsRelative();
1878 // Ensure that any early observers are watching before prefs are initialized.
1879 for (std::vector<ExtensionPrefsObserver*>::const_iterator iter =
1880 early_observers.begin();
1881 iter != early_observers.end();
1882 ++iter) {
1883 AddObserver(*iter);
1886 InitPrefStore();
1889 AppSorting* ExtensionPrefs::app_sorting() const {
1890 return ExtensionSystem::Get(browser_context_)->app_sorting();
1893 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1894 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1897 bool ExtensionPrefs::NeedsStorageGarbageCollection() const {
1898 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1901 // static
1902 void ExtensionPrefs::RegisterProfilePrefs(
1903 user_prefs::PrefRegistrySyncable* registry) {
1904 registry->RegisterDictionaryPref(pref_names::kExtensions);
1905 registry->RegisterListPref(pref_names::kToolbar,
1906 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1907 registry->RegisterIntegerPref(pref_names::kToolbarSize, -1);
1908 registry->RegisterDictionaryPref(kExtensionsBlacklistUpdate);
1909 registry->RegisterListPref(pref_names::kInstallAllowList);
1910 registry->RegisterListPref(pref_names::kInstallDenyList);
1911 registry->RegisterDictionaryPref(pref_names::kInstallForceList);
1912 registry->RegisterListPref(pref_names::kAllowedTypes);
1913 registry->RegisterBooleanPref(pref_names::kStorageGarbageCollect, false);
1914 registry->RegisterInt64Pref(pref_names::kLastUpdateCheck, 0);
1915 registry->RegisterInt64Pref(pref_names::kNextUpdateCheck, 0);
1916 registry->RegisterListPref(pref_names::kAllowedInstallSites);
1917 registry->RegisterStringPref(pref_names::kLastChromeVersion, std::string());
1918 registry->RegisterDictionaryPref(kInstallSignature);
1920 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist);
1921 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist);
1922 registry->RegisterBooleanPref(pref_names::kNativeMessagingUserLevelHosts,
1923 true);
1924 registry->RegisterIntegerPref(kCorruptedDisableCount, 0);
1926 #if !defined(OS_MACOSX)
1927 registry->RegisterBooleanPref(pref_names::kAppFullscreenAllowed, true);
1928 #endif
1931 template <class ExtensionIdContainer>
1932 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
1933 const char* pref,
1934 ExtensionIdContainer* id_container_out) const {
1935 DCHECK(id_container_out->empty());
1937 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
1938 const base::ListValue* user_pref_as_list;
1939 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
1940 return false;
1942 std::insert_iterator<ExtensionIdContainer> insert_iterator(
1943 *id_container_out, id_container_out->end());
1944 std::string extension_id;
1945 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
1946 value_it != user_pref_as_list->end(); ++value_it) {
1947 if (!(*value_it)->GetAsString(&extension_id)) {
1948 NOTREACHED();
1949 continue;
1951 insert_iterator = extension_id;
1953 return true;
1956 template <class ExtensionIdContainer>
1957 void ExtensionPrefs::SetExtensionPrefFromContainer(
1958 const char* pref,
1959 const ExtensionIdContainer& strings) {
1960 ListPrefUpdate update(prefs_, pref);
1961 base::ListValue* list_of_values = update.Get();
1962 list_of_values->Clear();
1963 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
1964 iter != strings.end(); ++iter) {
1965 list_of_values->Append(new base::StringValue(*iter));
1969 void ExtensionPrefs::PopulateExtensionInfoPrefs(
1970 const Extension* extension,
1971 const base::Time install_time,
1972 Extension::State initial_state,
1973 int install_flags,
1974 const std::string& install_parameter,
1975 base::DictionaryValue* extension_dict) const {
1976 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
1977 extension_dict->Set(kPrefLocation,
1978 new base::FundamentalValue(extension->location()));
1979 extension_dict->Set(kPrefCreationFlags,
1980 new base::FundamentalValue(extension->creation_flags()));
1981 extension_dict->Set(kPrefFromWebStore,
1982 new base::FundamentalValue(extension->from_webstore()));
1983 extension_dict->Set(kPrefFromBookmark,
1984 new base::FundamentalValue(extension->from_bookmark()));
1985 extension_dict->Set(
1986 kPrefWasInstalledByDefault,
1987 new base::FundamentalValue(extension->was_installed_by_default()));
1988 extension_dict->Set(
1989 kPrefWasInstalledByOem,
1990 new base::FundamentalValue(extension->was_installed_by_oem()));
1991 extension_dict->Set(kPrefInstallTime,
1992 new base::StringValue(
1993 base::Int64ToString(install_time.ToInternalValue())));
1994 if (install_flags & kInstallFlagIsBlacklistedForMalware)
1995 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
1997 if (install_flags & kInstallFlagIsEphemeral)
1998 extension_dict->Set(kPrefEphemeralApp, new base::FundamentalValue(true));
1999 else
2000 extension_dict->Remove(kPrefEphemeralApp, NULL);
2002 base::FilePath::StringType path = MakePathRelative(install_directory_,
2003 extension->path());
2004 extension_dict->Set(kPrefPath, new base::StringValue(path));
2005 if (!install_parameter.empty()) {
2006 extension_dict->Set(kPrefInstallParam,
2007 new base::StringValue(install_parameter));
2009 // We store prefs about LOAD extensions, but don't cache their manifest
2010 // since it may change on disk.
2011 if (!Manifest::IsUnpackedLocation(extension->location())) {
2012 extension_dict->Set(kPrefManifest,
2013 extension->manifest()->value()->DeepCopy());
2016 // Only writes kPrefDoNotSync when it is not the default.
2017 if (install_flags & kInstallFlagDoNotSync)
2018 extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true));
2019 else
2020 extension_dict->Remove(kPrefDoNotSync, NULL);
2023 void ExtensionPrefs::InitExtensionControlledPrefs(
2024 ExtensionPrefValueMap* value_map) {
2025 TRACE_EVENT0("browser,startup",
2026 "ExtensionPrefs::InitExtensionControlledPrefs")
2027 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitExtensionControlledPrefsTime");
2029 ExtensionIdList extension_ids;
2030 GetExtensions(&extension_ids);
2032 for (ExtensionIdList::iterator extension_id = extension_ids.begin();
2033 extension_id != extension_ids.end();
2034 ++extension_id) {
2035 base::Time install_time = GetInstallTime(*extension_id);
2036 bool is_enabled = !IsExtensionDisabled(*extension_id);
2037 bool is_incognito_enabled = IsIncognitoEnabled(*extension_id);
2038 value_map->RegisterExtension(
2039 *extension_id, install_time, is_enabled, is_incognito_enabled);
2041 FOR_EACH_OBSERVER(
2042 ExtensionPrefsObserver,
2043 observer_list_,
2044 OnExtensionRegistered(*extension_id, install_time, is_enabled));
2046 // Set regular extension controlled prefs.
2047 LoadExtensionControlledPrefs(
2048 this, value_map, *extension_id, kExtensionPrefsScopeRegular);
2049 // Set incognito extension controlled prefs.
2050 LoadExtensionControlledPrefs(this,
2051 value_map,
2052 *extension_id,
2053 kExtensionPrefsScopeIncognitoPersistent);
2054 // Set regular-only extension controlled prefs.
2055 LoadExtensionControlledPrefs(
2056 this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly);
2058 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
2059 observer_list_,
2060 OnExtensionPrefsLoaded(*extension_id, this));
2064 void ExtensionPrefs::FinishExtensionInfoPrefs(
2065 const std::string& extension_id,
2066 const base::Time install_time,
2067 bool needs_sort_ordinal,
2068 const syncer::StringOrdinal& suggested_page_ordinal,
2069 base::DictionaryValue* extension_dict) {
2070 // Reinitializes various preferences with empty dictionaries.
2071 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
2072 extension_dict->Set(pref_names::kPrefPreferences,
2073 new base::DictionaryValue);
2076 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
2077 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
2078 new base::DictionaryValue);
2081 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
2082 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
2083 new base::DictionaryValue);
2086 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
2087 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
2089 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
2090 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
2091 new base::ListValue);
2094 // If this point has been reached, any pending installs should be considered
2095 // out of date.
2096 extension_dict->Remove(kDelayedInstallInfo, NULL);
2098 // Clear state that may be registered from a previous install.
2099 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
2101 // FYI, all code below here races on sudden shutdown because |extension_dict|,
2102 // |app_sorting|, |extension_pref_value_map_|, and (potentially) observers
2103 // are updated non-transactionally. This is probably not fixable without
2104 // nested transactional updates to pref dictionaries.
2105 if (needs_sort_ordinal)
2106 app_sorting()->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
2108 bool is_enabled = false;
2109 int initial_state;
2110 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
2111 is_enabled = initial_state == Extension::ENABLED;
2113 bool is_incognito_enabled = IsIncognitoEnabled(extension_id);
2115 extension_pref_value_map_->RegisterExtension(
2116 extension_id, install_time, is_enabled, is_incognito_enabled);
2118 FOR_EACH_OBSERVER(
2119 ExtensionPrefsObserver,
2120 observer_list_,
2121 OnExtensionRegistered(extension_id, install_time, is_enabled));
2124 } // namespace extensions