Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / extensions / browser / extension_prefs.cc
blob87ea7bcffdb2f02ea9e7533792d6e17ea644af20
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/browser/extension_prefs.h"
7 #include <iterator>
9 #include "base/command_line.h"
10 #include "base/prefs/pref_notifier.h"
11 #include "base/prefs/pref_service.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_util.h"
14 #include "base/value_conversions.h"
15 #include "components/crx_file/id_util.h"
16 #include "components/pref_registry/pref_registry_syncable.h"
17 #include "extensions/browser/app_sorting.h"
18 #include "extensions/browser/event_router.h"
19 #include "extensions/browser/extension_pref_store.h"
20 #include "extensions/browser/extension_prefs_factory.h"
21 #include "extensions/browser/extension_prefs_observer.h"
22 #include "extensions/browser/install_flag.h"
23 #include "extensions/browser/pref_names.h"
24 #include "extensions/common/feature_switch.h"
25 #include "extensions/common/manifest.h"
26 #include "extensions/common/permissions/permission_set.h"
27 #include "extensions/common/permissions/permissions_info.h"
28 #include "extensions/common/url_pattern.h"
29 #include "extensions/common/user_script.h"
30 #include "ui/base/l10n/l10n_util.h"
32 using base::Value;
33 using base::DictionaryValue;
34 using base::ListValue;
36 namespace extensions {
38 namespace {
40 // Additional preferences keys, which are not needed by external clients.
42 // True if this extension is running. Note this preference stops getting updated
43 // during Chrome shutdown (and won't be updated on a browser crash) and so can
44 // be used at startup to determine whether the extension was running when Chrome
45 // was last terminated.
46 const char kPrefRunning[] = "running";
48 // Whether this extension had windows when it was last running.
49 const char kIsActive[] = "is_active";
51 // Where an extension was installed from. (see Manifest::Location)
52 const char kPrefLocation[] = "location";
54 // Enabled, disabled, killed, etc. (see Extension::State)
55 const char kPrefState[] = "state";
57 // The path to the current version's manifest file.
58 const char kPrefPath[] = "path";
60 // The dictionary containing the extension's manifest.
61 const char kPrefManifest[] = "manifest";
63 // The version number.
64 const char kPrefVersion[] = "manifest.version";
66 // Indicates whether an extension is blacklisted.
67 const char kPrefBlacklist[] = "blacklist";
69 // If extension is greylisted.
70 const char kPrefBlacklistState[] = "blacklist_state";
72 // The count of how many times we prompted the user to acknowledge an
73 // extension.
74 const char kPrefAcknowledgePromptCount[] = "ack_prompt_count";
76 // Indicates whether the user has acknowledged various types of extensions.
77 const char kPrefExternalAcknowledged[] = "ack_external";
78 const char kPrefBlacklistAcknowledged[] = "ack_blacklist";
80 // Indicates whether the external extension was installed during the first
81 // run of this profile.
82 const char kPrefExternalInstallFirstRun[] = "external_first_run";
84 // Indicates whether to show an install warning when the user enables.
85 const char kExtensionDidEscalatePermissions[] = "install_warning_on_enable";
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 // Provider of write access to a dictionary storing extension prefs.
197 class ScopedExtensionPrefUpdate : public DictionaryPrefUpdate {
198 public:
199 ScopedExtensionPrefUpdate(PrefService* service,
200 const std::string& extension_id) :
201 DictionaryPrefUpdate(service, pref_names::kExtensions),
202 extension_id_(extension_id) {}
204 ~ScopedExtensionPrefUpdate() override {}
206 // DictionaryPrefUpdate overrides:
207 base::DictionaryValue* Get() override {
208 base::DictionaryValue* dict = DictionaryPrefUpdate::Get();
209 base::DictionaryValue* extension = NULL;
210 if (!dict->GetDictionary(extension_id_, &extension)) {
211 // Extension pref does not exist, create it.
212 extension = new base::DictionaryValue();
213 dict->SetWithoutPathExpansion(extension_id_, extension);
215 return extension;
218 private:
219 const std::string extension_id_;
221 DISALLOW_COPY_AND_ASSIGN(ScopedExtensionPrefUpdate);
224 std::string JoinPrefs(const std::string& parent, const char* child) {
225 return parent + "." + child;
228 // Checks if kPrefBlacklist is set to true in the base::DictionaryValue.
229 // Return false if the value is false or kPrefBlacklist does not exist.
230 // This is used to decide if an extension is blacklisted.
231 bool IsBlacklistBitSet(const base::DictionaryValue* ext) {
232 bool bool_value;
233 return ext->GetBoolean(kPrefBlacklist, &bool_value) && bool_value;
236 void LoadExtensionControlledPrefs(ExtensionPrefs* prefs,
237 ExtensionPrefValueMap* value_map,
238 const std::string& extension_id,
239 ExtensionPrefsScope scope) {
240 std::string scope_string;
241 if (!pref_names::ScopeToPrefName(scope, &scope_string))
242 return;
243 std::string key = extension_id + "." + scope_string;
245 const base::DictionaryValue* source_dict =
246 prefs->pref_service()->GetDictionary(pref_names::kExtensions);
247 const base::DictionaryValue* preferences = NULL;
248 if (!source_dict->GetDictionary(key, &preferences))
249 return;
251 for (base::DictionaryValue::Iterator iter(*preferences); !iter.IsAtEnd();
252 iter.Advance()) {
253 value_map->SetExtensionPref(
254 extension_id, iter.key(), scope, iter.value().DeepCopy());
258 } // namespace
261 // TimeProvider
264 ExtensionPrefs::TimeProvider::TimeProvider() {
267 ExtensionPrefs::TimeProvider::~TimeProvider() {
270 base::Time ExtensionPrefs::TimeProvider::GetCurrentTime() const {
271 return base::Time::Now();
275 // ScopedUpdate
277 template <typename T, base::Value::Type type_enum_value>
278 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::ScopedUpdate(
279 ExtensionPrefs* prefs,
280 const std::string& extension_id,
281 const std::string& key)
282 : update_(prefs->pref_service(), pref_names::kExtensions),
283 extension_id_(extension_id),
284 key_(key) {
285 DCHECK(crx_file::id_util::IdIsValid(extension_id_));
288 template <typename T, base::Value::Type type_enum_value>
289 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::~ScopedUpdate() {
292 template <typename T, base::Value::Type type_enum_value>
293 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Get() {
294 base::DictionaryValue* dict = update_.Get();
295 base::DictionaryValue* extension = NULL;
296 base::Value* key_value = NULL;
297 if (!dict->GetDictionary(extension_id_, &extension) ||
298 !extension->Get(key_, &key_value)) {
299 return NULL;
301 return key_value->GetType() == type_enum_value ?
302 static_cast<T*>(key_value) :
303 NULL;
306 template <typename T, base::Value::Type type_enum_value>
307 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Create() {
308 base::DictionaryValue* dict = update_.Get();
309 base::DictionaryValue* extension = NULL;
310 base::Value* key_value = NULL;
311 T* value_as_t = NULL;
312 if (!dict->GetDictionary(extension_id_, &extension)) {
313 extension = new base::DictionaryValue;
314 dict->SetWithoutPathExpansion(extension_id_, extension);
316 if (!extension->Get(key_, &key_value)) {
317 value_as_t = new T;
318 extension->SetWithoutPathExpansion(key_, value_as_t);
319 } else {
320 CHECK(key_value->GetType() == type_enum_value);
321 value_as_t = static_cast<T*>(key_value);
323 return value_as_t;
326 // Explicit instantiations for Dictionary and List value types.
327 template class ExtensionPrefs::ScopedUpdate<base::DictionaryValue,
328 base::Value::TYPE_DICTIONARY>;
329 template class ExtensionPrefs::ScopedUpdate<base::ListValue,
330 base::Value::TYPE_LIST>;
333 // ExtensionPrefs
336 // static
337 ExtensionPrefs* ExtensionPrefs::Create(
338 PrefService* prefs,
339 const base::FilePath& root_dir,
340 ExtensionPrefValueMap* extension_pref_value_map,
341 scoped_ptr<AppSorting> app_sorting,
342 bool extensions_disabled,
343 const std::vector<ExtensionPrefsObserver*>& early_observers) {
344 return ExtensionPrefs::Create(prefs,
345 root_dir,
346 extension_pref_value_map,
347 app_sorting.Pass(),
348 extensions_disabled,
349 early_observers,
350 make_scoped_ptr(new TimeProvider()));
353 // static
354 ExtensionPrefs* ExtensionPrefs::Create(
355 PrefService* pref_service,
356 const base::FilePath& root_dir,
357 ExtensionPrefValueMap* extension_pref_value_map,
358 scoped_ptr<AppSorting> app_sorting,
359 bool extensions_disabled,
360 const std::vector<ExtensionPrefsObserver*>& early_observers,
361 scoped_ptr<TimeProvider> time_provider) {
362 return new ExtensionPrefs(pref_service,
363 root_dir,
364 extension_pref_value_map,
365 app_sorting.Pass(),
366 time_provider.Pass(),
367 extensions_disabled,
368 early_observers);
371 ExtensionPrefs::~ExtensionPrefs() {
374 // static
375 ExtensionPrefs* ExtensionPrefs::Get(content::BrowserContext* context) {
376 return ExtensionPrefsFactory::GetInstance()->GetForBrowserContext(context);
379 static base::FilePath::StringType MakePathRelative(const base::FilePath& parent,
380 const base::FilePath& child) {
381 if (!parent.IsParent(child))
382 return child.value();
384 base::FilePath::StringType retval = child.value().substr(
385 parent.value().length());
386 if (base::FilePath::IsSeparator(retval[0]))
387 return retval.substr(1);
388 else
389 return retval;
392 void ExtensionPrefs::MakePathsRelative() {
393 const base::DictionaryValue* dict =
394 prefs_->GetDictionary(pref_names::kExtensions);
395 if (!dict || dict->empty())
396 return;
398 // Collect all extensions ids with absolute paths in |absolute_keys|.
399 std::set<std::string> absolute_keys;
400 for (base::DictionaryValue::Iterator i(*dict); !i.IsAtEnd(); i.Advance()) {
401 const base::DictionaryValue* extension_dict = NULL;
402 if (!i.value().GetAsDictionary(&extension_dict))
403 continue;
404 int location_value;
405 if (extension_dict->GetInteger(kPrefLocation, &location_value) &&
406 Manifest::IsUnpackedLocation(
407 static_cast<Manifest::Location>(location_value))) {
408 // Unpacked extensions can have absolute paths.
409 continue;
411 base::FilePath::StringType path_string;
412 if (!extension_dict->GetString(kPrefPath, &path_string))
413 continue;
414 base::FilePath path(path_string);
415 if (path.IsAbsolute())
416 absolute_keys.insert(i.key());
418 if (absolute_keys.empty())
419 return;
421 // Fix these paths.
422 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
423 base::DictionaryValue* update_dict = update.Get();
424 for (std::set<std::string>::iterator i = absolute_keys.begin();
425 i != absolute_keys.end(); ++i) {
426 base::DictionaryValue* extension_dict = NULL;
427 if (!update_dict->GetDictionaryWithoutPathExpansion(*i, &extension_dict)) {
428 NOTREACHED() << "Control should never reach here for extension " << *i;
429 continue;
431 base::FilePath::StringType path_string;
432 extension_dict->GetString(kPrefPath, &path_string);
433 base::FilePath path(path_string);
434 extension_dict->SetString(kPrefPath,
435 MakePathRelative(install_directory_, path));
439 const base::DictionaryValue* ExtensionPrefs::GetExtensionPref(
440 const std::string& extension_id) const {
441 const base::DictionaryValue* extensions =
442 prefs_->GetDictionary(pref_names::kExtensions);
443 const base::DictionaryValue* extension_dict = NULL;
444 if (!extensions ||
445 !extensions->GetDictionary(extension_id, &extension_dict)) {
446 return NULL;
448 return extension_dict;
451 void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id,
452 const std::string& key,
453 base::Value* data_value) {
454 if (!crx_file::id_util::IdIsValid(extension_id)) {
455 NOTREACHED() << "Invalid extension_id " << extension_id;
456 return;
458 ScopedExtensionPrefUpdate update(prefs_, extension_id);
459 if (data_value)
460 update->Set(key, data_value);
461 else
462 update->Remove(key, NULL);
465 void ExtensionPrefs::DeleteExtensionPrefs(const std::string& extension_id) {
466 extension_pref_value_map_->UnregisterExtension(extension_id);
467 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
468 observer_list_,
469 OnExtensionPrefsDeleted(extension_id));
470 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
471 base::DictionaryValue* dict = update.Get();
472 dict->Remove(extension_id, NULL);
475 bool ExtensionPrefs::ReadPrefAsBoolean(const std::string& extension_id,
476 const std::string& pref_key,
477 bool* out_value) const {
478 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
479 if (!ext || !ext->GetBoolean(pref_key, out_value))
480 return false;
482 return true;
485 bool ExtensionPrefs::ReadPrefAsInteger(const std::string& extension_id,
486 const std::string& pref_key,
487 int* out_value) const {
488 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
489 if (!ext || !ext->GetInteger(pref_key, out_value))
490 return false;
492 return true;
495 bool ExtensionPrefs::ReadPrefAsString(const std::string& extension_id,
496 const std::string& pref_key,
497 std::string* out_value) const {
498 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
499 if (!ext || !ext->GetString(pref_key, out_value))
500 return false;
502 return true;
505 bool ExtensionPrefs::ReadPrefAsList(const std::string& extension_id,
506 const std::string& pref_key,
507 const base::ListValue** out_value) const {
508 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
509 const base::ListValue* out = NULL;
510 if (!ext || !ext->GetList(pref_key, &out))
511 return false;
512 if (out_value)
513 *out_value = out;
515 return true;
518 bool ExtensionPrefs::ReadPrefAsDictionary(
519 const std::string& extension_id,
520 const std::string& pref_key,
521 const base::DictionaryValue** out_value) const {
522 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
523 const base::DictionaryValue* out = NULL;
524 if (!ext || !ext->GetDictionary(pref_key, &out))
525 return false;
526 if (out_value)
527 *out_value = out;
529 return true;
532 bool ExtensionPrefs::HasPrefForExtension(
533 const std::string& extension_id) const {
534 return GetExtensionPref(extension_id) != NULL;
537 bool ExtensionPrefs::ReadPrefAsURLPatternSet(const std::string& extension_id,
538 const std::string& pref_key,
539 URLPatternSet* result,
540 int valid_schemes) {
541 const base::ListValue* value = NULL;
542 if (!ReadPrefAsList(extension_id, pref_key, &value))
543 return false;
545 bool allow_file_access = AllowFileAccess(extension_id);
546 return result->Populate(*value, valid_schemes, allow_file_access, NULL);
549 void ExtensionPrefs::SetExtensionPrefURLPatternSet(
550 const std::string& extension_id,
551 const std::string& pref_key,
552 const URLPatternSet& new_value) {
553 UpdateExtensionPref(extension_id, pref_key, new_value.ToValue().release());
556 bool ExtensionPrefs::ReadPrefAsBooleanAndReturn(
557 const std::string& extension_id,
558 const std::string& pref_key) const {
559 bool out_value = false;
560 return ReadPrefAsBoolean(extension_id, pref_key, &out_value) && out_value;
563 PermissionSet* ExtensionPrefs::ReadPrefAsPermissionSet(
564 const std::string& extension_id,
565 const std::string& pref_key) {
566 if (!GetExtensionPref(extension_id))
567 return NULL;
569 // Retrieve the API permissions. Please refer SetExtensionPrefPermissionSet()
570 // for api_values format.
571 APIPermissionSet apis;
572 const base::ListValue* api_values = NULL;
573 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
574 if (ReadPrefAsList(extension_id, api_pref, &api_values)) {
575 APIPermissionSet::ParseFromJSON(api_values,
576 APIPermissionSet::kAllowInternalPermissions,
577 &apis, NULL, NULL);
580 // Retrieve the Manifest Keys permissions. Please refer to
581 // |SetExtensionPrefPermissionSet| for manifest_permissions_values format.
582 ManifestPermissionSet manifest_permissions;
583 const base::ListValue* manifest_permissions_values = NULL;
584 std::string manifest_permission_pref =
585 JoinPrefs(pref_key, kPrefManifestPermissions);
586 if (ReadPrefAsList(extension_id, manifest_permission_pref,
587 &manifest_permissions_values)) {
588 ManifestPermissionSet::ParseFromJSON(
589 manifest_permissions_values, &manifest_permissions, NULL, NULL);
592 // Retrieve the explicit host permissions.
593 URLPatternSet explicit_hosts;
594 ReadPrefAsURLPatternSet(
595 extension_id, JoinPrefs(pref_key, kPrefExplicitHosts),
596 &explicit_hosts, Extension::kValidHostPermissionSchemes);
598 // Retrieve the scriptable host permissions.
599 URLPatternSet scriptable_hosts;
600 ReadPrefAsURLPatternSet(
601 extension_id, JoinPrefs(pref_key, kPrefScriptableHosts),
602 &scriptable_hosts, UserScript::ValidUserScriptSchemes());
604 return new PermissionSet(
605 apis, manifest_permissions, explicit_hosts, scriptable_hosts);
608 // Set the API or Manifest permissions.
609 // The format of api_values is:
610 // [ "permission_name1", // permissions do not support detail.
611 // "permission_name2",
612 // {"permission_name3": value },
613 // // permission supports detail, permission detail will be stored in value.
614 // ...
615 // ]
616 template<typename T>
617 static base::ListValue* CreatePermissionList(const T& permissions) {
618 base::ListValue* values = new base::ListValue();
619 for (typename T::const_iterator i = permissions.begin();
620 i != permissions.end(); ++i) {
621 scoped_ptr<base::Value> detail(i->ToValue());
622 if (detail) {
623 base::DictionaryValue* tmp = new base::DictionaryValue();
624 tmp->Set(i->name(), detail.release());
625 values->Append(tmp);
626 } else {
627 values->Append(new base::StringValue(i->name()));
630 return values;
633 void ExtensionPrefs::SetExtensionPrefPermissionSet(
634 const std::string& extension_id,
635 const std::string& pref_key,
636 const PermissionSet* new_value) {
637 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
638 base::ListValue* api_values = CreatePermissionList(new_value->apis());
639 UpdateExtensionPref(extension_id, api_pref, api_values);
641 std::string manifest_permissions_pref =
642 JoinPrefs(pref_key, kPrefManifestPermissions);
643 base::ListValue* manifest_permissions_values = CreatePermissionList(
644 new_value->manifest_permissions());
645 UpdateExtensionPref(extension_id,
646 manifest_permissions_pref,
647 manifest_permissions_values);
649 // Set the explicit host permissions.
650 if (!new_value->explicit_hosts().is_empty()) {
651 SetExtensionPrefURLPatternSet(extension_id,
652 JoinPrefs(pref_key, kPrefExplicitHosts),
653 new_value->explicit_hosts());
656 // Set the scriptable host permissions.
657 if (!new_value->scriptable_hosts().is_empty()) {
658 SetExtensionPrefURLPatternSet(extension_id,
659 JoinPrefs(pref_key, kPrefScriptableHosts),
660 new_value->scriptable_hosts());
664 int ExtensionPrefs::IncrementAcknowledgePromptCount(
665 const std::string& extension_id) {
666 int count = 0;
667 ReadPrefAsInteger(extension_id, kPrefAcknowledgePromptCount, &count);
668 ++count;
669 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount,
670 new base::FundamentalValue(count));
671 return count;
674 bool ExtensionPrefs::IsExternalExtensionAcknowledged(
675 const std::string& extension_id) {
676 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalAcknowledged);
679 void ExtensionPrefs::AcknowledgeExternalExtension(
680 const std::string& extension_id) {
681 DCHECK(crx_file::id_util::IdIsValid(extension_id));
682 UpdateExtensionPref(extension_id, kPrefExternalAcknowledged,
683 new base::FundamentalValue(true));
684 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
687 bool ExtensionPrefs::IsBlacklistedExtensionAcknowledged(
688 const std::string& extension_id) {
689 return ReadPrefAsBooleanAndReturn(extension_id, kPrefBlacklistAcknowledged);
692 void ExtensionPrefs::AcknowledgeBlacklistedExtension(
693 const std::string& extension_id) {
694 DCHECK(crx_file::id_util::IdIsValid(extension_id));
695 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged,
696 new base::FundamentalValue(true));
697 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
700 bool ExtensionPrefs::IsExternalInstallFirstRun(
701 const std::string& extension_id) {
702 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalInstallFirstRun);
705 void ExtensionPrefs::SetExternalInstallFirstRun(
706 const std::string& extension_id) {
707 DCHECK(crx_file::id_util::IdIsValid(extension_id));
708 UpdateExtensionPref(extension_id, kPrefExternalInstallFirstRun,
709 new base::FundamentalValue(true));
712 bool ExtensionPrefs::SetAlertSystemFirstRun() {
713 if (prefs_->GetBoolean(pref_names::kAlertsInitialized)) {
714 return true;
716 prefs_->SetBoolean(pref_names::kAlertsInitialized, true);
717 return false;
720 bool ExtensionPrefs::DidExtensionEscalatePermissions(
721 const std::string& extension_id) {
722 return ReadPrefAsBooleanAndReturn(extension_id,
723 kExtensionDidEscalatePermissions);
726 void ExtensionPrefs::SetDidExtensionEscalatePermissions(
727 const Extension* extension, bool did_escalate) {
728 UpdateExtensionPref(extension->id(), kExtensionDidEscalatePermissions,
729 new base::FundamentalValue(did_escalate));
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() {
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(const std::string& extension_id) {
920 DCHECK(crx_file::id_util::IdIsValid(extension_id));
921 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
924 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
925 const base::Time& time) {
926 DCHECK(crx_file::id_util::IdIsValid(extension_id));
927 ScopedExtensionPrefUpdate update(prefs_, extension_id);
928 SaveTime(update.Get(), kLastActivePingDay, time);
931 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) {
932 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
933 bool result = false;
934 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
935 return result;
936 return false;
939 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
940 bool active) {
941 UpdateExtensionPref(extension_id, kActiveBit,
942 new base::FundamentalValue(active));
945 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
946 PermissionsInfo* info = PermissionsInfo::GetInstance();
947 for (ExtensionIdList::const_iterator ext_id =
948 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
949 // An extension's granted permissions need to be migrated if the
950 // full_access bit is present. This bit was always present in the previous
951 // scheme and is never present now.
952 bool full_access = false;
953 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
954 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
955 continue;
957 // Remove the full access bit (empty list will get trimmed).
958 UpdateExtensionPref(
959 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
961 // Add the plugin permission if the full access bit was set.
962 if (full_access) {
963 const base::ListValue* apis = NULL;
964 base::ListValue* new_apis = NULL;
966 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
967 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
968 new_apis = apis->DeepCopy();
969 else
970 new_apis = new base::ListValue();
972 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
973 new_apis->Append(new base::StringValue(plugin_name));
974 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
977 // The granted permissions originally only held the effective hosts,
978 // which are a combination of host and user script host permissions.
979 // We now maintain these lists separately. For migration purposes, it
980 // does not matter how we treat the old effective hosts as long as the
981 // new effective hosts will be the same, so we move them to explicit
982 // host permissions.
983 const base::ListValue* hosts = NULL;
984 std::string explicit_hosts =
985 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
986 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
987 UpdateExtensionPref(
988 *ext_id, explicit_hosts, hosts->DeepCopy());
990 // We can get rid of the old one by setting it to an empty list.
991 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
996 void ExtensionPrefs::MigrateDisableReasons(
997 const ExtensionIdList& extension_ids) {
998 for (ExtensionIdList::const_iterator ext_id =
999 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
1000 int value = -1;
1001 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
1002 int new_value = Extension::DISABLE_NONE;
1003 switch (value) {
1004 case Extension::DEPRECATED_DISABLE_USER_ACTION:
1005 new_value = Extension::DISABLE_USER_ACTION;
1006 break;
1007 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
1008 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
1009 break;
1010 case Extension::DEPRECATED_DISABLE_RELOAD:
1011 new_value = Extension::DISABLE_RELOAD;
1012 break;
1015 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
1016 new base::FundamentalValue(new_value));
1017 // Remove the old disable reason.
1018 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
1023 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
1024 const std::string& extension_id) {
1025 CHECK(crx_file::id_util::IdIsValid(extension_id));
1026 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
1029 void ExtensionPrefs::AddGrantedPermissions(
1030 const std::string& extension_id,
1031 const PermissionSet* permissions) {
1032 CHECK(crx_file::id_util::IdIsValid(extension_id));
1034 scoped_refptr<PermissionSet> granted_permissions(
1035 GetGrantedPermissions(extension_id));
1037 // The new granted permissions are the union of the already granted
1038 // permissions and the newly granted permissions.
1039 scoped_refptr<PermissionSet> new_perms(
1040 PermissionSet::CreateUnion(
1041 permissions, granted_permissions.get()));
1043 SetExtensionPrefPermissionSet(
1044 extension_id, kPrefGrantedPermissions, new_perms.get());
1047 void ExtensionPrefs::RemoveGrantedPermissions(
1048 const std::string& extension_id,
1049 const PermissionSet* permissions) {
1050 CHECK(crx_file::id_util::IdIsValid(extension_id));
1052 scoped_refptr<PermissionSet> granted_permissions(
1053 GetGrantedPermissions(extension_id));
1055 // The new granted permissions are the difference of the already granted
1056 // permissions and the newly ungranted permissions.
1057 scoped_refptr<PermissionSet> new_perms(
1058 PermissionSet::CreateDifference(
1059 granted_permissions.get(), permissions));
1061 SetExtensionPrefPermissionSet(
1062 extension_id, kPrefGrantedPermissions, new_perms.get());
1065 PermissionSet* ExtensionPrefs::GetActivePermissions(
1066 const std::string& extension_id) {
1067 CHECK(crx_file::id_util::IdIsValid(extension_id));
1068 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
1071 void ExtensionPrefs::SetActivePermissions(
1072 const std::string& extension_id,
1073 const PermissionSet* permissions) {
1074 SetExtensionPrefPermissionSet(
1075 extension_id, kPrefActivePermissions, permissions);
1078 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1079 bool is_running) {
1080 base::Value* value = new base::FundamentalValue(is_running);
1081 UpdateExtensionPref(extension_id, kPrefRunning, value);
1084 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) {
1085 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1086 if (!extension)
1087 return false;
1088 bool running = false;
1089 extension->GetBoolean(kPrefRunning, &running);
1090 return running;
1093 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1094 bool is_active) {
1095 base::Value* value = new base::FundamentalValue(is_active);
1096 UpdateExtensionPref(extension_id, kIsActive, value);
1099 bool ExtensionPrefs::IsActive(const std::string& extension_id) {
1100 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1101 if (!extension)
1102 return false;
1103 bool is_active = false;
1104 extension->GetBoolean(kIsActive, &is_active);
1105 return is_active;
1108 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1109 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1112 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1113 bool enabled) {
1114 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1115 new base::FundamentalValue(enabled));
1116 extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled);
1119 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1120 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1123 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1124 bool allow) {
1125 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1126 new base::FundamentalValue(allow));
1129 bool ExtensionPrefs::HasAllowFileAccessSetting(
1130 const std::string& extension_id) const {
1131 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1132 return ext && ext->HasKey(kPrefAllowFileAccess);
1135 bool ExtensionPrefs::DoesExtensionHaveState(
1136 const std::string& id, Extension::State check_state) const {
1137 const base::DictionaryValue* extension = GetExtensionPref(id);
1138 int state = -1;
1139 if (!extension || !extension->GetInteger(kPrefState, &state))
1140 return false;
1142 if (state < 0 || state >= Extension::NUM_STATES) {
1143 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1144 return false;
1147 return state == check_state;
1150 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1151 const std::string& id) const {
1152 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1155 bool ExtensionPrefs::IsExtensionDisabled(
1156 const std::string& id) const {
1157 return DoesExtensionHaveState(id, Extension::DISABLED);
1160 ExtensionIdList ExtensionPrefs::GetToolbarOrder() {
1161 ExtensionIdList id_list_out;
1162 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1163 return id_list_out;
1166 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1167 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1170 void ExtensionPrefs::OnExtensionInstalled(
1171 const Extension* extension,
1172 Extension::State initial_state,
1173 const syncer::StringOrdinal& page_ordinal,
1174 int install_flags,
1175 const std::string& install_parameter) {
1176 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1177 base::DictionaryValue* extension_dict = update.Get();
1178 const base::Time install_time = time_provider_->GetCurrentTime();
1179 PopulateExtensionInfoPrefs(extension,
1180 install_time,
1181 initial_state,
1182 install_flags,
1183 install_parameter,
1184 extension_dict);
1186 bool requires_sort_ordinal = extension->RequiresSortOrdinal() &&
1187 (install_flags & kInstallFlagIsEphemeral) == 0;
1188 FinishExtensionInfoPrefs(extension->id(),
1189 install_time,
1190 requires_sort_ordinal,
1191 page_ordinal,
1192 extension_dict);
1195 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1196 const Manifest::Location& location,
1197 bool external_uninstall) {
1198 app_sorting_->ClearOrdinals(extension_id);
1200 // For external extensions, we save a preference reminding ourself not to try
1201 // and install the extension anymore (except when |external_uninstall| is
1202 // true, which signifies that the registry key was deleted or the pref file
1203 // no longer lists the extension).
1204 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1205 UpdateExtensionPref(extension_id, kPrefState,
1206 new base::FundamentalValue(
1207 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1208 extension_pref_value_map_->SetExtensionState(extension_id, false);
1209 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1210 observer_list_,
1211 OnExtensionStateChanged(extension_id, false));
1212 } else {
1213 DeleteExtensionPrefs(extension_id);
1217 void ExtensionPrefs::SetExtensionState(const std::string& extension_id,
1218 Extension::State state) {
1219 UpdateExtensionPref(extension_id, kPrefState,
1220 new base::FundamentalValue(state));
1221 bool enabled = (state == Extension::ENABLED);
1222 extension_pref_value_map_->SetExtensionState(extension_id, enabled);
1223 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1224 observer_list_,
1225 OnExtensionStateChanged(extension_id, enabled));
1228 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1229 BlacklistState state) {
1230 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1231 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1232 new base::FundamentalValue(state));
1235 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1236 const std::string& extension_id) {
1237 if (IsExtensionBlacklisted(extension_id))
1238 return BLACKLISTED_MALWARE;
1239 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1240 int int_value = 0;
1241 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1242 return static_cast<BlacklistState>(int_value);
1244 return NOT_BLACKLISTED;
1247 std::string ExtensionPrefs::GetVersionString(const std::string& extension_id) {
1248 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1249 if (!extension)
1250 return std::string();
1252 std::string version;
1253 extension->GetString(kPrefVersion, &version);
1255 return version;
1258 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1259 if (!Manifest::IsUnpackedLocation(extension->location())) {
1260 const base::DictionaryValue* extension_dict =
1261 GetExtensionPref(extension->id());
1262 if (!extension_dict)
1263 return;
1264 const base::DictionaryValue* old_manifest = NULL;
1265 bool update_required =
1266 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1267 !extension->manifest()->value()->Equals(old_manifest);
1268 if (update_required) {
1269 UpdateExtensionPref(extension->id(), kPrefManifest,
1270 extension->manifest()->value()->DeepCopy());
1275 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1276 const std::string& extension_id,
1277 const base::DictionaryValue* extension) const {
1278 int location_value;
1279 if (!extension->GetInteger(kPrefLocation, &location_value))
1280 return scoped_ptr<ExtensionInfo>();
1282 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1283 if (location == Manifest::COMPONENT) {
1284 // Component extensions are ignored. Component extensions may have data
1285 // saved in preferences, but they are already loaded at this point (by
1286 // ComponentLoader) and shouldn't be populated into the result of
1287 // GetInstalledExtensionsInfo, otherwise InstalledLoader would also want to
1288 // load them.
1289 return scoped_ptr<ExtensionInfo>();
1292 // Only the following extension types have data saved in the preferences.
1293 if (location != Manifest::INTERNAL &&
1294 !Manifest::IsUnpackedLocation(location) &&
1295 !Manifest::IsExternalLocation(location)) {
1296 NOTREACHED();
1297 return scoped_ptr<ExtensionInfo>();
1300 const base::DictionaryValue* manifest = NULL;
1301 if (!Manifest::IsUnpackedLocation(location) &&
1302 !extension->GetDictionary(kPrefManifest, &manifest)) {
1303 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1304 // Just a warning for now.
1307 base::FilePath::StringType path;
1308 if (!extension->GetString(kPrefPath, &path))
1309 return scoped_ptr<ExtensionInfo>();
1311 // Make path absolute. Most (but not all) extension types have relative paths.
1312 if (!base::FilePath(path).IsAbsolute())
1313 path = install_directory_.Append(path).value();
1315 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1316 manifest, extension_id, base::FilePath(path), location));
1319 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1320 const std::string& extension_id) const {
1321 const base::DictionaryValue* ext = NULL;
1322 const base::DictionaryValue* extensions =
1323 prefs_->GetDictionary(pref_names::kExtensions);
1324 if (!extensions ||
1325 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1326 return scoped_ptr<ExtensionInfo>();
1327 int state_value;
1328 if (ext->GetInteger(kPrefState, &state_value) &&
1329 state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1330 LOG(WARNING) << "External extension with id " << extension_id
1331 << " has been uninstalled by the user";
1332 return scoped_ptr<ExtensionInfo>();
1335 return GetInstalledInfoHelper(extension_id, ext);
1338 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1339 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1340 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1342 const base::DictionaryValue* extensions =
1343 prefs_->GetDictionary(pref_names::kExtensions);
1344 for (base::DictionaryValue::Iterator extension_id(*extensions);
1345 !extension_id.IsAtEnd(); extension_id.Advance()) {
1346 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1347 continue;
1349 scoped_ptr<ExtensionInfo> info =
1350 GetInstalledExtensionInfo(extension_id.key());
1351 if (info)
1352 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1355 return extensions_info.Pass();
1358 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1359 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1360 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1362 const base::DictionaryValue* extensions =
1363 prefs_->GetDictionary(pref_names::kExtensions);
1364 for (base::DictionaryValue::Iterator extension_id(*extensions);
1365 !extension_id.IsAtEnd(); extension_id.Advance()) {
1366 const base::DictionaryValue* ext = NULL;
1367 if (!crx_file::id_util::IdIsValid(extension_id.key()) ||
1368 !IsExternalExtensionUninstalled(extension_id.key()) ||
1369 !extension_id.value().GetAsDictionary(&ext))
1370 continue;
1372 scoped_ptr<ExtensionInfo> info =
1373 GetInstalledInfoHelper(extension_id.key(), ext);
1374 if (info)
1375 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1378 return extensions_info.Pass();
1381 void ExtensionPrefs::SetDelayedInstallInfo(
1382 const Extension* extension,
1383 Extension::State initial_state,
1384 int install_flags,
1385 DelayReason delay_reason,
1386 const syncer::StringOrdinal& page_ordinal,
1387 const std::string& install_parameter) {
1388 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1389 PopulateExtensionInfoPrefs(extension,
1390 time_provider_->GetCurrentTime(),
1391 initial_state,
1392 install_flags,
1393 install_parameter,
1394 extension_dict);
1396 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1397 // should not be in the final extension prefs. All entries here should have
1398 // a corresponding Remove() call in FinishDelayedInstallInfo().
1399 if (extension->RequiresSortOrdinal() &&
1400 (install_flags & kInstallFlagIsEphemeral) == 0) {
1401 extension_dict->SetString(
1402 kPrefSuggestedPageOrdinal,
1403 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1404 : std::string());
1406 extension_dict->SetInteger(kDelayedInstallReason,
1407 static_cast<int>(delay_reason));
1409 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1412 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1413 const std::string& extension_id) {
1414 if (!GetExtensionPref(extension_id))
1415 return false;
1416 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1417 bool result = update->Remove(kDelayedInstallInfo, NULL);
1418 return result;
1421 bool ExtensionPrefs::FinishDelayedInstallInfo(
1422 const std::string& extension_id) {
1423 CHECK(crx_file::id_util::IdIsValid(extension_id));
1424 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1425 base::DictionaryValue* extension_dict = update.Get();
1426 base::DictionaryValue* pending_install_dict = NULL;
1427 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1428 &pending_install_dict)) {
1429 return false;
1432 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1433 // Also do any other data cleanup that makes sense.
1434 std::string serialized_ordinal;
1435 syncer::StringOrdinal suggested_page_ordinal;
1436 bool needs_sort_ordinal = false;
1437 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1438 &serialized_ordinal)) {
1439 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1440 needs_sort_ordinal = true;
1441 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1443 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1445 const base::Time install_time = time_provider_->GetCurrentTime();
1446 pending_install_dict->Set(
1447 kPrefInstallTime,
1448 new base::StringValue(
1449 base::Int64ToString(install_time.ToInternalValue())));
1451 // Some extension pref values are written conditionally. If they are not
1452 // present in the delayed install data, they should be removed when the
1453 // delayed install is committed.
1454 extension_dict->Remove(kPrefEphemeralApp, NULL);
1456 // Commit the delayed install data.
1457 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1458 it.Advance()) {
1459 extension_dict->Set(it.key(), it.value().DeepCopy());
1461 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1462 suggested_page_ordinal, extension_dict);
1463 return true;
1466 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1467 const std::string& extension_id) const {
1468 const base::DictionaryValue* extension_prefs =
1469 GetExtensionPref(extension_id);
1470 if (!extension_prefs)
1471 return scoped_ptr<ExtensionInfo>();
1473 const base::DictionaryValue* ext = NULL;
1474 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1475 return scoped_ptr<ExtensionInfo>();
1477 return GetInstalledInfoHelper(extension_id, ext);
1480 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1481 const std::string& extension_id) const {
1482 const base::DictionaryValue* extension_prefs =
1483 GetExtensionPref(extension_id);
1484 if (!extension_prefs)
1485 return DELAY_REASON_NONE;
1487 const base::DictionaryValue* ext = NULL;
1488 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1489 return DELAY_REASON_NONE;
1491 int delay_reason;
1492 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1493 return DELAY_REASON_NONE;
1495 return static_cast<DelayReason>(delay_reason);
1498 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1499 GetAllDelayedInstallInfo() const {
1500 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1502 const base::DictionaryValue* extensions =
1503 prefs_->GetDictionary(pref_names::kExtensions);
1504 for (base::DictionaryValue::Iterator extension_id(*extensions);
1505 !extension_id.IsAtEnd(); extension_id.Advance()) {
1506 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1507 continue;
1509 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1510 if (info)
1511 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1514 return extensions_info.Pass();
1517 bool ExtensionPrefs::IsEphemeralApp(const std::string& extension_id) const {
1518 if (ReadPrefAsBooleanAndReturn(extension_id, kPrefEphemeralApp))
1519 return true;
1521 // Ephemerality was previously stored in the creation flags, so we must also
1522 // check it for backcompatibility.
1523 return (GetCreationFlags(extension_id) & Extension::IS_EPHEMERAL) != 0;
1526 void ExtensionPrefs::OnEphemeralAppPromoted(const std::string& extension_id) {
1527 DCHECK(IsEphemeralApp(extension_id));
1529 UpdateExtensionPref(extension_id, kPrefEphemeralApp, NULL);
1531 // Ephemerality was previously stored in the creation flags, so ensure the bit
1532 // is cleared.
1533 int creation_flags = Extension::NO_FLAGS;
1534 if (ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1535 if (creation_flags & Extension::IS_EPHEMERAL) {
1536 creation_flags &= ~static_cast<int>(Extension::IS_EPHEMERAL);
1537 UpdateExtensionPref(extension_id,
1538 kPrefCreationFlags,
1539 new base::FundamentalValue(creation_flags));
1544 bool ExtensionPrefs::WasAppDraggedByUser(const std::string& extension_id) {
1545 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1548 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1549 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1550 new base::FundamentalValue(true));
1553 bool ExtensionPrefs::IsFromWebStore(
1554 const std::string& extension_id) const {
1555 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1556 bool result = false;
1557 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1558 return result;
1559 return false;
1562 bool ExtensionPrefs::IsFromBookmark(
1563 const std::string& extension_id) const {
1564 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1565 bool result = false;
1566 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1567 return result;
1568 return false;
1571 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1572 int creation_flags = Extension::NO_FLAGS;
1573 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1574 // Since kPrefCreationFlags was added later, it will be missing for
1575 // previously installed extensions.
1576 if (IsFromBookmark(extension_id))
1577 creation_flags |= Extension::FROM_BOOKMARK;
1578 if (IsFromWebStore(extension_id))
1579 creation_flags |= Extension::FROM_WEBSTORE;
1580 if (WasInstalledByDefault(extension_id))
1581 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1582 if (WasInstalledByOem(extension_id))
1583 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
1585 return creation_flags;
1588 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1589 const std::string& extension_id) const {
1590 int creation_flags = Extension::NO_FLAGS;
1591 const base::DictionaryValue* delayed_info = NULL;
1592 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1593 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1595 return creation_flags;
1598 bool ExtensionPrefs::WasInstalledByDefault(
1599 const std::string& extension_id) const {
1600 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1601 bool result = false;
1602 if (dictionary &&
1603 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1604 return result;
1605 return false;
1608 bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const {
1609 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1610 bool result = false;
1611 if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result))
1612 return result;
1613 return false;
1616 base::Time ExtensionPrefs::GetInstallTime(
1617 const std::string& extension_id) const {
1618 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1619 if (!extension) {
1620 NOTREACHED();
1621 return base::Time();
1623 std::string install_time_str;
1624 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1625 return base::Time();
1626 int64 install_time_i64 = 0;
1627 if (!base::StringToInt64(install_time_str, &install_time_i64))
1628 return base::Time();
1629 return base::Time::FromInternalValue(install_time_i64);
1632 bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const {
1633 bool do_not_sync;
1634 if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync))
1635 return false;
1637 return do_not_sync;
1640 base::Time ExtensionPrefs::GetLastLaunchTime(
1641 const std::string& extension_id) const {
1642 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1643 if (!extension)
1644 return base::Time();
1646 std::string launch_time_str;
1647 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1648 return base::Time();
1649 int64 launch_time_i64 = 0;
1650 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1651 return base::Time();
1652 return base::Time::FromInternalValue(launch_time_i64);
1655 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1656 const base::Time& time) {
1657 DCHECK(crx_file::id_util::IdIsValid(extension_id));
1658 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1659 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1662 void ExtensionPrefs::ClearLastLaunchTimes() {
1663 const base::DictionaryValue* dict =
1664 prefs_->GetDictionary(pref_names::kExtensions);
1665 if (!dict || dict->empty())
1666 return;
1668 // Collect all the keys to remove the last launched preference from.
1669 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
1670 base::DictionaryValue* update_dict = update.Get();
1671 for (base::DictionaryValue::Iterator i(*update_dict); !i.IsAtEnd();
1672 i.Advance()) {
1673 base::DictionaryValue* extension_dict = NULL;
1674 if (!update_dict->GetDictionary(i.key(), &extension_dict))
1675 continue;
1677 if (extension_dict->HasKey(kPrefLastLaunchTime))
1678 extension_dict->Remove(kPrefLastLaunchTime, NULL);
1682 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) {
1683 CHECK(out);
1685 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1687 for (size_t i = 0; i < extensions_info->size(); ++i) {
1688 ExtensionInfo* info = extensions_info->at(i).get();
1689 out->push_back(info->extension_id);
1693 // static
1694 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1695 const PrefService* pref_service) {
1696 ExtensionIdList result;
1698 const base::DictionaryValue* extension_prefs = NULL;
1699 const base::Value* extension_prefs_value =
1700 pref_service->GetUserPrefValue(pref_names::kExtensions);
1701 if (!extension_prefs_value ||
1702 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1703 return result; // Empty set
1706 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1707 it.Advance()) {
1708 const base::DictionaryValue* ext = NULL;
1709 if (!it.value().GetAsDictionary(&ext)) {
1710 NOTREACHED() << "Invalid pref for extension " << it.key();
1711 continue;
1713 if (!IsBlacklistBitSet(ext))
1714 result.push_back(it.key());
1716 return result;
1719 void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) {
1720 observer_list_.AddObserver(observer);
1723 void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) {
1724 observer_list_.RemoveObserver(observer);
1727 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1728 // Fix old entries that did not get an installation time entry when they
1729 // were installed or don't have a preferences field.
1730 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1731 ext_id != extension_ids.end(); ++ext_id) {
1732 if (GetInstallTime(*ext_id) == base::Time()) {
1733 VLOG(1) << "Could not parse installation time of extension "
1734 << *ext_id << ". It was probably installed before setting "
1735 << kPrefInstallTime << " was introduced. Updating "
1736 << kPrefInstallTime << " to the current time.";
1737 const base::Time install_time = time_provider_->GetCurrentTime();
1738 UpdateExtensionPref(*ext_id,
1739 kPrefInstallTime,
1740 new base::StringValue(base::Int64ToString(
1741 install_time.ToInternalValue())));
1746 void ExtensionPrefs::InitPrefStore() {
1747 if (extensions_disabled_) {
1748 extension_pref_value_map_->NotifyInitializationCompleted();
1749 return;
1752 // When this is called, the PrefService is initialized and provides access
1753 // to the user preferences stored in a JSON file.
1754 ExtensionIdList extension_ids;
1755 GetExtensions(&extension_ids);
1756 // Create empty preferences dictionary for each extension (these dictionaries
1757 // are pruned when persisting the preferences to disk).
1758 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1759 ext_id != extension_ids.end(); ++ext_id) {
1760 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1761 // This creates an empty dictionary if none is stored.
1762 update.Get();
1765 FixMissingPrefs(extension_ids);
1766 MigratePermissions(extension_ids);
1767 MigrateDisableReasons(extension_ids);
1768 app_sorting_->Initialize(extension_ids);
1770 InitExtensionControlledPrefs(extension_pref_value_map_);
1772 extension_pref_value_map_->NotifyInitializationCompleted();
1775 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) {
1776 bool has_incognito_pref_value = false;
1777 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1778 true,
1779 &has_incognito_pref_value);
1780 return has_incognito_pref_value;
1783 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1784 const std::string& extension_id) const {
1785 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1786 if (!extension_prefs)
1787 return NULL;
1789 const base::DictionaryValue* ext = NULL;
1790 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1791 return NULL;
1793 return ext;
1796 void ExtensionPrefs::SetGeometryCache(
1797 const std::string& extension_id,
1798 scoped_ptr<base::DictionaryValue> cache) {
1799 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1802 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() {
1803 return prefs_->GetDictionary(kInstallSignature);
1806 void ExtensionPrefs::SetInstallSignature(
1807 const base::DictionaryValue* signature) {
1808 if (signature) {
1809 prefs_->Set(kInstallSignature, *signature);
1810 DVLOG(1) << "SetInstallSignature - saving";
1811 } else {
1812 DVLOG(1) << "SetInstallSignature - clearing";
1813 prefs_->ClearPref(kInstallSignature);
1817 std::string ExtensionPrefs::GetInstallParam(
1818 const std::string& extension_id) const {
1819 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1820 if (!extension) // Expected during unit testing.
1821 return std::string();
1822 std::string install_parameter;
1823 if (!extension->GetString(kPrefInstallParam, &install_parameter))
1824 return std::string();
1825 return install_parameter;
1828 void ExtensionPrefs::SetInstallParam(const std::string& extension_id,
1829 const std::string& install_parameter) {
1830 UpdateExtensionPref(extension_id,
1831 kPrefInstallParam,
1832 new base::StringValue(install_parameter));
1835 int ExtensionPrefs::GetCorruptedDisableCount() {
1836 return prefs_->GetInteger(kCorruptedDisableCount);
1839 void ExtensionPrefs::IncrementCorruptedDisableCount() {
1840 int count = prefs_->GetInteger(kCorruptedDisableCount);
1841 prefs_->SetInteger(kCorruptedDisableCount, count + 1);
1844 ExtensionPrefs::ExtensionPrefs(
1845 PrefService* prefs,
1846 const base::FilePath& root_dir,
1847 ExtensionPrefValueMap* extension_pref_value_map,
1848 scoped_ptr<AppSorting> app_sorting,
1849 scoped_ptr<TimeProvider> time_provider,
1850 bool extensions_disabled,
1851 const std::vector<ExtensionPrefsObserver*>& early_observers)
1852 : prefs_(prefs),
1853 install_directory_(root_dir),
1854 extension_pref_value_map_(extension_pref_value_map),
1855 app_sorting_(app_sorting.Pass()),
1856 time_provider_(time_provider.Pass()),
1857 extensions_disabled_(extensions_disabled) {
1858 app_sorting_->SetExtensionScopedPrefs(this);
1859 MakePathsRelative();
1861 // Ensure that any early observers are watching before prefs are initialized.
1862 for (std::vector<ExtensionPrefsObserver*>::const_iterator iter =
1863 early_observers.begin();
1864 iter != early_observers.end();
1865 ++iter) {
1866 AddObserver(*iter);
1869 InitPrefStore();
1872 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1873 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1876 bool ExtensionPrefs::NeedsStorageGarbageCollection() {
1877 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1880 // static
1881 void ExtensionPrefs::RegisterProfilePrefs(
1882 user_prefs::PrefRegistrySyncable* registry) {
1883 registry->RegisterDictionaryPref(
1884 pref_names::kExtensions,
1885 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1886 registry->RegisterListPref(pref_names::kToolbar,
1887 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1888 registry->RegisterIntegerPref(
1889 pref_names::kToolbarSize,
1890 -1, // default value
1891 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1892 registry->RegisterDictionaryPref(
1893 kExtensionsBlacklistUpdate,
1894 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1895 registry->RegisterListPref(pref_names::kInstallAllowList,
1896 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1897 registry->RegisterListPref(pref_names::kInstallDenyList,
1898 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1899 registry->RegisterDictionaryPref(
1900 pref_names::kInstallForceList,
1901 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1902 registry->RegisterListPref(pref_names::kAllowedTypes,
1903 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1904 registry->RegisterBooleanPref(
1905 pref_names::kStorageGarbageCollect,
1906 false, // default value
1907 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1908 registry->RegisterInt64Pref(
1909 pref_names::kLastUpdateCheck,
1910 0, // default value
1911 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1912 registry->RegisterInt64Pref(
1913 pref_names::kNextUpdateCheck,
1914 0, // default value
1915 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1916 registry->RegisterListPref(pref_names::kAllowedInstallSites,
1917 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1918 registry->RegisterStringPref(
1919 pref_names::kLastChromeVersion,
1920 std::string(), // default value
1921 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1922 registry->RegisterDictionaryPref(
1923 kInstallSignature,
1924 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1926 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist,
1927 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1928 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist,
1929 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1930 registry->RegisterBooleanPref(
1931 pref_names::kNativeMessagingUserLevelHosts,
1932 true, // default value
1933 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1934 registry->RegisterIntegerPref(
1935 kCorruptedDisableCount,
1936 0, // default value
1937 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1939 #if !defined(OS_MACOSX)
1940 registry->RegisterBooleanPref(
1941 pref_names::kAppFullscreenAllowed, true,
1942 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1943 #endif
1946 template <class ExtensionIdContainer>
1947 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
1948 const char* pref,
1949 ExtensionIdContainer* id_container_out) {
1950 DCHECK(id_container_out->empty());
1952 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
1953 const base::ListValue* user_pref_as_list;
1954 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
1955 return false;
1957 std::insert_iterator<ExtensionIdContainer> insert_iterator(
1958 *id_container_out, id_container_out->end());
1959 std::string extension_id;
1960 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
1961 value_it != user_pref_as_list->end(); ++value_it) {
1962 if (!(*value_it)->GetAsString(&extension_id)) {
1963 NOTREACHED();
1964 continue;
1966 insert_iterator = extension_id;
1968 return true;
1971 template <class ExtensionIdContainer>
1972 void ExtensionPrefs::SetExtensionPrefFromContainer(
1973 const char* pref,
1974 const ExtensionIdContainer& strings) {
1975 ListPrefUpdate update(prefs_, pref);
1976 base::ListValue* list_of_values = update.Get();
1977 list_of_values->Clear();
1978 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
1979 iter != strings.end(); ++iter) {
1980 list_of_values->Append(new base::StringValue(*iter));
1984 void ExtensionPrefs::PopulateExtensionInfoPrefs(
1985 const Extension* extension,
1986 const base::Time install_time,
1987 Extension::State initial_state,
1988 int install_flags,
1989 const std::string& install_parameter,
1990 base::DictionaryValue* extension_dict) {
1991 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
1992 extension_dict->Set(kPrefLocation,
1993 new base::FundamentalValue(extension->location()));
1994 extension_dict->Set(kPrefCreationFlags,
1995 new base::FundamentalValue(extension->creation_flags()));
1996 extension_dict->Set(kPrefFromWebStore,
1997 new base::FundamentalValue(extension->from_webstore()));
1998 extension_dict->Set(kPrefFromBookmark,
1999 new base::FundamentalValue(extension->from_bookmark()));
2000 extension_dict->Set(
2001 kPrefWasInstalledByDefault,
2002 new base::FundamentalValue(extension->was_installed_by_default()));
2003 extension_dict->Set(
2004 kPrefWasInstalledByOem,
2005 new base::FundamentalValue(extension->was_installed_by_oem()));
2006 extension_dict->Set(kPrefInstallTime,
2007 new base::StringValue(
2008 base::Int64ToString(install_time.ToInternalValue())));
2009 if (install_flags & kInstallFlagIsBlacklistedForMalware)
2010 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
2012 if (install_flags & kInstallFlagIsEphemeral)
2013 extension_dict->Set(kPrefEphemeralApp, new base::FundamentalValue(true));
2014 else
2015 extension_dict->Remove(kPrefEphemeralApp, NULL);
2017 base::FilePath::StringType path = MakePathRelative(install_directory_,
2018 extension->path());
2019 extension_dict->Set(kPrefPath, new base::StringValue(path));
2020 if (!install_parameter.empty()) {
2021 extension_dict->Set(kPrefInstallParam,
2022 new base::StringValue(install_parameter));
2024 // We store prefs about LOAD extensions, but don't cache their manifest
2025 // since it may change on disk.
2026 if (!Manifest::IsUnpackedLocation(extension->location())) {
2027 extension_dict->Set(kPrefManifest,
2028 extension->manifest()->value()->DeepCopy());
2031 // Only writes kPrefDoNotSync when it is not the default.
2032 if (install_flags & kInstallFlagDoNotSync)
2033 extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true));
2034 else
2035 extension_dict->Remove(kPrefDoNotSync, NULL);
2038 void ExtensionPrefs::InitExtensionControlledPrefs(
2039 ExtensionPrefValueMap* value_map) {
2040 ExtensionIdList extension_ids;
2041 GetExtensions(&extension_ids);
2043 for (ExtensionIdList::iterator extension_id = extension_ids.begin();
2044 extension_id != extension_ids.end();
2045 ++extension_id) {
2046 base::Time install_time = GetInstallTime(*extension_id);
2047 bool is_enabled = !IsExtensionDisabled(*extension_id);
2048 bool is_incognito_enabled = IsIncognitoEnabled(*extension_id);
2049 value_map->RegisterExtension(
2050 *extension_id, install_time, is_enabled, is_incognito_enabled);
2052 FOR_EACH_OBSERVER(
2053 ExtensionPrefsObserver,
2054 observer_list_,
2055 OnExtensionRegistered(*extension_id, install_time, is_enabled));
2057 // Set regular extension controlled prefs.
2058 LoadExtensionControlledPrefs(
2059 this, value_map, *extension_id, kExtensionPrefsScopeRegular);
2060 // Set incognito extension controlled prefs.
2061 LoadExtensionControlledPrefs(this,
2062 value_map,
2063 *extension_id,
2064 kExtensionPrefsScopeIncognitoPersistent);
2065 // Set regular-only extension controlled prefs.
2066 LoadExtensionControlledPrefs(
2067 this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly);
2069 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
2070 observer_list_,
2071 OnExtensionPrefsLoaded(*extension_id, this));
2075 void ExtensionPrefs::FinishExtensionInfoPrefs(
2076 const std::string& extension_id,
2077 const base::Time install_time,
2078 bool needs_sort_ordinal,
2079 const syncer::StringOrdinal& suggested_page_ordinal,
2080 base::DictionaryValue* extension_dict) {
2081 // Reinitializes various preferences with empty dictionaries.
2082 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
2083 extension_dict->Set(pref_names::kPrefPreferences,
2084 new base::DictionaryValue);
2087 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
2088 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
2089 new base::DictionaryValue);
2092 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
2093 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
2094 new base::DictionaryValue);
2097 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
2098 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
2100 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
2101 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
2102 new base::ListValue);
2105 // If this point has been reached, any pending installs should be considered
2106 // out of date.
2107 extension_dict->Remove(kDelayedInstallInfo, NULL);
2109 // Clear state that may be registered from a previous install.
2110 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
2112 // FYI, all code below here races on sudden shutdown because |extension_dict|,
2113 // |app_sorting_|, |extension_pref_value_map_|, and (potentially) observers
2114 // are updated non-transactionally. This is probably not fixable without
2115 // nested transactional updates to pref dictionaries.
2116 if (needs_sort_ordinal)
2117 app_sorting_->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
2119 bool is_enabled = false;
2120 int initial_state;
2121 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
2122 is_enabled = initial_state == Extension::ENABLED;
2124 bool is_incognito_enabled = IsIncognitoEnabled(extension_id);
2126 extension_pref_value_map_->RegisterExtension(
2127 extension_id, install_time, is_enabled, is_incognito_enabled);
2129 FOR_EACH_OBSERVER(
2130 ExtensionPrefsObserver,
2131 observer_list_,
2132 OnExtensionRegistered(extension_id, install_time, is_enabled));
2135 } // namespace extensions