Reland the ULONG -> SIZE_T change from 317177
[chromium-blink-merge.git] / extensions / browser / extension_prefs.cc
blobdc91d2ebd70c036a5c36be3264ab21c34c07574a
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/browser/extension_prefs.h"
7 #include <iterator>
9 #include "base/command_line.h"
10 #include "base/prefs/pref_notifier.h"
11 #include "base/prefs/pref_service.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_util.h"
14 #include "base/value_conversions.h"
15 #include "components/crx_file/id_util.h"
16 #include "components/pref_registry/pref_registry_syncable.h"
17 #include "extensions/browser/app_sorting.h"
18 #include "extensions/browser/event_router.h"
19 #include "extensions/browser/extension_pref_store.h"
20 #include "extensions/browser/extension_prefs_factory.h"
21 #include "extensions/browser/extension_prefs_observer.h"
22 #include "extensions/browser/install_flag.h"
23 #include "extensions/browser/pref_names.h"
24 #include "extensions/common/feature_switch.h"
25 #include "extensions/common/manifest.h"
26 #include "extensions/common/permissions/permission_set.h"
27 #include "extensions/common/permissions/permissions_info.h"
28 #include "extensions/common/url_pattern.h"
29 #include "extensions/common/user_script.h"
30 #include "ui/base/l10n/l10n_util.h"
32 using base::Value;
33 using base::DictionaryValue;
34 using base::ListValue;
36 namespace extensions {
38 namespace {
40 // Additional preferences keys, which are not needed by external clients.
42 // True if this extension is running. Note this preference stops getting updated
43 // during Chrome shutdown (and won't be updated on a browser crash) and so can
44 // be used at startup to determine whether the extension was running when Chrome
45 // was last terminated.
46 const char kPrefRunning[] = "running";
48 // Whether this extension had windows when it was last running.
49 const char kIsActive[] = "is_active";
51 // Where an extension was installed from. (see Manifest::Location)
52 const char kPrefLocation[] = "location";
54 // Enabled, disabled, killed, etc. (see Extension::State)
55 const char kPrefState[] = "state";
57 // The path to the current version's manifest file.
58 const char kPrefPath[] = "path";
60 // The dictionary containing the extension's manifest.
61 const char kPrefManifest[] = "manifest";
63 // The version number.
64 const char kPrefVersion[] = "manifest.version";
66 // Indicates whether an extension is blacklisted.
67 const char kPrefBlacklist[] = "blacklist";
69 // If extension is greylisted.
70 const char kPrefBlacklistState[] = "blacklist_state";
72 // The count of how many times we prompted the user to acknowledge an
73 // extension.
74 const char kPrefAcknowledgePromptCount[] = "ack_prompt_count";
76 // Indicates whether the user has acknowledged various types of extensions.
77 const char kPrefExternalAcknowledged[] = "ack_external";
78 const char kPrefBlacklistAcknowledged[] = "ack_blacklist";
80 // Indicates whether the external extension was installed during the first
81 // run of this profile.
82 const char kPrefExternalInstallFirstRun[] = "external_first_run";
84 // Indicates whether to show an install warning when the user enables.
85 const char kExtensionDidEscalatePermissions[] = "install_warning_on_enable";
87 // DO NOT USE, use kPrefDisableReasons instead.
88 // Indicates whether the extension was updated while it was disabled.
89 const char kDeprecatedPrefDisableReason[] = "disable_reason";
91 // A bitmask of all the reasons an extension is disabled.
92 const char kPrefDisableReasons[] = "disable_reasons";
94 // The key for a serialized Time value indicating the start of the day (from the
95 // server's perspective) an extension last included a "ping" parameter during
96 // its update check.
97 const char kLastPingDay[] = "lastpingday";
99 // Similar to kLastPingDay, but for "active" instead of "rollcall" pings.
100 const char kLastActivePingDay[] = "last_active_pingday";
102 // A bit we use to keep track of whether we need to do an "active" ping.
103 const char kActiveBit[] = "active_bit";
105 // Path for settings specific to blacklist update.
106 const char kExtensionsBlacklistUpdate[] = "extensions.blacklistupdate";
108 // Path for the delayed install info dictionary preference. The actual string
109 // value is a legacy artifact for when delayed installs only pertained to
110 // updates that were waiting for idle.
111 const char kDelayedInstallInfo[] = "idle_install_info";
113 // Reason why the extension's install was delayed.
114 const char kDelayedInstallReason[] = "delay_install_reason";
116 // Path for the suggested page ordinal of a delayed extension install.
117 const char kPrefSuggestedPageOrdinal[] = "suggested_page_ordinal";
119 // A preference that, if true, will allow this extension to run in incognito
120 // mode.
121 const char kPrefIncognitoEnabled[] = "incognito";
123 // A preference to control whether an extension is allowed to inject script in
124 // pages with file URLs.
125 const char kPrefAllowFileAccess[] = "newAllowFileAccess";
126 // TODO(jstritar): As part of fixing http://crbug.com/91577, we revoked all
127 // extension file access by renaming the pref. We should eventually clean up
128 // the old flag and possibly go back to that name.
129 // const char kPrefAllowFileAccessOld[] = "allowFileAccess";
131 // A preference specifying if the user dragged the app on the NTP.
132 const char kPrefUserDraggedApp[] = "user_dragged_app_ntp";
134 // Preferences that hold which permissions the user has granted the extension.
135 // We explicitly keep track of these so that extensions can contain unknown
136 // permissions, for backwards compatibility reasons, and we can still prompt
137 // the user to accept them once recognized. We store the active permission
138 // permissions because they may differ from those defined in the manifest.
139 const char kPrefActivePermissions[] = "active_permissions";
140 const char kPrefGrantedPermissions[] = "granted_permissions";
142 // The preference names for PermissionSet values.
143 const char kPrefAPIs[] = "api";
144 const char kPrefManifestPermissions[] = "manifest_permissions";
145 const char kPrefExplicitHosts[] = "explicit_host";
146 const char kPrefScriptableHosts[] = "scriptable_host";
148 // The preference names for the old granted permissions scheme.
149 const char kPrefOldGrantedFullAccess[] = "granted_permissions.full";
150 const char kPrefOldGrantedHosts[] = "granted_permissions.host";
151 const char kPrefOldGrantedAPIs[] = "granted_permissions.api";
153 // A preference that indicates when an extension was installed.
154 const char kPrefInstallTime[] = "install_time";
156 // A preference which saves the creation flags for extensions.
157 const char kPrefCreationFlags[] = "creation_flags";
159 // A preference that indicates whether the extension was installed from the
160 // Chrome Web Store.
161 const char kPrefFromWebStore[] = "from_webstore";
163 // A preference that indicates whether the extension was installed from a
164 // mock App created from a bookmark.
165 const char kPrefFromBookmark[] = "from_bookmark";
167 // A preference that indicates whether the extension was installed as a
168 // default app.
169 const char kPrefWasInstalledByDefault[] = "was_installed_by_default";
171 // A preference that indicates whether the extension was installed as an
172 // OEM app.
173 const char kPrefWasInstalledByOem[] = "was_installed_by_oem";
175 // Key for Geometry Cache preference.
176 const char kPrefGeometryCache[] = "geometry_cache";
178 // A preference that indicates when an extension is last launched.
179 const char kPrefLastLaunchTime[] = "last_launch_time";
181 // A preference indicating whether the extension is an ephemeral app.
182 const char kPrefEphemeralApp[] = "ephemeral_app";
184 // Am installation parameter bundled with an extension.
185 const char kPrefInstallParam[] = "install_parameter";
187 // A list of installed ids and a signature.
188 const char kInstallSignature[] = "extensions.install_signature";
190 // A boolean preference that indicates whether the extension should not be
191 // synced. Default value is false.
192 const char kPrefDoNotSync[] = "do_not_sync";
194 const char kCorruptedDisableCount[] = "extensions.corrupted_disable_count";
196 // Provider of write access to a dictionary storing extension prefs.
197 class ScopedExtensionPrefUpdate : public DictionaryPrefUpdate {
198 public:
199 ScopedExtensionPrefUpdate(PrefService* service,
200 const std::string& extension_id) :
201 DictionaryPrefUpdate(service, pref_names::kExtensions),
202 extension_id_(extension_id) {}
204 ~ScopedExtensionPrefUpdate() override {}
206 // DictionaryPrefUpdate overrides:
207 base::DictionaryValue* Get() override {
208 base::DictionaryValue* dict = DictionaryPrefUpdate::Get();
209 base::DictionaryValue* extension = NULL;
210 if (!dict->GetDictionary(extension_id_, &extension)) {
211 // Extension pref does not exist, create it.
212 extension = new base::DictionaryValue();
213 dict->SetWithoutPathExpansion(extension_id_, extension);
215 return extension;
218 private:
219 const std::string extension_id_;
221 DISALLOW_COPY_AND_ASSIGN(ScopedExtensionPrefUpdate);
224 std::string JoinPrefs(const std::string& parent, const char* child) {
225 return parent + "." + child;
228 // Checks if kPrefBlacklist is set to true in the base::DictionaryValue.
229 // Return false if the value is false or kPrefBlacklist does not exist.
230 // This is used to decide if an extension is blacklisted.
231 bool IsBlacklistBitSet(const base::DictionaryValue* ext) {
232 bool bool_value;
233 return ext->GetBoolean(kPrefBlacklist, &bool_value) && bool_value;
236 void LoadExtensionControlledPrefs(ExtensionPrefs* prefs,
237 ExtensionPrefValueMap* value_map,
238 const std::string& extension_id,
239 ExtensionPrefsScope scope) {
240 std::string scope_string;
241 if (!pref_names::ScopeToPrefName(scope, &scope_string))
242 return;
243 std::string key = extension_id + "." + scope_string;
245 const base::DictionaryValue* source_dict =
246 prefs->pref_service()->GetDictionary(pref_names::kExtensions);
247 const base::DictionaryValue* preferences = NULL;
248 if (!source_dict->GetDictionary(key, &preferences))
249 return;
251 for (base::DictionaryValue::Iterator iter(*preferences); !iter.IsAtEnd();
252 iter.Advance()) {
253 value_map->SetExtensionPref(
254 extension_id, iter.key(), scope, iter.value().DeepCopy());
258 } // namespace
261 // TimeProvider
264 ExtensionPrefs::TimeProvider::TimeProvider() {
267 ExtensionPrefs::TimeProvider::~TimeProvider() {
270 base::Time ExtensionPrefs::TimeProvider::GetCurrentTime() const {
271 return base::Time::Now();
275 // ScopedUpdate
277 template <typename T, base::Value::Type type_enum_value>
278 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::ScopedUpdate(
279 ExtensionPrefs* prefs,
280 const std::string& extension_id,
281 const std::string& key)
282 : update_(prefs->pref_service(), pref_names::kExtensions),
283 extension_id_(extension_id),
284 key_(key) {
285 DCHECK(crx_file::id_util::IdIsValid(extension_id_));
288 template <typename T, base::Value::Type type_enum_value>
289 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::~ScopedUpdate() {
292 template <typename T, base::Value::Type type_enum_value>
293 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Get() {
294 base::DictionaryValue* dict = update_.Get();
295 base::DictionaryValue* extension = NULL;
296 base::Value* key_value = NULL;
297 if (!dict->GetDictionary(extension_id_, &extension) ||
298 !extension->Get(key_, &key_value)) {
299 return NULL;
301 return key_value->GetType() == type_enum_value ?
302 static_cast<T*>(key_value) :
303 NULL;
306 template <typename T, base::Value::Type type_enum_value>
307 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Create() {
308 base::DictionaryValue* dict = update_.Get();
309 base::DictionaryValue* extension = NULL;
310 base::Value* key_value = NULL;
311 T* value_as_t = NULL;
312 if (!dict->GetDictionary(extension_id_, &extension)) {
313 extension = new base::DictionaryValue;
314 dict->SetWithoutPathExpansion(extension_id_, extension);
316 if (!extension->Get(key_, &key_value)) {
317 value_as_t = new T;
318 extension->SetWithoutPathExpansion(key_, value_as_t);
319 } else {
320 CHECK(key_value->GetType() == type_enum_value);
321 value_as_t = static_cast<T*>(key_value);
323 return value_as_t;
326 // Explicit instantiations for Dictionary and List value types.
327 template class ExtensionPrefs::ScopedUpdate<base::DictionaryValue,
328 base::Value::TYPE_DICTIONARY>;
329 template class ExtensionPrefs::ScopedUpdate<base::ListValue,
330 base::Value::TYPE_LIST>;
333 // ExtensionPrefs
336 // static
337 ExtensionPrefs* ExtensionPrefs::Create(
338 PrefService* prefs,
339 const base::FilePath& root_dir,
340 ExtensionPrefValueMap* extension_pref_value_map,
341 scoped_ptr<AppSorting> app_sorting,
342 bool extensions_disabled,
343 const std::vector<ExtensionPrefsObserver*>& early_observers) {
344 return ExtensionPrefs::Create(prefs,
345 root_dir,
346 extension_pref_value_map,
347 app_sorting.Pass(),
348 extensions_disabled,
349 early_observers,
350 make_scoped_ptr(new TimeProvider()));
353 // static
354 ExtensionPrefs* ExtensionPrefs::Create(
355 PrefService* pref_service,
356 const base::FilePath& root_dir,
357 ExtensionPrefValueMap* extension_pref_value_map,
358 scoped_ptr<AppSorting> app_sorting,
359 bool extensions_disabled,
360 const std::vector<ExtensionPrefsObserver*>& early_observers,
361 scoped_ptr<TimeProvider> time_provider) {
362 return new ExtensionPrefs(pref_service,
363 root_dir,
364 extension_pref_value_map,
365 app_sorting.Pass(),
366 time_provider.Pass(),
367 extensions_disabled,
368 early_observers);
371 ExtensionPrefs::~ExtensionPrefs() {
374 // static
375 ExtensionPrefs* ExtensionPrefs::Get(content::BrowserContext* context) {
376 return ExtensionPrefsFactory::GetInstance()->GetForBrowserContext(context);
379 static base::FilePath::StringType MakePathRelative(const base::FilePath& parent,
380 const base::FilePath& child) {
381 if (!parent.IsParent(child))
382 return child.value();
384 base::FilePath::StringType retval = child.value().substr(
385 parent.value().length());
386 if (base::FilePath::IsSeparator(retval[0]))
387 return retval.substr(1);
388 else
389 return retval;
392 void ExtensionPrefs::MakePathsRelative() {
393 const base::DictionaryValue* dict =
394 prefs_->GetDictionary(pref_names::kExtensions);
395 if (!dict || dict->empty())
396 return;
398 // Collect all extensions ids with absolute paths in |absolute_keys|.
399 std::set<std::string> absolute_keys;
400 for (base::DictionaryValue::Iterator i(*dict); !i.IsAtEnd(); i.Advance()) {
401 const base::DictionaryValue* extension_dict = NULL;
402 if (!i.value().GetAsDictionary(&extension_dict))
403 continue;
404 int location_value;
405 if (extension_dict->GetInteger(kPrefLocation, &location_value) &&
406 Manifest::IsUnpackedLocation(
407 static_cast<Manifest::Location>(location_value))) {
408 // Unpacked extensions can have absolute paths.
409 continue;
411 base::FilePath::StringType path_string;
412 if (!extension_dict->GetString(kPrefPath, &path_string))
413 continue;
414 base::FilePath path(path_string);
415 if (path.IsAbsolute())
416 absolute_keys.insert(i.key());
418 if (absolute_keys.empty())
419 return;
421 // Fix these paths.
422 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
423 base::DictionaryValue* update_dict = update.Get();
424 for (std::set<std::string>::iterator i = absolute_keys.begin();
425 i != absolute_keys.end(); ++i) {
426 base::DictionaryValue* extension_dict = NULL;
427 if (!update_dict->GetDictionaryWithoutPathExpansion(*i, &extension_dict)) {
428 NOTREACHED() << "Control should never reach here for extension " << *i;
429 continue;
431 base::FilePath::StringType path_string;
432 extension_dict->GetString(kPrefPath, &path_string);
433 base::FilePath path(path_string);
434 extension_dict->SetString(kPrefPath,
435 MakePathRelative(install_directory_, path));
439 const base::DictionaryValue* ExtensionPrefs::GetExtensionPref(
440 const std::string& extension_id) const {
441 const base::DictionaryValue* extensions =
442 prefs_->GetDictionary(pref_names::kExtensions);
443 const base::DictionaryValue* extension_dict = NULL;
444 if (!extensions ||
445 !extensions->GetDictionary(extension_id, &extension_dict)) {
446 return NULL;
448 return extension_dict;
451 void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id,
452 const std::string& key,
453 base::Value* data_value) {
454 if (!crx_file::id_util::IdIsValid(extension_id)) {
455 NOTREACHED() << "Invalid extension_id " << extension_id;
456 return;
458 ScopedExtensionPrefUpdate update(prefs_, extension_id);
459 if (data_value)
460 update->Set(key, data_value);
461 else
462 update->Remove(key, NULL);
465 void ExtensionPrefs::DeleteExtensionPrefs(const std::string& extension_id) {
466 extension_pref_value_map_->UnregisterExtension(extension_id);
467 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
468 observer_list_,
469 OnExtensionPrefsDeleted(extension_id));
470 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
471 base::DictionaryValue* dict = update.Get();
472 dict->Remove(extension_id, NULL);
475 bool ExtensionPrefs::ReadPrefAsBoolean(const std::string& extension_id,
476 const std::string& pref_key,
477 bool* out_value) const {
478 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
479 if (!ext || !ext->GetBoolean(pref_key, out_value))
480 return false;
482 return true;
485 bool ExtensionPrefs::ReadPrefAsInteger(const std::string& extension_id,
486 const std::string& pref_key,
487 int* out_value) const {
488 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
489 if (!ext || !ext->GetInteger(pref_key, out_value))
490 return false;
492 return true;
495 bool ExtensionPrefs::ReadPrefAsString(const std::string& extension_id,
496 const std::string& pref_key,
497 std::string* out_value) const {
498 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
499 if (!ext || !ext->GetString(pref_key, out_value))
500 return false;
502 return true;
505 bool ExtensionPrefs::ReadPrefAsList(const std::string& extension_id,
506 const std::string& pref_key,
507 const base::ListValue** out_value) const {
508 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
509 const base::ListValue* out = NULL;
510 if (!ext || !ext->GetList(pref_key, &out))
511 return false;
512 if (out_value)
513 *out_value = out;
515 return true;
518 bool ExtensionPrefs::ReadPrefAsDictionary(
519 const std::string& extension_id,
520 const std::string& pref_key,
521 const base::DictionaryValue** out_value) const {
522 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
523 const base::DictionaryValue* out = NULL;
524 if (!ext || !ext->GetDictionary(pref_key, &out))
525 return false;
526 if (out_value)
527 *out_value = out;
529 return true;
532 bool ExtensionPrefs::HasPrefForExtension(
533 const std::string& extension_id) const {
534 return GetExtensionPref(extension_id) != NULL;
537 bool ExtensionPrefs::ReadPrefAsURLPatternSet(const std::string& extension_id,
538 const std::string& pref_key,
539 URLPatternSet* result,
540 int valid_schemes) {
541 const base::ListValue* value = NULL;
542 if (!ReadPrefAsList(extension_id, pref_key, &value))
543 return false;
545 bool allow_file_access = AllowFileAccess(extension_id);
546 return result->Populate(*value, valid_schemes, allow_file_access, NULL);
549 void ExtensionPrefs::SetExtensionPrefURLPatternSet(
550 const std::string& extension_id,
551 const std::string& pref_key,
552 const URLPatternSet& new_value) {
553 UpdateExtensionPref(extension_id, pref_key, new_value.ToValue().release());
556 bool ExtensionPrefs::ReadPrefAsBooleanAndReturn(
557 const std::string& extension_id,
558 const std::string& pref_key) const {
559 bool out_value = false;
560 return ReadPrefAsBoolean(extension_id, pref_key, &out_value) && out_value;
563 PermissionSet* ExtensionPrefs::ReadPrefAsPermissionSet(
564 const std::string& extension_id,
565 const std::string& pref_key) {
566 if (!GetExtensionPref(extension_id))
567 return NULL;
569 // Retrieve the API permissions. Please refer SetExtensionPrefPermissionSet()
570 // for api_values format.
571 APIPermissionSet apis;
572 const base::ListValue* api_values = NULL;
573 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
574 if (ReadPrefAsList(extension_id, api_pref, &api_values)) {
575 APIPermissionSet::ParseFromJSON(api_values,
576 APIPermissionSet::kAllowInternalPermissions,
577 &apis, NULL, NULL);
580 // Retrieve the Manifest Keys permissions. Please refer to
581 // |SetExtensionPrefPermissionSet| for manifest_permissions_values format.
582 ManifestPermissionSet manifest_permissions;
583 const base::ListValue* manifest_permissions_values = NULL;
584 std::string manifest_permission_pref =
585 JoinPrefs(pref_key, kPrefManifestPermissions);
586 if (ReadPrefAsList(extension_id, manifest_permission_pref,
587 &manifest_permissions_values)) {
588 ManifestPermissionSet::ParseFromJSON(
589 manifest_permissions_values, &manifest_permissions, NULL, NULL);
592 // Retrieve the explicit host permissions.
593 URLPatternSet explicit_hosts;
594 ReadPrefAsURLPatternSet(
595 extension_id, JoinPrefs(pref_key, kPrefExplicitHosts),
596 &explicit_hosts, Extension::kValidHostPermissionSchemes);
598 // Retrieve the scriptable host permissions.
599 URLPatternSet scriptable_hosts;
600 ReadPrefAsURLPatternSet(
601 extension_id, JoinPrefs(pref_key, kPrefScriptableHosts),
602 &scriptable_hosts, UserScript::ValidUserScriptSchemes());
604 return new PermissionSet(
605 apis, manifest_permissions, explicit_hosts, scriptable_hosts);
608 // Set the API or Manifest permissions.
609 // The format of api_values is:
610 // [ "permission_name1", // permissions do not support detail.
611 // "permission_name2",
612 // {"permission_name3": value },
613 // // permission supports detail, permission detail will be stored in value.
614 // ...
615 // ]
616 template<typename T>
617 static base::ListValue* CreatePermissionList(const T& permissions) {
618 base::ListValue* values = new base::ListValue();
619 for (typename T::const_iterator i = permissions.begin();
620 i != permissions.end(); ++i) {
621 scoped_ptr<base::Value> detail(i->ToValue());
622 if (detail) {
623 base::DictionaryValue* tmp = new base::DictionaryValue();
624 tmp->Set(i->name(), detail.release());
625 values->Append(tmp);
626 } else {
627 values->Append(new base::StringValue(i->name()));
630 return values;
633 void ExtensionPrefs::SetExtensionPrefPermissionSet(
634 const std::string& extension_id,
635 const std::string& pref_key,
636 const PermissionSet* new_value) {
637 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
638 base::ListValue* api_values = CreatePermissionList(new_value->apis());
639 UpdateExtensionPref(extension_id, api_pref, api_values);
641 std::string manifest_permissions_pref =
642 JoinPrefs(pref_key, kPrefManifestPermissions);
643 base::ListValue* manifest_permissions_values = CreatePermissionList(
644 new_value->manifest_permissions());
645 UpdateExtensionPref(extension_id,
646 manifest_permissions_pref,
647 manifest_permissions_values);
649 // Set the explicit host permissions.
650 if (!new_value->explicit_hosts().is_empty()) {
651 SetExtensionPrefURLPatternSet(extension_id,
652 JoinPrefs(pref_key, kPrefExplicitHosts),
653 new_value->explicit_hosts());
656 // Set the scriptable host permissions.
657 if (!new_value->scriptable_hosts().is_empty()) {
658 SetExtensionPrefURLPatternSet(extension_id,
659 JoinPrefs(pref_key, kPrefScriptableHosts),
660 new_value->scriptable_hosts());
664 int ExtensionPrefs::IncrementAcknowledgePromptCount(
665 const std::string& extension_id) {
666 int count = 0;
667 ReadPrefAsInteger(extension_id, kPrefAcknowledgePromptCount, &count);
668 ++count;
669 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount,
670 new base::FundamentalValue(count));
671 return count;
674 bool ExtensionPrefs::IsExternalExtensionAcknowledged(
675 const std::string& extension_id) {
676 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalAcknowledged);
679 void ExtensionPrefs::AcknowledgeExternalExtension(
680 const std::string& extension_id) {
681 DCHECK(crx_file::id_util::IdIsValid(extension_id));
682 UpdateExtensionPref(extension_id, kPrefExternalAcknowledged,
683 new base::FundamentalValue(true));
684 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
687 bool ExtensionPrefs::IsBlacklistedExtensionAcknowledged(
688 const std::string& extension_id) {
689 return ReadPrefAsBooleanAndReturn(extension_id, kPrefBlacklistAcknowledged);
692 void ExtensionPrefs::AcknowledgeBlacklistedExtension(
693 const std::string& extension_id) {
694 DCHECK(crx_file::id_util::IdIsValid(extension_id));
695 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged,
696 new base::FundamentalValue(true));
697 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
700 bool ExtensionPrefs::IsExternalInstallFirstRun(
701 const std::string& extension_id) {
702 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalInstallFirstRun);
705 void ExtensionPrefs::SetExternalInstallFirstRun(
706 const std::string& extension_id) {
707 DCHECK(crx_file::id_util::IdIsValid(extension_id));
708 UpdateExtensionPref(extension_id, kPrefExternalInstallFirstRun,
709 new base::FundamentalValue(true));
712 bool ExtensionPrefs::SetAlertSystemFirstRun() {
713 if (prefs_->GetBoolean(pref_names::kAlertsInitialized)) {
714 return true;
716 prefs_->SetBoolean(pref_names::kAlertsInitialized, true);
717 return false;
720 bool ExtensionPrefs::DidExtensionEscalatePermissions(
721 const std::string& extension_id) {
722 return ReadPrefAsBooleanAndReturn(extension_id,
723 kExtensionDidEscalatePermissions);
726 void ExtensionPrefs::SetDidExtensionEscalatePermissions(
727 const Extension* extension, bool did_escalate) {
728 UpdateExtensionPref(extension->id(), kExtensionDidEscalatePermissions,
729 new base::FundamentalValue(did_escalate));
732 int ExtensionPrefs::GetDisableReasons(const std::string& extension_id) const {
733 int value = -1;
734 if (ReadPrefAsInteger(extension_id, kPrefDisableReasons, &value) &&
735 value >= 0) {
736 return value;
738 return Extension::DISABLE_NONE;
741 bool ExtensionPrefs::HasDisableReason(
742 const std::string& extension_id,
743 Extension::DisableReason disable_reason) const {
744 return (GetDisableReasons(extension_id) & disable_reason) != 0;
747 void ExtensionPrefs::AddDisableReason(const std::string& extension_id,
748 Extension::DisableReason disable_reason) {
749 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_ADD);
752 void ExtensionPrefs::AddDisableReasons(const std::string& extension_id,
753 int disable_reasons) {
754 ModifyDisableReasons(extension_id, disable_reasons, DISABLE_REASON_ADD);
757 void ExtensionPrefs::RemoveDisableReason(
758 const std::string& extension_id,
759 Extension::DisableReason disable_reason) {
760 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_REMOVE);
763 void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) {
764 ModifyDisableReasons(extension_id, Extension::DISABLE_NONE,
765 DISABLE_REASON_CLEAR);
768 void ExtensionPrefs::ModifyDisableReasons(const std::string& extension_id,
769 int reasons,
770 DisableReasonChange change) {
771 int old_value = GetDisableReasons(extension_id);
772 int new_value = old_value;
773 switch (change) {
774 case DISABLE_REASON_ADD:
775 new_value |= reasons;
776 break;
777 case DISABLE_REASON_REMOVE:
778 new_value &= ~reasons;
779 break;
780 case DISABLE_REASON_CLEAR:
781 new_value = Extension::DISABLE_NONE;
782 break;
785 if (old_value == new_value) // no change, return.
786 return;
788 if (new_value == Extension::DISABLE_NONE) {
789 UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
790 } else {
791 UpdateExtensionPref(extension_id,
792 kPrefDisableReasons,
793 new base::FundamentalValue(new_value));
796 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
797 observer_list_,
798 OnExtensionDisableReasonsChanged(extension_id, new_value));
801 std::set<std::string> ExtensionPrefs::GetBlacklistedExtensions() {
802 std::set<std::string> ids;
804 const base::DictionaryValue* extensions =
805 prefs_->GetDictionary(pref_names::kExtensions);
806 if (!extensions)
807 return ids;
809 for (base::DictionaryValue::Iterator it(*extensions);
810 !it.IsAtEnd(); it.Advance()) {
811 if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) {
812 NOTREACHED() << "Invalid pref for extension " << it.key();
813 continue;
815 if (IsBlacklistBitSet(
816 static_cast<const base::DictionaryValue*>(&it.value()))) {
817 ids.insert(it.key());
821 return ids;
824 void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id,
825 bool is_blacklisted) {
826 bool currently_blacklisted = IsExtensionBlacklisted(extension_id);
827 if (is_blacklisted == currently_blacklisted)
828 return;
830 // Always make sure the "acknowledged" bit is cleared since the blacklist bit
831 // is changing.
832 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL);
834 if (is_blacklisted) {
835 UpdateExtensionPref(extension_id,
836 kPrefBlacklist,
837 new base::FundamentalValue(true));
838 } else {
839 UpdateExtensionPref(extension_id, kPrefBlacklist, NULL);
840 const base::DictionaryValue* dict = GetExtensionPref(extension_id);
841 if (dict && dict->empty())
842 DeleteExtensionPrefs(extension_id);
846 bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const {
847 const base::DictionaryValue* ext_prefs = GetExtensionPref(id);
848 return ext_prefs && IsBlacklistBitSet(ext_prefs);
851 namespace {
853 // Serializes a 64bit integer as a string value.
854 void SaveInt64(base::DictionaryValue* dictionary,
855 const char* key,
856 const int64 value) {
857 if (!dictionary)
858 return;
860 std::string string_value = base::Int64ToString(value);
861 dictionary->SetString(key, string_value);
864 // Deserializes a 64bit integer stored as a string value.
865 bool ReadInt64(const base::DictionaryValue* dictionary,
866 const char* key,
867 int64* value) {
868 if (!dictionary)
869 return false;
871 std::string string_value;
872 if (!dictionary->GetString(key, &string_value))
873 return false;
875 return base::StringToInt64(string_value, value);
878 // Serializes |time| as a string value mapped to |key| in |dictionary|.
879 void SaveTime(base::DictionaryValue* dictionary,
880 const char* key,
881 const base::Time& time) {
882 SaveInt64(dictionary, key, time.ToInternalValue());
885 // The opposite of SaveTime. If |key| is not found, this returns an empty Time
886 // (is_null() will return true).
887 base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) {
888 int64 value;
889 if (ReadInt64(dictionary, key, &value))
890 return base::Time::FromInternalValue(value);
892 return base::Time();
895 } // namespace
897 base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const {
898 DCHECK(crx_file::id_util::IdIsValid(extension_id));
899 return ReadTime(GetExtensionPref(extension_id), kLastPingDay);
902 void ExtensionPrefs::SetLastPingDay(const std::string& extension_id,
903 const base::Time& time) {
904 DCHECK(crx_file::id_util::IdIsValid(extension_id));
905 ScopedExtensionPrefUpdate update(prefs_, extension_id);
906 SaveTime(update.Get(), kLastPingDay, time);
909 base::Time ExtensionPrefs::BlacklistLastPingDay() const {
910 return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate),
911 kLastPingDay);
914 void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) {
915 DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate);
916 SaveTime(update.Get(), kLastPingDay, time);
919 base::Time ExtensionPrefs::LastActivePingDay(const std::string& extension_id) {
920 DCHECK(crx_file::id_util::IdIsValid(extension_id));
921 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
924 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
925 const base::Time& time) {
926 DCHECK(crx_file::id_util::IdIsValid(extension_id));
927 ScopedExtensionPrefUpdate update(prefs_, extension_id);
928 SaveTime(update.Get(), kLastActivePingDay, time);
931 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) {
932 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
933 bool result = false;
934 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
935 return result;
936 return false;
939 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
940 bool active) {
941 UpdateExtensionPref(extension_id, kActiveBit,
942 new base::FundamentalValue(active));
945 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
946 PermissionsInfo* info = PermissionsInfo::GetInstance();
947 for (ExtensionIdList::const_iterator ext_id =
948 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
949 // An extension's granted permissions need to be migrated if the
950 // full_access bit is present. This bit was always present in the previous
951 // scheme and is never present now.
952 bool full_access = false;
953 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
954 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
955 continue;
957 // Remove the full access bit (empty list will get trimmed).
958 UpdateExtensionPref(
959 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
961 // Add the plugin permission if the full access bit was set.
962 if (full_access) {
963 const base::ListValue* apis = NULL;
964 base::ListValue* new_apis = NULL;
966 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
967 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
968 new_apis = apis->DeepCopy();
969 else
970 new_apis = new base::ListValue();
972 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
973 new_apis->Append(new base::StringValue(plugin_name));
974 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
977 // The granted permissions originally only held the effective hosts,
978 // which are a combination of host and user script host permissions.
979 // We now maintain these lists separately. For migration purposes, it
980 // does not matter how we treat the old effective hosts as long as the
981 // new effective hosts will be the same, so we move them to explicit
982 // host permissions.
983 const base::ListValue* hosts = NULL;
984 std::string explicit_hosts =
985 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
986 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
987 UpdateExtensionPref(
988 *ext_id, explicit_hosts, hosts->DeepCopy());
990 // We can get rid of the old one by setting it to an empty list.
991 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
996 void ExtensionPrefs::MigrateDisableReasons(
997 const ExtensionIdList& extension_ids) {
998 for (ExtensionIdList::const_iterator ext_id =
999 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
1000 int value = -1;
1001 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
1002 int new_value = Extension::DISABLE_NONE;
1003 switch (value) {
1004 case Extension::DEPRECATED_DISABLE_USER_ACTION:
1005 new_value = Extension::DISABLE_USER_ACTION;
1006 break;
1007 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
1008 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
1009 break;
1010 case Extension::DEPRECATED_DISABLE_RELOAD:
1011 new_value = Extension::DISABLE_RELOAD;
1012 break;
1015 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
1016 new base::FundamentalValue(new_value));
1017 // Remove the old disable reason.
1018 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
1023 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
1024 const std::string& extension_id) {
1025 CHECK(crx_file::id_util::IdIsValid(extension_id));
1026 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
1029 void ExtensionPrefs::AddGrantedPermissions(
1030 const std::string& extension_id,
1031 const PermissionSet* permissions) {
1032 CHECK(crx_file::id_util::IdIsValid(extension_id));
1034 scoped_refptr<PermissionSet> granted_permissions(
1035 GetGrantedPermissions(extension_id));
1037 // The new granted permissions are the union of the already granted
1038 // permissions and the newly granted permissions.
1039 scoped_refptr<PermissionSet> new_perms(
1040 PermissionSet::CreateUnion(
1041 permissions, granted_permissions.get()));
1043 SetExtensionPrefPermissionSet(
1044 extension_id, kPrefGrantedPermissions, new_perms.get());
1047 void ExtensionPrefs::RemoveGrantedPermissions(
1048 const std::string& extension_id,
1049 const PermissionSet* permissions) {
1050 CHECK(crx_file::id_util::IdIsValid(extension_id));
1052 scoped_refptr<PermissionSet> granted_permissions(
1053 GetGrantedPermissions(extension_id));
1055 // The new granted permissions are the difference of the already granted
1056 // permissions and the newly ungranted permissions.
1057 scoped_refptr<PermissionSet> new_perms(
1058 PermissionSet::CreateDifference(
1059 granted_permissions.get(), permissions));
1061 SetExtensionPrefPermissionSet(
1062 extension_id, kPrefGrantedPermissions, new_perms.get());
1065 PermissionSet* ExtensionPrefs::GetActivePermissions(
1066 const std::string& extension_id) {
1067 CHECK(crx_file::id_util::IdIsValid(extension_id));
1068 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
1071 void ExtensionPrefs::SetActivePermissions(
1072 const std::string& extension_id,
1073 const PermissionSet* permissions) {
1074 SetExtensionPrefPermissionSet(
1075 extension_id, kPrefActivePermissions, permissions);
1078 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1079 bool is_running) {
1080 base::Value* value = new base::FundamentalValue(is_running);
1081 UpdateExtensionPref(extension_id, kPrefRunning, value);
1084 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) {
1085 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1086 if (!extension)
1087 return false;
1088 bool running = false;
1089 extension->GetBoolean(kPrefRunning, &running);
1090 return running;
1093 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1094 bool is_active) {
1095 base::Value* value = new base::FundamentalValue(is_active);
1096 UpdateExtensionPref(extension_id, kIsActive, value);
1099 bool ExtensionPrefs::IsActive(const std::string& extension_id) {
1100 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1101 if (!extension)
1102 return false;
1103 bool is_active = false;
1104 extension->GetBoolean(kIsActive, &is_active);
1105 return is_active;
1108 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1109 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1112 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1113 bool enabled) {
1114 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1115 new base::FundamentalValue(enabled));
1116 extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled);
1119 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1120 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1123 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1124 bool allow) {
1125 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1126 new base::FundamentalValue(allow));
1129 bool ExtensionPrefs::HasAllowFileAccessSetting(
1130 const std::string& extension_id) const {
1131 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1132 return ext && ext->HasKey(kPrefAllowFileAccess);
1135 bool ExtensionPrefs::DoesExtensionHaveState(
1136 const std::string& id, Extension::State check_state) const {
1137 const base::DictionaryValue* extension = GetExtensionPref(id);
1138 int state = -1;
1139 if (!extension || !extension->GetInteger(kPrefState, &state))
1140 return false;
1142 if (state < 0 || state >= Extension::NUM_STATES) {
1143 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1144 return false;
1147 return state == check_state;
1150 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1151 const std::string& id) const {
1152 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1155 bool ExtensionPrefs::IsExtensionDisabled(
1156 const std::string& id) const {
1157 return DoesExtensionHaveState(id, Extension::DISABLED);
1160 ExtensionIdList ExtensionPrefs::GetToolbarOrder() {
1161 ExtensionIdList id_list_out;
1162 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1163 return id_list_out;
1166 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1167 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1170 void ExtensionPrefs::OnExtensionInstalled(
1171 const Extension* extension,
1172 Extension::State initial_state,
1173 const syncer::StringOrdinal& page_ordinal,
1174 int install_flags,
1175 const std::string& install_parameter) {
1176 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1177 base::DictionaryValue* extension_dict = update.Get();
1178 const base::Time install_time = time_provider_->GetCurrentTime();
1179 PopulateExtensionInfoPrefs(extension,
1180 install_time,
1181 initial_state,
1182 install_flags,
1183 install_parameter,
1184 extension_dict);
1186 bool requires_sort_ordinal = extension->RequiresSortOrdinal() &&
1187 (install_flags & kInstallFlagIsEphemeral) == 0;
1188 FinishExtensionInfoPrefs(extension->id(),
1189 install_time,
1190 requires_sort_ordinal,
1191 page_ordinal,
1192 extension_dict);
1195 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1196 const Manifest::Location& location,
1197 bool external_uninstall) {
1198 app_sorting_->ClearOrdinals(extension_id);
1200 // For external extensions, we save a preference reminding ourself not to try
1201 // and install the extension anymore (except when |external_uninstall| is
1202 // true, which signifies that the registry key was deleted or the pref file
1203 // no longer lists the extension).
1204 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1205 UpdateExtensionPref(extension_id, kPrefState,
1206 new base::FundamentalValue(
1207 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1208 extension_pref_value_map_->SetExtensionState(extension_id, false);
1209 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1210 observer_list_,
1211 OnExtensionStateChanged(extension_id, false));
1212 } else {
1213 DeleteExtensionPrefs(extension_id);
1217 void ExtensionPrefs::SetExtensionState(const std::string& extension_id,
1218 Extension::State state) {
1219 UpdateExtensionPref(extension_id, kPrefState,
1220 new base::FundamentalValue(state));
1221 bool enabled = (state == Extension::ENABLED);
1222 extension_pref_value_map_->SetExtensionState(extension_id, enabled);
1223 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1224 observer_list_,
1225 OnExtensionStateChanged(extension_id, enabled));
1228 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1229 BlacklistState state) {
1230 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1231 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1232 new base::FundamentalValue(state));
1235 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1236 const std::string& extension_id) {
1237 if (IsExtensionBlacklisted(extension_id))
1238 return BLACKLISTED_MALWARE;
1239 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1240 int int_value = 0;
1241 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1242 return static_cast<BlacklistState>(int_value);
1244 return NOT_BLACKLISTED;
1247 std::string ExtensionPrefs::GetVersionString(const std::string& extension_id) {
1248 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1249 if (!extension)
1250 return std::string();
1252 std::string version;
1253 extension->GetString(kPrefVersion, &version);
1255 return version;
1258 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1259 if (!Manifest::IsUnpackedLocation(extension->location())) {
1260 const base::DictionaryValue* extension_dict =
1261 GetExtensionPref(extension->id());
1262 if (!extension_dict)
1263 return;
1264 const base::DictionaryValue* old_manifest = NULL;
1265 bool update_required =
1266 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1267 !extension->manifest()->value()->Equals(old_manifest);
1268 if (update_required) {
1269 UpdateExtensionPref(extension->id(), kPrefManifest,
1270 extension->manifest()->value()->DeepCopy());
1275 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1276 const std::string& extension_id,
1277 const base::DictionaryValue* extension) const {
1278 int location_value;
1279 if (!extension->GetInteger(kPrefLocation, &location_value))
1280 return scoped_ptr<ExtensionInfo>();
1282 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1283 if (location == Manifest::COMPONENT) {
1284 // Component extensions are ignored. Component extensions may have data
1285 // saved in preferences, but they are already loaded at this point (by
1286 // ComponentLoader) and shouldn't be populated into the result of
1287 // GetInstalledExtensionsInfo, otherwise InstalledLoader would also want to
1288 // load them.
1289 return scoped_ptr<ExtensionInfo>();
1292 // Only the following extension types have data saved in the preferences.
1293 if (location != Manifest::INTERNAL &&
1294 !Manifest::IsUnpackedLocation(location) &&
1295 !Manifest::IsExternalLocation(location)) {
1296 NOTREACHED();
1297 return scoped_ptr<ExtensionInfo>();
1300 const base::DictionaryValue* manifest = NULL;
1301 if (!Manifest::IsUnpackedLocation(location) &&
1302 !extension->GetDictionary(kPrefManifest, &manifest)) {
1303 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1304 // Just a warning for now.
1307 base::FilePath::StringType path;
1308 if (!extension->GetString(kPrefPath, &path))
1309 return scoped_ptr<ExtensionInfo>();
1311 // Make path absolute. Most (but not all) extension types have relative paths.
1312 if (!base::FilePath(path).IsAbsolute())
1313 path = install_directory_.Append(path).value();
1315 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1316 manifest, extension_id, base::FilePath(path), location));
1319 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1320 const std::string& extension_id) const {
1321 const base::DictionaryValue* ext = NULL;
1322 const base::DictionaryValue* extensions =
1323 prefs_->GetDictionary(pref_names::kExtensions);
1324 if (!extensions ||
1325 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1326 return scoped_ptr<ExtensionInfo>();
1327 int state_value;
1328 if (ext->GetInteger(kPrefState, &state_value) &&
1329 state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1330 LOG(WARNING) << "External extension with id " << extension_id
1331 << " has been uninstalled by the user";
1332 return scoped_ptr<ExtensionInfo>();
1335 return GetInstalledInfoHelper(extension_id, ext);
1338 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1339 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1340 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1342 const base::DictionaryValue* extensions =
1343 prefs_->GetDictionary(pref_names::kExtensions);
1344 for (base::DictionaryValue::Iterator extension_id(*extensions);
1345 !extension_id.IsAtEnd(); extension_id.Advance()) {
1346 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1347 continue;
1349 scoped_ptr<ExtensionInfo> info =
1350 GetInstalledExtensionInfo(extension_id.key());
1351 if (info)
1352 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1355 return extensions_info.Pass();
1358 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1359 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1360 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1362 const base::DictionaryValue* extensions =
1363 prefs_->GetDictionary(pref_names::kExtensions);
1364 for (base::DictionaryValue::Iterator extension_id(*extensions);
1365 !extension_id.IsAtEnd(); extension_id.Advance()) {
1366 const base::DictionaryValue* ext = NULL;
1367 if (!crx_file::id_util::IdIsValid(extension_id.key()) ||
1368 !IsExternalExtensionUninstalled(extension_id.key()) ||
1369 !extension_id.value().GetAsDictionary(&ext))
1370 continue;
1372 scoped_ptr<ExtensionInfo> info =
1373 GetInstalledInfoHelper(extension_id.key(), ext);
1374 if (info)
1375 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1378 return extensions_info.Pass();
1381 void ExtensionPrefs::SetDelayedInstallInfo(
1382 const Extension* extension,
1383 Extension::State initial_state,
1384 int install_flags,
1385 DelayReason delay_reason,
1386 const syncer::StringOrdinal& page_ordinal,
1387 const std::string& install_parameter) {
1388 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1389 PopulateExtensionInfoPrefs(extension,
1390 time_provider_->GetCurrentTime(),
1391 initial_state,
1392 install_flags,
1393 install_parameter,
1394 extension_dict);
1396 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1397 // should not be in the final extension prefs. All entries here should have
1398 // a corresponding Remove() call in FinishDelayedInstallInfo().
1399 if (extension->RequiresSortOrdinal() &&
1400 (install_flags & kInstallFlagIsEphemeral) == 0) {
1401 extension_dict->SetString(
1402 kPrefSuggestedPageOrdinal,
1403 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1404 : std::string());
1406 extension_dict->SetInteger(kDelayedInstallReason,
1407 static_cast<int>(delay_reason));
1409 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1412 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1413 const std::string& extension_id) {
1414 if (!GetExtensionPref(extension_id))
1415 return false;
1416 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1417 bool result = update->Remove(kDelayedInstallInfo, NULL);
1418 return result;
1421 bool ExtensionPrefs::FinishDelayedInstallInfo(
1422 const std::string& extension_id) {
1423 CHECK(crx_file::id_util::IdIsValid(extension_id));
1424 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1425 base::DictionaryValue* extension_dict = update.Get();
1426 base::DictionaryValue* pending_install_dict = NULL;
1427 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1428 &pending_install_dict)) {
1429 return false;
1432 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1433 // Also do any other data cleanup that makes sense.
1434 std::string serialized_ordinal;
1435 syncer::StringOrdinal suggested_page_ordinal;
1436 bool needs_sort_ordinal = false;
1437 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1438 &serialized_ordinal)) {
1439 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1440 needs_sort_ordinal = true;
1441 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1443 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1445 const base::Time install_time = time_provider_->GetCurrentTime();
1446 pending_install_dict->Set(
1447 kPrefInstallTime,
1448 new base::StringValue(
1449 base::Int64ToString(install_time.ToInternalValue())));
1451 // Some extension pref values are written conditionally. If they are not
1452 // present in the delayed install data, they should be removed when the
1453 // delayed install is committed.
1454 extension_dict->Remove(kPrefEphemeralApp, NULL);
1456 // Commit the delayed install data.
1457 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1458 it.Advance()) {
1459 extension_dict->Set(it.key(), it.value().DeepCopy());
1461 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1462 suggested_page_ordinal, extension_dict);
1463 return true;
1466 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1467 const std::string& extension_id) const {
1468 const base::DictionaryValue* extension_prefs =
1469 GetExtensionPref(extension_id);
1470 if (!extension_prefs)
1471 return scoped_ptr<ExtensionInfo>();
1473 const base::DictionaryValue* ext = NULL;
1474 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1475 return scoped_ptr<ExtensionInfo>();
1477 return GetInstalledInfoHelper(extension_id, ext);
1480 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1481 const std::string& extension_id) const {
1482 const base::DictionaryValue* extension_prefs =
1483 GetExtensionPref(extension_id);
1484 if (!extension_prefs)
1485 return DELAY_REASON_NONE;
1487 const base::DictionaryValue* ext = NULL;
1488 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1489 return DELAY_REASON_NONE;
1491 int delay_reason;
1492 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1493 return DELAY_REASON_NONE;
1495 return static_cast<DelayReason>(delay_reason);
1498 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1499 GetAllDelayedInstallInfo() const {
1500 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1502 const base::DictionaryValue* extensions =
1503 prefs_->GetDictionary(pref_names::kExtensions);
1504 for (base::DictionaryValue::Iterator extension_id(*extensions);
1505 !extension_id.IsAtEnd(); extension_id.Advance()) {
1506 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1507 continue;
1509 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1510 if (info)
1511 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1514 return extensions_info.Pass();
1517 bool ExtensionPrefs::IsEphemeralApp(const std::string& extension_id) const {
1518 if (ReadPrefAsBooleanAndReturn(extension_id, kPrefEphemeralApp))
1519 return true;
1521 // Ephemerality was previously stored in the creation flags, so we must also
1522 // check it for backcompatibility.
1523 return (GetCreationFlags(extension_id) & Extension::IS_EPHEMERAL) != 0;
1526 void ExtensionPrefs::OnEphemeralAppPromoted(const std::string& extension_id) {
1527 DCHECK(IsEphemeralApp(extension_id));
1529 UpdateExtensionPref(extension_id, kPrefEphemeralApp, NULL);
1531 // Ephemerality was previously stored in the creation flags, so ensure the bit
1532 // is cleared.
1533 int creation_flags = Extension::NO_FLAGS;
1534 if (ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1535 if (creation_flags & Extension::IS_EPHEMERAL) {
1536 creation_flags &= ~static_cast<int>(Extension::IS_EPHEMERAL);
1537 UpdateExtensionPref(extension_id,
1538 kPrefCreationFlags,
1539 new base::FundamentalValue(creation_flags));
1544 bool ExtensionPrefs::WasAppDraggedByUser(const std::string& extension_id) {
1545 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1548 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1549 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1550 new base::FundamentalValue(true));
1553 bool ExtensionPrefs::IsFromWebStore(
1554 const std::string& extension_id) const {
1555 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1556 bool result = false;
1557 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1558 return result;
1559 return false;
1562 bool ExtensionPrefs::IsFromBookmark(
1563 const std::string& extension_id) const {
1564 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1565 bool result = false;
1566 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1567 return result;
1568 return false;
1571 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1572 int creation_flags = Extension::NO_FLAGS;
1573 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1574 // Since kPrefCreationFlags was added later, it will be missing for
1575 // previously installed extensions.
1576 if (IsFromBookmark(extension_id))
1577 creation_flags |= Extension::FROM_BOOKMARK;
1578 if (IsFromWebStore(extension_id))
1579 creation_flags |= Extension::FROM_WEBSTORE;
1580 if (WasInstalledByDefault(extension_id))
1581 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1582 if (WasInstalledByOem(extension_id))
1583 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
1585 return creation_flags;
1588 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1589 const std::string& extension_id) const {
1590 int creation_flags = Extension::NO_FLAGS;
1591 const base::DictionaryValue* delayed_info = NULL;
1592 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1593 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1595 return creation_flags;
1598 bool ExtensionPrefs::WasInstalledByDefault(
1599 const std::string& extension_id) const {
1600 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1601 bool result = false;
1602 if (dictionary &&
1603 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1604 return result;
1605 return false;
1608 bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const {
1609 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1610 bool result = false;
1611 if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result))
1612 return result;
1613 return false;
1616 base::Time ExtensionPrefs::GetInstallTime(
1617 const std::string& extension_id) const {
1618 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1619 if (!extension) {
1620 NOTREACHED();
1621 return base::Time();
1623 std::string install_time_str;
1624 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1625 return base::Time();
1626 int64 install_time_i64 = 0;
1627 if (!base::StringToInt64(install_time_str, &install_time_i64))
1628 return base::Time();
1629 return base::Time::FromInternalValue(install_time_i64);
1632 bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const {
1633 bool do_not_sync;
1634 if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync))
1635 return false;
1637 return do_not_sync;
1640 base::Time ExtensionPrefs::GetLastLaunchTime(
1641 const std::string& extension_id) const {
1642 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1643 if (!extension)
1644 return base::Time();
1646 std::string launch_time_str;
1647 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1648 return base::Time();
1649 int64 launch_time_i64 = 0;
1650 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1651 return base::Time();
1652 return base::Time::FromInternalValue(launch_time_i64);
1655 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1656 const base::Time& time) {
1657 DCHECK(crx_file::id_util::IdIsValid(extension_id));
1658 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1659 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1662 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) {
1663 CHECK(out);
1665 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1667 for (size_t i = 0; i < extensions_info->size(); ++i) {
1668 ExtensionInfo* info = extensions_info->at(i).get();
1669 out->push_back(info->extension_id);
1673 // static
1674 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1675 const PrefService* pref_service) {
1676 ExtensionIdList result;
1678 const base::DictionaryValue* extension_prefs = NULL;
1679 const base::Value* extension_prefs_value =
1680 pref_service->GetUserPrefValue(pref_names::kExtensions);
1681 if (!extension_prefs_value ||
1682 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1683 return result; // Empty set
1686 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1687 it.Advance()) {
1688 const base::DictionaryValue* ext = NULL;
1689 if (!it.value().GetAsDictionary(&ext)) {
1690 NOTREACHED() << "Invalid pref for extension " << it.key();
1691 continue;
1693 if (!IsBlacklistBitSet(ext))
1694 result.push_back(it.key());
1696 return result;
1699 void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) {
1700 observer_list_.AddObserver(observer);
1703 void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) {
1704 observer_list_.RemoveObserver(observer);
1707 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1708 // Fix old entries that did not get an installation time entry when they
1709 // were installed or don't have a preferences field.
1710 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1711 ext_id != extension_ids.end(); ++ext_id) {
1712 if (GetInstallTime(*ext_id) == base::Time()) {
1713 VLOG(1) << "Could not parse installation time of extension "
1714 << *ext_id << ". It was probably installed before setting "
1715 << kPrefInstallTime << " was introduced. Updating "
1716 << kPrefInstallTime << " to the current time.";
1717 const base::Time install_time = time_provider_->GetCurrentTime();
1718 UpdateExtensionPref(*ext_id,
1719 kPrefInstallTime,
1720 new base::StringValue(base::Int64ToString(
1721 install_time.ToInternalValue())));
1726 void ExtensionPrefs::InitPrefStore() {
1727 if (extensions_disabled_) {
1728 extension_pref_value_map_->NotifyInitializationCompleted();
1729 return;
1732 // When this is called, the PrefService is initialized and provides access
1733 // to the user preferences stored in a JSON file.
1734 ExtensionIdList extension_ids;
1735 GetExtensions(&extension_ids);
1736 // Create empty preferences dictionary for each extension (these dictionaries
1737 // are pruned when persisting the preferences to disk).
1738 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1739 ext_id != extension_ids.end(); ++ext_id) {
1740 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1741 // This creates an empty dictionary if none is stored.
1742 update.Get();
1745 FixMissingPrefs(extension_ids);
1746 MigratePermissions(extension_ids);
1747 MigrateDisableReasons(extension_ids);
1748 app_sorting_->Initialize(extension_ids);
1750 InitExtensionControlledPrefs(extension_pref_value_map_);
1752 extension_pref_value_map_->NotifyInitializationCompleted();
1755 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) {
1756 bool has_incognito_pref_value = false;
1757 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1758 true,
1759 &has_incognito_pref_value);
1760 return has_incognito_pref_value;
1763 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1764 const std::string& extension_id) const {
1765 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1766 if (!extension_prefs)
1767 return NULL;
1769 const base::DictionaryValue* ext = NULL;
1770 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1771 return NULL;
1773 return ext;
1776 void ExtensionPrefs::SetGeometryCache(
1777 const std::string& extension_id,
1778 scoped_ptr<base::DictionaryValue> cache) {
1779 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1782 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() {
1783 return prefs_->GetDictionary(kInstallSignature);
1786 void ExtensionPrefs::SetInstallSignature(
1787 const base::DictionaryValue* signature) {
1788 if (signature) {
1789 prefs_->Set(kInstallSignature, *signature);
1790 DVLOG(1) << "SetInstallSignature - saving";
1791 } else {
1792 DVLOG(1) << "SetInstallSignature - clearing";
1793 prefs_->ClearPref(kInstallSignature);
1797 std::string ExtensionPrefs::GetInstallParam(
1798 const std::string& extension_id) const {
1799 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1800 if (!extension) // Expected during unit testing.
1801 return std::string();
1802 std::string install_parameter;
1803 if (!extension->GetString(kPrefInstallParam, &install_parameter))
1804 return std::string();
1805 return install_parameter;
1808 void ExtensionPrefs::SetInstallParam(const std::string& extension_id,
1809 const std::string& install_parameter) {
1810 UpdateExtensionPref(extension_id,
1811 kPrefInstallParam,
1812 new base::StringValue(install_parameter));
1815 int ExtensionPrefs::GetCorruptedDisableCount() {
1816 return prefs_->GetInteger(kCorruptedDisableCount);
1819 void ExtensionPrefs::IncrementCorruptedDisableCount() {
1820 int count = prefs_->GetInteger(kCorruptedDisableCount);
1821 prefs_->SetInteger(kCorruptedDisableCount, count + 1);
1824 ExtensionPrefs::ExtensionPrefs(
1825 PrefService* prefs,
1826 const base::FilePath& root_dir,
1827 ExtensionPrefValueMap* extension_pref_value_map,
1828 scoped_ptr<AppSorting> app_sorting,
1829 scoped_ptr<TimeProvider> time_provider,
1830 bool extensions_disabled,
1831 const std::vector<ExtensionPrefsObserver*>& early_observers)
1832 : prefs_(prefs),
1833 install_directory_(root_dir),
1834 extension_pref_value_map_(extension_pref_value_map),
1835 app_sorting_(app_sorting.Pass()),
1836 time_provider_(time_provider.Pass()),
1837 extensions_disabled_(extensions_disabled) {
1838 app_sorting_->SetExtensionScopedPrefs(this);
1839 MakePathsRelative();
1841 // Ensure that any early observers are watching before prefs are initialized.
1842 for (std::vector<ExtensionPrefsObserver*>::const_iterator iter =
1843 early_observers.begin();
1844 iter != early_observers.end();
1845 ++iter) {
1846 AddObserver(*iter);
1849 InitPrefStore();
1852 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1853 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1856 bool ExtensionPrefs::NeedsStorageGarbageCollection() {
1857 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1860 // static
1861 void ExtensionPrefs::RegisterProfilePrefs(
1862 user_prefs::PrefRegistrySyncable* registry) {
1863 registry->RegisterDictionaryPref(
1864 pref_names::kExtensions,
1865 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1866 registry->RegisterListPref(pref_names::kToolbar,
1867 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1868 registry->RegisterIntegerPref(
1869 pref_names::kToolbarSize,
1870 -1, // default value
1871 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1872 registry->RegisterDictionaryPref(
1873 kExtensionsBlacklistUpdate,
1874 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1875 registry->RegisterListPref(pref_names::kInstallAllowList,
1876 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1877 registry->RegisterListPref(pref_names::kInstallDenyList,
1878 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1879 registry->RegisterDictionaryPref(
1880 pref_names::kInstallForceList,
1881 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1882 registry->RegisterListPref(pref_names::kAllowedTypes,
1883 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1884 registry->RegisterBooleanPref(
1885 pref_names::kStorageGarbageCollect,
1886 false, // default value
1887 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1888 registry->RegisterInt64Pref(
1889 pref_names::kLastUpdateCheck,
1890 0, // default value
1891 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1892 registry->RegisterInt64Pref(
1893 pref_names::kNextUpdateCheck,
1894 0, // default value
1895 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1896 registry->RegisterListPref(pref_names::kAllowedInstallSites,
1897 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1898 registry->RegisterStringPref(
1899 pref_names::kLastChromeVersion,
1900 std::string(), // default value
1901 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1902 registry->RegisterDictionaryPref(
1903 kInstallSignature,
1904 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1906 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist,
1907 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1908 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist,
1909 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1910 registry->RegisterBooleanPref(
1911 pref_names::kNativeMessagingUserLevelHosts,
1912 true, // default value
1913 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1914 registry->RegisterIntegerPref(
1915 kCorruptedDisableCount,
1916 0, // default value
1917 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1919 #if !defined(OS_MACOSX)
1920 registry->RegisterBooleanPref(
1921 pref_names::kAppFullscreenAllowed, true,
1922 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1923 #endif
1926 template <class ExtensionIdContainer>
1927 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
1928 const char* pref,
1929 ExtensionIdContainer* id_container_out) {
1930 DCHECK(id_container_out->empty());
1932 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
1933 const base::ListValue* user_pref_as_list;
1934 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
1935 return false;
1937 std::insert_iterator<ExtensionIdContainer> insert_iterator(
1938 *id_container_out, id_container_out->end());
1939 std::string extension_id;
1940 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
1941 value_it != user_pref_as_list->end(); ++value_it) {
1942 if (!(*value_it)->GetAsString(&extension_id)) {
1943 NOTREACHED();
1944 continue;
1946 insert_iterator = extension_id;
1948 return true;
1951 template <class ExtensionIdContainer>
1952 void ExtensionPrefs::SetExtensionPrefFromContainer(
1953 const char* pref,
1954 const ExtensionIdContainer& strings) {
1955 ListPrefUpdate update(prefs_, pref);
1956 base::ListValue* list_of_values = update.Get();
1957 list_of_values->Clear();
1958 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
1959 iter != strings.end(); ++iter) {
1960 list_of_values->Append(new base::StringValue(*iter));
1964 void ExtensionPrefs::PopulateExtensionInfoPrefs(
1965 const Extension* extension,
1966 const base::Time install_time,
1967 Extension::State initial_state,
1968 int install_flags,
1969 const std::string& install_parameter,
1970 base::DictionaryValue* extension_dict) {
1971 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
1972 extension_dict->Set(kPrefLocation,
1973 new base::FundamentalValue(extension->location()));
1974 extension_dict->Set(kPrefCreationFlags,
1975 new base::FundamentalValue(extension->creation_flags()));
1976 extension_dict->Set(kPrefFromWebStore,
1977 new base::FundamentalValue(extension->from_webstore()));
1978 extension_dict->Set(kPrefFromBookmark,
1979 new base::FundamentalValue(extension->from_bookmark()));
1980 extension_dict->Set(
1981 kPrefWasInstalledByDefault,
1982 new base::FundamentalValue(extension->was_installed_by_default()));
1983 extension_dict->Set(
1984 kPrefWasInstalledByOem,
1985 new base::FundamentalValue(extension->was_installed_by_oem()));
1986 extension_dict->Set(kPrefInstallTime,
1987 new base::StringValue(
1988 base::Int64ToString(install_time.ToInternalValue())));
1989 if (install_flags & kInstallFlagIsBlacklistedForMalware)
1990 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
1992 if (install_flags & kInstallFlagIsEphemeral)
1993 extension_dict->Set(kPrefEphemeralApp, new base::FundamentalValue(true));
1994 else
1995 extension_dict->Remove(kPrefEphemeralApp, NULL);
1997 base::FilePath::StringType path = MakePathRelative(install_directory_,
1998 extension->path());
1999 extension_dict->Set(kPrefPath, new base::StringValue(path));
2000 if (!install_parameter.empty()) {
2001 extension_dict->Set(kPrefInstallParam,
2002 new base::StringValue(install_parameter));
2004 // We store prefs about LOAD extensions, but don't cache their manifest
2005 // since it may change on disk.
2006 if (!Manifest::IsUnpackedLocation(extension->location())) {
2007 extension_dict->Set(kPrefManifest,
2008 extension->manifest()->value()->DeepCopy());
2011 // Only writes kPrefDoNotSync when it is not the default.
2012 if (install_flags & kInstallFlagDoNotSync)
2013 extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true));
2014 else
2015 extension_dict->Remove(kPrefDoNotSync, NULL);
2018 void ExtensionPrefs::InitExtensionControlledPrefs(
2019 ExtensionPrefValueMap* value_map) {
2020 ExtensionIdList extension_ids;
2021 GetExtensions(&extension_ids);
2023 for (ExtensionIdList::iterator extension_id = extension_ids.begin();
2024 extension_id != extension_ids.end();
2025 ++extension_id) {
2026 base::Time install_time = GetInstallTime(*extension_id);
2027 bool is_enabled = !IsExtensionDisabled(*extension_id);
2028 bool is_incognito_enabled = IsIncognitoEnabled(*extension_id);
2029 value_map->RegisterExtension(
2030 *extension_id, install_time, is_enabled, is_incognito_enabled);
2032 FOR_EACH_OBSERVER(
2033 ExtensionPrefsObserver,
2034 observer_list_,
2035 OnExtensionRegistered(*extension_id, install_time, is_enabled));
2037 // Set regular extension controlled prefs.
2038 LoadExtensionControlledPrefs(
2039 this, value_map, *extension_id, kExtensionPrefsScopeRegular);
2040 // Set incognito extension controlled prefs.
2041 LoadExtensionControlledPrefs(this,
2042 value_map,
2043 *extension_id,
2044 kExtensionPrefsScopeIncognitoPersistent);
2045 // Set regular-only extension controlled prefs.
2046 LoadExtensionControlledPrefs(
2047 this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly);
2049 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
2050 observer_list_,
2051 OnExtensionPrefsLoaded(*extension_id, this));
2055 void ExtensionPrefs::FinishExtensionInfoPrefs(
2056 const std::string& extension_id,
2057 const base::Time install_time,
2058 bool needs_sort_ordinal,
2059 const syncer::StringOrdinal& suggested_page_ordinal,
2060 base::DictionaryValue* extension_dict) {
2061 // Reinitializes various preferences with empty dictionaries.
2062 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
2063 extension_dict->Set(pref_names::kPrefPreferences,
2064 new base::DictionaryValue);
2067 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
2068 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
2069 new base::DictionaryValue);
2072 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
2073 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
2074 new base::DictionaryValue);
2077 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
2078 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
2080 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
2081 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
2082 new base::ListValue);
2085 // If this point has been reached, any pending installs should be considered
2086 // out of date.
2087 extension_dict->Remove(kDelayedInstallInfo, NULL);
2089 // Clear state that may be registered from a previous install.
2090 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
2092 // FYI, all code below here races on sudden shutdown because |extension_dict|,
2093 // |app_sorting_|, |extension_pref_value_map_|, and (potentially) observers
2094 // are updated non-transactionally. This is probably not fixable without
2095 // nested transactional updates to pref dictionaries.
2096 if (needs_sort_ordinal)
2097 app_sorting_->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
2099 bool is_enabled = false;
2100 int initial_state;
2101 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
2102 is_enabled = initial_state == Extension::ENABLED;
2104 bool is_incognito_enabled = IsIncognitoEnabled(extension_id);
2106 extension_pref_value_map_->RegisterExtension(
2107 extension_id, install_time, is_enabled, is_incognito_enabled);
2109 FOR_EACH_OBSERVER(
2110 ExtensionPrefsObserver,
2111 observer_list_,
2112 OnExtensionRegistered(extension_id, install_time, is_enabled));
2115 } // namespace extensions