Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / extensions / browser / extension_prefs.cc
blob58ccad71e6c0e4fd030571804bc5a99f79d80d5c
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/browser/extension_prefs.h"
7 #include <iterator>
9 #include "base/command_line.h"
10 #include "base/metrics/histogram_macros.h"
11 #include "base/prefs/pref_notifier.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_util.h"
15 #include "base/trace_event/trace_event.h"
16 #include "base/value_conversions.h"
17 #include "components/crx_file/id_util.h"
18 #include "components/pref_registry/pref_registry_syncable.h"
19 #include "extensions/browser/app_sorting.h"
20 #include "extensions/browser/event_router.h"
21 #include "extensions/browser/extension_pref_store.h"
22 #include "extensions/browser/extension_prefs_factory.h"
23 #include "extensions/browser/extension_prefs_observer.h"
24 #include "extensions/browser/install_flag.h"
25 #include "extensions/browser/pref_names.h"
26 #include "extensions/common/feature_switch.h"
27 #include "extensions/common/manifest.h"
28 #include "extensions/common/permissions/permission_set.h"
29 #include "extensions/common/permissions/permissions_info.h"
30 #include "extensions/common/url_pattern.h"
31 #include "extensions/common/user_script.h"
32 #include "ui/base/l10n/l10n_util.h"
34 using base::Value;
35 using base::DictionaryValue;
36 using base::ListValue;
38 namespace extensions {
40 namespace {
42 // Additional preferences keys, which are not needed by external clients.
44 // True if this extension is running. Note this preference stops getting updated
45 // during Chrome shutdown (and won't be updated on a browser crash) and so can
46 // be used at startup to determine whether the extension was running when Chrome
47 // was last terminated.
48 const char kPrefRunning[] = "running";
50 // Whether this extension had windows when it was last running.
51 const char kIsActive[] = "is_active";
53 // Where an extension was installed from. (see Manifest::Location)
54 const char kPrefLocation[] = "location";
56 // Enabled, disabled, killed, etc. (see Extension::State)
57 const char kPrefState[] = "state";
59 // The path to the current version's manifest file.
60 const char kPrefPath[] = "path";
62 // The dictionary containing the extension's manifest.
63 const char kPrefManifest[] = "manifest";
65 // The version number.
66 const char kPrefVersion[] = "manifest.version";
68 // Indicates whether an extension is blacklisted.
69 const char kPrefBlacklist[] = "blacklist";
71 // If extension is greylisted.
72 const char kPrefBlacklistState[] = "blacklist_state";
74 // The count of how many times we prompted the user to acknowledge an
75 // extension.
76 const char kPrefAcknowledgePromptCount[] = "ack_prompt_count";
78 // Indicates whether the user has acknowledged various types of extensions.
79 const char kPrefExternalAcknowledged[] = "ack_external";
80 const char kPrefBlacklistAcknowledged[] = "ack_blacklist";
82 // Indicates whether the external extension was installed during the first
83 // run of this profile.
84 const char kPrefExternalInstallFirstRun[] = "external_first_run";
86 // DO NOT USE, use kPrefDisableReasons instead.
87 // Indicates whether the extension was updated while it was disabled.
88 const char kDeprecatedPrefDisableReason[] = "disable_reason";
90 // A bitmask of all the reasons an extension is disabled.
91 const char kPrefDisableReasons[] = "disable_reasons";
93 // The key for a serialized Time value indicating the start of the day (from the
94 // server's perspective) an extension last included a "ping" parameter during
95 // its update check.
96 const char kLastPingDay[] = "lastpingday";
98 // Similar to kLastPingDay, but for "active" instead of "rollcall" pings.
99 const char kLastActivePingDay[] = "last_active_pingday";
101 // A bit we use to keep track of whether we need to do an "active" ping.
102 const char kActiveBit[] = "active_bit";
104 // Path for settings specific to blacklist update.
105 const char kExtensionsBlacklistUpdate[] = "extensions.blacklistupdate";
107 // Path for the delayed install info dictionary preference. The actual string
108 // value is a legacy artifact for when delayed installs only pertained to
109 // updates that were waiting for idle.
110 const char kDelayedInstallInfo[] = "idle_install_info";
112 // Reason why the extension's install was delayed.
113 const char kDelayedInstallReason[] = "delay_install_reason";
115 // Path for the suggested page ordinal of a delayed extension install.
116 const char kPrefSuggestedPageOrdinal[] = "suggested_page_ordinal";
118 // A preference that, if true, will allow this extension to run in incognito
119 // mode.
120 const char kPrefIncognitoEnabled[] = "incognito";
122 // A preference to control whether an extension is allowed to inject script in
123 // pages with file URLs.
124 const char kPrefAllowFileAccess[] = "newAllowFileAccess";
125 // TODO(jstritar): As part of fixing http://crbug.com/91577, we revoked all
126 // extension file access by renaming the pref. We should eventually clean up
127 // the old flag and possibly go back to that name.
128 // const char kPrefAllowFileAccessOld[] = "allowFileAccess";
130 // A preference specifying if the user dragged the app on the NTP.
131 const char kPrefUserDraggedApp[] = "user_dragged_app_ntp";
133 // Preferences that hold which permissions the user has granted the extension.
134 // We explicitly keep track of these so that extensions can contain unknown
135 // permissions, for backwards compatibility reasons, and we can still prompt
136 // the user to accept them once recognized. We store the active permission
137 // permissions because they may differ from those defined in the manifest.
138 const char kPrefActivePermissions[] = "active_permissions";
139 const char kPrefGrantedPermissions[] = "granted_permissions";
141 // The preference names for PermissionSet values.
142 const char kPrefAPIs[] = "api";
143 const char kPrefManifestPermissions[] = "manifest_permissions";
144 const char kPrefExplicitHosts[] = "explicit_host";
145 const char kPrefScriptableHosts[] = "scriptable_host";
147 // The preference names for the old granted permissions scheme.
148 const char kPrefOldGrantedFullAccess[] = "granted_permissions.full";
149 const char kPrefOldGrantedHosts[] = "granted_permissions.host";
150 const char kPrefOldGrantedAPIs[] = "granted_permissions.api";
152 // A preference that indicates when an extension was installed.
153 const char kPrefInstallTime[] = "install_time";
155 // A preference which saves the creation flags for extensions.
156 const char kPrefCreationFlags[] = "creation_flags";
158 // A preference that indicates whether the extension was installed from the
159 // Chrome Web Store.
160 const char kPrefFromWebStore[] = "from_webstore";
162 // A preference that indicates whether the extension was installed from a
163 // mock App created from a bookmark.
164 const char kPrefFromBookmark[] = "from_bookmark";
166 // A preference that indicates whether the extension was installed as a
167 // default app.
168 const char kPrefWasInstalledByDefault[] = "was_installed_by_default";
170 // A preference that indicates whether the extension was installed as an
171 // OEM app.
172 const char kPrefWasInstalledByOem[] = "was_installed_by_oem";
174 // Key for Geometry Cache preference.
175 const char kPrefGeometryCache[] = "geometry_cache";
177 // A preference that indicates when an extension is last launched.
178 const char kPrefLastLaunchTime[] = "last_launch_time";
180 // A preference indicating whether the extension is an ephemeral app.
181 const char kPrefEphemeralApp[] = "ephemeral_app";
183 // Am installation parameter bundled with an extension.
184 const char kPrefInstallParam[] = "install_parameter";
186 // A list of installed ids and a signature.
187 const char kInstallSignature[] = "extensions.install_signature";
189 // A boolean preference that indicates whether the extension should not be
190 // synced. Default value is false.
191 const char kPrefDoNotSync[] = "do_not_sync";
193 const char kCorruptedDisableCount[] = "extensions.corrupted_disable_count";
195 // A boolean preference that indicates whether the extension has local changes
196 // that need to be synced. Default value is false.
197 const char kPrefNeedsSync[] = "needs_sync";
199 // Provider of write access to a dictionary storing extension prefs.
200 class ScopedExtensionPrefUpdate : public DictionaryPrefUpdate {
201 public:
202 ScopedExtensionPrefUpdate(PrefService* service,
203 const std::string& extension_id) :
204 DictionaryPrefUpdate(service, pref_names::kExtensions),
205 extension_id_(extension_id) {}
207 ~ScopedExtensionPrefUpdate() override {}
209 // DictionaryPrefUpdate overrides:
210 base::DictionaryValue* Get() override {
211 base::DictionaryValue* dict = DictionaryPrefUpdate::Get();
212 base::DictionaryValue* extension = NULL;
213 if (!dict->GetDictionary(extension_id_, &extension)) {
214 // Extension pref does not exist, create it.
215 extension = new base::DictionaryValue();
216 dict->SetWithoutPathExpansion(extension_id_, extension);
218 return extension;
221 private:
222 const std::string extension_id_;
224 DISALLOW_COPY_AND_ASSIGN(ScopedExtensionPrefUpdate);
227 std::string JoinPrefs(const std::string& parent, const char* child) {
228 return parent + "." + child;
231 // Checks if kPrefBlacklist is set to true in the base::DictionaryValue.
232 // Return false if the value is false or kPrefBlacklist does not exist.
233 // This is used to decide if an extension is blacklisted.
234 bool IsBlacklistBitSet(const base::DictionaryValue* ext) {
235 bool bool_value;
236 return ext->GetBoolean(kPrefBlacklist, &bool_value) && bool_value;
239 void LoadExtensionControlledPrefs(ExtensionPrefs* prefs,
240 ExtensionPrefValueMap* value_map,
241 const std::string& extension_id,
242 ExtensionPrefsScope scope) {
243 std::string scope_string;
244 if (!pref_names::ScopeToPrefName(scope, &scope_string))
245 return;
246 std::string key = extension_id + "." + scope_string;
248 const base::DictionaryValue* source_dict =
249 prefs->pref_service()->GetDictionary(pref_names::kExtensions);
250 const base::DictionaryValue* preferences = NULL;
251 if (!source_dict->GetDictionary(key, &preferences))
252 return;
254 for (base::DictionaryValue::Iterator iter(*preferences); !iter.IsAtEnd();
255 iter.Advance()) {
256 value_map->SetExtensionPref(
257 extension_id, iter.key(), scope, iter.value().DeepCopy());
261 } // namespace
264 // TimeProvider
267 ExtensionPrefs::TimeProvider::TimeProvider() {
270 ExtensionPrefs::TimeProvider::~TimeProvider() {
273 base::Time ExtensionPrefs::TimeProvider::GetCurrentTime() const {
274 return base::Time::Now();
278 // ScopedUpdate
280 template <typename T, base::Value::Type type_enum_value>
281 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::ScopedUpdate(
282 ExtensionPrefs* prefs,
283 const std::string& extension_id,
284 const std::string& key)
285 : update_(prefs->pref_service(), pref_names::kExtensions),
286 extension_id_(extension_id),
287 key_(key) {
288 DCHECK(crx_file::id_util::IdIsValid(extension_id_));
291 template <typename T, base::Value::Type type_enum_value>
292 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::~ScopedUpdate() {
295 template <typename T, base::Value::Type type_enum_value>
296 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Get() {
297 base::DictionaryValue* dict = update_.Get();
298 base::DictionaryValue* extension = NULL;
299 base::Value* key_value = NULL;
300 if (!dict->GetDictionary(extension_id_, &extension) ||
301 !extension->Get(key_, &key_value)) {
302 return NULL;
304 return key_value->GetType() == type_enum_value ?
305 static_cast<T*>(key_value) :
306 NULL;
309 template <typename T, base::Value::Type type_enum_value>
310 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Create() {
311 base::DictionaryValue* dict = update_.Get();
312 base::DictionaryValue* extension = NULL;
313 base::Value* key_value = NULL;
314 T* value_as_t = NULL;
315 if (!dict->GetDictionary(extension_id_, &extension)) {
316 extension = new base::DictionaryValue;
317 dict->SetWithoutPathExpansion(extension_id_, extension);
319 if (!extension->Get(key_, &key_value)) {
320 value_as_t = new T;
321 extension->SetWithoutPathExpansion(key_, value_as_t);
322 } else {
323 CHECK(key_value->GetType() == type_enum_value);
324 value_as_t = static_cast<T*>(key_value);
326 return value_as_t;
329 // Explicit instantiations for Dictionary and List value types.
330 template class ExtensionPrefs::ScopedUpdate<base::DictionaryValue,
331 base::Value::TYPE_DICTIONARY>;
332 template class ExtensionPrefs::ScopedUpdate<base::ListValue,
333 base::Value::TYPE_LIST>;
336 // ExtensionPrefs
339 // static
340 ExtensionPrefs* ExtensionPrefs::Create(
341 PrefService* prefs,
342 const base::FilePath& root_dir,
343 ExtensionPrefValueMap* extension_pref_value_map,
344 scoped_ptr<AppSorting> app_sorting,
345 bool extensions_disabled,
346 const std::vector<ExtensionPrefsObserver*>& early_observers) {
347 return ExtensionPrefs::Create(prefs,
348 root_dir,
349 extension_pref_value_map,
350 app_sorting.Pass(),
351 extensions_disabled,
352 early_observers,
353 make_scoped_ptr(new TimeProvider()));
356 // static
357 ExtensionPrefs* ExtensionPrefs::Create(
358 PrefService* pref_service,
359 const base::FilePath& root_dir,
360 ExtensionPrefValueMap* extension_pref_value_map,
361 scoped_ptr<AppSorting> app_sorting,
362 bool extensions_disabled,
363 const std::vector<ExtensionPrefsObserver*>& early_observers,
364 scoped_ptr<TimeProvider> time_provider) {
365 return new ExtensionPrefs(pref_service,
366 root_dir,
367 extension_pref_value_map,
368 app_sorting.Pass(),
369 time_provider.Pass(),
370 extensions_disabled,
371 early_observers);
374 ExtensionPrefs::~ExtensionPrefs() {
377 // static
378 ExtensionPrefs* ExtensionPrefs::Get(content::BrowserContext* context) {
379 return ExtensionPrefsFactory::GetInstance()->GetForBrowserContext(context);
382 static base::FilePath::StringType MakePathRelative(const base::FilePath& parent,
383 const base::FilePath& child) {
384 if (!parent.IsParent(child))
385 return child.value();
387 base::FilePath::StringType retval = child.value().substr(
388 parent.value().length());
389 if (base::FilePath::IsSeparator(retval[0]))
390 return retval.substr(1);
391 else
392 return retval;
395 void ExtensionPrefs::MakePathsRelative() {
396 const base::DictionaryValue* dict =
397 prefs_->GetDictionary(pref_names::kExtensions);
398 if (!dict || dict->empty())
399 return;
401 // Collect all extensions ids with absolute paths in |absolute_keys|.
402 std::set<std::string> absolute_keys;
403 for (base::DictionaryValue::Iterator i(*dict); !i.IsAtEnd(); i.Advance()) {
404 const base::DictionaryValue* extension_dict = NULL;
405 if (!i.value().GetAsDictionary(&extension_dict))
406 continue;
407 int location_value;
408 if (extension_dict->GetInteger(kPrefLocation, &location_value) &&
409 Manifest::IsUnpackedLocation(
410 static_cast<Manifest::Location>(location_value))) {
411 // Unpacked extensions can have absolute paths.
412 continue;
414 base::FilePath::StringType path_string;
415 if (!extension_dict->GetString(kPrefPath, &path_string))
416 continue;
417 base::FilePath path(path_string);
418 if (path.IsAbsolute())
419 absolute_keys.insert(i.key());
421 if (absolute_keys.empty())
422 return;
424 // Fix these paths.
425 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
426 base::DictionaryValue* update_dict = update.Get();
427 for (std::set<std::string>::iterator i = absolute_keys.begin();
428 i != absolute_keys.end(); ++i) {
429 base::DictionaryValue* extension_dict = NULL;
430 if (!update_dict->GetDictionaryWithoutPathExpansion(*i, &extension_dict)) {
431 NOTREACHED() << "Control should never reach here for extension " << *i;
432 continue;
434 base::FilePath::StringType path_string;
435 extension_dict->GetString(kPrefPath, &path_string);
436 base::FilePath path(path_string);
437 extension_dict->SetString(kPrefPath,
438 MakePathRelative(install_directory_, path));
442 const base::DictionaryValue* ExtensionPrefs::GetExtensionPref(
443 const std::string& extension_id) const {
444 const base::DictionaryValue* extensions =
445 prefs_->GetDictionary(pref_names::kExtensions);
446 const base::DictionaryValue* extension_dict = NULL;
447 if (!extensions ||
448 !extensions->GetDictionary(extension_id, &extension_dict)) {
449 return NULL;
451 return extension_dict;
454 void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id,
455 const std::string& key,
456 base::Value* data_value) {
457 if (!crx_file::id_util::IdIsValid(extension_id)) {
458 NOTREACHED() << "Invalid extension_id " << extension_id;
459 return;
461 ScopedExtensionPrefUpdate update(prefs_, extension_id);
462 if (data_value)
463 update->Set(key, data_value);
464 else
465 update->Remove(key, NULL);
468 void ExtensionPrefs::DeleteExtensionPrefs(const std::string& extension_id) {
469 extension_pref_value_map_->UnregisterExtension(extension_id);
470 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
471 observer_list_,
472 OnExtensionPrefsDeleted(extension_id));
473 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
474 base::DictionaryValue* dict = update.Get();
475 dict->Remove(extension_id, NULL);
478 bool ExtensionPrefs::ReadPrefAsBoolean(const std::string& extension_id,
479 const std::string& pref_key,
480 bool* out_value) const {
481 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
482 if (!ext || !ext->GetBoolean(pref_key, out_value))
483 return false;
485 return true;
488 bool ExtensionPrefs::ReadPrefAsInteger(const std::string& extension_id,
489 const std::string& pref_key,
490 int* out_value) const {
491 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
492 if (!ext || !ext->GetInteger(pref_key, out_value))
493 return false;
495 return true;
498 bool ExtensionPrefs::ReadPrefAsString(const std::string& extension_id,
499 const std::string& pref_key,
500 std::string* out_value) const {
501 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
502 if (!ext || !ext->GetString(pref_key, out_value))
503 return false;
505 return true;
508 bool ExtensionPrefs::ReadPrefAsList(const std::string& extension_id,
509 const std::string& pref_key,
510 const base::ListValue** out_value) const {
511 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
512 const base::ListValue* out = NULL;
513 if (!ext || !ext->GetList(pref_key, &out))
514 return false;
515 if (out_value)
516 *out_value = out;
518 return true;
521 bool ExtensionPrefs::ReadPrefAsDictionary(
522 const std::string& extension_id,
523 const std::string& pref_key,
524 const base::DictionaryValue** out_value) const {
525 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
526 const base::DictionaryValue* out = NULL;
527 if (!ext || !ext->GetDictionary(pref_key, &out))
528 return false;
529 if (out_value)
530 *out_value = out;
532 return true;
535 bool ExtensionPrefs::HasPrefForExtension(
536 const std::string& extension_id) const {
537 return GetExtensionPref(extension_id) != NULL;
540 bool ExtensionPrefs::ReadPrefAsURLPatternSet(const std::string& extension_id,
541 const std::string& pref_key,
542 URLPatternSet* result,
543 int valid_schemes) const {
544 const base::ListValue* value = NULL;
545 if (!ReadPrefAsList(extension_id, pref_key, &value))
546 return false;
547 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
548 if (!extension)
549 return false;
550 int location;
551 if (extension->GetInteger(kPrefLocation, &location) &&
552 static_cast<Manifest::Location>(location) == Manifest::COMPONENT) {
553 valid_schemes |= URLPattern::SCHEME_CHROMEUI;
556 bool allow_file_access = AllowFileAccess(extension_id);
557 return result->Populate(*value, valid_schemes, allow_file_access, NULL);
560 void ExtensionPrefs::SetExtensionPrefURLPatternSet(
561 const std::string& extension_id,
562 const std::string& pref_key,
563 const URLPatternSet& new_value) {
564 UpdateExtensionPref(extension_id, pref_key, new_value.ToValue().release());
567 bool ExtensionPrefs::ReadPrefAsBooleanAndReturn(
568 const std::string& extension_id,
569 const std::string& pref_key) const {
570 bool out_value = false;
571 return ReadPrefAsBoolean(extension_id, pref_key, &out_value) && out_value;
574 PermissionSet* ExtensionPrefs::ReadPrefAsPermissionSet(
575 const std::string& extension_id,
576 const std::string& pref_key) const {
577 if (!GetExtensionPref(extension_id))
578 return NULL;
580 // Retrieve the API permissions. Please refer SetExtensionPrefPermissionSet()
581 // for api_values format.
582 APIPermissionSet apis;
583 const base::ListValue* api_values = NULL;
584 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
585 if (ReadPrefAsList(extension_id, api_pref, &api_values)) {
586 APIPermissionSet::ParseFromJSON(api_values,
587 APIPermissionSet::kAllowInternalPermissions,
588 &apis, NULL, NULL);
591 // Retrieve the Manifest Keys permissions. Please refer to
592 // |SetExtensionPrefPermissionSet| for manifest_permissions_values format.
593 ManifestPermissionSet manifest_permissions;
594 const base::ListValue* manifest_permissions_values = NULL;
595 std::string manifest_permission_pref =
596 JoinPrefs(pref_key, kPrefManifestPermissions);
597 if (ReadPrefAsList(extension_id, manifest_permission_pref,
598 &manifest_permissions_values)) {
599 ManifestPermissionSet::ParseFromJSON(
600 manifest_permissions_values, &manifest_permissions, NULL, NULL);
603 // Retrieve the explicit host permissions.
604 URLPatternSet explicit_hosts;
605 ReadPrefAsURLPatternSet(
606 extension_id, JoinPrefs(pref_key, kPrefExplicitHosts),
607 &explicit_hosts, Extension::kValidHostPermissionSchemes);
609 // Retrieve the scriptable host permissions.
610 URLPatternSet scriptable_hosts;
611 ReadPrefAsURLPatternSet(
612 extension_id, JoinPrefs(pref_key, kPrefScriptableHosts),
613 &scriptable_hosts, UserScript::ValidUserScriptSchemes());
615 return new PermissionSet(
616 apis, manifest_permissions, explicit_hosts, scriptable_hosts);
619 // Set the API or Manifest permissions.
620 // The format of api_values is:
621 // [ "permission_name1", // permissions do not support detail.
622 // "permission_name2",
623 // {"permission_name3": value },
624 // // permission supports detail, permission detail will be stored in value.
625 // ...
626 // ]
627 template<typename T>
628 static base::ListValue* CreatePermissionList(const T& permissions) {
629 base::ListValue* values = new base::ListValue();
630 for (typename T::const_iterator i = permissions.begin();
631 i != permissions.end(); ++i) {
632 scoped_ptr<base::Value> detail(i->ToValue());
633 if (detail) {
634 base::DictionaryValue* tmp = new base::DictionaryValue();
635 tmp->Set(i->name(), detail.release());
636 values->Append(tmp);
637 } else {
638 values->Append(new base::StringValue(i->name()));
641 return values;
644 void ExtensionPrefs::SetExtensionPrefPermissionSet(
645 const std::string& extension_id,
646 const std::string& pref_key,
647 const PermissionSet* new_value) {
648 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
649 base::ListValue* api_values = CreatePermissionList(new_value->apis());
650 UpdateExtensionPref(extension_id, api_pref, api_values);
652 std::string manifest_permissions_pref =
653 JoinPrefs(pref_key, kPrefManifestPermissions);
654 base::ListValue* manifest_permissions_values = CreatePermissionList(
655 new_value->manifest_permissions());
656 UpdateExtensionPref(extension_id,
657 manifest_permissions_pref,
658 manifest_permissions_values);
660 // Set the explicit host permissions.
661 if (!new_value->explicit_hosts().is_empty()) {
662 SetExtensionPrefURLPatternSet(extension_id,
663 JoinPrefs(pref_key, kPrefExplicitHosts),
664 new_value->explicit_hosts());
667 // Set the scriptable host permissions.
668 if (!new_value->scriptable_hosts().is_empty()) {
669 SetExtensionPrefURLPatternSet(extension_id,
670 JoinPrefs(pref_key, kPrefScriptableHosts),
671 new_value->scriptable_hosts());
675 int ExtensionPrefs::IncrementAcknowledgePromptCount(
676 const std::string& extension_id) {
677 int count = 0;
678 ReadPrefAsInteger(extension_id, kPrefAcknowledgePromptCount, &count);
679 ++count;
680 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount,
681 new base::FundamentalValue(count));
682 return count;
685 bool ExtensionPrefs::IsExternalExtensionAcknowledged(
686 const std::string& extension_id) const {
687 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalAcknowledged);
690 void ExtensionPrefs::AcknowledgeExternalExtension(
691 const std::string& extension_id) {
692 DCHECK(crx_file::id_util::IdIsValid(extension_id));
693 UpdateExtensionPref(extension_id, kPrefExternalAcknowledged,
694 new base::FundamentalValue(true));
695 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
698 bool ExtensionPrefs::IsBlacklistedExtensionAcknowledged(
699 const std::string& extension_id) const {
700 return ReadPrefAsBooleanAndReturn(extension_id, kPrefBlacklistAcknowledged);
703 void ExtensionPrefs::AcknowledgeBlacklistedExtension(
704 const std::string& extension_id) {
705 DCHECK(crx_file::id_util::IdIsValid(extension_id));
706 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged,
707 new base::FundamentalValue(true));
708 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
711 bool ExtensionPrefs::IsExternalInstallFirstRun(
712 const std::string& extension_id) const {
713 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalInstallFirstRun);
716 void ExtensionPrefs::SetExternalInstallFirstRun(
717 const std::string& extension_id) {
718 DCHECK(crx_file::id_util::IdIsValid(extension_id));
719 UpdateExtensionPref(extension_id, kPrefExternalInstallFirstRun,
720 new base::FundamentalValue(true));
723 bool ExtensionPrefs::SetAlertSystemFirstRun() {
724 if (prefs_->GetBoolean(pref_names::kAlertsInitialized)) {
725 return true;
727 prefs_->SetBoolean(pref_names::kAlertsInitialized, true);
728 return false;
731 bool ExtensionPrefs::DidExtensionEscalatePermissions(
732 const std::string& extension_id) const {
733 return HasDisableReason(extension_id,
734 Extension::DISABLE_PERMISSIONS_INCREASE) ||
735 HasDisableReason(extension_id, Extension::DISABLE_REMOTE_INSTALL);
738 int ExtensionPrefs::GetDisableReasons(const std::string& extension_id) const {
739 int value = -1;
740 if (ReadPrefAsInteger(extension_id, kPrefDisableReasons, &value) &&
741 value >= 0) {
742 return value;
744 return Extension::DISABLE_NONE;
747 bool ExtensionPrefs::HasDisableReason(
748 const std::string& extension_id,
749 Extension::DisableReason disable_reason) const {
750 return (GetDisableReasons(extension_id) & disable_reason) != 0;
753 void ExtensionPrefs::AddDisableReason(const std::string& extension_id,
754 Extension::DisableReason disable_reason) {
755 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_ADD);
758 void ExtensionPrefs::AddDisableReasons(const std::string& extension_id,
759 int disable_reasons) {
760 ModifyDisableReasons(extension_id, disable_reasons, DISABLE_REASON_ADD);
763 void ExtensionPrefs::RemoveDisableReason(
764 const std::string& extension_id,
765 Extension::DisableReason disable_reason) {
766 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_REMOVE);
769 void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) {
770 ModifyDisableReasons(extension_id, Extension::DISABLE_NONE,
771 DISABLE_REASON_CLEAR);
774 void ExtensionPrefs::ModifyDisableReasons(const std::string& extension_id,
775 int reasons,
776 DisableReasonChange change) {
777 int old_value = GetDisableReasons(extension_id);
778 int new_value = old_value;
779 switch (change) {
780 case DISABLE_REASON_ADD:
781 new_value |= reasons;
782 break;
783 case DISABLE_REASON_REMOVE:
784 new_value &= ~reasons;
785 break;
786 case DISABLE_REASON_CLEAR:
787 new_value = Extension::DISABLE_NONE;
788 break;
791 if (old_value == new_value) // no change, return.
792 return;
794 if (new_value == Extension::DISABLE_NONE) {
795 UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
796 } else {
797 UpdateExtensionPref(extension_id,
798 kPrefDisableReasons,
799 new base::FundamentalValue(new_value));
802 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
803 observer_list_,
804 OnExtensionDisableReasonsChanged(extension_id, new_value));
807 std::set<std::string> ExtensionPrefs::GetBlacklistedExtensions() const {
808 std::set<std::string> ids;
810 const base::DictionaryValue* extensions =
811 prefs_->GetDictionary(pref_names::kExtensions);
812 if (!extensions)
813 return ids;
815 for (base::DictionaryValue::Iterator it(*extensions);
816 !it.IsAtEnd(); it.Advance()) {
817 if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) {
818 NOTREACHED() << "Invalid pref for extension " << it.key();
819 continue;
821 if (IsBlacklistBitSet(
822 static_cast<const base::DictionaryValue*>(&it.value()))) {
823 ids.insert(it.key());
827 return ids;
830 void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id,
831 bool is_blacklisted) {
832 bool currently_blacklisted = IsExtensionBlacklisted(extension_id);
833 if (is_blacklisted == currently_blacklisted)
834 return;
836 // Always make sure the "acknowledged" bit is cleared since the blacklist bit
837 // is changing.
838 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL);
840 if (is_blacklisted) {
841 UpdateExtensionPref(extension_id,
842 kPrefBlacklist,
843 new base::FundamentalValue(true));
844 } else {
845 UpdateExtensionPref(extension_id, kPrefBlacklist, NULL);
846 const base::DictionaryValue* dict = GetExtensionPref(extension_id);
847 if (dict && dict->empty())
848 DeleteExtensionPrefs(extension_id);
852 bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const {
853 const base::DictionaryValue* ext_prefs = GetExtensionPref(id);
854 return ext_prefs && IsBlacklistBitSet(ext_prefs);
857 namespace {
859 // Serializes a 64bit integer as a string value.
860 void SaveInt64(base::DictionaryValue* dictionary,
861 const char* key,
862 const int64 value) {
863 if (!dictionary)
864 return;
866 std::string string_value = base::Int64ToString(value);
867 dictionary->SetString(key, string_value);
870 // Deserializes a 64bit integer stored as a string value.
871 bool ReadInt64(const base::DictionaryValue* dictionary,
872 const char* key,
873 int64* value) {
874 if (!dictionary)
875 return false;
877 std::string string_value;
878 if (!dictionary->GetString(key, &string_value))
879 return false;
881 return base::StringToInt64(string_value, value);
884 // Serializes |time| as a string value mapped to |key| in |dictionary|.
885 void SaveTime(base::DictionaryValue* dictionary,
886 const char* key,
887 const base::Time& time) {
888 SaveInt64(dictionary, key, time.ToInternalValue());
891 // The opposite of SaveTime. If |key| is not found, this returns an empty Time
892 // (is_null() will return true).
893 base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) {
894 int64 value;
895 if (ReadInt64(dictionary, key, &value))
896 return base::Time::FromInternalValue(value);
898 return base::Time();
901 } // namespace
903 base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const {
904 DCHECK(crx_file::id_util::IdIsValid(extension_id));
905 return ReadTime(GetExtensionPref(extension_id), kLastPingDay);
908 void ExtensionPrefs::SetLastPingDay(const std::string& extension_id,
909 const base::Time& time) {
910 DCHECK(crx_file::id_util::IdIsValid(extension_id));
911 ScopedExtensionPrefUpdate update(prefs_, extension_id);
912 SaveTime(update.Get(), kLastPingDay, time);
915 base::Time ExtensionPrefs::BlacklistLastPingDay() const {
916 return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate),
917 kLastPingDay);
920 void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) {
921 DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate);
922 SaveTime(update.Get(), kLastPingDay, time);
925 base::Time ExtensionPrefs::LastActivePingDay(
926 const std::string& extension_id) const {
927 DCHECK(crx_file::id_util::IdIsValid(extension_id));
928 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
931 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
932 const base::Time& time) {
933 DCHECK(crx_file::id_util::IdIsValid(extension_id));
934 ScopedExtensionPrefUpdate update(prefs_, extension_id);
935 SaveTime(update.Get(), kLastActivePingDay, time);
938 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) const {
939 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
940 bool result = false;
941 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
942 return result;
943 return false;
946 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
947 bool active) {
948 UpdateExtensionPref(extension_id, kActiveBit,
949 new base::FundamentalValue(active));
952 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
953 PermissionsInfo* info = PermissionsInfo::GetInstance();
954 for (ExtensionIdList::const_iterator ext_id =
955 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
956 // An extension's granted permissions need to be migrated if the
957 // full_access bit is present. This bit was always present in the previous
958 // scheme and is never present now.
959 bool full_access = false;
960 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
961 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
962 continue;
964 // Remove the full access bit (empty list will get trimmed).
965 UpdateExtensionPref(
966 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
968 // Add the plugin permission if the full access bit was set.
969 if (full_access) {
970 const base::ListValue* apis = NULL;
971 base::ListValue* new_apis = NULL;
973 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
974 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
975 new_apis = apis->DeepCopy();
976 else
977 new_apis = new base::ListValue();
979 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
980 new_apis->Append(new base::StringValue(plugin_name));
981 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
984 // The granted permissions originally only held the effective hosts,
985 // which are a combination of host and user script host permissions.
986 // We now maintain these lists separately. For migration purposes, it
987 // does not matter how we treat the old effective hosts as long as the
988 // new effective hosts will be the same, so we move them to explicit
989 // host permissions.
990 const base::ListValue* hosts = NULL;
991 std::string explicit_hosts =
992 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
993 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
994 UpdateExtensionPref(
995 *ext_id, explicit_hosts, hosts->DeepCopy());
997 // We can get rid of the old one by setting it to an empty list.
998 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
1003 void ExtensionPrefs::MigrateDisableReasons(
1004 const ExtensionIdList& extension_ids) {
1005 for (ExtensionIdList::const_iterator ext_id =
1006 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
1007 int value = -1;
1008 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
1009 int new_value = Extension::DISABLE_NONE;
1010 switch (value) {
1011 case Extension::DEPRECATED_DISABLE_USER_ACTION:
1012 new_value = Extension::DISABLE_USER_ACTION;
1013 break;
1014 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
1015 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
1016 break;
1017 case Extension::DEPRECATED_DISABLE_RELOAD:
1018 new_value = Extension::DISABLE_RELOAD;
1019 break;
1022 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
1023 new base::FundamentalValue(new_value));
1024 // Remove the old disable reason.
1025 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
1030 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
1031 const std::string& extension_id) const {
1032 CHECK(crx_file::id_util::IdIsValid(extension_id));
1033 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
1036 void ExtensionPrefs::AddGrantedPermissions(
1037 const std::string& extension_id,
1038 const PermissionSet* permissions) {
1039 CHECK(crx_file::id_util::IdIsValid(extension_id));
1041 scoped_refptr<PermissionSet> granted_permissions(
1042 GetGrantedPermissions(extension_id));
1044 // The new granted permissions are the union of the already granted
1045 // permissions and the newly granted permissions.
1046 scoped_refptr<PermissionSet> new_perms(
1047 PermissionSet::CreateUnion(
1048 permissions, granted_permissions.get()));
1050 SetExtensionPrefPermissionSet(
1051 extension_id, kPrefGrantedPermissions, new_perms.get());
1054 void ExtensionPrefs::RemoveGrantedPermissions(
1055 const std::string& extension_id,
1056 const PermissionSet* permissions) {
1057 CHECK(crx_file::id_util::IdIsValid(extension_id));
1059 scoped_refptr<PermissionSet> granted_permissions(
1060 GetGrantedPermissions(extension_id));
1062 // The new granted permissions are the difference of the already granted
1063 // permissions and the newly ungranted permissions.
1064 scoped_refptr<PermissionSet> new_perms(
1065 PermissionSet::CreateDifference(
1066 granted_permissions.get(), permissions));
1068 SetExtensionPrefPermissionSet(
1069 extension_id, kPrefGrantedPermissions, new_perms.get());
1072 PermissionSet* ExtensionPrefs::GetActivePermissions(
1073 const std::string& extension_id) const {
1074 CHECK(crx_file::id_util::IdIsValid(extension_id));
1075 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
1078 void ExtensionPrefs::SetActivePermissions(
1079 const std::string& extension_id,
1080 const PermissionSet* permissions) {
1081 SetExtensionPrefPermissionSet(
1082 extension_id, kPrefActivePermissions, permissions);
1085 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1086 bool is_running) {
1087 base::Value* value = new base::FundamentalValue(is_running);
1088 UpdateExtensionPref(extension_id, kPrefRunning, value);
1091 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) const {
1092 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1093 if (!extension)
1094 return false;
1095 bool running = false;
1096 extension->GetBoolean(kPrefRunning, &running);
1097 return running;
1100 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1101 bool is_active) {
1102 base::Value* value = new base::FundamentalValue(is_active);
1103 UpdateExtensionPref(extension_id, kIsActive, value);
1106 bool ExtensionPrefs::IsActive(const std::string& extension_id) const {
1107 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1108 if (!extension)
1109 return false;
1110 bool is_active = false;
1111 extension->GetBoolean(kIsActive, &is_active);
1112 return is_active;
1115 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1116 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1119 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1120 bool enabled) {
1121 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1122 new base::FundamentalValue(enabled));
1123 extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled);
1126 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1127 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1130 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1131 bool allow) {
1132 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1133 new base::FundamentalValue(allow));
1136 bool ExtensionPrefs::HasAllowFileAccessSetting(
1137 const std::string& extension_id) const {
1138 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1139 return ext && ext->HasKey(kPrefAllowFileAccess);
1142 bool ExtensionPrefs::DoesExtensionHaveState(
1143 const std::string& id, Extension::State check_state) const {
1144 const base::DictionaryValue* extension = GetExtensionPref(id);
1145 int state = -1;
1146 if (!extension || !extension->GetInteger(kPrefState, &state))
1147 return false;
1149 if (state < 0 || state >= Extension::NUM_STATES) {
1150 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1151 return false;
1154 return state == check_state;
1157 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1158 const std::string& id) const {
1159 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1162 bool ExtensionPrefs::IsExtensionDisabled(
1163 const std::string& id) const {
1164 return DoesExtensionHaveState(id, Extension::DISABLED);
1167 ExtensionIdList ExtensionPrefs::GetToolbarOrder() const {
1168 ExtensionIdList id_list_out;
1169 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1170 return id_list_out;
1173 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1174 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1177 void ExtensionPrefs::OnExtensionInstalled(
1178 const Extension* extension,
1179 Extension::State initial_state,
1180 const syncer::StringOrdinal& page_ordinal,
1181 int install_flags,
1182 const std::string& install_parameter) {
1183 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1184 base::DictionaryValue* extension_dict = update.Get();
1185 const base::Time install_time = time_provider_->GetCurrentTime();
1186 PopulateExtensionInfoPrefs(extension,
1187 install_time,
1188 initial_state,
1189 install_flags,
1190 install_parameter,
1191 extension_dict);
1193 bool requires_sort_ordinal = extension->RequiresSortOrdinal() &&
1194 (install_flags & kInstallFlagIsEphemeral) == 0;
1195 FinishExtensionInfoPrefs(extension->id(),
1196 install_time,
1197 requires_sort_ordinal,
1198 page_ordinal,
1199 extension_dict);
1202 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1203 const Manifest::Location& location,
1204 bool external_uninstall) {
1205 app_sorting_->ClearOrdinals(extension_id);
1207 // For external extensions, we save a preference reminding ourself not to try
1208 // and install the extension anymore (except when |external_uninstall| is
1209 // true, which signifies that the registry key was deleted or the pref file
1210 // no longer lists the extension).
1211 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1212 UpdateExtensionPref(extension_id, kPrefState,
1213 new base::FundamentalValue(
1214 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1215 extension_pref_value_map_->SetExtensionState(extension_id, false);
1216 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1217 observer_list_,
1218 OnExtensionStateChanged(extension_id, false));
1219 } else {
1220 DeleteExtensionPrefs(extension_id);
1224 void ExtensionPrefs::SetExtensionState(const std::string& extension_id,
1225 Extension::State state) {
1226 UpdateExtensionPref(extension_id, kPrefState,
1227 new base::FundamentalValue(state));
1228 bool enabled = (state == Extension::ENABLED);
1229 extension_pref_value_map_->SetExtensionState(extension_id, enabled);
1230 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1231 observer_list_,
1232 OnExtensionStateChanged(extension_id, enabled));
1235 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1236 BlacklistState state) {
1237 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1238 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1239 new base::FundamentalValue(state));
1242 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1243 const std::string& extension_id) const {
1244 if (IsExtensionBlacklisted(extension_id))
1245 return BLACKLISTED_MALWARE;
1246 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1247 int int_value = 0;
1248 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1249 return static_cast<BlacklistState>(int_value);
1251 return NOT_BLACKLISTED;
1254 std::string ExtensionPrefs::GetVersionString(
1255 const std::string& extension_id) const {
1256 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1257 if (!extension)
1258 return std::string();
1260 std::string version;
1261 extension->GetString(kPrefVersion, &version);
1263 return version;
1266 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1267 if (!Manifest::IsUnpackedLocation(extension->location())) {
1268 const base::DictionaryValue* extension_dict =
1269 GetExtensionPref(extension->id());
1270 if (!extension_dict)
1271 return;
1272 const base::DictionaryValue* old_manifest = NULL;
1273 bool update_required =
1274 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1275 !extension->manifest()->value()->Equals(old_manifest);
1276 if (update_required) {
1277 UpdateExtensionPref(extension->id(), kPrefManifest,
1278 extension->manifest()->value()->DeepCopy());
1283 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1284 const std::string& extension_id,
1285 const base::DictionaryValue* extension) const {
1286 int location_value;
1287 if (!extension->GetInteger(kPrefLocation, &location_value))
1288 return scoped_ptr<ExtensionInfo>();
1290 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1291 if (location == Manifest::COMPONENT) {
1292 // Component extensions are ignored. Component extensions may have data
1293 // saved in preferences, but they are already loaded at this point (by
1294 // ComponentLoader) and shouldn't be populated into the result of
1295 // GetInstalledExtensionsInfo, otherwise InstalledLoader would also want to
1296 // load them.
1297 return scoped_ptr<ExtensionInfo>();
1300 // Only the following extension types have data saved in the preferences.
1301 if (location != Manifest::INTERNAL &&
1302 !Manifest::IsUnpackedLocation(location) &&
1303 !Manifest::IsExternalLocation(location)) {
1304 NOTREACHED();
1305 return scoped_ptr<ExtensionInfo>();
1308 const base::DictionaryValue* manifest = NULL;
1309 if (!Manifest::IsUnpackedLocation(location) &&
1310 !extension->GetDictionary(kPrefManifest, &manifest)) {
1311 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1312 // Just a warning for now.
1315 base::FilePath::StringType path;
1316 if (!extension->GetString(kPrefPath, &path))
1317 return scoped_ptr<ExtensionInfo>();
1319 // Make path absolute. Most (but not all) extension types have relative paths.
1320 if (!base::FilePath(path).IsAbsolute())
1321 path = install_directory_.Append(path).value();
1323 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1324 manifest, extension_id, base::FilePath(path), location));
1327 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1328 const std::string& extension_id) const {
1329 const base::DictionaryValue* ext = NULL;
1330 const base::DictionaryValue* extensions =
1331 prefs_->GetDictionary(pref_names::kExtensions);
1332 if (!extensions ||
1333 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1334 return scoped_ptr<ExtensionInfo>();
1335 int state_value;
1336 if (ext->GetInteger(kPrefState, &state_value) &&
1337 state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1338 LOG(WARNING) << "External extension with id " << extension_id
1339 << " has been uninstalled by the user";
1340 return scoped_ptr<ExtensionInfo>();
1343 return GetInstalledInfoHelper(extension_id, ext);
1346 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1347 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1348 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1350 const base::DictionaryValue* extensions =
1351 prefs_->GetDictionary(pref_names::kExtensions);
1352 for (base::DictionaryValue::Iterator extension_id(*extensions);
1353 !extension_id.IsAtEnd(); extension_id.Advance()) {
1354 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1355 continue;
1357 scoped_ptr<ExtensionInfo> info =
1358 GetInstalledExtensionInfo(extension_id.key());
1359 if (info)
1360 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1363 return extensions_info.Pass();
1366 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1367 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1368 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1370 const base::DictionaryValue* extensions =
1371 prefs_->GetDictionary(pref_names::kExtensions);
1372 for (base::DictionaryValue::Iterator extension_id(*extensions);
1373 !extension_id.IsAtEnd(); extension_id.Advance()) {
1374 const base::DictionaryValue* ext = NULL;
1375 if (!crx_file::id_util::IdIsValid(extension_id.key()) ||
1376 !IsExternalExtensionUninstalled(extension_id.key()) ||
1377 !extension_id.value().GetAsDictionary(&ext))
1378 continue;
1380 scoped_ptr<ExtensionInfo> info =
1381 GetInstalledInfoHelper(extension_id.key(), ext);
1382 if (info)
1383 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1386 return extensions_info.Pass();
1389 void ExtensionPrefs::SetDelayedInstallInfo(
1390 const Extension* extension,
1391 Extension::State initial_state,
1392 int install_flags,
1393 DelayReason delay_reason,
1394 const syncer::StringOrdinal& page_ordinal,
1395 const std::string& install_parameter) {
1396 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1397 PopulateExtensionInfoPrefs(extension,
1398 time_provider_->GetCurrentTime(),
1399 initial_state,
1400 install_flags,
1401 install_parameter,
1402 extension_dict);
1404 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1405 // should not be in the final extension prefs. All entries here should have
1406 // a corresponding Remove() call in FinishDelayedInstallInfo().
1407 if (extension->RequiresSortOrdinal() &&
1408 (install_flags & kInstallFlagIsEphemeral) == 0) {
1409 extension_dict->SetString(
1410 kPrefSuggestedPageOrdinal,
1411 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1412 : std::string());
1414 extension_dict->SetInteger(kDelayedInstallReason,
1415 static_cast<int>(delay_reason));
1417 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1420 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1421 const std::string& extension_id) {
1422 if (!GetExtensionPref(extension_id))
1423 return false;
1424 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1425 bool result = update->Remove(kDelayedInstallInfo, NULL);
1426 return result;
1429 bool ExtensionPrefs::FinishDelayedInstallInfo(
1430 const std::string& extension_id) {
1431 CHECK(crx_file::id_util::IdIsValid(extension_id));
1432 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1433 base::DictionaryValue* extension_dict = update.Get();
1434 base::DictionaryValue* pending_install_dict = NULL;
1435 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1436 &pending_install_dict)) {
1437 return false;
1440 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1441 // Also do any other data cleanup that makes sense.
1442 std::string serialized_ordinal;
1443 syncer::StringOrdinal suggested_page_ordinal;
1444 bool needs_sort_ordinal = false;
1445 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1446 &serialized_ordinal)) {
1447 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1448 needs_sort_ordinal = true;
1449 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1451 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1453 const base::Time install_time = time_provider_->GetCurrentTime();
1454 pending_install_dict->Set(
1455 kPrefInstallTime,
1456 new base::StringValue(
1457 base::Int64ToString(install_time.ToInternalValue())));
1459 // Some extension pref values are written conditionally. If they are not
1460 // present in the delayed install data, they should be removed when the
1461 // delayed install is committed.
1462 extension_dict->Remove(kPrefEphemeralApp, NULL);
1464 // Commit the delayed install data.
1465 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1466 it.Advance()) {
1467 extension_dict->Set(it.key(), it.value().DeepCopy());
1469 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1470 suggested_page_ordinal, extension_dict);
1471 return true;
1474 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1475 const std::string& extension_id) const {
1476 const base::DictionaryValue* extension_prefs =
1477 GetExtensionPref(extension_id);
1478 if (!extension_prefs)
1479 return scoped_ptr<ExtensionInfo>();
1481 const base::DictionaryValue* ext = NULL;
1482 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1483 return scoped_ptr<ExtensionInfo>();
1485 return GetInstalledInfoHelper(extension_id, ext);
1488 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1489 const std::string& extension_id) const {
1490 const base::DictionaryValue* extension_prefs =
1491 GetExtensionPref(extension_id);
1492 if (!extension_prefs)
1493 return DELAY_REASON_NONE;
1495 const base::DictionaryValue* ext = NULL;
1496 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1497 return DELAY_REASON_NONE;
1499 int delay_reason;
1500 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1501 return DELAY_REASON_NONE;
1503 return static_cast<DelayReason>(delay_reason);
1506 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1507 GetAllDelayedInstallInfo() const {
1508 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1510 const base::DictionaryValue* extensions =
1511 prefs_->GetDictionary(pref_names::kExtensions);
1512 for (base::DictionaryValue::Iterator extension_id(*extensions);
1513 !extension_id.IsAtEnd(); extension_id.Advance()) {
1514 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1515 continue;
1517 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1518 if (info)
1519 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1522 return extensions_info.Pass();
1525 bool ExtensionPrefs::IsEphemeralApp(const std::string& extension_id) const {
1526 if (ReadPrefAsBooleanAndReturn(extension_id, kPrefEphemeralApp))
1527 return true;
1529 // Ephemerality was previously stored in the creation flags, so we must also
1530 // check it for backcompatibility.
1531 return (GetCreationFlags(extension_id) & Extension::IS_EPHEMERAL) != 0;
1534 void ExtensionPrefs::OnEphemeralAppPromoted(const std::string& extension_id) {
1535 DCHECK(IsEphemeralApp(extension_id));
1537 UpdateExtensionPref(extension_id, kPrefEphemeralApp, NULL);
1539 // Ephemerality was previously stored in the creation flags, so ensure the bit
1540 // is cleared.
1541 int creation_flags = Extension::NO_FLAGS;
1542 if (ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1543 if (creation_flags & Extension::IS_EPHEMERAL) {
1544 creation_flags &= ~static_cast<int>(Extension::IS_EPHEMERAL);
1545 UpdateExtensionPref(extension_id,
1546 kPrefCreationFlags,
1547 new base::FundamentalValue(creation_flags));
1552 bool ExtensionPrefs::WasAppDraggedByUser(
1553 const std::string& extension_id) const {
1554 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1557 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1558 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1559 new base::FundamentalValue(true));
1562 bool ExtensionPrefs::IsFromWebStore(
1563 const std::string& extension_id) const {
1564 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1565 bool result = false;
1566 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1567 return result;
1568 return false;
1571 bool ExtensionPrefs::IsFromBookmark(
1572 const std::string& extension_id) const {
1573 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1574 bool result = false;
1575 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1576 return result;
1577 return false;
1580 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1581 int creation_flags = Extension::NO_FLAGS;
1582 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1583 // Since kPrefCreationFlags was added later, it will be missing for
1584 // previously installed extensions.
1585 if (IsFromBookmark(extension_id))
1586 creation_flags |= Extension::FROM_BOOKMARK;
1587 if (IsFromWebStore(extension_id))
1588 creation_flags |= Extension::FROM_WEBSTORE;
1589 if (WasInstalledByDefault(extension_id))
1590 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1591 if (WasInstalledByOem(extension_id))
1592 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
1594 return creation_flags;
1597 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1598 const std::string& extension_id) const {
1599 int creation_flags = Extension::NO_FLAGS;
1600 const base::DictionaryValue* delayed_info = NULL;
1601 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1602 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1604 return creation_flags;
1607 bool ExtensionPrefs::WasInstalledByDefault(
1608 const std::string& extension_id) const {
1609 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1610 bool result = false;
1611 if (dictionary &&
1612 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1613 return result;
1614 return false;
1617 bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const {
1618 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1619 bool result = false;
1620 if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result))
1621 return result;
1622 return false;
1625 base::Time ExtensionPrefs::GetInstallTime(
1626 const std::string& extension_id) const {
1627 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1628 if (!extension) {
1629 NOTREACHED();
1630 return base::Time();
1632 std::string install_time_str;
1633 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1634 return base::Time();
1635 int64 install_time_i64 = 0;
1636 if (!base::StringToInt64(install_time_str, &install_time_i64))
1637 return base::Time();
1638 return base::Time::FromInternalValue(install_time_i64);
1641 bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const {
1642 bool do_not_sync;
1643 if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync))
1644 return false;
1646 return do_not_sync;
1649 base::Time ExtensionPrefs::GetLastLaunchTime(
1650 const std::string& extension_id) const {
1651 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1652 if (!extension)
1653 return base::Time();
1655 std::string launch_time_str;
1656 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1657 return base::Time();
1658 int64 launch_time_i64 = 0;
1659 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1660 return base::Time();
1661 return base::Time::FromInternalValue(launch_time_i64);
1664 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1665 const base::Time& time) {
1666 DCHECK(crx_file::id_util::IdIsValid(extension_id));
1667 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1668 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1671 void ExtensionPrefs::ClearLastLaunchTimes() {
1672 const base::DictionaryValue* dict =
1673 prefs_->GetDictionary(pref_names::kExtensions);
1674 if (!dict || dict->empty())
1675 return;
1677 // Collect all the keys to remove the last launched preference from.
1678 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
1679 base::DictionaryValue* update_dict = update.Get();
1680 for (base::DictionaryValue::Iterator i(*update_dict); !i.IsAtEnd();
1681 i.Advance()) {
1682 base::DictionaryValue* extension_dict = NULL;
1683 if (!update_dict->GetDictionary(i.key(), &extension_dict))
1684 continue;
1686 if (extension_dict->HasKey(kPrefLastLaunchTime))
1687 extension_dict->Remove(kPrefLastLaunchTime, NULL);
1691 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) const {
1692 CHECK(out);
1694 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1696 for (size_t i = 0; i < extensions_info->size(); ++i) {
1697 ExtensionInfo* info = extensions_info->at(i).get();
1698 out->push_back(info->extension_id);
1702 // static
1703 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1704 const PrefService* pref_service) {
1705 ExtensionIdList result;
1707 const base::DictionaryValue* extension_prefs = NULL;
1708 const base::Value* extension_prefs_value =
1709 pref_service->GetUserPrefValue(pref_names::kExtensions);
1710 if (!extension_prefs_value ||
1711 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1712 return result; // Empty set
1715 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1716 it.Advance()) {
1717 const base::DictionaryValue* ext = NULL;
1718 if (!it.value().GetAsDictionary(&ext)) {
1719 NOTREACHED() << "Invalid pref for extension " << it.key();
1720 continue;
1722 if (!IsBlacklistBitSet(ext))
1723 result.push_back(it.key());
1725 return result;
1728 void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) {
1729 observer_list_.AddObserver(observer);
1732 void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) {
1733 observer_list_.RemoveObserver(observer);
1736 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1737 // Fix old entries that did not get an installation time entry when they
1738 // were installed or don't have a preferences field.
1739 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1740 ext_id != extension_ids.end(); ++ext_id) {
1741 if (GetInstallTime(*ext_id) == base::Time()) {
1742 VLOG(1) << "Could not parse installation time of extension "
1743 << *ext_id << ". It was probably installed before setting "
1744 << kPrefInstallTime << " was introduced. Updating "
1745 << kPrefInstallTime << " to the current time.";
1746 const base::Time install_time = time_provider_->GetCurrentTime();
1747 UpdateExtensionPref(*ext_id,
1748 kPrefInstallTime,
1749 new base::StringValue(base::Int64ToString(
1750 install_time.ToInternalValue())));
1755 void ExtensionPrefs::InitPrefStore() {
1756 TRACE_EVENT0("browser,startup", "ExtensionPrefs::InitPrefStore")
1757 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefStoreTime");
1759 if (extensions_disabled_) {
1760 extension_pref_value_map_->NotifyInitializationCompleted();
1761 return;
1764 // When this is called, the PrefService is initialized and provides access
1765 // to the user preferences stored in a JSON file.
1766 ExtensionIdList extension_ids;
1768 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefGetExtensionsTime");
1769 GetExtensions(&extension_ids);
1771 // Create empty preferences dictionary for each extension (these dictionaries
1772 // are pruned when persisting the preferences to disk).
1773 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1774 ext_id != extension_ids.end(); ++ext_id) {
1775 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1776 // This creates an empty dictionary if none is stored.
1777 update.Get();
1780 FixMissingPrefs(extension_ids);
1781 MigratePermissions(extension_ids);
1782 MigrateDisableReasons(extension_ids);
1783 app_sorting_->Initialize(extension_ids);
1785 InitExtensionControlledPrefs(extension_pref_value_map_);
1787 extension_pref_value_map_->NotifyInitializationCompleted();
1790 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) const {
1791 bool has_incognito_pref_value = false;
1792 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1793 true,
1794 &has_incognito_pref_value);
1795 return has_incognito_pref_value;
1798 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1799 const std::string& extension_id) const {
1800 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1801 if (!extension_prefs)
1802 return NULL;
1804 const base::DictionaryValue* ext = NULL;
1805 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1806 return NULL;
1808 return ext;
1811 void ExtensionPrefs::SetGeometryCache(
1812 const std::string& extension_id,
1813 scoped_ptr<base::DictionaryValue> cache) {
1814 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1817 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() const {
1818 return prefs_->GetDictionary(kInstallSignature);
1821 void ExtensionPrefs::SetInstallSignature(
1822 const base::DictionaryValue* signature) {
1823 if (signature) {
1824 prefs_->Set(kInstallSignature, *signature);
1825 DVLOG(1) << "SetInstallSignature - saving";
1826 } else {
1827 DVLOG(1) << "SetInstallSignature - clearing";
1828 prefs_->ClearPref(kInstallSignature);
1832 std::string ExtensionPrefs::GetInstallParam(
1833 const std::string& extension_id) const {
1834 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1835 if (!extension) // Expected during unit testing.
1836 return std::string();
1837 std::string install_parameter;
1838 if (!extension->GetString(kPrefInstallParam, &install_parameter))
1839 return std::string();
1840 return install_parameter;
1843 void ExtensionPrefs::SetInstallParam(const std::string& extension_id,
1844 const std::string& install_parameter) {
1845 UpdateExtensionPref(extension_id,
1846 kPrefInstallParam,
1847 new base::StringValue(install_parameter));
1850 int ExtensionPrefs::GetCorruptedDisableCount() const {
1851 return prefs_->GetInteger(kCorruptedDisableCount);
1854 void ExtensionPrefs::IncrementCorruptedDisableCount() {
1855 int count = prefs_->GetInteger(kCorruptedDisableCount);
1856 prefs_->SetInteger(kCorruptedDisableCount, count + 1);
1859 bool ExtensionPrefs::NeedsSync(const std::string& extension_id) const {
1860 return ReadPrefAsBooleanAndReturn(extension_id, kPrefNeedsSync);
1863 void ExtensionPrefs::SetNeedsSync(const std::string& extension_id,
1864 bool needs_sync) {
1865 UpdateExtensionPref(extension_id, kPrefNeedsSync,
1866 needs_sync ? new base::FundamentalValue(true) : nullptr);
1869 ExtensionPrefs::ExtensionPrefs(
1870 PrefService* prefs,
1871 const base::FilePath& root_dir,
1872 ExtensionPrefValueMap* extension_pref_value_map,
1873 scoped_ptr<AppSorting> app_sorting,
1874 scoped_ptr<TimeProvider> time_provider,
1875 bool extensions_disabled,
1876 const std::vector<ExtensionPrefsObserver*>& early_observers)
1877 : prefs_(prefs),
1878 install_directory_(root_dir),
1879 extension_pref_value_map_(extension_pref_value_map),
1880 app_sorting_(app_sorting.Pass()),
1881 time_provider_(time_provider.Pass()),
1882 extensions_disabled_(extensions_disabled) {
1883 // TODO(mgiuca): Added these checks to try and diagnose
1884 // http://crbug.com/476648. Remove them after the investigation is concluded.
1885 CHECK(this);
1886 app_sorting_->SetExtensionScopedPrefs(this);
1887 app_sorting_->CheckExtensionScopedPrefs();
1888 MakePathsRelative();
1890 // Ensure that any early observers are watching before prefs are initialized.
1891 for (std::vector<ExtensionPrefsObserver*>::const_iterator iter =
1892 early_observers.begin();
1893 iter != early_observers.end();
1894 ++iter) {
1895 AddObserver(*iter);
1898 InitPrefStore();
1901 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1902 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1905 bool ExtensionPrefs::NeedsStorageGarbageCollection() const {
1906 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1909 // static
1910 void ExtensionPrefs::RegisterProfilePrefs(
1911 user_prefs::PrefRegistrySyncable* registry) {
1912 registry->RegisterDictionaryPref(pref_names::kExtensions);
1913 registry->RegisterListPref(pref_names::kToolbar,
1914 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1915 registry->RegisterIntegerPref(pref_names::kToolbarSize, -1);
1916 registry->RegisterDictionaryPref(kExtensionsBlacklistUpdate);
1917 registry->RegisterListPref(pref_names::kInstallAllowList);
1918 registry->RegisterListPref(pref_names::kInstallDenyList);
1919 registry->RegisterDictionaryPref(pref_names::kInstallForceList);
1920 registry->RegisterListPref(pref_names::kAllowedTypes);
1921 registry->RegisterBooleanPref(pref_names::kStorageGarbageCollect, false);
1922 registry->RegisterInt64Pref(pref_names::kLastUpdateCheck, 0);
1923 registry->RegisterInt64Pref(pref_names::kNextUpdateCheck, 0);
1924 registry->RegisterListPref(pref_names::kAllowedInstallSites);
1925 registry->RegisterStringPref(pref_names::kLastChromeVersion, std::string());
1926 registry->RegisterDictionaryPref(kInstallSignature);
1928 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist);
1929 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist);
1930 registry->RegisterBooleanPref(pref_names::kNativeMessagingUserLevelHosts,
1931 true);
1932 registry->RegisterIntegerPref(kCorruptedDisableCount, 0);
1934 #if !defined(OS_MACOSX)
1935 registry->RegisterBooleanPref(pref_names::kAppFullscreenAllowed, true);
1936 #endif
1939 template <class ExtensionIdContainer>
1940 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
1941 const char* pref,
1942 ExtensionIdContainer* id_container_out) const {
1943 DCHECK(id_container_out->empty());
1945 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
1946 const base::ListValue* user_pref_as_list;
1947 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
1948 return false;
1950 std::insert_iterator<ExtensionIdContainer> insert_iterator(
1951 *id_container_out, id_container_out->end());
1952 std::string extension_id;
1953 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
1954 value_it != user_pref_as_list->end(); ++value_it) {
1955 if (!(*value_it)->GetAsString(&extension_id)) {
1956 NOTREACHED();
1957 continue;
1959 insert_iterator = extension_id;
1961 return true;
1964 template <class ExtensionIdContainer>
1965 void ExtensionPrefs::SetExtensionPrefFromContainer(
1966 const char* pref,
1967 const ExtensionIdContainer& strings) {
1968 ListPrefUpdate update(prefs_, pref);
1969 base::ListValue* list_of_values = update.Get();
1970 list_of_values->Clear();
1971 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
1972 iter != strings.end(); ++iter) {
1973 list_of_values->Append(new base::StringValue(*iter));
1977 void ExtensionPrefs::PopulateExtensionInfoPrefs(
1978 const Extension* extension,
1979 const base::Time install_time,
1980 Extension::State initial_state,
1981 int install_flags,
1982 const std::string& install_parameter,
1983 base::DictionaryValue* extension_dict) const {
1984 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
1985 extension_dict->Set(kPrefLocation,
1986 new base::FundamentalValue(extension->location()));
1987 extension_dict->Set(kPrefCreationFlags,
1988 new base::FundamentalValue(extension->creation_flags()));
1989 extension_dict->Set(kPrefFromWebStore,
1990 new base::FundamentalValue(extension->from_webstore()));
1991 extension_dict->Set(kPrefFromBookmark,
1992 new base::FundamentalValue(extension->from_bookmark()));
1993 extension_dict->Set(
1994 kPrefWasInstalledByDefault,
1995 new base::FundamentalValue(extension->was_installed_by_default()));
1996 extension_dict->Set(
1997 kPrefWasInstalledByOem,
1998 new base::FundamentalValue(extension->was_installed_by_oem()));
1999 extension_dict->Set(kPrefInstallTime,
2000 new base::StringValue(
2001 base::Int64ToString(install_time.ToInternalValue())));
2002 if (install_flags & kInstallFlagIsBlacklistedForMalware)
2003 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
2005 if (install_flags & kInstallFlagIsEphemeral)
2006 extension_dict->Set(kPrefEphemeralApp, new base::FundamentalValue(true));
2007 else
2008 extension_dict->Remove(kPrefEphemeralApp, NULL);
2010 base::FilePath::StringType path = MakePathRelative(install_directory_,
2011 extension->path());
2012 extension_dict->Set(kPrefPath, new base::StringValue(path));
2013 if (!install_parameter.empty()) {
2014 extension_dict->Set(kPrefInstallParam,
2015 new base::StringValue(install_parameter));
2017 // We store prefs about LOAD extensions, but don't cache their manifest
2018 // since it may change on disk.
2019 if (!Manifest::IsUnpackedLocation(extension->location())) {
2020 extension_dict->Set(kPrefManifest,
2021 extension->manifest()->value()->DeepCopy());
2024 // Only writes kPrefDoNotSync when it is not the default.
2025 if (install_flags & kInstallFlagDoNotSync)
2026 extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true));
2027 else
2028 extension_dict->Remove(kPrefDoNotSync, NULL);
2031 void ExtensionPrefs::InitExtensionControlledPrefs(
2032 ExtensionPrefValueMap* value_map) {
2033 TRACE_EVENT0("browser,startup",
2034 "ExtensionPrefs::InitExtensionControlledPrefs")
2035 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitExtensionControlledPrefsTime");
2037 ExtensionIdList extension_ids;
2038 GetExtensions(&extension_ids);
2040 for (ExtensionIdList::iterator extension_id = extension_ids.begin();
2041 extension_id != extension_ids.end();
2042 ++extension_id) {
2043 base::Time install_time = GetInstallTime(*extension_id);
2044 bool is_enabled = !IsExtensionDisabled(*extension_id);
2045 bool is_incognito_enabled = IsIncognitoEnabled(*extension_id);
2046 value_map->RegisterExtension(
2047 *extension_id, install_time, is_enabled, is_incognito_enabled);
2049 FOR_EACH_OBSERVER(
2050 ExtensionPrefsObserver,
2051 observer_list_,
2052 OnExtensionRegistered(*extension_id, install_time, is_enabled));
2054 // Set regular extension controlled prefs.
2055 LoadExtensionControlledPrefs(
2056 this, value_map, *extension_id, kExtensionPrefsScopeRegular);
2057 // Set incognito extension controlled prefs.
2058 LoadExtensionControlledPrefs(this,
2059 value_map,
2060 *extension_id,
2061 kExtensionPrefsScopeIncognitoPersistent);
2062 // Set regular-only extension controlled prefs.
2063 LoadExtensionControlledPrefs(
2064 this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly);
2066 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
2067 observer_list_,
2068 OnExtensionPrefsLoaded(*extension_id, this));
2072 void ExtensionPrefs::FinishExtensionInfoPrefs(
2073 const std::string& extension_id,
2074 const base::Time install_time,
2075 bool needs_sort_ordinal,
2076 const syncer::StringOrdinal& suggested_page_ordinal,
2077 base::DictionaryValue* extension_dict) {
2078 // Reinitializes various preferences with empty dictionaries.
2079 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
2080 extension_dict->Set(pref_names::kPrefPreferences,
2081 new base::DictionaryValue);
2084 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
2085 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
2086 new base::DictionaryValue);
2089 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
2090 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
2091 new base::DictionaryValue);
2094 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
2095 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
2097 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
2098 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
2099 new base::ListValue);
2102 // If this point has been reached, any pending installs should be considered
2103 // out of date.
2104 extension_dict->Remove(kDelayedInstallInfo, NULL);
2106 // Clear state that may be registered from a previous install.
2107 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
2109 // FYI, all code below here races on sudden shutdown because |extension_dict|,
2110 // |app_sorting_|, |extension_pref_value_map_|, and (potentially) observers
2111 // are updated non-transactionally. This is probably not fixable without
2112 // nested transactional updates to pref dictionaries.
2113 if (needs_sort_ordinal)
2114 app_sorting_->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
2116 bool is_enabled = false;
2117 int initial_state;
2118 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
2119 is_enabled = initial_state == Extension::ENABLED;
2121 bool is_incognito_enabled = IsIncognitoEnabled(extension_id);
2123 extension_pref_value_map_->RegisterExtension(
2124 extension_id, install_time, is_enabled, is_incognito_enabled);
2126 FOR_EACH_OBSERVER(
2127 ExtensionPrefsObserver,
2128 observer_list_,
2129 OnExtensionRegistered(extension_id, install_time, is_enabled));
2132 } // namespace extensions