Add testing/scripts/OWNERS
[chromium-blink-merge.git] / extensions / browser / extension_prefs.cc
blob4d476f52a408a5c429f06dbd2ebc0e38aa9ecb10
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 ModifyDisableReason(extension_id, disable_reason, DISABLE_REASON_ADD);
752 void ExtensionPrefs::RemoveDisableReason(
753 const std::string& extension_id,
754 Extension::DisableReason disable_reason) {
755 ModifyDisableReason(extension_id, disable_reason, DISABLE_REASON_REMOVE);
758 void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) {
759 ModifyDisableReason(
760 extension_id, Extension::DISABLE_NONE, DISABLE_REASON_CLEAR);
763 void ExtensionPrefs::ModifyDisableReason(const std::string& extension_id,
764 Extension::DisableReason reason,
765 DisableReasonChange change) {
766 int old_value = GetDisableReasons(extension_id);
767 int new_value = old_value;
768 switch (change) {
769 case DISABLE_REASON_ADD:
770 new_value |= static_cast<int>(reason);
771 break;
772 case DISABLE_REASON_REMOVE:
773 new_value &= ~static_cast<int>(reason);
774 break;
775 case DISABLE_REASON_CLEAR:
776 new_value = Extension::DISABLE_NONE;
777 break;
780 if (old_value == new_value) // no change, return.
781 return;
783 if (new_value == Extension::DISABLE_NONE) {
784 UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
785 } else {
786 UpdateExtensionPref(extension_id,
787 kPrefDisableReasons,
788 new base::FundamentalValue(new_value));
791 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
792 observer_list_,
793 OnExtensionDisableReasonsChanged(extension_id, new_value));
796 std::set<std::string> ExtensionPrefs::GetBlacklistedExtensions() {
797 std::set<std::string> ids;
799 const base::DictionaryValue* extensions =
800 prefs_->GetDictionary(pref_names::kExtensions);
801 if (!extensions)
802 return ids;
804 for (base::DictionaryValue::Iterator it(*extensions);
805 !it.IsAtEnd(); it.Advance()) {
806 if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) {
807 NOTREACHED() << "Invalid pref for extension " << it.key();
808 continue;
810 if (IsBlacklistBitSet(
811 static_cast<const base::DictionaryValue*>(&it.value()))) {
812 ids.insert(it.key());
816 return ids;
819 void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id,
820 bool is_blacklisted) {
821 bool currently_blacklisted = IsExtensionBlacklisted(extension_id);
822 if (is_blacklisted == currently_blacklisted)
823 return;
825 // Always make sure the "acknowledged" bit is cleared since the blacklist bit
826 // is changing.
827 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL);
829 if (is_blacklisted) {
830 UpdateExtensionPref(extension_id,
831 kPrefBlacklist,
832 new base::FundamentalValue(true));
833 } else {
834 UpdateExtensionPref(extension_id, kPrefBlacklist, NULL);
835 const base::DictionaryValue* dict = GetExtensionPref(extension_id);
836 if (dict && dict->empty())
837 DeleteExtensionPrefs(extension_id);
841 bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const {
842 const base::DictionaryValue* ext_prefs = GetExtensionPref(id);
843 return ext_prefs && IsBlacklistBitSet(ext_prefs);
846 namespace {
848 // Serializes a 64bit integer as a string value.
849 void SaveInt64(base::DictionaryValue* dictionary,
850 const char* key,
851 const int64 value) {
852 if (!dictionary)
853 return;
855 std::string string_value = base::Int64ToString(value);
856 dictionary->SetString(key, string_value);
859 // Deserializes a 64bit integer stored as a string value.
860 bool ReadInt64(const base::DictionaryValue* dictionary,
861 const char* key,
862 int64* value) {
863 if (!dictionary)
864 return false;
866 std::string string_value;
867 if (!dictionary->GetString(key, &string_value))
868 return false;
870 return base::StringToInt64(string_value, value);
873 // Serializes |time| as a string value mapped to |key| in |dictionary|.
874 void SaveTime(base::DictionaryValue* dictionary,
875 const char* key,
876 const base::Time& time) {
877 SaveInt64(dictionary, key, time.ToInternalValue());
880 // The opposite of SaveTime. If |key| is not found, this returns an empty Time
881 // (is_null() will return true).
882 base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) {
883 int64 value;
884 if (ReadInt64(dictionary, key, &value))
885 return base::Time::FromInternalValue(value);
887 return base::Time();
890 } // namespace
892 base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const {
893 DCHECK(crx_file::id_util::IdIsValid(extension_id));
894 return ReadTime(GetExtensionPref(extension_id), kLastPingDay);
897 void ExtensionPrefs::SetLastPingDay(const std::string& extension_id,
898 const base::Time& time) {
899 DCHECK(crx_file::id_util::IdIsValid(extension_id));
900 ScopedExtensionPrefUpdate update(prefs_, extension_id);
901 SaveTime(update.Get(), kLastPingDay, time);
904 base::Time ExtensionPrefs::BlacklistLastPingDay() const {
905 return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate),
906 kLastPingDay);
909 void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) {
910 DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate);
911 SaveTime(update.Get(), kLastPingDay, time);
914 base::Time ExtensionPrefs::LastActivePingDay(const std::string& extension_id) {
915 DCHECK(crx_file::id_util::IdIsValid(extension_id));
916 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
919 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
920 const base::Time& time) {
921 DCHECK(crx_file::id_util::IdIsValid(extension_id));
922 ScopedExtensionPrefUpdate update(prefs_, extension_id);
923 SaveTime(update.Get(), kLastActivePingDay, time);
926 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) {
927 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
928 bool result = false;
929 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
930 return result;
931 return false;
934 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
935 bool active) {
936 UpdateExtensionPref(extension_id, kActiveBit,
937 new base::FundamentalValue(active));
940 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
941 PermissionsInfo* info = PermissionsInfo::GetInstance();
942 for (ExtensionIdList::const_iterator ext_id =
943 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
944 // An extension's granted permissions need to be migrated if the
945 // full_access bit is present. This bit was always present in the previous
946 // scheme and is never present now.
947 bool full_access = false;
948 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
949 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
950 continue;
952 // Remove the full access bit (empty list will get trimmed).
953 UpdateExtensionPref(
954 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
956 // Add the plugin permission if the full access bit was set.
957 if (full_access) {
958 const base::ListValue* apis = NULL;
959 base::ListValue* new_apis = NULL;
961 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
962 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
963 new_apis = apis->DeepCopy();
964 else
965 new_apis = new base::ListValue();
967 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
968 new_apis->Append(new base::StringValue(plugin_name));
969 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
972 // The granted permissions originally only held the effective hosts,
973 // which are a combination of host and user script host permissions.
974 // We now maintain these lists separately. For migration purposes, it
975 // does not matter how we treat the old effective hosts as long as the
976 // new effective hosts will be the same, so we move them to explicit
977 // host permissions.
978 const base::ListValue* hosts = NULL;
979 std::string explicit_hosts =
980 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
981 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
982 UpdateExtensionPref(
983 *ext_id, explicit_hosts, hosts->DeepCopy());
985 // We can get rid of the old one by setting it to an empty list.
986 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
991 void ExtensionPrefs::MigrateDisableReasons(
992 const ExtensionIdList& extension_ids) {
993 for (ExtensionIdList::const_iterator ext_id =
994 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
995 int value = -1;
996 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
997 int new_value = Extension::DISABLE_NONE;
998 switch (value) {
999 case Extension::DEPRECATED_DISABLE_USER_ACTION:
1000 new_value = Extension::DISABLE_USER_ACTION;
1001 break;
1002 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
1003 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
1004 break;
1005 case Extension::DEPRECATED_DISABLE_RELOAD:
1006 new_value = Extension::DISABLE_RELOAD;
1007 break;
1010 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
1011 new base::FundamentalValue(new_value));
1012 // Remove the old disable reason.
1013 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
1018 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
1019 const std::string& extension_id) {
1020 CHECK(crx_file::id_util::IdIsValid(extension_id));
1021 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
1024 void ExtensionPrefs::AddGrantedPermissions(
1025 const std::string& extension_id,
1026 const PermissionSet* permissions) {
1027 CHECK(crx_file::id_util::IdIsValid(extension_id));
1029 scoped_refptr<PermissionSet> granted_permissions(
1030 GetGrantedPermissions(extension_id));
1032 // The new granted permissions are the union of the already granted
1033 // permissions and the newly granted permissions.
1034 scoped_refptr<PermissionSet> new_perms(
1035 PermissionSet::CreateUnion(
1036 permissions, granted_permissions.get()));
1038 SetExtensionPrefPermissionSet(
1039 extension_id, kPrefGrantedPermissions, new_perms.get());
1042 void ExtensionPrefs::RemoveGrantedPermissions(
1043 const std::string& extension_id,
1044 const PermissionSet* permissions) {
1045 CHECK(crx_file::id_util::IdIsValid(extension_id));
1047 scoped_refptr<PermissionSet> granted_permissions(
1048 GetGrantedPermissions(extension_id));
1050 // The new granted permissions are the difference of the already granted
1051 // permissions and the newly ungranted permissions.
1052 scoped_refptr<PermissionSet> new_perms(
1053 PermissionSet::CreateDifference(
1054 granted_permissions.get(), permissions));
1056 SetExtensionPrefPermissionSet(
1057 extension_id, kPrefGrantedPermissions, new_perms.get());
1060 PermissionSet* ExtensionPrefs::GetActivePermissions(
1061 const std::string& extension_id) {
1062 CHECK(crx_file::id_util::IdIsValid(extension_id));
1063 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
1066 void ExtensionPrefs::SetActivePermissions(
1067 const std::string& extension_id,
1068 const PermissionSet* permissions) {
1069 SetExtensionPrefPermissionSet(
1070 extension_id, kPrefActivePermissions, permissions);
1073 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1074 bool is_running) {
1075 base::Value* value = new base::FundamentalValue(is_running);
1076 UpdateExtensionPref(extension_id, kPrefRunning, value);
1079 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) {
1080 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1081 if (!extension)
1082 return false;
1083 bool running = false;
1084 extension->GetBoolean(kPrefRunning, &running);
1085 return running;
1088 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1089 bool is_active) {
1090 base::Value* value = new base::FundamentalValue(is_active);
1091 UpdateExtensionPref(extension_id, kIsActive, value);
1094 bool ExtensionPrefs::IsActive(const std::string& extension_id) {
1095 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1096 if (!extension)
1097 return false;
1098 bool is_active = false;
1099 extension->GetBoolean(kIsActive, &is_active);
1100 return is_active;
1103 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1104 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1107 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1108 bool enabled) {
1109 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1110 new base::FundamentalValue(enabled));
1111 extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled);
1114 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1115 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1118 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1119 bool allow) {
1120 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1121 new base::FundamentalValue(allow));
1124 bool ExtensionPrefs::HasAllowFileAccessSetting(
1125 const std::string& extension_id) const {
1126 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1127 return ext && ext->HasKey(kPrefAllowFileAccess);
1130 bool ExtensionPrefs::DoesExtensionHaveState(
1131 const std::string& id, Extension::State check_state) const {
1132 const base::DictionaryValue* extension = GetExtensionPref(id);
1133 int state = -1;
1134 if (!extension || !extension->GetInteger(kPrefState, &state))
1135 return false;
1137 if (state < 0 || state >= Extension::NUM_STATES) {
1138 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1139 return false;
1142 return state == check_state;
1145 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1146 const std::string& id) const {
1147 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1150 bool ExtensionPrefs::IsExtensionDisabled(
1151 const std::string& id) const {
1152 return DoesExtensionHaveState(id, Extension::DISABLED);
1155 ExtensionIdList ExtensionPrefs::GetToolbarOrder() {
1156 ExtensionIdList id_list_out;
1157 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1158 return id_list_out;
1161 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1162 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1165 void ExtensionPrefs::OnExtensionInstalled(
1166 const Extension* extension,
1167 Extension::State initial_state,
1168 const syncer::StringOrdinal& page_ordinal,
1169 int install_flags,
1170 const std::string& install_parameter) {
1171 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1172 base::DictionaryValue* extension_dict = update.Get();
1173 const base::Time install_time = time_provider_->GetCurrentTime();
1174 PopulateExtensionInfoPrefs(extension,
1175 install_time,
1176 initial_state,
1177 install_flags,
1178 install_parameter,
1179 extension_dict);
1181 bool requires_sort_ordinal = extension->RequiresSortOrdinal() &&
1182 (install_flags & kInstallFlagIsEphemeral) == 0;
1183 FinishExtensionInfoPrefs(extension->id(),
1184 install_time,
1185 requires_sort_ordinal,
1186 page_ordinal,
1187 extension_dict);
1190 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1191 const Manifest::Location& location,
1192 bool external_uninstall) {
1193 app_sorting_->ClearOrdinals(extension_id);
1195 // For external extensions, we save a preference reminding ourself not to try
1196 // and install the extension anymore (except when |external_uninstall| is
1197 // true, which signifies that the registry key was deleted or the pref file
1198 // no longer lists the extension).
1199 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1200 UpdateExtensionPref(extension_id, kPrefState,
1201 new base::FundamentalValue(
1202 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1203 extension_pref_value_map_->SetExtensionState(extension_id, false);
1204 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1205 observer_list_,
1206 OnExtensionStateChanged(extension_id, false));
1207 } else {
1208 DeleteExtensionPrefs(extension_id);
1212 void ExtensionPrefs::SetExtensionState(const std::string& extension_id,
1213 Extension::State state) {
1214 UpdateExtensionPref(extension_id, kPrefState,
1215 new base::FundamentalValue(state));
1216 bool enabled = (state == Extension::ENABLED);
1217 extension_pref_value_map_->SetExtensionState(extension_id, enabled);
1218 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1219 observer_list_,
1220 OnExtensionStateChanged(extension_id, enabled));
1223 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1224 BlacklistState state) {
1225 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1226 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1227 new base::FundamentalValue(state));
1230 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1231 const std::string& extension_id) {
1232 if (IsExtensionBlacklisted(extension_id))
1233 return BLACKLISTED_MALWARE;
1234 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1235 int int_value = 0;
1236 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1237 return static_cast<BlacklistState>(int_value);
1239 return NOT_BLACKLISTED;
1242 std::string ExtensionPrefs::GetVersionString(const std::string& extension_id) {
1243 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1244 if (!extension)
1245 return std::string();
1247 std::string version;
1248 extension->GetString(kPrefVersion, &version);
1250 return version;
1253 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1254 if (!Manifest::IsUnpackedLocation(extension->location())) {
1255 const base::DictionaryValue* extension_dict =
1256 GetExtensionPref(extension->id());
1257 if (!extension_dict)
1258 return;
1259 const base::DictionaryValue* old_manifest = NULL;
1260 bool update_required =
1261 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1262 !extension->manifest()->value()->Equals(old_manifest);
1263 if (update_required) {
1264 UpdateExtensionPref(extension->id(), kPrefManifest,
1265 extension->manifest()->value()->DeepCopy());
1270 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1271 const std::string& extension_id,
1272 const base::DictionaryValue* extension) const {
1273 int location_value;
1274 if (!extension->GetInteger(kPrefLocation, &location_value))
1275 return scoped_ptr<ExtensionInfo>();
1277 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1278 if (location == Manifest::COMPONENT) {
1279 // Component extensions are ignored. Component extensions may have data
1280 // saved in preferences, but they are already loaded at this point (by
1281 // ComponentLoader) and shouldn't be populated into the result of
1282 // GetInstalledExtensionsInfo, otherwise InstalledLoader would also want to
1283 // load them.
1284 return scoped_ptr<ExtensionInfo>();
1287 // Only the following extension types have data saved in the preferences.
1288 if (location != Manifest::INTERNAL &&
1289 !Manifest::IsUnpackedLocation(location) &&
1290 !Manifest::IsExternalLocation(location)) {
1291 NOTREACHED();
1292 return scoped_ptr<ExtensionInfo>();
1295 const base::DictionaryValue* manifest = NULL;
1296 if (!Manifest::IsUnpackedLocation(location) &&
1297 !extension->GetDictionary(kPrefManifest, &manifest)) {
1298 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1299 // Just a warning for now.
1302 base::FilePath::StringType path;
1303 if (!extension->GetString(kPrefPath, &path))
1304 return scoped_ptr<ExtensionInfo>();
1306 // Make path absolute. Most (but not all) extension types have relative paths.
1307 if (!base::FilePath(path).IsAbsolute())
1308 path = install_directory_.Append(path).value();
1310 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1311 manifest, extension_id, base::FilePath(path), location));
1314 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1315 const std::string& extension_id) const {
1316 const base::DictionaryValue* ext = NULL;
1317 const base::DictionaryValue* extensions =
1318 prefs_->GetDictionary(pref_names::kExtensions);
1319 if (!extensions ||
1320 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1321 return scoped_ptr<ExtensionInfo>();
1322 int state_value;
1323 if (ext->GetInteger(kPrefState, &state_value) &&
1324 state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1325 LOG(WARNING) << "External extension with id " << extension_id
1326 << " has been uninstalled by the user";
1327 return scoped_ptr<ExtensionInfo>();
1330 return GetInstalledInfoHelper(extension_id, ext);
1333 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1334 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1335 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1337 const base::DictionaryValue* extensions =
1338 prefs_->GetDictionary(pref_names::kExtensions);
1339 for (base::DictionaryValue::Iterator extension_id(*extensions);
1340 !extension_id.IsAtEnd(); extension_id.Advance()) {
1341 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1342 continue;
1344 scoped_ptr<ExtensionInfo> info =
1345 GetInstalledExtensionInfo(extension_id.key());
1346 if (info)
1347 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1350 return extensions_info.Pass();
1353 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1354 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1355 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1357 const base::DictionaryValue* extensions =
1358 prefs_->GetDictionary(pref_names::kExtensions);
1359 for (base::DictionaryValue::Iterator extension_id(*extensions);
1360 !extension_id.IsAtEnd(); extension_id.Advance()) {
1361 const base::DictionaryValue* ext = NULL;
1362 if (!crx_file::id_util::IdIsValid(extension_id.key()) ||
1363 !IsExternalExtensionUninstalled(extension_id.key()) ||
1364 !extension_id.value().GetAsDictionary(&ext))
1365 continue;
1367 scoped_ptr<ExtensionInfo> info =
1368 GetInstalledInfoHelper(extension_id.key(), ext);
1369 if (info)
1370 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1373 return extensions_info.Pass();
1376 void ExtensionPrefs::SetDelayedInstallInfo(
1377 const Extension* extension,
1378 Extension::State initial_state,
1379 int install_flags,
1380 DelayReason delay_reason,
1381 const syncer::StringOrdinal& page_ordinal,
1382 const std::string& install_parameter) {
1383 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1384 PopulateExtensionInfoPrefs(extension,
1385 time_provider_->GetCurrentTime(),
1386 initial_state,
1387 install_flags,
1388 install_parameter,
1389 extension_dict);
1391 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1392 // should not be in the final extension prefs. All entries here should have
1393 // a corresponding Remove() call in FinishDelayedInstallInfo().
1394 if (extension->RequiresSortOrdinal() &&
1395 (install_flags & kInstallFlagIsEphemeral) == 0) {
1396 extension_dict->SetString(
1397 kPrefSuggestedPageOrdinal,
1398 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1399 : std::string());
1401 extension_dict->SetInteger(kDelayedInstallReason,
1402 static_cast<int>(delay_reason));
1404 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1407 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1408 const std::string& extension_id) {
1409 if (!GetExtensionPref(extension_id))
1410 return false;
1411 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1412 bool result = update->Remove(kDelayedInstallInfo, NULL);
1413 return result;
1416 bool ExtensionPrefs::FinishDelayedInstallInfo(
1417 const std::string& extension_id) {
1418 CHECK(crx_file::id_util::IdIsValid(extension_id));
1419 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1420 base::DictionaryValue* extension_dict = update.Get();
1421 base::DictionaryValue* pending_install_dict = NULL;
1422 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1423 &pending_install_dict)) {
1424 return false;
1427 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1428 // Also do any other data cleanup that makes sense.
1429 std::string serialized_ordinal;
1430 syncer::StringOrdinal suggested_page_ordinal;
1431 bool needs_sort_ordinal = false;
1432 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1433 &serialized_ordinal)) {
1434 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1435 needs_sort_ordinal = true;
1436 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1438 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1440 const base::Time install_time = time_provider_->GetCurrentTime();
1441 pending_install_dict->Set(
1442 kPrefInstallTime,
1443 new base::StringValue(
1444 base::Int64ToString(install_time.ToInternalValue())));
1446 // Some extension pref values are written conditionally. If they are not
1447 // present in the delayed install data, they should be removed when the
1448 // delayed install is committed.
1449 extension_dict->Remove(kPrefEphemeralApp, NULL);
1451 // Commit the delayed install data.
1452 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1453 it.Advance()) {
1454 extension_dict->Set(it.key(), it.value().DeepCopy());
1456 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1457 suggested_page_ordinal, extension_dict);
1458 return true;
1461 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1462 const std::string& extension_id) const {
1463 const base::DictionaryValue* extension_prefs =
1464 GetExtensionPref(extension_id);
1465 if (!extension_prefs)
1466 return scoped_ptr<ExtensionInfo>();
1468 const base::DictionaryValue* ext = NULL;
1469 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1470 return scoped_ptr<ExtensionInfo>();
1472 return GetInstalledInfoHelper(extension_id, ext);
1475 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1476 const std::string& extension_id) const {
1477 const base::DictionaryValue* extension_prefs =
1478 GetExtensionPref(extension_id);
1479 if (!extension_prefs)
1480 return DELAY_REASON_NONE;
1482 const base::DictionaryValue* ext = NULL;
1483 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1484 return DELAY_REASON_NONE;
1486 int delay_reason;
1487 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1488 return DELAY_REASON_NONE;
1490 return static_cast<DelayReason>(delay_reason);
1493 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1494 GetAllDelayedInstallInfo() const {
1495 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1497 const base::DictionaryValue* extensions =
1498 prefs_->GetDictionary(pref_names::kExtensions);
1499 for (base::DictionaryValue::Iterator extension_id(*extensions);
1500 !extension_id.IsAtEnd(); extension_id.Advance()) {
1501 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1502 continue;
1504 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1505 if (info)
1506 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1509 return extensions_info.Pass();
1512 bool ExtensionPrefs::IsEphemeralApp(const std::string& extension_id) const {
1513 if (ReadPrefAsBooleanAndReturn(extension_id, kPrefEphemeralApp))
1514 return true;
1516 // Ephemerality was previously stored in the creation flags, so we must also
1517 // check it for backcompatibility.
1518 return (GetCreationFlags(extension_id) & Extension::IS_EPHEMERAL) != 0;
1521 void ExtensionPrefs::OnEphemeralAppPromoted(const std::string& extension_id) {
1522 DCHECK(IsEphemeralApp(extension_id));
1524 UpdateExtensionPref(extension_id, kPrefEphemeralApp, NULL);
1526 // Ephemerality was previously stored in the creation flags, so ensure the bit
1527 // is cleared.
1528 int creation_flags = Extension::NO_FLAGS;
1529 if (ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1530 if (creation_flags & Extension::IS_EPHEMERAL) {
1531 creation_flags &= ~static_cast<int>(Extension::IS_EPHEMERAL);
1532 UpdateExtensionPref(extension_id,
1533 kPrefCreationFlags,
1534 new base::FundamentalValue(creation_flags));
1539 bool ExtensionPrefs::WasAppDraggedByUser(const std::string& extension_id) {
1540 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1543 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1544 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1545 new base::FundamentalValue(true));
1548 bool ExtensionPrefs::IsFromWebStore(
1549 const std::string& extension_id) const {
1550 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1551 bool result = false;
1552 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1553 return result;
1554 return false;
1557 bool ExtensionPrefs::IsFromBookmark(
1558 const std::string& extension_id) const {
1559 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1560 bool result = false;
1561 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1562 return result;
1563 return false;
1566 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1567 int creation_flags = Extension::NO_FLAGS;
1568 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1569 // Since kPrefCreationFlags was added later, it will be missing for
1570 // previously installed extensions.
1571 if (IsFromBookmark(extension_id))
1572 creation_flags |= Extension::FROM_BOOKMARK;
1573 if (IsFromWebStore(extension_id))
1574 creation_flags |= Extension::FROM_WEBSTORE;
1575 if (WasInstalledByDefault(extension_id))
1576 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1577 if (WasInstalledByOem(extension_id))
1578 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
1580 return creation_flags;
1583 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1584 const std::string& extension_id) const {
1585 int creation_flags = Extension::NO_FLAGS;
1586 const base::DictionaryValue* delayed_info = NULL;
1587 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1588 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1590 return creation_flags;
1593 bool ExtensionPrefs::WasInstalledByDefault(
1594 const std::string& extension_id) const {
1595 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1596 bool result = false;
1597 if (dictionary &&
1598 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1599 return result;
1600 return false;
1603 bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const {
1604 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1605 bool result = false;
1606 if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result))
1607 return result;
1608 return false;
1611 base::Time ExtensionPrefs::GetInstallTime(
1612 const std::string& extension_id) const {
1613 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1614 if (!extension) {
1615 NOTREACHED();
1616 return base::Time();
1618 std::string install_time_str;
1619 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1620 return base::Time();
1621 int64 install_time_i64 = 0;
1622 if (!base::StringToInt64(install_time_str, &install_time_i64))
1623 return base::Time();
1624 return base::Time::FromInternalValue(install_time_i64);
1627 bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const {
1628 bool do_not_sync;
1629 if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync))
1630 return false;
1632 return do_not_sync;
1635 base::Time ExtensionPrefs::GetLastLaunchTime(
1636 const std::string& extension_id) const {
1637 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1638 if (!extension)
1639 return base::Time();
1641 std::string launch_time_str;
1642 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1643 return base::Time();
1644 int64 launch_time_i64 = 0;
1645 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1646 return base::Time();
1647 return base::Time::FromInternalValue(launch_time_i64);
1650 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1651 const base::Time& time) {
1652 DCHECK(crx_file::id_util::IdIsValid(extension_id));
1653 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1654 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1657 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) {
1658 CHECK(out);
1660 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1662 for (size_t i = 0; i < extensions_info->size(); ++i) {
1663 ExtensionInfo* info = extensions_info->at(i).get();
1664 out->push_back(info->extension_id);
1668 // static
1669 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1670 const PrefService* pref_service) {
1671 ExtensionIdList result;
1673 const base::DictionaryValue* extension_prefs = NULL;
1674 const base::Value* extension_prefs_value =
1675 pref_service->GetUserPrefValue(pref_names::kExtensions);
1676 if (!extension_prefs_value ||
1677 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1678 return result; // Empty set
1681 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1682 it.Advance()) {
1683 const base::DictionaryValue* ext = NULL;
1684 if (!it.value().GetAsDictionary(&ext)) {
1685 NOTREACHED() << "Invalid pref for extension " << it.key();
1686 continue;
1688 if (!IsBlacklistBitSet(ext))
1689 result.push_back(it.key());
1691 return result;
1694 void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) {
1695 observer_list_.AddObserver(observer);
1698 void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) {
1699 observer_list_.RemoveObserver(observer);
1702 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1703 // Fix old entries that did not get an installation time entry when they
1704 // were installed or don't have a preferences field.
1705 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1706 ext_id != extension_ids.end(); ++ext_id) {
1707 if (GetInstallTime(*ext_id) == base::Time()) {
1708 VLOG(1) << "Could not parse installation time of extension "
1709 << *ext_id << ". It was probably installed before setting "
1710 << kPrefInstallTime << " was introduced. Updating "
1711 << kPrefInstallTime << " to the current time.";
1712 const base::Time install_time = time_provider_->GetCurrentTime();
1713 UpdateExtensionPref(*ext_id,
1714 kPrefInstallTime,
1715 new base::StringValue(base::Int64ToString(
1716 install_time.ToInternalValue())));
1721 void ExtensionPrefs::InitPrefStore() {
1722 if (extensions_disabled_) {
1723 extension_pref_value_map_->NotifyInitializationCompleted();
1724 return;
1727 // When this is called, the PrefService is initialized and provides access
1728 // to the user preferences stored in a JSON file.
1729 ExtensionIdList extension_ids;
1730 GetExtensions(&extension_ids);
1731 // Create empty preferences dictionary for each extension (these dictionaries
1732 // are pruned when persisting the preferences to disk).
1733 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1734 ext_id != extension_ids.end(); ++ext_id) {
1735 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1736 // This creates an empty dictionary if none is stored.
1737 update.Get();
1740 FixMissingPrefs(extension_ids);
1741 MigratePermissions(extension_ids);
1742 MigrateDisableReasons(extension_ids);
1743 app_sorting_->Initialize(extension_ids);
1745 InitExtensionControlledPrefs(extension_pref_value_map_);
1747 extension_pref_value_map_->NotifyInitializationCompleted();
1750 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) {
1751 bool has_incognito_pref_value = false;
1752 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1753 true,
1754 &has_incognito_pref_value);
1755 return has_incognito_pref_value;
1758 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1759 const std::string& extension_id) const {
1760 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1761 if (!extension_prefs)
1762 return NULL;
1764 const base::DictionaryValue* ext = NULL;
1765 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1766 return NULL;
1768 return ext;
1771 void ExtensionPrefs::SetGeometryCache(
1772 const std::string& extension_id,
1773 scoped_ptr<base::DictionaryValue> cache) {
1774 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1777 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() {
1778 return prefs_->GetDictionary(kInstallSignature);
1781 void ExtensionPrefs::SetInstallSignature(
1782 const base::DictionaryValue* signature) {
1783 if (signature) {
1784 prefs_->Set(kInstallSignature, *signature);
1785 DVLOG(1) << "SetInstallSignature - saving";
1786 } else {
1787 DVLOG(1) << "SetInstallSignature - clearing";
1788 prefs_->ClearPref(kInstallSignature);
1792 std::string ExtensionPrefs::GetInstallParam(
1793 const std::string& extension_id) const {
1794 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1795 if (!extension) // Expected during unit testing.
1796 return std::string();
1797 std::string install_parameter;
1798 if (!extension->GetString(kPrefInstallParam, &install_parameter))
1799 return std::string();
1800 return install_parameter;
1803 void ExtensionPrefs::SetInstallParam(const std::string& extension_id,
1804 const std::string& install_parameter) {
1805 UpdateExtensionPref(extension_id,
1806 kPrefInstallParam,
1807 new base::StringValue(install_parameter));
1810 int ExtensionPrefs::GetCorruptedDisableCount() {
1811 return prefs_->GetInteger(kCorruptedDisableCount);
1814 void ExtensionPrefs::IncrementCorruptedDisableCount() {
1815 int count = prefs_->GetInteger(kCorruptedDisableCount);
1816 prefs_->SetInteger(kCorruptedDisableCount, count + 1);
1819 ExtensionPrefs::ExtensionPrefs(
1820 PrefService* prefs,
1821 const base::FilePath& root_dir,
1822 ExtensionPrefValueMap* extension_pref_value_map,
1823 scoped_ptr<AppSorting> app_sorting,
1824 scoped_ptr<TimeProvider> time_provider,
1825 bool extensions_disabled,
1826 const std::vector<ExtensionPrefsObserver*>& early_observers)
1827 : prefs_(prefs),
1828 install_directory_(root_dir),
1829 extension_pref_value_map_(extension_pref_value_map),
1830 app_sorting_(app_sorting.Pass()),
1831 time_provider_(time_provider.Pass()),
1832 extensions_disabled_(extensions_disabled) {
1833 app_sorting_->SetExtensionScopedPrefs(this);
1834 MakePathsRelative();
1836 // Ensure that any early observers are watching before prefs are initialized.
1837 for (std::vector<ExtensionPrefsObserver*>::const_iterator iter =
1838 early_observers.begin();
1839 iter != early_observers.end();
1840 ++iter) {
1841 AddObserver(*iter);
1844 InitPrefStore();
1847 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1848 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1851 bool ExtensionPrefs::NeedsStorageGarbageCollection() {
1852 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1855 // static
1856 void ExtensionPrefs::RegisterProfilePrefs(
1857 user_prefs::PrefRegistrySyncable* registry) {
1858 registry->RegisterDictionaryPref(
1859 pref_names::kExtensions,
1860 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1861 registry->RegisterListPref(pref_names::kToolbar,
1862 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1863 registry->RegisterIntegerPref(
1864 pref_names::kToolbarSize,
1865 -1, // default value
1866 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1867 registry->RegisterDictionaryPref(
1868 kExtensionsBlacklistUpdate,
1869 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1870 registry->RegisterListPref(pref_names::kInstallAllowList,
1871 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1872 registry->RegisterListPref(pref_names::kInstallDenyList,
1873 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1874 registry->RegisterDictionaryPref(
1875 pref_names::kInstallForceList,
1876 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1877 registry->RegisterListPref(pref_names::kAllowedTypes,
1878 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1879 registry->RegisterBooleanPref(
1880 pref_names::kStorageGarbageCollect,
1881 false, // default value
1882 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1883 registry->RegisterInt64Pref(
1884 pref_names::kLastUpdateCheck,
1885 0, // default value
1886 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1887 registry->RegisterInt64Pref(
1888 pref_names::kNextUpdateCheck,
1889 0, // default value
1890 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1891 registry->RegisterListPref(pref_names::kAllowedInstallSites,
1892 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1893 registry->RegisterStringPref(
1894 pref_names::kLastChromeVersion,
1895 std::string(), // default value
1896 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1897 registry->RegisterDictionaryPref(
1898 kInstallSignature,
1899 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1901 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist,
1902 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1903 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist,
1904 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1905 registry->RegisterBooleanPref(
1906 pref_names::kNativeMessagingUserLevelHosts,
1907 true, // default value
1908 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1909 registry->RegisterIntegerPref(
1910 kCorruptedDisableCount,
1911 0, // default value
1912 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1914 #if !defined(OS_MACOSX)
1915 registry->RegisterBooleanPref(
1916 pref_names::kAppFullscreenAllowed, true,
1917 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1918 #endif
1921 template <class ExtensionIdContainer>
1922 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
1923 const char* pref,
1924 ExtensionIdContainer* id_container_out) {
1925 DCHECK(id_container_out->empty());
1927 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
1928 const base::ListValue* user_pref_as_list;
1929 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
1930 return false;
1932 std::insert_iterator<ExtensionIdContainer> insert_iterator(
1933 *id_container_out, id_container_out->end());
1934 std::string extension_id;
1935 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
1936 value_it != user_pref_as_list->end(); ++value_it) {
1937 if (!(*value_it)->GetAsString(&extension_id)) {
1938 NOTREACHED();
1939 continue;
1941 insert_iterator = extension_id;
1943 return true;
1946 template <class ExtensionIdContainer>
1947 void ExtensionPrefs::SetExtensionPrefFromContainer(
1948 const char* pref,
1949 const ExtensionIdContainer& strings) {
1950 ListPrefUpdate update(prefs_, pref);
1951 base::ListValue* list_of_values = update.Get();
1952 list_of_values->Clear();
1953 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
1954 iter != strings.end(); ++iter) {
1955 list_of_values->Append(new base::StringValue(*iter));
1959 void ExtensionPrefs::PopulateExtensionInfoPrefs(
1960 const Extension* extension,
1961 const base::Time install_time,
1962 Extension::State initial_state,
1963 int install_flags,
1964 const std::string& install_parameter,
1965 base::DictionaryValue* extension_dict) {
1966 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
1967 extension_dict->Set(kPrefLocation,
1968 new base::FundamentalValue(extension->location()));
1969 extension_dict->Set(kPrefCreationFlags,
1970 new base::FundamentalValue(extension->creation_flags()));
1971 extension_dict->Set(kPrefFromWebStore,
1972 new base::FundamentalValue(extension->from_webstore()));
1973 extension_dict->Set(kPrefFromBookmark,
1974 new base::FundamentalValue(extension->from_bookmark()));
1975 extension_dict->Set(
1976 kPrefWasInstalledByDefault,
1977 new base::FundamentalValue(extension->was_installed_by_default()));
1978 extension_dict->Set(
1979 kPrefWasInstalledByOem,
1980 new base::FundamentalValue(extension->was_installed_by_oem()));
1981 extension_dict->Set(kPrefInstallTime,
1982 new base::StringValue(
1983 base::Int64ToString(install_time.ToInternalValue())));
1984 if (install_flags & kInstallFlagIsBlacklistedForMalware)
1985 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
1987 if (install_flags & kInstallFlagIsEphemeral)
1988 extension_dict->Set(kPrefEphemeralApp, new base::FundamentalValue(true));
1989 else
1990 extension_dict->Remove(kPrefEphemeralApp, NULL);
1992 base::FilePath::StringType path = MakePathRelative(install_directory_,
1993 extension->path());
1994 extension_dict->Set(kPrefPath, new base::StringValue(path));
1995 if (!install_parameter.empty()) {
1996 extension_dict->Set(kPrefInstallParam,
1997 new base::StringValue(install_parameter));
1999 // We store prefs about LOAD extensions, but don't cache their manifest
2000 // since it may change on disk.
2001 if (!Manifest::IsUnpackedLocation(extension->location())) {
2002 extension_dict->Set(kPrefManifest,
2003 extension->manifest()->value()->DeepCopy());
2006 // Only writes kPrefDoNotSync when it is not the default.
2007 if (install_flags & kInstallFlagDoNotSync)
2008 extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true));
2009 else
2010 extension_dict->Remove(kPrefDoNotSync, NULL);
2013 void ExtensionPrefs::InitExtensionControlledPrefs(
2014 ExtensionPrefValueMap* value_map) {
2015 ExtensionIdList extension_ids;
2016 GetExtensions(&extension_ids);
2018 for (ExtensionIdList::iterator extension_id = extension_ids.begin();
2019 extension_id != extension_ids.end();
2020 ++extension_id) {
2021 base::Time install_time = GetInstallTime(*extension_id);
2022 bool is_enabled = !IsExtensionDisabled(*extension_id);
2023 bool is_incognito_enabled = IsIncognitoEnabled(*extension_id);
2024 value_map->RegisterExtension(
2025 *extension_id, install_time, is_enabled, is_incognito_enabled);
2027 FOR_EACH_OBSERVER(
2028 ExtensionPrefsObserver,
2029 observer_list_,
2030 OnExtensionRegistered(*extension_id, install_time, is_enabled));
2032 // Set regular extension controlled prefs.
2033 LoadExtensionControlledPrefs(
2034 this, value_map, *extension_id, kExtensionPrefsScopeRegular);
2035 // Set incognito extension controlled prefs.
2036 LoadExtensionControlledPrefs(this,
2037 value_map,
2038 *extension_id,
2039 kExtensionPrefsScopeIncognitoPersistent);
2040 // Set regular-only extension controlled prefs.
2041 LoadExtensionControlledPrefs(
2042 this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly);
2044 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
2045 observer_list_,
2046 OnExtensionPrefsLoaded(*extension_id, this));
2050 void ExtensionPrefs::FinishExtensionInfoPrefs(
2051 const std::string& extension_id,
2052 const base::Time install_time,
2053 bool needs_sort_ordinal,
2054 const syncer::StringOrdinal& suggested_page_ordinal,
2055 base::DictionaryValue* extension_dict) {
2056 // Reinitializes various preferences with empty dictionaries.
2057 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
2058 extension_dict->Set(pref_names::kPrefPreferences,
2059 new base::DictionaryValue);
2062 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
2063 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
2064 new base::DictionaryValue);
2067 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
2068 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
2069 new base::DictionaryValue);
2072 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
2073 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
2075 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
2076 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
2077 new base::ListValue);
2080 // If this point has been reached, any pending installs should be considered
2081 // out of date.
2082 extension_dict->Remove(kDelayedInstallInfo, NULL);
2084 // Clear state that may be registered from a previous install.
2085 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
2087 // FYI, all code below here races on sudden shutdown because |extension_dict|,
2088 // |app_sorting_|, |extension_pref_value_map_|, and (potentially) observers
2089 // are updated non-transactionally. This is probably not fixable without
2090 // nested transactional updates to pref dictionaries.
2091 if (needs_sort_ordinal)
2092 app_sorting_->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
2094 bool is_enabled = false;
2095 int initial_state;
2096 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
2097 is_enabled = initial_state == Extension::ENABLED;
2099 bool is_incognito_enabled = IsIncognitoEnabled(extension_id);
2101 extension_pref_value_map_->RegisterExtension(
2102 extension_id, install_time, is_enabled, is_incognito_enabled);
2104 FOR_EACH_OBSERVER(
2105 ExtensionPrefsObserver,
2106 observer_list_,
2107 OnExtensionRegistered(extension_id, install_time, is_enabled));
2110 } // namespace extensions