Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / extensions / browser / extension_prefs.cc
blob864a4f9a1b72c007db5544a99bc5659d9b618e33
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/admin_policy.h"
18 #include "extensions/browser/app_sorting.h"
19 #include "extensions/browser/event_router.h"
20 #include "extensions/browser/extension_pref_store.h"
21 #include "extensions/browser/extension_prefs_factory.h"
22 #include "extensions/browser/extension_prefs_observer.h"
23 #include "extensions/browser/install_flag.h"
24 #include "extensions/browser/pref_names.h"
25 #include "extensions/common/feature_switch.h"
26 #include "extensions/common/manifest.h"
27 #include "extensions/common/permissions/permission_set.h"
28 #include "extensions/common/permissions/permissions_info.h"
29 #include "extensions/common/url_pattern.h"
30 #include "extensions/common/user_script.h"
31 #include "ui/base/l10n/l10n_util.h"
33 using base::Value;
34 using base::DictionaryValue;
35 using base::ListValue;
37 namespace extensions {
39 namespace {
41 // Additional preferences keys, which are not needed by external clients.
43 // True if this extension is running. Note this preference stops getting updated
44 // during Chrome shutdown (and won't be updated on a browser crash) and so can
45 // be used at startup to determine whether the extension was running when Chrome
46 // was last terminated.
47 const char kPrefRunning[] = "running";
49 // Whether this extension had windows when it was last running.
50 const char kIsActive[] = "is_active";
52 // Where an extension was installed from. (see Manifest::Location)
53 const char kPrefLocation[] = "location";
55 // Enabled, disabled, killed, etc. (see Extension::State)
56 const char kPrefState[] = "state";
58 // The path to the current version's manifest file.
59 const char kPrefPath[] = "path";
61 // The dictionary containing the extension's manifest.
62 const char kPrefManifest[] = "manifest";
64 // The version number.
65 const char kPrefVersion[] = "manifest.version";
67 // Indicates whether an extension is blacklisted.
68 const char kPrefBlacklist[] = "blacklist";
70 // If extension is greylisted.
71 const char kPrefBlacklistState[] = "blacklist_state";
73 // The count of how many times we prompted the user to acknowledge an
74 // extension.
75 const char kPrefAcknowledgePromptCount[] = "ack_prompt_count";
77 // Indicates whether the user has acknowledged various types of extensions.
78 const char kPrefExternalAcknowledged[] = "ack_external";
79 const char kPrefBlacklistAcknowledged[] = "ack_blacklist";
80 const char kPrefWipeoutAcknowledged[] = "ack_wiped";
81 const char kPrefSettingsBubbleAcknowledged[] = "ack_settings_bubble";
82 const char kPrefNtpBubbleAcknowledged[] = "ack_ntp_bubble";
83 const char kPrefProxyBubbleAcknowledged[] = "ack_proxy_bubble";
85 // Indicates whether the external extension was installed during the first
86 // run of this profile.
87 const char kPrefExternalInstallFirstRun[] = "external_first_run";
89 // Indicates whether to show an install warning when the user enables.
90 const char kExtensionDidEscalatePermissions[] = "install_warning_on_enable";
92 // DO NOT USE, use kPrefDisableReasons instead.
93 // Indicates whether the extension was updated while it was disabled.
94 const char kDeprecatedPrefDisableReason[] = "disable_reason";
96 // A bitmask of all the reasons an extension is disabled.
97 const char kPrefDisableReasons[] = "disable_reasons";
99 // The key for a serialized Time value indicating the start of the day (from the
100 // server's perspective) an extension last included a "ping" parameter during
101 // its update check.
102 const char kLastPingDay[] = "lastpingday";
104 // Similar to kLastPingDay, but for "active" instead of "rollcall" pings.
105 const char kLastActivePingDay[] = "last_active_pingday";
107 // A bit we use to keep track of whether we need to do an "active" ping.
108 const char kActiveBit[] = "active_bit";
110 // Path for settings specific to blacklist update.
111 const char kExtensionsBlacklistUpdate[] = "extensions.blacklistupdate";
113 // Path for the delayed install info dictionary preference. The actual string
114 // value is a legacy artifact for when delayed installs only pertained to
115 // updates that were waiting for idle.
116 const char kDelayedInstallInfo[] = "idle_install_info";
118 // Reason why the extension's install was delayed.
119 const char kDelayedInstallReason[] = "delay_install_reason";
121 // Path for the suggested page ordinal of a delayed extension install.
122 const char kPrefSuggestedPageOrdinal[] = "suggested_page_ordinal";
124 // A preference that, if true, will allow this extension to run in incognito
125 // mode.
126 const char kPrefIncognitoEnabled[] = "incognito";
128 // A preference to control whether an extension is allowed to inject script in
129 // pages with file URLs.
130 const char kPrefAllowFileAccess[] = "newAllowFileAccess";
131 // TODO(jstritar): As part of fixing http://crbug.com/91577, we revoked all
132 // extension file access by renaming the pref. We should eventually clean up
133 // the old flag and possibly go back to that name.
134 // const char kPrefAllowFileAccessOld[] = "allowFileAccess";
136 // A preference specifying if the user dragged the app on the NTP.
137 const char kPrefUserDraggedApp[] = "user_dragged_app_ntp";
139 // Preferences that hold which permissions the user has granted the extension.
140 // We explicitly keep track of these so that extensions can contain unknown
141 // permissions, for backwards compatibility reasons, and we can still prompt
142 // the user to accept them once recognized. We store the active permission
143 // permissions because they may differ from those defined in the manifest.
144 const char kPrefActivePermissions[] = "active_permissions";
145 const char kPrefGrantedPermissions[] = "granted_permissions";
147 // The preference names for PermissionSet values.
148 const char kPrefAPIs[] = "api";
149 const char kPrefManifestPermissions[] = "manifest_permissions";
150 const char kPrefExplicitHosts[] = "explicit_host";
151 const char kPrefScriptableHosts[] = "scriptable_host";
153 // The preference names for the old granted permissions scheme.
154 const char kPrefOldGrantedFullAccess[] = "granted_permissions.full";
155 const char kPrefOldGrantedHosts[] = "granted_permissions.host";
156 const char kPrefOldGrantedAPIs[] = "granted_permissions.api";
158 // A preference that indicates when an extension was installed.
159 const char kPrefInstallTime[] = "install_time";
161 // A preference which saves the creation flags for extensions.
162 const char kPrefCreationFlags[] = "creation_flags";
164 // A preference that indicates whether the extension was installed from the
165 // Chrome Web Store.
166 const char kPrefFromWebStore[] = "from_webstore";
168 // A preference that indicates whether the extension was installed from a
169 // mock App created from a bookmark.
170 const char kPrefFromBookmark[] = "from_bookmark";
172 // A preference that indicates whether the extension was installed as a
173 // default app.
174 const char kPrefWasInstalledByDefault[] = "was_installed_by_default";
176 // A preference that indicates whether the extension was installed as an
177 // OEM app.
178 const char kPrefWasInstalledByOem[] = "was_installed_by_oem";
180 // Key for Geometry Cache preference.
181 const char kPrefGeometryCache[] = "geometry_cache";
183 // A preference that indicates when an extension is last launched.
184 const char kPrefLastLaunchTime[] = "last_launch_time";
186 // A preference indicating whether the extension is an ephemeral app.
187 const char kPrefEphemeralApp[] = "ephemeral_app";
189 // Am installation parameter bundled with an extension.
190 const char kPrefInstallParam[] = "install_parameter";
192 // A list of installed ids and a signature.
193 const char kInstallSignature[] = "extensions.install_signature";
195 // A boolean preference that indicates whether the extension should not be
196 // synced. Default value is false.
197 const char kPrefDoNotSync[] = "do_not_sync";
199 const char kCorruptedDisableCount[] = "extensions.corrupted_disable_count";
201 // Provider of write access to a dictionary storing extension prefs.
202 class ScopedExtensionPrefUpdate : public DictionaryPrefUpdate {
203 public:
204 ScopedExtensionPrefUpdate(PrefService* service,
205 const std::string& extension_id) :
206 DictionaryPrefUpdate(service, pref_names::kExtensions),
207 extension_id_(extension_id) {}
209 virtual ~ScopedExtensionPrefUpdate() {
212 // DictionaryPrefUpdate overrides:
213 virtual base::DictionaryValue* Get() OVERRIDE {
214 base::DictionaryValue* dict = DictionaryPrefUpdate::Get();
215 base::DictionaryValue* extension = NULL;
216 if (!dict->GetDictionary(extension_id_, &extension)) {
217 // Extension pref does not exist, create it.
218 extension = new base::DictionaryValue();
219 dict->SetWithoutPathExpansion(extension_id_, extension);
221 return extension;
224 private:
225 const std::string extension_id_;
227 DISALLOW_COPY_AND_ASSIGN(ScopedExtensionPrefUpdate);
230 std::string JoinPrefs(const std::string& parent, const char* child) {
231 return parent + "." + child;
234 // Checks if kPrefBlacklist is set to true in the base::DictionaryValue.
235 // Return false if the value is false or kPrefBlacklist does not exist.
236 // This is used to decide if an extension is blacklisted.
237 bool IsBlacklistBitSet(const base::DictionaryValue* ext) {
238 bool bool_value;
239 return ext->GetBoolean(kPrefBlacklist, &bool_value) && bool_value;
242 void LoadExtensionControlledPrefs(ExtensionPrefs* prefs,
243 ExtensionPrefValueMap* value_map,
244 const std::string& extension_id,
245 ExtensionPrefsScope scope) {
246 std::string scope_string;
247 if (!pref_names::ScopeToPrefName(scope, &scope_string))
248 return;
249 std::string key = extension_id + "." + scope_string;
251 const base::DictionaryValue* source_dict =
252 prefs->pref_service()->GetDictionary(pref_names::kExtensions);
253 const base::DictionaryValue* preferences = NULL;
254 if (!source_dict->GetDictionary(key, &preferences))
255 return;
257 for (base::DictionaryValue::Iterator iter(*preferences); !iter.IsAtEnd();
258 iter.Advance()) {
259 value_map->SetExtensionPref(
260 extension_id, iter.key(), scope, iter.value().DeepCopy());
264 } // namespace
267 // TimeProvider
270 ExtensionPrefs::TimeProvider::TimeProvider() {
273 ExtensionPrefs::TimeProvider::~TimeProvider() {
276 base::Time ExtensionPrefs::TimeProvider::GetCurrentTime() const {
277 return base::Time::Now();
281 // ScopedUpdate
283 template <typename T, base::Value::Type type_enum_value>
284 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::ScopedUpdate(
285 ExtensionPrefs* prefs,
286 const std::string& extension_id,
287 const std::string& key)
288 : update_(prefs->pref_service(), pref_names::kExtensions),
289 extension_id_(extension_id),
290 key_(key) {
291 DCHECK(crx_file::id_util::IdIsValid(extension_id_));
294 template <typename T, base::Value::Type type_enum_value>
295 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::~ScopedUpdate() {
298 template <typename T, base::Value::Type type_enum_value>
299 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Get() {
300 base::DictionaryValue* dict = update_.Get();
301 base::DictionaryValue* extension = NULL;
302 base::Value* key_value = NULL;
303 if (!dict->GetDictionary(extension_id_, &extension) ||
304 !extension->Get(key_, &key_value)) {
305 return NULL;
307 return key_value->GetType() == type_enum_value ?
308 static_cast<T*>(key_value) :
309 NULL;
312 template <typename T, base::Value::Type type_enum_value>
313 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Create() {
314 base::DictionaryValue* dict = update_.Get();
315 base::DictionaryValue* extension = NULL;
316 base::Value* key_value = NULL;
317 T* value_as_t = NULL;
318 if (!dict->GetDictionary(extension_id_, &extension)) {
319 extension = new base::DictionaryValue;
320 dict->SetWithoutPathExpansion(extension_id_, extension);
322 if (!extension->Get(key_, &key_value)) {
323 value_as_t = new T;
324 extension->SetWithoutPathExpansion(key_, value_as_t);
325 } else {
326 CHECK(key_value->GetType() == type_enum_value);
327 value_as_t = static_cast<T*>(key_value);
329 return value_as_t;
332 // Explicit instantiations for Dictionary and List value types.
333 template class ExtensionPrefs::ScopedUpdate<base::DictionaryValue,
334 base::Value::TYPE_DICTIONARY>;
335 template class ExtensionPrefs::ScopedUpdate<base::ListValue,
336 base::Value::TYPE_LIST>;
339 // ExtensionPrefs
342 // static
343 ExtensionPrefs* ExtensionPrefs::Create(
344 PrefService* prefs,
345 const base::FilePath& root_dir,
346 ExtensionPrefValueMap* extension_pref_value_map,
347 scoped_ptr<AppSorting> app_sorting,
348 bool extensions_disabled,
349 const std::vector<ExtensionPrefsObserver*>& early_observers) {
350 return ExtensionPrefs::Create(prefs,
351 root_dir,
352 extension_pref_value_map,
353 app_sorting.Pass(),
354 extensions_disabled,
355 early_observers,
356 make_scoped_ptr(new TimeProvider()));
359 // static
360 ExtensionPrefs* ExtensionPrefs::Create(
361 PrefService* pref_service,
362 const base::FilePath& root_dir,
363 ExtensionPrefValueMap* extension_pref_value_map,
364 scoped_ptr<AppSorting> app_sorting,
365 bool extensions_disabled,
366 const std::vector<ExtensionPrefsObserver*>& early_observers,
367 scoped_ptr<TimeProvider> time_provider) {
368 return new ExtensionPrefs(pref_service,
369 root_dir,
370 extension_pref_value_map,
371 app_sorting.Pass(),
372 time_provider.Pass(),
373 extensions_disabled,
374 early_observers);
377 ExtensionPrefs::~ExtensionPrefs() {
380 // static
381 ExtensionPrefs* ExtensionPrefs::Get(content::BrowserContext* context) {
382 return ExtensionPrefsFactory::GetInstance()->GetForBrowserContext(context);
385 static base::FilePath::StringType MakePathRelative(const base::FilePath& parent,
386 const base::FilePath& child) {
387 if (!parent.IsParent(child))
388 return child.value();
390 base::FilePath::StringType retval = child.value().substr(
391 parent.value().length());
392 if (base::FilePath::IsSeparator(retval[0]))
393 return retval.substr(1);
394 else
395 return retval;
398 void ExtensionPrefs::MakePathsRelative() {
399 const base::DictionaryValue* dict =
400 prefs_->GetDictionary(pref_names::kExtensions);
401 if (!dict || dict->empty())
402 return;
404 // Collect all extensions ids with absolute paths in |absolute_keys|.
405 std::set<std::string> absolute_keys;
406 for (base::DictionaryValue::Iterator i(*dict); !i.IsAtEnd(); i.Advance()) {
407 const base::DictionaryValue* extension_dict = NULL;
408 if (!i.value().GetAsDictionary(&extension_dict))
409 continue;
410 int location_value;
411 if (extension_dict->GetInteger(kPrefLocation, &location_value) &&
412 Manifest::IsUnpackedLocation(
413 static_cast<Manifest::Location>(location_value))) {
414 // Unpacked extensions can have absolute paths.
415 continue;
417 base::FilePath::StringType path_string;
418 if (!extension_dict->GetString(kPrefPath, &path_string))
419 continue;
420 base::FilePath path(path_string);
421 if (path.IsAbsolute())
422 absolute_keys.insert(i.key());
424 if (absolute_keys.empty())
425 return;
427 // Fix these paths.
428 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
429 base::DictionaryValue* update_dict = update.Get();
430 for (std::set<std::string>::iterator i = absolute_keys.begin();
431 i != absolute_keys.end(); ++i) {
432 base::DictionaryValue* extension_dict = NULL;
433 if (!update_dict->GetDictionaryWithoutPathExpansion(*i, &extension_dict)) {
434 NOTREACHED() << "Control should never reach here for extension " << *i;
435 continue;
437 base::FilePath::StringType path_string;
438 extension_dict->GetString(kPrefPath, &path_string);
439 base::FilePath path(path_string);
440 extension_dict->SetString(kPrefPath,
441 MakePathRelative(install_directory_, path));
445 const base::DictionaryValue* ExtensionPrefs::GetExtensionPref(
446 const std::string& extension_id) const {
447 const base::DictionaryValue* extensions =
448 prefs_->GetDictionary(pref_names::kExtensions);
449 const base::DictionaryValue* extension_dict = NULL;
450 if (!extensions ||
451 !extensions->GetDictionary(extension_id, &extension_dict)) {
452 return NULL;
454 return extension_dict;
457 void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id,
458 const std::string& key,
459 base::Value* data_value) {
460 if (!crx_file::id_util::IdIsValid(extension_id)) {
461 NOTREACHED() << "Invalid extension_id " << extension_id;
462 return;
464 ScopedExtensionPrefUpdate update(prefs_, extension_id);
465 if (data_value)
466 update->Set(key, data_value);
467 else
468 update->Remove(key, NULL);
471 void ExtensionPrefs::DeleteExtensionPrefs(const std::string& extension_id) {
472 extension_pref_value_map_->UnregisterExtension(extension_id);
473 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
474 observer_list_,
475 OnExtensionPrefsDeleted(extension_id));
476 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
477 base::DictionaryValue* dict = update.Get();
478 dict->Remove(extension_id, NULL);
481 bool ExtensionPrefs::ReadPrefAsBoolean(const std::string& extension_id,
482 const std::string& pref_key,
483 bool* out_value) const {
484 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
485 if (!ext || !ext->GetBoolean(pref_key, out_value))
486 return false;
488 return true;
491 bool ExtensionPrefs::ReadPrefAsInteger(const std::string& extension_id,
492 const std::string& pref_key,
493 int* out_value) const {
494 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
495 if (!ext || !ext->GetInteger(pref_key, out_value))
496 return false;
498 return true;
501 bool ExtensionPrefs::ReadPrefAsString(const std::string& extension_id,
502 const std::string& pref_key,
503 std::string* out_value) const {
504 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
505 if (!ext || !ext->GetString(pref_key, out_value))
506 return false;
508 return true;
511 bool ExtensionPrefs::ReadPrefAsList(const std::string& extension_id,
512 const std::string& pref_key,
513 const base::ListValue** out_value) const {
514 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
515 const base::ListValue* out = NULL;
516 if (!ext || !ext->GetList(pref_key, &out))
517 return false;
518 if (out_value)
519 *out_value = out;
521 return true;
524 bool ExtensionPrefs::ReadPrefAsDictionary(
525 const std::string& extension_id,
526 const std::string& pref_key,
527 const base::DictionaryValue** out_value) const {
528 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
529 const base::DictionaryValue* out = NULL;
530 if (!ext || !ext->GetDictionary(pref_key, &out))
531 return false;
532 if (out_value)
533 *out_value = out;
535 return true;
538 bool ExtensionPrefs::HasPrefForExtension(
539 const std::string& extension_id) const {
540 return GetExtensionPref(extension_id) != NULL;
543 bool ExtensionPrefs::ReadPrefAsURLPatternSet(const std::string& extension_id,
544 const std::string& pref_key,
545 URLPatternSet* result,
546 int valid_schemes) {
547 const base::ListValue* value = NULL;
548 if (!ReadPrefAsList(extension_id, pref_key, &value))
549 return false;
551 bool allow_file_access = AllowFileAccess(extension_id);
552 return result->Populate(*value, valid_schemes, allow_file_access, NULL);
555 void ExtensionPrefs::SetExtensionPrefURLPatternSet(
556 const std::string& extension_id,
557 const std::string& pref_key,
558 const URLPatternSet& new_value) {
559 UpdateExtensionPref(extension_id, pref_key, new_value.ToValue().release());
562 bool ExtensionPrefs::ReadPrefAsBooleanAndReturn(
563 const std::string& extension_id,
564 const std::string& pref_key) const {
565 bool out_value = false;
566 return ReadPrefAsBoolean(extension_id, pref_key, &out_value) && out_value;
569 PermissionSet* ExtensionPrefs::ReadPrefAsPermissionSet(
570 const std::string& extension_id,
571 const std::string& pref_key) {
572 if (!GetExtensionPref(extension_id))
573 return NULL;
575 // Retrieve the API permissions. Please refer SetExtensionPrefPermissionSet()
576 // for api_values format.
577 APIPermissionSet apis;
578 const base::ListValue* api_values = NULL;
579 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
580 if (ReadPrefAsList(extension_id, api_pref, &api_values)) {
581 APIPermissionSet::ParseFromJSON(api_values,
582 APIPermissionSet::kAllowInternalPermissions,
583 &apis, NULL, NULL);
586 // Retrieve the Manifest Keys permissions. Please refer to
587 // |SetExtensionPrefPermissionSet| for manifest_permissions_values format.
588 ManifestPermissionSet manifest_permissions;
589 const base::ListValue* manifest_permissions_values = NULL;
590 std::string manifest_permission_pref =
591 JoinPrefs(pref_key, kPrefManifestPermissions);
592 if (ReadPrefAsList(extension_id, manifest_permission_pref,
593 &manifest_permissions_values)) {
594 ManifestPermissionSet::ParseFromJSON(
595 manifest_permissions_values, &manifest_permissions, NULL, NULL);
598 // Retrieve the explicit host permissions.
599 URLPatternSet explicit_hosts;
600 ReadPrefAsURLPatternSet(
601 extension_id, JoinPrefs(pref_key, kPrefExplicitHosts),
602 &explicit_hosts, Extension::kValidHostPermissionSchemes);
604 // Retrieve the scriptable host permissions.
605 URLPatternSet scriptable_hosts;
606 ReadPrefAsURLPatternSet(
607 extension_id, JoinPrefs(pref_key, kPrefScriptableHosts),
608 &scriptable_hosts, UserScript::ValidUserScriptSchemes());
610 return new PermissionSet(
611 apis, manifest_permissions, explicit_hosts, scriptable_hosts);
614 // Set the API or Manifest permissions.
615 // The format of api_values is:
616 // [ "permission_name1", // permissions do not support detail.
617 // "permission_name2",
618 // {"permission_name3": value },
619 // // permission supports detail, permission detail will be stored in value.
620 // ...
621 // ]
622 template<typename T>
623 static base::ListValue* CreatePermissionList(const T& permissions) {
624 base::ListValue* values = new base::ListValue();
625 for (typename T::const_iterator i = permissions.begin();
626 i != permissions.end(); ++i) {
627 scoped_ptr<base::Value> detail(i->ToValue());
628 if (detail) {
629 base::DictionaryValue* tmp = new base::DictionaryValue();
630 tmp->Set(i->name(), detail.release());
631 values->Append(tmp);
632 } else {
633 values->Append(new base::StringValue(i->name()));
636 return values;
639 void ExtensionPrefs::SetExtensionPrefPermissionSet(
640 const std::string& extension_id,
641 const std::string& pref_key,
642 const PermissionSet* new_value) {
643 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
644 base::ListValue* api_values = CreatePermissionList(new_value->apis());
645 UpdateExtensionPref(extension_id, api_pref, api_values);
647 std::string manifest_permissions_pref =
648 JoinPrefs(pref_key, kPrefManifestPermissions);
649 base::ListValue* manifest_permissions_values = CreatePermissionList(
650 new_value->manifest_permissions());
651 UpdateExtensionPref(extension_id,
652 manifest_permissions_pref,
653 manifest_permissions_values);
655 // Set the explicit host permissions.
656 if (!new_value->explicit_hosts().is_empty()) {
657 SetExtensionPrefURLPatternSet(extension_id,
658 JoinPrefs(pref_key, kPrefExplicitHosts),
659 new_value->explicit_hosts());
662 // Set the scriptable host permissions.
663 if (!new_value->scriptable_hosts().is_empty()) {
664 SetExtensionPrefURLPatternSet(extension_id,
665 JoinPrefs(pref_key, kPrefScriptableHosts),
666 new_value->scriptable_hosts());
670 int ExtensionPrefs::IncrementAcknowledgePromptCount(
671 const std::string& extension_id) {
672 int count = 0;
673 ReadPrefAsInteger(extension_id, kPrefAcknowledgePromptCount, &count);
674 ++count;
675 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount,
676 new base::FundamentalValue(count));
677 return count;
680 bool ExtensionPrefs::IsExternalExtensionAcknowledged(
681 const std::string& extension_id) {
682 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalAcknowledged);
685 void ExtensionPrefs::AcknowledgeExternalExtension(
686 const std::string& extension_id) {
687 DCHECK(crx_file::id_util::IdIsValid(extension_id));
688 UpdateExtensionPref(extension_id, kPrefExternalAcknowledged,
689 new base::FundamentalValue(true));
690 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
693 bool ExtensionPrefs::IsBlacklistedExtensionAcknowledged(
694 const std::string& extension_id) {
695 return ReadPrefAsBooleanAndReturn(extension_id, kPrefBlacklistAcknowledged);
698 void ExtensionPrefs::AcknowledgeBlacklistedExtension(
699 const std::string& extension_id) {
700 DCHECK(crx_file::id_util::IdIsValid(extension_id));
701 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged,
702 new base::FundamentalValue(true));
703 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
706 bool ExtensionPrefs::IsExternalInstallFirstRun(
707 const std::string& extension_id) {
708 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalInstallFirstRun);
711 void ExtensionPrefs::SetExternalInstallFirstRun(
712 const std::string& extension_id) {
713 DCHECK(crx_file::id_util::IdIsValid(extension_id));
714 UpdateExtensionPref(extension_id, kPrefExternalInstallFirstRun,
715 new base::FundamentalValue(true));
718 bool ExtensionPrefs::HasWipeoutBeenAcknowledged(
719 const std::string& extension_id) {
720 return ReadPrefAsBooleanAndReturn(extension_id, kPrefWipeoutAcknowledged);
723 void ExtensionPrefs::SetWipeoutAcknowledged(
724 const std::string& extension_id,
725 bool value) {
726 UpdateExtensionPref(extension_id,
727 kPrefWipeoutAcknowledged,
728 value ? new base::FundamentalValue(value) : NULL);
731 bool ExtensionPrefs::HasSettingsApiBubbleBeenAcknowledged(
732 const std::string& extension_id) {
733 return ReadPrefAsBooleanAndReturn(extension_id,
734 kPrefSettingsBubbleAcknowledged);
737 void ExtensionPrefs::SetSettingsApiBubbleBeenAcknowledged(
738 const std::string& extension_id,
739 bool value) {
740 UpdateExtensionPref(extension_id,
741 kPrefSettingsBubbleAcknowledged,
742 value ? new base::FundamentalValue(value) : NULL);
745 bool ExtensionPrefs::HasNtpOverriddenBubbleBeenAcknowledged(
746 const std::string& extension_id) {
747 return ReadPrefAsBooleanAndReturn(extension_id, kPrefNtpBubbleAcknowledged);
750 void ExtensionPrefs::SetNtpOverriddenBubbleBeenAcknowledged(
751 const std::string& extension_id,
752 bool value) {
753 UpdateExtensionPref(extension_id,
754 kPrefNtpBubbleAcknowledged,
755 value ? new base::FundamentalValue(value) : NULL);
758 bool ExtensionPrefs::HasProxyOverriddenBubbleBeenAcknowledged(
759 const std::string& extension_id) {
760 return ReadPrefAsBooleanAndReturn(extension_id, kPrefProxyBubbleAcknowledged);
763 void ExtensionPrefs::SetProxyOverriddenBubbleBeenAcknowledged(
764 const std::string& extension_id,
765 bool value) {
766 UpdateExtensionPref(extension_id,
767 kPrefProxyBubbleAcknowledged,
768 value ? new base::FundamentalValue(value) : NULL);
771 bool ExtensionPrefs::SetAlertSystemFirstRun() {
772 if (prefs_->GetBoolean(pref_names::kAlertsInitialized)) {
773 return true;
775 prefs_->SetBoolean(pref_names::kAlertsInitialized, true);
776 return false;
779 bool ExtensionPrefs::ExtensionsBlacklistedByDefault() const {
780 return admin_policy::BlacklistedByDefault(
781 prefs_->GetList(pref_names::kInstallDenyList));
784 bool ExtensionPrefs::DidExtensionEscalatePermissions(
785 const std::string& extension_id) {
786 return ReadPrefAsBooleanAndReturn(extension_id,
787 kExtensionDidEscalatePermissions);
790 void ExtensionPrefs::SetDidExtensionEscalatePermissions(
791 const Extension* extension, bool did_escalate) {
792 UpdateExtensionPref(extension->id(), kExtensionDidEscalatePermissions,
793 new base::FundamentalValue(did_escalate));
796 int ExtensionPrefs::GetDisableReasons(const std::string& extension_id) const {
797 int value = -1;
798 if (ReadPrefAsInteger(extension_id, kPrefDisableReasons, &value) &&
799 value >= 0) {
800 return value;
802 return Extension::DISABLE_NONE;
805 bool ExtensionPrefs::HasDisableReason(
806 const std::string& extension_id,
807 Extension::DisableReason disable_reason) const {
808 return (GetDisableReasons(extension_id) & disable_reason) != 0;
811 void ExtensionPrefs::AddDisableReason(const std::string& extension_id,
812 Extension::DisableReason disable_reason) {
813 ModifyDisableReason(extension_id, disable_reason, DISABLE_REASON_ADD);
816 void ExtensionPrefs::RemoveDisableReason(
817 const std::string& extension_id,
818 Extension::DisableReason disable_reason) {
819 ModifyDisableReason(extension_id, disable_reason, DISABLE_REASON_REMOVE);
822 void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) {
823 ModifyDisableReason(
824 extension_id, Extension::DISABLE_NONE, DISABLE_REASON_CLEAR);
827 void ExtensionPrefs::ModifyDisableReason(const std::string& extension_id,
828 Extension::DisableReason reason,
829 DisableReasonChange change) {
830 int old_value = GetDisableReasons(extension_id);
831 int new_value = old_value;
832 switch (change) {
833 case DISABLE_REASON_ADD:
834 new_value |= static_cast<int>(reason);
835 break;
836 case DISABLE_REASON_REMOVE:
837 new_value &= ~static_cast<int>(reason);
838 break;
839 case DISABLE_REASON_CLEAR:
840 new_value = Extension::DISABLE_NONE;
841 break;
844 if (old_value == new_value) // no change, return.
845 return;
847 if (new_value == Extension::DISABLE_NONE) {
848 UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
849 } else {
850 UpdateExtensionPref(extension_id,
851 kPrefDisableReasons,
852 new base::FundamentalValue(new_value));
855 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
856 observer_list_,
857 OnExtensionDisableReasonsChanged(extension_id, new_value));
860 std::set<std::string> ExtensionPrefs::GetBlacklistedExtensions() {
861 std::set<std::string> ids;
863 const base::DictionaryValue* extensions =
864 prefs_->GetDictionary(pref_names::kExtensions);
865 if (!extensions)
866 return ids;
868 for (base::DictionaryValue::Iterator it(*extensions);
869 !it.IsAtEnd(); it.Advance()) {
870 if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) {
871 NOTREACHED() << "Invalid pref for extension " << it.key();
872 continue;
874 if (IsBlacklistBitSet(
875 static_cast<const base::DictionaryValue*>(&it.value()))) {
876 ids.insert(it.key());
880 return ids;
883 void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id,
884 bool is_blacklisted) {
885 bool currently_blacklisted = IsExtensionBlacklisted(extension_id);
886 if (is_blacklisted == currently_blacklisted)
887 return;
889 // Always make sure the "acknowledged" bit is cleared since the blacklist bit
890 // is changing.
891 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL);
893 if (is_blacklisted) {
894 UpdateExtensionPref(extension_id,
895 kPrefBlacklist,
896 new base::FundamentalValue(true));
897 } else {
898 UpdateExtensionPref(extension_id, kPrefBlacklist, NULL);
899 const base::DictionaryValue* dict = GetExtensionPref(extension_id);
900 if (dict && dict->empty())
901 DeleteExtensionPrefs(extension_id);
905 bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const {
906 const base::DictionaryValue* ext_prefs = GetExtensionPref(id);
907 return ext_prefs && IsBlacklistBitSet(ext_prefs);
910 namespace {
912 // Serializes a 64bit integer as a string value.
913 void SaveInt64(base::DictionaryValue* dictionary,
914 const char* key,
915 const int64 value) {
916 if (!dictionary)
917 return;
919 std::string string_value = base::Int64ToString(value);
920 dictionary->SetString(key, string_value);
923 // Deserializes a 64bit integer stored as a string value.
924 bool ReadInt64(const base::DictionaryValue* dictionary,
925 const char* key,
926 int64* value) {
927 if (!dictionary)
928 return false;
930 std::string string_value;
931 if (!dictionary->GetString(key, &string_value))
932 return false;
934 return base::StringToInt64(string_value, value);
937 // Serializes |time| as a string value mapped to |key| in |dictionary|.
938 void SaveTime(base::DictionaryValue* dictionary,
939 const char* key,
940 const base::Time& time) {
941 SaveInt64(dictionary, key, time.ToInternalValue());
944 // The opposite of SaveTime. If |key| is not found, this returns an empty Time
945 // (is_null() will return true).
946 base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) {
947 int64 value;
948 if (ReadInt64(dictionary, key, &value))
949 return base::Time::FromInternalValue(value);
951 return base::Time();
954 } // namespace
956 base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const {
957 DCHECK(crx_file::id_util::IdIsValid(extension_id));
958 return ReadTime(GetExtensionPref(extension_id), kLastPingDay);
961 void ExtensionPrefs::SetLastPingDay(const std::string& extension_id,
962 const base::Time& time) {
963 DCHECK(crx_file::id_util::IdIsValid(extension_id));
964 ScopedExtensionPrefUpdate update(prefs_, extension_id);
965 SaveTime(update.Get(), kLastPingDay, time);
968 base::Time ExtensionPrefs::BlacklistLastPingDay() const {
969 return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate),
970 kLastPingDay);
973 void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) {
974 DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate);
975 SaveTime(update.Get(), kLastPingDay, time);
978 base::Time ExtensionPrefs::LastActivePingDay(const std::string& extension_id) {
979 DCHECK(crx_file::id_util::IdIsValid(extension_id));
980 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
983 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
984 const base::Time& time) {
985 DCHECK(crx_file::id_util::IdIsValid(extension_id));
986 ScopedExtensionPrefUpdate update(prefs_, extension_id);
987 SaveTime(update.Get(), kLastActivePingDay, time);
990 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) {
991 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
992 bool result = false;
993 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
994 return result;
995 return false;
998 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
999 bool active) {
1000 UpdateExtensionPref(extension_id, kActiveBit,
1001 new base::FundamentalValue(active));
1004 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
1005 PermissionsInfo* info = PermissionsInfo::GetInstance();
1006 for (ExtensionIdList::const_iterator ext_id =
1007 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
1008 // An extension's granted permissions need to be migrated if the
1009 // full_access bit is present. This bit was always present in the previous
1010 // scheme and is never present now.
1011 bool full_access = false;
1012 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
1013 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
1014 continue;
1016 // Remove the full access bit (empty list will get trimmed).
1017 UpdateExtensionPref(
1018 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
1020 // Add the plugin permission if the full access bit was set.
1021 if (full_access) {
1022 const base::ListValue* apis = NULL;
1023 base::ListValue* new_apis = NULL;
1025 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
1026 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
1027 new_apis = apis->DeepCopy();
1028 else
1029 new_apis = new base::ListValue();
1031 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
1032 new_apis->Append(new base::StringValue(plugin_name));
1033 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
1036 // The granted permissions originally only held the effective hosts,
1037 // which are a combination of host and user script host permissions.
1038 // We now maintain these lists separately. For migration purposes, it
1039 // does not matter how we treat the old effective hosts as long as the
1040 // new effective hosts will be the same, so we move them to explicit
1041 // host permissions.
1042 const base::ListValue* hosts = NULL;
1043 std::string explicit_hosts =
1044 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
1045 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
1046 UpdateExtensionPref(
1047 *ext_id, explicit_hosts, hosts->DeepCopy());
1049 // We can get rid of the old one by setting it to an empty list.
1050 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
1055 void ExtensionPrefs::MigrateDisableReasons(
1056 const ExtensionIdList& extension_ids) {
1057 for (ExtensionIdList::const_iterator ext_id =
1058 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
1059 int value = -1;
1060 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
1061 int new_value = Extension::DISABLE_NONE;
1062 switch (value) {
1063 case Extension::DEPRECATED_DISABLE_USER_ACTION:
1064 new_value = Extension::DISABLE_USER_ACTION;
1065 break;
1066 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
1067 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
1068 break;
1069 case Extension::DEPRECATED_DISABLE_RELOAD:
1070 new_value = Extension::DISABLE_RELOAD;
1071 break;
1074 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
1075 new base::FundamentalValue(new_value));
1076 // Remove the old disable reason.
1077 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
1082 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
1083 const std::string& extension_id) {
1084 CHECK(crx_file::id_util::IdIsValid(extension_id));
1085 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
1088 void ExtensionPrefs::AddGrantedPermissions(
1089 const std::string& extension_id,
1090 const PermissionSet* permissions) {
1091 CHECK(crx_file::id_util::IdIsValid(extension_id));
1093 scoped_refptr<PermissionSet> granted_permissions(
1094 GetGrantedPermissions(extension_id));
1096 // The new granted permissions are the union of the already granted
1097 // permissions and the newly granted permissions.
1098 scoped_refptr<PermissionSet> new_perms(
1099 PermissionSet::CreateUnion(
1100 permissions, granted_permissions.get()));
1102 SetExtensionPrefPermissionSet(
1103 extension_id, kPrefGrantedPermissions, new_perms.get());
1106 void ExtensionPrefs::RemoveGrantedPermissions(
1107 const std::string& extension_id,
1108 const PermissionSet* permissions) {
1109 CHECK(crx_file::id_util::IdIsValid(extension_id));
1111 scoped_refptr<PermissionSet> granted_permissions(
1112 GetGrantedPermissions(extension_id));
1114 // The new granted permissions are the difference of the already granted
1115 // permissions and the newly ungranted permissions.
1116 scoped_refptr<PermissionSet> new_perms(
1117 PermissionSet::CreateDifference(
1118 granted_permissions.get(), permissions));
1120 SetExtensionPrefPermissionSet(
1121 extension_id, kPrefGrantedPermissions, new_perms.get());
1124 PermissionSet* ExtensionPrefs::GetActivePermissions(
1125 const std::string& extension_id) {
1126 CHECK(crx_file::id_util::IdIsValid(extension_id));
1127 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
1130 void ExtensionPrefs::SetActivePermissions(
1131 const std::string& extension_id,
1132 const PermissionSet* permissions) {
1133 SetExtensionPrefPermissionSet(
1134 extension_id, kPrefActivePermissions, permissions);
1137 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1138 bool is_running) {
1139 base::Value* value = new base::FundamentalValue(is_running);
1140 UpdateExtensionPref(extension_id, kPrefRunning, value);
1143 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) {
1144 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1145 if (!extension)
1146 return false;
1147 bool running = false;
1148 extension->GetBoolean(kPrefRunning, &running);
1149 return running;
1152 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1153 bool is_active) {
1154 base::Value* value = new base::FundamentalValue(is_active);
1155 UpdateExtensionPref(extension_id, kIsActive, value);
1158 bool ExtensionPrefs::IsActive(const std::string& extension_id) {
1159 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1160 if (!extension)
1161 return false;
1162 bool is_active = false;
1163 extension->GetBoolean(kIsActive, &is_active);
1164 return is_active;
1167 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1168 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1171 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1172 bool enabled) {
1173 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1174 new base::FundamentalValue(enabled));
1175 extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled);
1178 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1179 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1182 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1183 bool allow) {
1184 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1185 new base::FundamentalValue(allow));
1188 bool ExtensionPrefs::HasAllowFileAccessSetting(
1189 const std::string& extension_id) const {
1190 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1191 return ext && ext->HasKey(kPrefAllowFileAccess);
1194 bool ExtensionPrefs::DoesExtensionHaveState(
1195 const std::string& id, Extension::State check_state) const {
1196 const base::DictionaryValue* extension = GetExtensionPref(id);
1197 int state = -1;
1198 if (!extension || !extension->GetInteger(kPrefState, &state))
1199 return false;
1201 if (state < 0 || state >= Extension::NUM_STATES) {
1202 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1203 return false;
1206 return state == check_state;
1209 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1210 const std::string& id) const {
1211 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1214 bool ExtensionPrefs::IsExtensionDisabled(
1215 const std::string& id) const {
1216 return DoesExtensionHaveState(id, Extension::DISABLED);
1219 ExtensionIdList ExtensionPrefs::GetToolbarOrder() {
1220 ExtensionIdList id_list_out;
1221 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1222 return id_list_out;
1225 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1226 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1229 void ExtensionPrefs::OnExtensionInstalled(
1230 const Extension* extension,
1231 Extension::State initial_state,
1232 const syncer::StringOrdinal& page_ordinal,
1233 int install_flags,
1234 const std::string& install_parameter) {
1235 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1236 base::DictionaryValue* extension_dict = update.Get();
1237 const base::Time install_time = time_provider_->GetCurrentTime();
1238 PopulateExtensionInfoPrefs(extension,
1239 install_time,
1240 initial_state,
1241 install_flags,
1242 install_parameter,
1243 extension_dict);
1245 bool requires_sort_ordinal = extension->RequiresSortOrdinal() &&
1246 (install_flags & kInstallFlagIsEphemeral) == 0;
1247 FinishExtensionInfoPrefs(extension->id(),
1248 install_time,
1249 requires_sort_ordinal,
1250 page_ordinal,
1251 extension_dict);
1254 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1255 const Manifest::Location& location,
1256 bool external_uninstall) {
1257 app_sorting_->ClearOrdinals(extension_id);
1259 // For external extensions, we save a preference reminding ourself not to try
1260 // and install the extension anymore (except when |external_uninstall| is
1261 // true, which signifies that the registry key was deleted or the pref file
1262 // no longer lists the extension).
1263 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1264 UpdateExtensionPref(extension_id, kPrefState,
1265 new base::FundamentalValue(
1266 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1267 extension_pref_value_map_->SetExtensionState(extension_id, false);
1268 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1269 observer_list_,
1270 OnExtensionStateChanged(extension_id, false));
1271 } else {
1272 DeleteExtensionPrefs(extension_id);
1276 void ExtensionPrefs::SetExtensionState(const std::string& extension_id,
1277 Extension::State state) {
1278 UpdateExtensionPref(extension_id, kPrefState,
1279 new base::FundamentalValue(state));
1280 bool enabled = (state == Extension::ENABLED);
1281 extension_pref_value_map_->SetExtensionState(extension_id, enabled);
1282 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1283 observer_list_,
1284 OnExtensionStateChanged(extension_id, enabled));
1287 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1288 BlacklistState state) {
1289 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1290 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1291 new base::FundamentalValue(state));
1294 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1295 const std::string& extension_id) {
1296 if (IsExtensionBlacklisted(extension_id))
1297 return BLACKLISTED_MALWARE;
1298 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1299 int int_value = 0;
1300 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1301 return static_cast<BlacklistState>(int_value);
1303 return NOT_BLACKLISTED;
1306 std::string ExtensionPrefs::GetVersionString(const std::string& extension_id) {
1307 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1308 if (!extension)
1309 return std::string();
1311 std::string version;
1312 extension->GetString(kPrefVersion, &version);
1314 return version;
1317 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1318 if (!Manifest::IsUnpackedLocation(extension->location())) {
1319 const base::DictionaryValue* extension_dict =
1320 GetExtensionPref(extension->id());
1321 if (!extension_dict)
1322 return;
1323 const base::DictionaryValue* old_manifest = NULL;
1324 bool update_required =
1325 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1326 !extension->manifest()->value()->Equals(old_manifest);
1327 if (update_required) {
1328 UpdateExtensionPref(extension->id(), kPrefManifest,
1329 extension->manifest()->value()->DeepCopy());
1334 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1335 const std::string& extension_id,
1336 const base::DictionaryValue* extension) const {
1337 int location_value;
1338 if (!extension->GetInteger(kPrefLocation, &location_value))
1339 return scoped_ptr<ExtensionInfo>();
1341 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1342 if (location == Manifest::COMPONENT) {
1343 // Component extensions are ignored. Component extensions may have data
1344 // saved in preferences, but they are already loaded at this point (by
1345 // ComponentLoader) and shouldn't be populated into the result of
1346 // GetInstalledExtensionsInfo, otherwise InstalledLoader would also want to
1347 // load them.
1348 return scoped_ptr<ExtensionInfo>();
1351 // Only the following extension types have data saved in the preferences.
1352 if (location != Manifest::INTERNAL &&
1353 !Manifest::IsUnpackedLocation(location) &&
1354 !Manifest::IsExternalLocation(location)) {
1355 NOTREACHED();
1356 return scoped_ptr<ExtensionInfo>();
1359 const base::DictionaryValue* manifest = NULL;
1360 if (!Manifest::IsUnpackedLocation(location) &&
1361 !extension->GetDictionary(kPrefManifest, &manifest)) {
1362 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1363 // Just a warning for now.
1366 base::FilePath::StringType path;
1367 if (!extension->GetString(kPrefPath, &path))
1368 return scoped_ptr<ExtensionInfo>();
1370 // Make path absolute. Most (but not all) extension types have relative paths.
1371 if (!base::FilePath(path).IsAbsolute())
1372 path = install_directory_.Append(path).value();
1374 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1375 manifest, extension_id, base::FilePath(path), location));
1378 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1379 const std::string& extension_id) const {
1380 const base::DictionaryValue* ext = NULL;
1381 const base::DictionaryValue* extensions =
1382 prefs_->GetDictionary(pref_names::kExtensions);
1383 if (!extensions ||
1384 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1385 return scoped_ptr<ExtensionInfo>();
1386 int state_value;
1387 if (ext->GetInteger(kPrefState, &state_value) &&
1388 state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1389 LOG(WARNING) << "External extension with id " << extension_id
1390 << " has been uninstalled by the user";
1391 return scoped_ptr<ExtensionInfo>();
1394 return GetInstalledInfoHelper(extension_id, ext);
1397 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1398 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1399 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1401 const base::DictionaryValue* extensions =
1402 prefs_->GetDictionary(pref_names::kExtensions);
1403 for (base::DictionaryValue::Iterator extension_id(*extensions);
1404 !extension_id.IsAtEnd(); extension_id.Advance()) {
1405 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1406 continue;
1408 scoped_ptr<ExtensionInfo> info =
1409 GetInstalledExtensionInfo(extension_id.key());
1410 if (info)
1411 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1414 return extensions_info.Pass();
1417 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1418 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1419 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1421 const base::DictionaryValue* extensions =
1422 prefs_->GetDictionary(pref_names::kExtensions);
1423 for (base::DictionaryValue::Iterator extension_id(*extensions);
1424 !extension_id.IsAtEnd(); extension_id.Advance()) {
1425 const base::DictionaryValue* ext = NULL;
1426 if (!crx_file::id_util::IdIsValid(extension_id.key()) ||
1427 !IsExternalExtensionUninstalled(extension_id.key()) ||
1428 !extension_id.value().GetAsDictionary(&ext))
1429 continue;
1431 scoped_ptr<ExtensionInfo> info =
1432 GetInstalledInfoHelper(extension_id.key(), ext);
1433 if (info)
1434 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1437 return extensions_info.Pass();
1440 void ExtensionPrefs::SetDelayedInstallInfo(
1441 const Extension* extension,
1442 Extension::State initial_state,
1443 int install_flags,
1444 DelayReason delay_reason,
1445 const syncer::StringOrdinal& page_ordinal,
1446 const std::string& install_parameter) {
1447 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1448 PopulateExtensionInfoPrefs(extension,
1449 time_provider_->GetCurrentTime(),
1450 initial_state,
1451 install_flags,
1452 install_parameter,
1453 extension_dict);
1455 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1456 // should not be in the final extension prefs. All entries here should have
1457 // a corresponding Remove() call in FinishDelayedInstallInfo().
1458 if (extension->RequiresSortOrdinal() &&
1459 (install_flags & kInstallFlagIsEphemeral) == 0) {
1460 extension_dict->SetString(
1461 kPrefSuggestedPageOrdinal,
1462 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1463 : std::string());
1465 extension_dict->SetInteger(kDelayedInstallReason,
1466 static_cast<int>(delay_reason));
1468 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1471 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1472 const std::string& extension_id) {
1473 if (!GetExtensionPref(extension_id))
1474 return false;
1475 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1476 bool result = update->Remove(kDelayedInstallInfo, NULL);
1477 return result;
1480 bool ExtensionPrefs::FinishDelayedInstallInfo(
1481 const std::string& extension_id) {
1482 CHECK(crx_file::id_util::IdIsValid(extension_id));
1483 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1484 base::DictionaryValue* extension_dict = update.Get();
1485 base::DictionaryValue* pending_install_dict = NULL;
1486 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1487 &pending_install_dict)) {
1488 return false;
1491 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1492 // Also do any other data cleanup that makes sense.
1493 std::string serialized_ordinal;
1494 syncer::StringOrdinal suggested_page_ordinal;
1495 bool needs_sort_ordinal = false;
1496 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1497 &serialized_ordinal)) {
1498 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1499 needs_sort_ordinal = true;
1500 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1502 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1504 const base::Time install_time = time_provider_->GetCurrentTime();
1505 pending_install_dict->Set(
1506 kPrefInstallTime,
1507 new base::StringValue(
1508 base::Int64ToString(install_time.ToInternalValue())));
1510 // Some extension pref values are written conditionally. If they are not
1511 // present in the delayed install data, they should be removed when the
1512 // delayed install is committed.
1513 extension_dict->Remove(kPrefEphemeralApp, NULL);
1515 // Commit the delayed install data.
1516 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1517 it.Advance()) {
1518 extension_dict->Set(it.key(), it.value().DeepCopy());
1520 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1521 suggested_page_ordinal, extension_dict);
1522 return true;
1525 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1526 const std::string& extension_id) const {
1527 const base::DictionaryValue* extension_prefs =
1528 GetExtensionPref(extension_id);
1529 if (!extension_prefs)
1530 return scoped_ptr<ExtensionInfo>();
1532 const base::DictionaryValue* ext = NULL;
1533 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1534 return scoped_ptr<ExtensionInfo>();
1536 return GetInstalledInfoHelper(extension_id, ext);
1539 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1540 const std::string& extension_id) const {
1541 const base::DictionaryValue* extension_prefs =
1542 GetExtensionPref(extension_id);
1543 if (!extension_prefs)
1544 return DELAY_REASON_NONE;
1546 const base::DictionaryValue* ext = NULL;
1547 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1548 return DELAY_REASON_NONE;
1550 int delay_reason;
1551 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1552 return DELAY_REASON_NONE;
1554 return static_cast<DelayReason>(delay_reason);
1557 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1558 GetAllDelayedInstallInfo() const {
1559 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1561 const base::DictionaryValue* extensions =
1562 prefs_->GetDictionary(pref_names::kExtensions);
1563 for (base::DictionaryValue::Iterator extension_id(*extensions);
1564 !extension_id.IsAtEnd(); extension_id.Advance()) {
1565 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1566 continue;
1568 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1569 if (info)
1570 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1573 return extensions_info.Pass();
1576 bool ExtensionPrefs::IsEphemeralApp(const std::string& extension_id) const {
1577 if (ReadPrefAsBooleanAndReturn(extension_id, kPrefEphemeralApp))
1578 return true;
1580 // Ephemerality was previously stored in the creation flags, so we must also
1581 // check it for backcompatibility.
1582 return (GetCreationFlags(extension_id) & Extension::IS_EPHEMERAL) != 0;
1585 void ExtensionPrefs::OnEphemeralAppPromoted(const std::string& extension_id) {
1586 DCHECK(IsEphemeralApp(extension_id));
1588 UpdateExtensionPref(extension_id, kPrefEphemeralApp, NULL);
1590 // Ephemerality was previously stored in the creation flags, so ensure the bit
1591 // is cleared.
1592 int creation_flags = Extension::NO_FLAGS;
1593 if (ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1594 if (creation_flags & Extension::IS_EPHEMERAL) {
1595 creation_flags &= ~static_cast<int>(Extension::IS_EPHEMERAL);
1596 UpdateExtensionPref(extension_id,
1597 kPrefCreationFlags,
1598 new base::FundamentalValue(creation_flags));
1603 bool ExtensionPrefs::WasAppDraggedByUser(const std::string& extension_id) {
1604 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1607 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1608 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1609 new base::FundamentalValue(true));
1612 bool ExtensionPrefs::IsFromWebStore(
1613 const std::string& extension_id) const {
1614 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1615 bool result = false;
1616 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1617 return result;
1618 return false;
1621 bool ExtensionPrefs::IsFromBookmark(
1622 const std::string& extension_id) const {
1623 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1624 bool result = false;
1625 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1626 return result;
1627 return false;
1630 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1631 int creation_flags = Extension::NO_FLAGS;
1632 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1633 // Since kPrefCreationFlags was added later, it will be missing for
1634 // previously installed extensions.
1635 if (IsFromBookmark(extension_id))
1636 creation_flags |= Extension::FROM_BOOKMARK;
1637 if (IsFromWebStore(extension_id))
1638 creation_flags |= Extension::FROM_WEBSTORE;
1639 if (WasInstalledByDefault(extension_id))
1640 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1641 if (WasInstalledByOem(extension_id))
1642 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
1644 return creation_flags;
1647 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1648 const std::string& extension_id) const {
1649 int creation_flags = Extension::NO_FLAGS;
1650 const base::DictionaryValue* delayed_info = NULL;
1651 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1652 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1654 return creation_flags;
1657 bool ExtensionPrefs::WasInstalledByDefault(
1658 const std::string& extension_id) const {
1659 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1660 bool result = false;
1661 if (dictionary &&
1662 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1663 return result;
1664 return false;
1667 bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const {
1668 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1669 bool result = false;
1670 if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result))
1671 return result;
1672 return false;
1675 base::Time ExtensionPrefs::GetInstallTime(
1676 const std::string& extension_id) const {
1677 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1678 if (!extension) {
1679 NOTREACHED();
1680 return base::Time();
1682 std::string install_time_str;
1683 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1684 return base::Time();
1685 int64 install_time_i64 = 0;
1686 if (!base::StringToInt64(install_time_str, &install_time_i64))
1687 return base::Time();
1688 return base::Time::FromInternalValue(install_time_i64);
1691 bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const {
1692 bool do_not_sync;
1693 if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync))
1694 return false;
1696 return do_not_sync;
1699 base::Time ExtensionPrefs::GetLastLaunchTime(
1700 const std::string& extension_id) const {
1701 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1702 if (!extension)
1703 return base::Time();
1705 std::string launch_time_str;
1706 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1707 return base::Time();
1708 int64 launch_time_i64 = 0;
1709 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1710 return base::Time();
1711 return base::Time::FromInternalValue(launch_time_i64);
1714 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1715 const base::Time& time) {
1716 DCHECK(crx_file::id_util::IdIsValid(extension_id));
1717 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1718 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1721 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) {
1722 CHECK(out);
1724 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1726 for (size_t i = 0; i < extensions_info->size(); ++i) {
1727 ExtensionInfo* info = extensions_info->at(i).get();
1728 out->push_back(info->extension_id);
1732 // static
1733 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1734 const PrefService* pref_service) {
1735 ExtensionIdList result;
1737 const base::DictionaryValue* extension_prefs = NULL;
1738 const base::Value* extension_prefs_value =
1739 pref_service->GetUserPrefValue(pref_names::kExtensions);
1740 if (!extension_prefs_value ||
1741 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1742 return result; // Empty set
1745 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1746 it.Advance()) {
1747 const base::DictionaryValue* ext = NULL;
1748 if (!it.value().GetAsDictionary(&ext)) {
1749 NOTREACHED() << "Invalid pref for extension " << it.key();
1750 continue;
1752 if (!IsBlacklistBitSet(ext))
1753 result.push_back(it.key());
1755 return result;
1758 void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) {
1759 observer_list_.AddObserver(observer);
1762 void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) {
1763 observer_list_.RemoveObserver(observer);
1766 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1767 // Fix old entries that did not get an installation time entry when they
1768 // were installed or don't have a preferences field.
1769 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1770 ext_id != extension_ids.end(); ++ext_id) {
1771 if (GetInstallTime(*ext_id) == base::Time()) {
1772 VLOG(1) << "Could not parse installation time of extension "
1773 << *ext_id << ". It was probably installed before setting "
1774 << kPrefInstallTime << " was introduced. Updating "
1775 << kPrefInstallTime << " to the current time.";
1776 const base::Time install_time = time_provider_->GetCurrentTime();
1777 UpdateExtensionPref(*ext_id,
1778 kPrefInstallTime,
1779 new base::StringValue(base::Int64ToString(
1780 install_time.ToInternalValue())));
1785 void ExtensionPrefs::InitPrefStore() {
1786 if (extensions_disabled_) {
1787 extension_pref_value_map_->NotifyInitializationCompleted();
1788 return;
1791 // When this is called, the PrefService is initialized and provides access
1792 // to the user preferences stored in a JSON file.
1793 ExtensionIdList extension_ids;
1794 GetExtensions(&extension_ids);
1795 // Create empty preferences dictionary for each extension (these dictionaries
1796 // are pruned when persisting the preferences to disk).
1797 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1798 ext_id != extension_ids.end(); ++ext_id) {
1799 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1800 // This creates an empty dictionary if none is stored.
1801 update.Get();
1804 FixMissingPrefs(extension_ids);
1805 MigratePermissions(extension_ids);
1806 MigrateDisableReasons(extension_ids);
1807 app_sorting_->Initialize(extension_ids);
1809 InitExtensionControlledPrefs(extension_pref_value_map_);
1811 extension_pref_value_map_->NotifyInitializationCompleted();
1814 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) {
1815 bool has_incognito_pref_value = false;
1816 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1817 true,
1818 &has_incognito_pref_value);
1819 return has_incognito_pref_value;
1822 URLPatternSet ExtensionPrefs::GetAllowedInstallSites() {
1823 URLPatternSet result;
1824 const base::ListValue* list =
1825 prefs_->GetList(pref_names::kAllowedInstallSites);
1826 CHECK(list);
1828 for (size_t i = 0; i < list->GetSize(); ++i) {
1829 std::string entry_string;
1830 URLPattern entry(URLPattern::SCHEME_ALL);
1831 if (!list->GetString(i, &entry_string) ||
1832 entry.Parse(entry_string) != URLPattern::PARSE_SUCCESS) {
1833 LOG(ERROR) << "Invalid value for preference: "
1834 << pref_names::kAllowedInstallSites << "." << i;
1835 continue;
1837 result.AddPattern(entry);
1840 return result;
1843 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1844 const std::string& extension_id) const {
1845 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1846 if (!extension_prefs)
1847 return NULL;
1849 const base::DictionaryValue* ext = NULL;
1850 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1851 return NULL;
1853 return ext;
1856 void ExtensionPrefs::SetGeometryCache(
1857 const std::string& extension_id,
1858 scoped_ptr<base::DictionaryValue> cache) {
1859 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1862 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() {
1863 return prefs_->GetDictionary(kInstallSignature);
1866 void ExtensionPrefs::SetInstallSignature(
1867 const base::DictionaryValue* signature) {
1868 if (signature) {
1869 prefs_->Set(kInstallSignature, *signature);
1870 DVLOG(1) << "SetInstallSignature - saving";
1871 } else {
1872 DVLOG(1) << "SetInstallSignature - clearing";
1873 prefs_->ClearPref(kInstallSignature);
1877 std::string ExtensionPrefs::GetInstallParam(
1878 const std::string& extension_id) const {
1879 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1880 if (!extension) // Expected during unit testing.
1881 return std::string();
1882 std::string install_parameter;
1883 if (!extension->GetString(kPrefInstallParam, &install_parameter))
1884 return std::string();
1885 return install_parameter;
1888 void ExtensionPrefs::SetInstallParam(const std::string& extension_id,
1889 const std::string& install_parameter) {
1890 UpdateExtensionPref(extension_id,
1891 kPrefInstallParam,
1892 new base::StringValue(install_parameter));
1895 int ExtensionPrefs::GetCorruptedDisableCount() {
1896 return prefs_->GetInteger(kCorruptedDisableCount);
1899 void ExtensionPrefs::IncrementCorruptedDisableCount() {
1900 int count = prefs_->GetInteger(kCorruptedDisableCount);
1901 prefs_->SetInteger(kCorruptedDisableCount, count + 1);
1904 ExtensionPrefs::ExtensionPrefs(
1905 PrefService* prefs,
1906 const base::FilePath& root_dir,
1907 ExtensionPrefValueMap* extension_pref_value_map,
1908 scoped_ptr<AppSorting> app_sorting,
1909 scoped_ptr<TimeProvider> time_provider,
1910 bool extensions_disabled,
1911 const std::vector<ExtensionPrefsObserver*>& early_observers)
1912 : prefs_(prefs),
1913 install_directory_(root_dir),
1914 extension_pref_value_map_(extension_pref_value_map),
1915 app_sorting_(app_sorting.Pass()),
1916 time_provider_(time_provider.Pass()),
1917 extensions_disabled_(extensions_disabled) {
1918 app_sorting_->SetExtensionScopedPrefs(this);
1919 MakePathsRelative();
1921 // Ensure that any early observers are watching before prefs are initialized.
1922 for (std::vector<ExtensionPrefsObserver*>::const_iterator iter =
1923 early_observers.begin();
1924 iter != early_observers.end();
1925 ++iter) {
1926 AddObserver(*iter);
1929 InitPrefStore();
1932 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1933 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1936 bool ExtensionPrefs::NeedsStorageGarbageCollection() {
1937 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1940 // static
1941 void ExtensionPrefs::RegisterProfilePrefs(
1942 user_prefs::PrefRegistrySyncable* registry) {
1943 registry->RegisterDictionaryPref(
1944 pref_names::kExtensions,
1945 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1946 registry->RegisterListPref(pref_names::kToolbar,
1947 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1948 registry->RegisterIntegerPref(
1949 pref_names::kToolbarSize,
1950 -1, // default value
1951 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1952 registry->RegisterDictionaryPref(
1953 kExtensionsBlacklistUpdate,
1954 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1955 registry->RegisterListPref(pref_names::kInstallAllowList,
1956 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1957 registry->RegisterListPref(pref_names::kInstallDenyList,
1958 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1959 registry->RegisterDictionaryPref(
1960 pref_names::kInstallForceList,
1961 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1962 registry->RegisterListPref(pref_names::kAllowedTypes,
1963 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1964 registry->RegisterBooleanPref(
1965 pref_names::kStorageGarbageCollect,
1966 false, // default value
1967 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1968 registry->RegisterInt64Pref(
1969 pref_names::kLastUpdateCheck,
1970 0, // default value
1971 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1972 registry->RegisterInt64Pref(
1973 pref_names::kNextUpdateCheck,
1974 0, // default value
1975 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1976 registry->RegisterListPref(pref_names::kAllowedInstallSites,
1977 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1978 registry->RegisterStringPref(
1979 pref_names::kLastChromeVersion,
1980 std::string(), // default value
1981 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1982 registry->RegisterDictionaryPref(
1983 kInstallSignature,
1984 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1986 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist,
1987 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1988 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist,
1989 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1990 registry->RegisterBooleanPref(
1991 pref_names::kNativeMessagingUserLevelHosts,
1992 true, // default value
1993 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1994 registry->RegisterIntegerPref(
1995 kCorruptedDisableCount,
1996 0, // default value
1997 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1999 #if !defined(OS_MACOSX)
2000 registry->RegisterBooleanPref(
2001 pref_names::kAppFullscreenAllowed, true,
2002 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
2003 #endif
2006 template <class ExtensionIdContainer>
2007 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
2008 const char* pref,
2009 ExtensionIdContainer* id_container_out) {
2010 DCHECK(id_container_out->empty());
2012 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
2013 const base::ListValue* user_pref_as_list;
2014 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
2015 return false;
2017 std::insert_iterator<ExtensionIdContainer> insert_iterator(
2018 *id_container_out, id_container_out->end());
2019 std::string extension_id;
2020 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
2021 value_it != user_pref_as_list->end(); ++value_it) {
2022 if (!(*value_it)->GetAsString(&extension_id)) {
2023 NOTREACHED();
2024 continue;
2026 insert_iterator = extension_id;
2028 return true;
2031 template <class ExtensionIdContainer>
2032 void ExtensionPrefs::SetExtensionPrefFromContainer(
2033 const char* pref,
2034 const ExtensionIdContainer& strings) {
2035 ListPrefUpdate update(prefs_, pref);
2036 base::ListValue* list_of_values = update.Get();
2037 list_of_values->Clear();
2038 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
2039 iter != strings.end(); ++iter) {
2040 list_of_values->Append(new base::StringValue(*iter));
2044 void ExtensionPrefs::PopulateExtensionInfoPrefs(
2045 const Extension* extension,
2046 const base::Time install_time,
2047 Extension::State initial_state,
2048 int install_flags,
2049 const std::string& install_parameter,
2050 base::DictionaryValue* extension_dict) {
2051 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
2052 extension_dict->Set(kPrefLocation,
2053 new base::FundamentalValue(extension->location()));
2054 extension_dict->Set(kPrefCreationFlags,
2055 new base::FundamentalValue(extension->creation_flags()));
2056 extension_dict->Set(kPrefFromWebStore,
2057 new base::FundamentalValue(extension->from_webstore()));
2058 extension_dict->Set(kPrefFromBookmark,
2059 new base::FundamentalValue(extension->from_bookmark()));
2060 extension_dict->Set(
2061 kPrefWasInstalledByDefault,
2062 new base::FundamentalValue(extension->was_installed_by_default()));
2063 extension_dict->Set(
2064 kPrefWasInstalledByOem,
2065 new base::FundamentalValue(extension->was_installed_by_oem()));
2066 extension_dict->Set(kPrefInstallTime,
2067 new base::StringValue(
2068 base::Int64ToString(install_time.ToInternalValue())));
2069 if (install_flags & kInstallFlagIsBlacklistedForMalware)
2070 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
2072 if (install_flags & kInstallFlagIsEphemeral)
2073 extension_dict->Set(kPrefEphemeralApp, new base::FundamentalValue(true));
2074 else
2075 extension_dict->Remove(kPrefEphemeralApp, NULL);
2077 base::FilePath::StringType path = MakePathRelative(install_directory_,
2078 extension->path());
2079 extension_dict->Set(kPrefPath, new base::StringValue(path));
2080 if (!install_parameter.empty()) {
2081 extension_dict->Set(kPrefInstallParam,
2082 new base::StringValue(install_parameter));
2084 // We store prefs about LOAD extensions, but don't cache their manifest
2085 // since it may change on disk.
2086 if (!Manifest::IsUnpackedLocation(extension->location())) {
2087 extension_dict->Set(kPrefManifest,
2088 extension->manifest()->value()->DeepCopy());
2091 // Only writes kPrefDoNotSync when it is not the default.
2092 if (install_flags & kInstallFlagDoNotSync)
2093 extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true));
2094 else
2095 extension_dict->Remove(kPrefDoNotSync, NULL);
2098 void ExtensionPrefs::InitExtensionControlledPrefs(
2099 ExtensionPrefValueMap* value_map) {
2100 ExtensionIdList extension_ids;
2101 GetExtensions(&extension_ids);
2103 for (ExtensionIdList::iterator extension_id = extension_ids.begin();
2104 extension_id != extension_ids.end();
2105 ++extension_id) {
2106 base::Time install_time = GetInstallTime(*extension_id);
2107 bool is_enabled = !IsExtensionDisabled(*extension_id);
2108 bool is_incognito_enabled = IsIncognitoEnabled(*extension_id);
2109 value_map->RegisterExtension(
2110 *extension_id, install_time, is_enabled, is_incognito_enabled);
2112 FOR_EACH_OBSERVER(
2113 ExtensionPrefsObserver,
2114 observer_list_,
2115 OnExtensionRegistered(*extension_id, install_time, is_enabled));
2117 // Set regular extension controlled prefs.
2118 LoadExtensionControlledPrefs(
2119 this, value_map, *extension_id, kExtensionPrefsScopeRegular);
2120 // Set incognito extension controlled prefs.
2121 LoadExtensionControlledPrefs(this,
2122 value_map,
2123 *extension_id,
2124 kExtensionPrefsScopeIncognitoPersistent);
2125 // Set regular-only extension controlled prefs.
2126 LoadExtensionControlledPrefs(
2127 this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly);
2129 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
2130 observer_list_,
2131 OnExtensionPrefsLoaded(*extension_id, this));
2135 void ExtensionPrefs::FinishExtensionInfoPrefs(
2136 const std::string& extension_id,
2137 const base::Time install_time,
2138 bool needs_sort_ordinal,
2139 const syncer::StringOrdinal& suggested_page_ordinal,
2140 base::DictionaryValue* extension_dict) {
2141 // Reinitializes various preferences with empty dictionaries.
2142 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
2143 extension_dict->Set(pref_names::kPrefPreferences,
2144 new base::DictionaryValue);
2147 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
2148 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
2149 new base::DictionaryValue);
2152 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
2153 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
2154 new base::DictionaryValue);
2157 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
2158 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
2160 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
2161 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
2162 new base::ListValue);
2165 // If this point has been reached, any pending installs should be considered
2166 // out of date.
2167 extension_dict->Remove(kDelayedInstallInfo, NULL);
2169 // Clear state that may be registered from a previous install.
2170 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
2172 // FYI, all code below here races on sudden shutdown because |extension_dict|,
2173 // |app_sorting_|, |extension_pref_value_map_|, and (potentially) observers
2174 // are updated non-transactionally. This is probably not fixable without
2175 // nested transactional updates to pref dictionaries.
2176 if (needs_sort_ordinal)
2177 app_sorting_->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
2179 bool is_enabled = false;
2180 int initial_state;
2181 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
2182 is_enabled = initial_state == Extension::ENABLED;
2184 bool is_incognito_enabled = IsIncognitoEnabled(extension_id);
2186 extension_pref_value_map_->RegisterExtension(
2187 extension_id, install_time, is_enabled, is_incognito_enabled);
2189 FOR_EACH_OBSERVER(
2190 ExtensionPrefsObserver,
2191 observer_list_,
2192 OnExtensionRegistered(extension_id, install_time, is_enabled));
2195 } // namespace extensions