Revert "Fix broken channel icon in chrome://help on CrOS" and try again
[chromium-blink-merge.git] / extensions / browser / extension_prefs.cc
blob57a4e05523e6d6e9591d715c8a454a9fdccea206
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/metrics/histogram_macros.h"
10 #include "base/prefs/pref_service.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/strings/string_util.h"
13 #include "base/trace_event/trace_event.h"
14 #include "components/crx_file/id_util.h"
15 #include "components/pref_registry/pref_registry_syncable.h"
16 #include "extensions/browser/app_sorting.h"
17 #include "extensions/browser/event_router.h"
18 #include "extensions/browser/extension_pref_store.h"
19 #include "extensions/browser/extension_prefs_factory.h"
20 #include "extensions/browser/extension_prefs_observer.h"
21 #include "extensions/browser/extension_system.h"
22 #include "extensions/browser/install_flag.h"
23 #include "extensions/browser/pref_names.h"
24 #include "extensions/common/manifest.h"
25 #include "extensions/common/permissions/permission_set.h"
26 #include "extensions/common/permissions/permissions_info.h"
27 #include "extensions/common/url_pattern.h"
28 #include "extensions/common/user_script.h"
30 namespace extensions {
32 namespace {
34 // Additional preferences keys, which are not needed by external clients.
36 // True if this extension is running. Note this preference stops getting updated
37 // during Chrome shutdown (and won't be updated on a browser crash) and so can
38 // be used at startup to determine whether the extension was running when Chrome
39 // was last terminated.
40 const char kPrefRunning[] = "running";
42 // Whether this extension had windows when it was last running.
43 const char kIsActive[] = "is_active";
45 // Where an extension was installed from. (see Manifest::Location)
46 const char kPrefLocation[] = "location";
48 // Enabled, disabled, killed, etc. (see Extension::State)
49 const char kPrefState[] = "state";
51 // The path to the current version's manifest file.
52 const char kPrefPath[] = "path";
54 // The dictionary containing the extension's manifest.
55 const char kPrefManifest[] = "manifest";
57 // The version number.
58 const char kPrefVersion[] = "manifest.version";
60 // Indicates whether an extension is blacklisted.
61 const char kPrefBlacklist[] = "blacklist";
63 // If extension is greylisted.
64 const char kPrefBlacklistState[] = "blacklist_state";
66 // The count of how many times we prompted the user to acknowledge an
67 // extension.
68 const char kPrefAcknowledgePromptCount[] = "ack_prompt_count";
70 // Indicates whether the user has acknowledged various types of extensions.
71 const char kPrefExternalAcknowledged[] = "ack_external";
72 const char kPrefBlacklistAcknowledged[] = "ack_blacklist";
74 // Indicates whether the external extension was installed during the first
75 // run of this profile.
76 const char kPrefExternalInstallFirstRun[] = "external_first_run";
78 // DO NOT USE, use kPrefDisableReasons instead.
79 // Indicates whether the extension was updated while it was disabled.
80 const char kDeprecatedPrefDisableReason[] = "disable_reason";
82 // A bitmask of all the reasons an extension is disabled.
83 const char kPrefDisableReasons[] = "disable_reasons";
85 // The key for a serialized Time value indicating the start of the day (from the
86 // server's perspective) an extension last included a "ping" parameter during
87 // its update check.
88 const char kLastPingDay[] = "lastpingday";
90 // Similar to kLastPingDay, but for "active" instead of "rollcall" pings.
91 const char kLastActivePingDay[] = "last_active_pingday";
93 // A bit we use to keep track of whether we need to do an "active" ping.
94 const char kActiveBit[] = "active_bit";
96 // Path for settings specific to blacklist update.
97 const char kExtensionsBlacklistUpdate[] = "extensions.blacklistupdate";
99 // Path for the delayed install info dictionary preference. The actual string
100 // value is a legacy artifact for when delayed installs only pertained to
101 // updates that were waiting for idle.
102 const char kDelayedInstallInfo[] = "idle_install_info";
104 // Reason why the extension's install was delayed.
105 const char kDelayedInstallReason[] = "delay_install_reason";
107 // Path for the suggested page ordinal of a delayed extension install.
108 const char kPrefSuggestedPageOrdinal[] = "suggested_page_ordinal";
110 // A preference that, if true, will allow this extension to run in incognito
111 // mode.
112 const char kPrefIncognitoEnabled[] = "incognito";
114 // A preference to control whether an extension is allowed to inject script in
115 // pages with file URLs.
116 const char kPrefAllowFileAccess[] = "newAllowFileAccess";
117 // TODO(jstritar): As part of fixing http://crbug.com/91577, we revoked all
118 // extension file access by renaming the pref. We should eventually clean up
119 // the old flag and possibly go back to that name.
120 // const char kPrefAllowFileAccessOld[] = "allowFileAccess";
122 // A preference specifying if the user dragged the app on the NTP.
123 const char kPrefUserDraggedApp[] = "user_dragged_app_ntp";
125 // Preferences that hold which permissions the user has granted the extension.
126 // We explicitly keep track of these so that extensions can contain unknown
127 // permissions, for backwards compatibility reasons, and we can still prompt
128 // the user to accept them once recognized. We store the active permission
129 // permissions because they may differ from those defined in the manifest.
130 const char kPrefActivePermissions[] = "active_permissions";
131 const char kPrefGrantedPermissions[] = "granted_permissions";
133 // The preference names for PermissionSet values.
134 const char kPrefAPIs[] = "api";
135 const char kPrefManifestPermissions[] = "manifest_permissions";
136 const char kPrefExplicitHosts[] = "explicit_host";
137 const char kPrefScriptableHosts[] = "scriptable_host";
139 // The preference names for the old granted permissions scheme.
140 const char kPrefOldGrantedFullAccess[] = "granted_permissions.full";
141 const char kPrefOldGrantedHosts[] = "granted_permissions.host";
142 const char kPrefOldGrantedAPIs[] = "granted_permissions.api";
144 // A preference that indicates when an extension was installed.
145 const char kPrefInstallTime[] = "install_time";
147 // A preference which saves the creation flags for extensions.
148 const char kPrefCreationFlags[] = "creation_flags";
150 // A preference that indicates whether the extension was installed from the
151 // Chrome Web Store.
152 const char kPrefFromWebStore[] = "from_webstore";
154 // A preference that indicates whether the extension was installed from a
155 // mock App created from a bookmark.
156 const char kPrefFromBookmark[] = "from_bookmark";
158 // A preference that indicates whether the extension was installed as a
159 // default app.
160 const char kPrefWasInstalledByDefault[] = "was_installed_by_default";
162 // A preference that indicates whether the extension was installed as an
163 // OEM app.
164 const char kPrefWasInstalledByOem[] = "was_installed_by_oem";
166 // Key for Geometry Cache preference.
167 const char kPrefGeometryCache[] = "geometry_cache";
169 // A preference that indicates when an extension is last launched.
170 const char kPrefLastLaunchTime[] = "last_launch_time";
172 // A preference indicating whether the extension is an ephemeral app.
173 const char kPrefEphemeralApp[] = "ephemeral_app";
175 // Am installation parameter bundled with an extension.
176 const char kPrefInstallParam[] = "install_parameter";
178 // A list of installed ids and a signature.
179 const char kInstallSignature[] = "extensions.install_signature";
181 // A boolean preference that indicates whether the extension should not be
182 // synced. Default value is false.
183 const char kPrefDoNotSync[] = "do_not_sync";
185 const char kCorruptedDisableCount[] = "extensions.corrupted_disable_count";
187 // A boolean preference that indicates whether the extension has local changes
188 // that need to be synced. Default value is false.
189 const char kPrefNeedsSync[] = "needs_sync";
191 // Provider of write access to a dictionary storing extension prefs.
192 class ScopedExtensionPrefUpdate : public DictionaryPrefUpdate {
193 public:
194 ScopedExtensionPrefUpdate(PrefService* service,
195 const std::string& extension_id) :
196 DictionaryPrefUpdate(service, pref_names::kExtensions),
197 extension_id_(extension_id) {}
199 ~ScopedExtensionPrefUpdate() override {}
201 // DictionaryPrefUpdate overrides:
202 base::DictionaryValue* Get() override {
203 base::DictionaryValue* dict = DictionaryPrefUpdate::Get();
204 base::DictionaryValue* extension = NULL;
205 if (!dict->GetDictionary(extension_id_, &extension)) {
206 // Extension pref does not exist, create it.
207 extension = new base::DictionaryValue();
208 dict->SetWithoutPathExpansion(extension_id_, extension);
210 return extension;
213 private:
214 const std::string extension_id_;
216 DISALLOW_COPY_AND_ASSIGN(ScopedExtensionPrefUpdate);
219 std::string JoinPrefs(const std::string& parent, const char* child) {
220 return parent + "." + child;
223 // Checks if kPrefBlacklist is set to true in the base::DictionaryValue.
224 // Return false if the value is false or kPrefBlacklist does not exist.
225 // This is used to decide if an extension is blacklisted.
226 bool IsBlacklistBitSet(const base::DictionaryValue* ext) {
227 bool bool_value;
228 return ext->GetBoolean(kPrefBlacklist, &bool_value) && bool_value;
231 void LoadExtensionControlledPrefs(ExtensionPrefs* prefs,
232 ExtensionPrefValueMap* value_map,
233 const std::string& extension_id,
234 ExtensionPrefsScope scope) {
235 std::string scope_string;
236 if (!pref_names::ScopeToPrefName(scope, &scope_string))
237 return;
238 std::string key = extension_id + "." + scope_string;
240 const base::DictionaryValue* source_dict =
241 prefs->pref_service()->GetDictionary(pref_names::kExtensions);
242 const base::DictionaryValue* preferences = NULL;
243 if (!source_dict->GetDictionary(key, &preferences))
244 return;
246 for (base::DictionaryValue::Iterator iter(*preferences); !iter.IsAtEnd();
247 iter.Advance()) {
248 value_map->SetExtensionPref(
249 extension_id, iter.key(), scope, iter.value().DeepCopy());
253 } // namespace
256 // TimeProvider
259 ExtensionPrefs::TimeProvider::TimeProvider() {
262 ExtensionPrefs::TimeProvider::~TimeProvider() {
265 base::Time ExtensionPrefs::TimeProvider::GetCurrentTime() const {
266 return base::Time::Now();
270 // ScopedUpdate
272 template <typename T, base::Value::Type type_enum_value>
273 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::ScopedUpdate(
274 ExtensionPrefs* prefs,
275 const std::string& extension_id,
276 const std::string& key)
277 : update_(prefs->pref_service(), pref_names::kExtensions),
278 extension_id_(extension_id),
279 key_(key) {
280 DCHECK(crx_file::id_util::IdIsValid(extension_id_));
283 template <typename T, base::Value::Type type_enum_value>
284 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::~ScopedUpdate() {
287 template <typename T, base::Value::Type type_enum_value>
288 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Get() {
289 base::DictionaryValue* dict = update_.Get();
290 base::DictionaryValue* extension = NULL;
291 base::Value* key_value = NULL;
292 if (!dict->GetDictionary(extension_id_, &extension) ||
293 !extension->Get(key_, &key_value)) {
294 return NULL;
296 return key_value->GetType() == type_enum_value ?
297 static_cast<T*>(key_value) :
298 NULL;
301 template <typename T, base::Value::Type type_enum_value>
302 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Create() {
303 base::DictionaryValue* dict = update_.Get();
304 base::DictionaryValue* extension = NULL;
305 base::Value* key_value = NULL;
306 T* value_as_t = NULL;
307 if (!dict->GetDictionary(extension_id_, &extension)) {
308 extension = new base::DictionaryValue;
309 dict->SetWithoutPathExpansion(extension_id_, extension);
311 if (!extension->Get(key_, &key_value)) {
312 value_as_t = new T;
313 extension->SetWithoutPathExpansion(key_, value_as_t);
314 } else {
315 CHECK(key_value->GetType() == type_enum_value);
316 value_as_t = static_cast<T*>(key_value);
318 return value_as_t;
321 // Explicit instantiations for Dictionary and List value types.
322 template class ExtensionPrefs::ScopedUpdate<base::DictionaryValue,
323 base::Value::TYPE_DICTIONARY>;
324 template class ExtensionPrefs::ScopedUpdate<base::ListValue,
325 base::Value::TYPE_LIST>;
328 // ExtensionPrefs
331 // static
332 ExtensionPrefs* ExtensionPrefs::Create(
333 content::BrowserContext* browser_context,
334 PrefService* prefs,
335 const base::FilePath& root_dir,
336 ExtensionPrefValueMap* extension_pref_value_map,
337 bool extensions_disabled,
338 const std::vector<ExtensionPrefsObserver*>& early_observers) {
339 return ExtensionPrefs::Create(browser_context, prefs, root_dir,
340 extension_pref_value_map, extensions_disabled,
341 early_observers,
342 make_scoped_ptr(new TimeProvider()));
345 // static
346 ExtensionPrefs* ExtensionPrefs::Create(
347 content::BrowserContext* browser_context,
348 PrefService* pref_service,
349 const base::FilePath& root_dir,
350 ExtensionPrefValueMap* extension_pref_value_map,
351 bool extensions_disabled,
352 const std::vector<ExtensionPrefsObserver*>& early_observers,
353 scoped_ptr<TimeProvider> time_provider) {
354 return new ExtensionPrefs(browser_context, pref_service, root_dir,
355 extension_pref_value_map, time_provider.Pass(),
356 extensions_disabled, early_observers);
359 ExtensionPrefs::~ExtensionPrefs() {
362 // static
363 ExtensionPrefs* ExtensionPrefs::Get(content::BrowserContext* context) {
364 return ExtensionPrefsFactory::GetInstance()->GetForBrowserContext(context);
367 static base::FilePath::StringType MakePathRelative(const base::FilePath& parent,
368 const base::FilePath& child) {
369 if (!parent.IsParent(child))
370 return child.value();
372 base::FilePath::StringType retval = child.value().substr(
373 parent.value().length());
374 if (base::FilePath::IsSeparator(retval[0]))
375 return retval.substr(1);
376 else
377 return retval;
380 void ExtensionPrefs::MakePathsRelative() {
381 const base::DictionaryValue* dict =
382 prefs_->GetDictionary(pref_names::kExtensions);
383 if (!dict || dict->empty())
384 return;
386 // Collect all extensions ids with absolute paths in |absolute_keys|.
387 std::set<std::string> absolute_keys;
388 for (base::DictionaryValue::Iterator i(*dict); !i.IsAtEnd(); i.Advance()) {
389 const base::DictionaryValue* extension_dict = NULL;
390 if (!i.value().GetAsDictionary(&extension_dict))
391 continue;
392 int location_value;
393 if (extension_dict->GetInteger(kPrefLocation, &location_value) &&
394 Manifest::IsUnpackedLocation(
395 static_cast<Manifest::Location>(location_value))) {
396 // Unpacked extensions can have absolute paths.
397 continue;
399 base::FilePath::StringType path_string;
400 if (!extension_dict->GetString(kPrefPath, &path_string))
401 continue;
402 base::FilePath path(path_string);
403 if (path.IsAbsolute())
404 absolute_keys.insert(i.key());
406 if (absolute_keys.empty())
407 return;
409 // Fix these paths.
410 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
411 base::DictionaryValue* update_dict = update.Get();
412 for (std::set<std::string>::iterator i = absolute_keys.begin();
413 i != absolute_keys.end(); ++i) {
414 base::DictionaryValue* extension_dict = NULL;
415 if (!update_dict->GetDictionaryWithoutPathExpansion(*i, &extension_dict)) {
416 NOTREACHED() << "Control should never reach here for extension " << *i;
417 continue;
419 base::FilePath::StringType path_string;
420 extension_dict->GetString(kPrefPath, &path_string);
421 base::FilePath path(path_string);
422 extension_dict->SetString(kPrefPath,
423 MakePathRelative(install_directory_, path));
427 const base::DictionaryValue* ExtensionPrefs::GetExtensionPref(
428 const std::string& extension_id) const {
429 const base::DictionaryValue* extensions =
430 prefs_->GetDictionary(pref_names::kExtensions);
431 const base::DictionaryValue* extension_dict = NULL;
432 if (!extensions ||
433 !extensions->GetDictionary(extension_id, &extension_dict)) {
434 return NULL;
436 return extension_dict;
439 void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id,
440 const std::string& key,
441 base::Value* data_value) {
442 if (!crx_file::id_util::IdIsValid(extension_id)) {
443 NOTREACHED() << "Invalid extension_id " << extension_id;
444 return;
446 ScopedExtensionPrefUpdate update(prefs_, extension_id);
447 if (data_value)
448 update->Set(key, data_value);
449 else
450 update->Remove(key, NULL);
453 void ExtensionPrefs::DeleteExtensionPrefs(const std::string& extension_id) {
454 extension_pref_value_map_->UnregisterExtension(extension_id);
455 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
456 observer_list_,
457 OnExtensionPrefsDeleted(extension_id));
458 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
459 base::DictionaryValue* dict = update.Get();
460 dict->Remove(extension_id, NULL);
463 bool ExtensionPrefs::ReadPrefAsBoolean(const std::string& extension_id,
464 const std::string& pref_key,
465 bool* out_value) const {
466 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
467 if (!ext || !ext->GetBoolean(pref_key, out_value))
468 return false;
470 return true;
473 bool ExtensionPrefs::ReadPrefAsInteger(const std::string& extension_id,
474 const std::string& pref_key,
475 int* out_value) const {
476 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
477 if (!ext || !ext->GetInteger(pref_key, out_value))
478 return false;
480 return true;
483 bool ExtensionPrefs::ReadPrefAsString(const std::string& extension_id,
484 const std::string& pref_key,
485 std::string* out_value) const {
486 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
487 if (!ext || !ext->GetString(pref_key, out_value))
488 return false;
490 return true;
493 bool ExtensionPrefs::ReadPrefAsList(const std::string& extension_id,
494 const std::string& pref_key,
495 const base::ListValue** out_value) const {
496 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
497 const base::ListValue* out = NULL;
498 if (!ext || !ext->GetList(pref_key, &out))
499 return false;
500 if (out_value)
501 *out_value = out;
503 return true;
506 bool ExtensionPrefs::ReadPrefAsDictionary(
507 const std::string& extension_id,
508 const std::string& pref_key,
509 const base::DictionaryValue** out_value) const {
510 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
511 const base::DictionaryValue* out = NULL;
512 if (!ext || !ext->GetDictionary(pref_key, &out))
513 return false;
514 if (out_value)
515 *out_value = out;
517 return true;
520 bool ExtensionPrefs::HasPrefForExtension(
521 const std::string& extension_id) const {
522 return GetExtensionPref(extension_id) != NULL;
525 bool ExtensionPrefs::ReadPrefAsURLPatternSet(const std::string& extension_id,
526 const std::string& pref_key,
527 URLPatternSet* result,
528 int valid_schemes) const {
529 const base::ListValue* value = NULL;
530 if (!ReadPrefAsList(extension_id, pref_key, &value))
531 return false;
532 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
533 if (!extension)
534 return false;
535 int location;
536 if (extension->GetInteger(kPrefLocation, &location) &&
537 static_cast<Manifest::Location>(location) == Manifest::COMPONENT) {
538 valid_schemes |= URLPattern::SCHEME_CHROMEUI;
541 bool allow_file_access = AllowFileAccess(extension_id);
542 return result->Populate(*value, valid_schemes, allow_file_access, NULL);
545 void ExtensionPrefs::SetExtensionPrefURLPatternSet(
546 const std::string& extension_id,
547 const std::string& pref_key,
548 const URLPatternSet& new_value) {
549 UpdateExtensionPref(extension_id, pref_key, new_value.ToValue().release());
552 bool ExtensionPrefs::ReadPrefAsBooleanAndReturn(
553 const std::string& extension_id,
554 const std::string& pref_key) const {
555 bool out_value = false;
556 return ReadPrefAsBoolean(extension_id, pref_key, &out_value) && out_value;
559 PermissionSet* ExtensionPrefs::ReadPrefAsPermissionSet(
560 const std::string& extension_id,
561 const std::string& pref_key) const {
562 if (!GetExtensionPref(extension_id))
563 return NULL;
565 // Retrieve the API permissions. Please refer SetExtensionPrefPermissionSet()
566 // for api_values format.
567 APIPermissionSet apis;
568 const base::ListValue* api_values = NULL;
569 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
570 if (ReadPrefAsList(extension_id, api_pref, &api_values)) {
571 APIPermissionSet::ParseFromJSON(api_values,
572 APIPermissionSet::kAllowInternalPermissions,
573 &apis, NULL, NULL);
576 // Retrieve the Manifest Keys permissions. Please refer to
577 // |SetExtensionPrefPermissionSet| for manifest_permissions_values format.
578 ManifestPermissionSet manifest_permissions;
579 const base::ListValue* manifest_permissions_values = NULL;
580 std::string manifest_permission_pref =
581 JoinPrefs(pref_key, kPrefManifestPermissions);
582 if (ReadPrefAsList(extension_id, manifest_permission_pref,
583 &manifest_permissions_values)) {
584 ManifestPermissionSet::ParseFromJSON(
585 manifest_permissions_values, &manifest_permissions, NULL, NULL);
588 // Retrieve the explicit host permissions.
589 URLPatternSet explicit_hosts;
590 ReadPrefAsURLPatternSet(
591 extension_id, JoinPrefs(pref_key, kPrefExplicitHosts),
592 &explicit_hosts, Extension::kValidHostPermissionSchemes);
594 // Retrieve the scriptable host permissions.
595 URLPatternSet scriptable_hosts;
596 ReadPrefAsURLPatternSet(
597 extension_id, JoinPrefs(pref_key, kPrefScriptableHosts),
598 &scriptable_hosts, UserScript::ValidUserScriptSchemes());
600 return new PermissionSet(
601 apis, manifest_permissions, explicit_hosts, scriptable_hosts);
604 // Set the API or Manifest permissions.
605 // The format of api_values is:
606 // [ "permission_name1", // permissions do not support detail.
607 // "permission_name2",
608 // {"permission_name3": value },
609 // // permission supports detail, permission detail will be stored in value.
610 // ...
611 // ]
612 template<typename T>
613 static base::ListValue* CreatePermissionList(const T& permissions) {
614 base::ListValue* values = new base::ListValue();
615 for (typename T::const_iterator i = permissions.begin();
616 i != permissions.end(); ++i) {
617 scoped_ptr<base::Value> detail(i->ToValue());
618 if (detail) {
619 base::DictionaryValue* tmp = new base::DictionaryValue();
620 tmp->Set(i->name(), detail.release());
621 values->Append(tmp);
622 } else {
623 values->Append(new base::StringValue(i->name()));
626 return values;
629 void ExtensionPrefs::SetExtensionPrefPermissionSet(
630 const std::string& extension_id,
631 const std::string& pref_key,
632 const PermissionSet* new_value) {
633 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
634 base::ListValue* api_values = CreatePermissionList(new_value->apis());
635 UpdateExtensionPref(extension_id, api_pref, api_values);
637 std::string manifest_permissions_pref =
638 JoinPrefs(pref_key, kPrefManifestPermissions);
639 base::ListValue* manifest_permissions_values = CreatePermissionList(
640 new_value->manifest_permissions());
641 UpdateExtensionPref(extension_id,
642 manifest_permissions_pref,
643 manifest_permissions_values);
645 // Set the explicit host permissions.
646 if (!new_value->explicit_hosts().is_empty()) {
647 SetExtensionPrefURLPatternSet(extension_id,
648 JoinPrefs(pref_key, kPrefExplicitHosts),
649 new_value->explicit_hosts());
652 // Set the scriptable host permissions.
653 if (!new_value->scriptable_hosts().is_empty()) {
654 SetExtensionPrefURLPatternSet(extension_id,
655 JoinPrefs(pref_key, kPrefScriptableHosts),
656 new_value->scriptable_hosts());
660 int ExtensionPrefs::IncrementAcknowledgePromptCount(
661 const std::string& extension_id) {
662 int count = 0;
663 ReadPrefAsInteger(extension_id, kPrefAcknowledgePromptCount, &count);
664 ++count;
665 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount,
666 new base::FundamentalValue(count));
667 return count;
670 bool ExtensionPrefs::IsExternalExtensionAcknowledged(
671 const std::string& extension_id) const {
672 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalAcknowledged);
675 void ExtensionPrefs::AcknowledgeExternalExtension(
676 const std::string& extension_id) {
677 DCHECK(crx_file::id_util::IdIsValid(extension_id));
678 UpdateExtensionPref(extension_id, kPrefExternalAcknowledged,
679 new base::FundamentalValue(true));
680 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
683 bool ExtensionPrefs::IsBlacklistedExtensionAcknowledged(
684 const std::string& extension_id) const {
685 return ReadPrefAsBooleanAndReturn(extension_id, kPrefBlacklistAcknowledged);
688 void ExtensionPrefs::AcknowledgeBlacklistedExtension(
689 const std::string& extension_id) {
690 DCHECK(crx_file::id_util::IdIsValid(extension_id));
691 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged,
692 new base::FundamentalValue(true));
693 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
696 bool ExtensionPrefs::IsExternalInstallFirstRun(
697 const std::string& extension_id) const {
698 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalInstallFirstRun);
701 void ExtensionPrefs::SetExternalInstallFirstRun(
702 const std::string& extension_id) {
703 DCHECK(crx_file::id_util::IdIsValid(extension_id));
704 UpdateExtensionPref(extension_id, kPrefExternalInstallFirstRun,
705 new base::FundamentalValue(true));
708 bool ExtensionPrefs::SetAlertSystemFirstRun() {
709 if (prefs_->GetBoolean(pref_names::kAlertsInitialized)) {
710 return true;
712 prefs_->SetBoolean(pref_names::kAlertsInitialized, true);
713 return false;
716 bool ExtensionPrefs::DidExtensionEscalatePermissions(
717 const std::string& extension_id) const {
718 return HasDisableReason(extension_id,
719 Extension::DISABLE_PERMISSIONS_INCREASE) ||
720 HasDisableReason(extension_id, Extension::DISABLE_REMOTE_INSTALL);
723 int ExtensionPrefs::GetDisableReasons(const std::string& extension_id) const {
724 int value = -1;
725 if (ReadPrefAsInteger(extension_id, kPrefDisableReasons, &value) &&
726 value >= 0) {
727 return value;
729 return Extension::DISABLE_NONE;
732 bool ExtensionPrefs::HasDisableReason(
733 const std::string& extension_id,
734 Extension::DisableReason disable_reason) const {
735 return (GetDisableReasons(extension_id) & disable_reason) != 0;
738 void ExtensionPrefs::AddDisableReason(const std::string& extension_id,
739 Extension::DisableReason disable_reason) {
740 DCHECK(!DoesExtensionHaveState(extension_id, Extension::ENABLED));
741 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_ADD);
744 void ExtensionPrefs::AddDisableReasons(const std::string& extension_id,
745 int disable_reasons) {
746 DCHECK(!DoesExtensionHaveState(extension_id, Extension::ENABLED));
747 ModifyDisableReasons(extension_id, disable_reasons, DISABLE_REASON_ADD);
750 void ExtensionPrefs::RemoveDisableReason(
751 const std::string& extension_id,
752 Extension::DisableReason disable_reason) {
753 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_REMOVE);
756 void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) {
757 ModifyDisableReasons(extension_id, Extension::DISABLE_NONE,
758 DISABLE_REASON_CLEAR);
761 void ExtensionPrefs::ModifyDisableReasons(const std::string& extension_id,
762 int reasons,
763 DisableReasonChange change) {
764 int old_value = GetDisableReasons(extension_id);
765 int new_value = old_value;
766 switch (change) {
767 case DISABLE_REASON_ADD:
768 new_value |= reasons;
769 break;
770 case DISABLE_REASON_REMOVE:
771 new_value &= ~reasons;
772 break;
773 case DISABLE_REASON_CLEAR:
774 new_value = Extension::DISABLE_NONE;
775 break;
778 if (old_value == new_value) // no change, return.
779 return;
781 if (new_value == Extension::DISABLE_NONE) {
782 UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
783 } else {
784 UpdateExtensionPref(extension_id,
785 kPrefDisableReasons,
786 new base::FundamentalValue(new_value));
789 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
790 observer_list_,
791 OnExtensionDisableReasonsChanged(extension_id, new_value));
794 std::set<std::string> ExtensionPrefs::GetBlacklistedExtensions() const {
795 std::set<std::string> ids;
797 const base::DictionaryValue* extensions =
798 prefs_->GetDictionary(pref_names::kExtensions);
799 if (!extensions)
800 return ids;
802 for (base::DictionaryValue::Iterator it(*extensions);
803 !it.IsAtEnd(); it.Advance()) {
804 if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) {
805 NOTREACHED() << "Invalid pref for extension " << it.key();
806 continue;
808 if (IsBlacklistBitSet(
809 static_cast<const base::DictionaryValue*>(&it.value()))) {
810 ids.insert(it.key());
814 return ids;
817 void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id,
818 bool is_blacklisted) {
819 bool currently_blacklisted = IsExtensionBlacklisted(extension_id);
820 if (is_blacklisted == currently_blacklisted)
821 return;
823 // Always make sure the "acknowledged" bit is cleared since the blacklist bit
824 // is changing.
825 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL);
827 if (is_blacklisted) {
828 UpdateExtensionPref(extension_id,
829 kPrefBlacklist,
830 new base::FundamentalValue(true));
831 } else {
832 UpdateExtensionPref(extension_id, kPrefBlacklist, NULL);
833 const base::DictionaryValue* dict = GetExtensionPref(extension_id);
834 if (dict && dict->empty())
835 DeleteExtensionPrefs(extension_id);
839 bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const {
840 const base::DictionaryValue* ext_prefs = GetExtensionPref(id);
841 return ext_prefs && IsBlacklistBitSet(ext_prefs);
844 namespace {
846 // Serializes a 64bit integer as a string value.
847 void SaveInt64(base::DictionaryValue* dictionary,
848 const char* key,
849 const int64 value) {
850 if (!dictionary)
851 return;
853 std::string string_value = base::Int64ToString(value);
854 dictionary->SetString(key, string_value);
857 // Deserializes a 64bit integer stored as a string value.
858 bool ReadInt64(const base::DictionaryValue* dictionary,
859 const char* key,
860 int64* value) {
861 if (!dictionary)
862 return false;
864 std::string string_value;
865 if (!dictionary->GetString(key, &string_value))
866 return false;
868 return base::StringToInt64(string_value, value);
871 // Serializes |time| as a string value mapped to |key| in |dictionary|.
872 void SaveTime(base::DictionaryValue* dictionary,
873 const char* key,
874 const base::Time& time) {
875 SaveInt64(dictionary, key, time.ToInternalValue());
878 // The opposite of SaveTime. If |key| is not found, this returns an empty Time
879 // (is_null() will return true).
880 base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) {
881 int64 value;
882 if (ReadInt64(dictionary, key, &value))
883 return base::Time::FromInternalValue(value);
885 return base::Time();
888 } // namespace
890 base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const {
891 DCHECK(crx_file::id_util::IdIsValid(extension_id));
892 return ReadTime(GetExtensionPref(extension_id), kLastPingDay);
895 void ExtensionPrefs::SetLastPingDay(const std::string& extension_id,
896 const base::Time& time) {
897 DCHECK(crx_file::id_util::IdIsValid(extension_id));
898 ScopedExtensionPrefUpdate update(prefs_, extension_id);
899 SaveTime(update.Get(), kLastPingDay, time);
902 base::Time ExtensionPrefs::BlacklistLastPingDay() const {
903 return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate),
904 kLastPingDay);
907 void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) {
908 DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate);
909 SaveTime(update.Get(), kLastPingDay, time);
912 base::Time ExtensionPrefs::LastActivePingDay(
913 const std::string& extension_id) const {
914 DCHECK(crx_file::id_util::IdIsValid(extension_id));
915 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
918 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
919 const base::Time& time) {
920 DCHECK(crx_file::id_util::IdIsValid(extension_id));
921 ScopedExtensionPrefUpdate update(prefs_, extension_id);
922 SaveTime(update.Get(), kLastActivePingDay, time);
925 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) const {
926 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
927 bool result = false;
928 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
929 return result;
930 return false;
933 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
934 bool active) {
935 UpdateExtensionPref(extension_id, kActiveBit,
936 new base::FundamentalValue(active));
939 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
940 PermissionsInfo* info = PermissionsInfo::GetInstance();
941 for (ExtensionIdList::const_iterator ext_id =
942 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
943 // An extension's granted permissions need to be migrated if the
944 // full_access bit is present. This bit was always present in the previous
945 // scheme and is never present now.
946 bool full_access = false;
947 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
948 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
949 continue;
951 // Remove the full access bit (empty list will get trimmed).
952 UpdateExtensionPref(
953 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
955 // Add the plugin permission if the full access bit was set.
956 if (full_access) {
957 const base::ListValue* apis = NULL;
958 base::ListValue* new_apis = NULL;
960 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
961 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
962 new_apis = apis->DeepCopy();
963 else
964 new_apis = new base::ListValue();
966 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
967 new_apis->Append(new base::StringValue(plugin_name));
968 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
971 // The granted permissions originally only held the effective hosts,
972 // which are a combination of host and user script host permissions.
973 // We now maintain these lists separately. For migration purposes, it
974 // does not matter how we treat the old effective hosts as long as the
975 // new effective hosts will be the same, so we move them to explicit
976 // host permissions.
977 const base::ListValue* hosts = NULL;
978 std::string explicit_hosts =
979 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
980 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
981 UpdateExtensionPref(
982 *ext_id, explicit_hosts, hosts->DeepCopy());
984 // We can get rid of the old one by setting it to an empty list.
985 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
990 void ExtensionPrefs::MigrateDisableReasons(
991 const ExtensionIdList& extension_ids) {
992 for (ExtensionIdList::const_iterator ext_id =
993 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
994 int value = -1;
995 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
996 int new_value = Extension::DISABLE_NONE;
997 switch (value) {
998 case Extension::DEPRECATED_DISABLE_USER_ACTION:
999 new_value = Extension::DISABLE_USER_ACTION;
1000 break;
1001 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
1002 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
1003 break;
1004 case Extension::DEPRECATED_DISABLE_RELOAD:
1005 new_value = Extension::DISABLE_RELOAD;
1006 break;
1009 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
1010 new base::FundamentalValue(new_value));
1011 // Remove the old disable reason.
1012 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
1017 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
1018 const std::string& extension_id) const {
1019 CHECK(crx_file::id_util::IdIsValid(extension_id));
1020 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
1023 void ExtensionPrefs::AddGrantedPermissions(
1024 const std::string& extension_id,
1025 const PermissionSet* permissions) {
1026 CHECK(crx_file::id_util::IdIsValid(extension_id));
1028 scoped_refptr<PermissionSet> granted_permissions(
1029 GetGrantedPermissions(extension_id));
1031 // The new granted permissions are the union of the already granted
1032 // permissions and the newly granted permissions.
1033 scoped_refptr<PermissionSet> new_perms(
1034 PermissionSet::CreateUnion(
1035 permissions, granted_permissions.get()));
1037 SetExtensionPrefPermissionSet(
1038 extension_id, kPrefGrantedPermissions, new_perms.get());
1041 void ExtensionPrefs::RemoveGrantedPermissions(
1042 const std::string& extension_id,
1043 const PermissionSet* permissions) {
1044 CHECK(crx_file::id_util::IdIsValid(extension_id));
1046 scoped_refptr<PermissionSet> granted_permissions(
1047 GetGrantedPermissions(extension_id));
1049 // The new granted permissions are the difference of the already granted
1050 // permissions and the newly ungranted permissions.
1051 scoped_refptr<PermissionSet> new_perms(
1052 PermissionSet::CreateDifference(
1053 granted_permissions.get(), permissions));
1055 SetExtensionPrefPermissionSet(
1056 extension_id, kPrefGrantedPermissions, new_perms.get());
1059 PermissionSet* ExtensionPrefs::GetActivePermissions(
1060 const std::string& extension_id) const {
1061 CHECK(crx_file::id_util::IdIsValid(extension_id));
1062 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
1065 void ExtensionPrefs::SetActivePermissions(
1066 const std::string& extension_id,
1067 const PermissionSet* permissions) {
1068 SetExtensionPrefPermissionSet(
1069 extension_id, kPrefActivePermissions, permissions);
1072 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1073 bool is_running) {
1074 base::Value* value = new base::FundamentalValue(is_running);
1075 UpdateExtensionPref(extension_id, kPrefRunning, value);
1078 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) const {
1079 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1080 if (!extension)
1081 return false;
1082 bool running = false;
1083 extension->GetBoolean(kPrefRunning, &running);
1084 return running;
1087 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1088 bool is_active) {
1089 base::Value* value = new base::FundamentalValue(is_active);
1090 UpdateExtensionPref(extension_id, kIsActive, value);
1093 bool ExtensionPrefs::IsActive(const std::string& extension_id) const {
1094 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1095 if (!extension)
1096 return false;
1097 bool is_active = false;
1098 extension->GetBoolean(kIsActive, &is_active);
1099 return is_active;
1102 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1103 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1106 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1107 bool enabled) {
1108 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1109 new base::FundamentalValue(enabled));
1110 extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled);
1113 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1114 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1117 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1118 bool allow) {
1119 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1120 new base::FundamentalValue(allow));
1123 bool ExtensionPrefs::HasAllowFileAccessSetting(
1124 const std::string& extension_id) const {
1125 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1126 return ext && ext->HasKey(kPrefAllowFileAccess);
1129 bool ExtensionPrefs::DoesExtensionHaveState(
1130 const std::string& id, Extension::State check_state) const {
1131 const base::DictionaryValue* extension = GetExtensionPref(id);
1132 int state = -1;
1133 if (!extension || !extension->GetInteger(kPrefState, &state))
1134 return false;
1136 if (state < 0 || state >= Extension::NUM_STATES) {
1137 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1138 return false;
1141 return state == check_state;
1144 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1145 const std::string& id) const {
1146 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1149 bool ExtensionPrefs::IsExtensionDisabled(const std::string& id) const {
1150 return DoesExtensionHaveState(id, Extension::DISABLED);
1153 ExtensionIdList ExtensionPrefs::GetToolbarOrder() const {
1154 ExtensionIdList id_list_out;
1155 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1156 return id_list_out;
1159 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1160 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1163 void ExtensionPrefs::OnExtensionInstalled(
1164 const Extension* extension,
1165 Extension::State initial_state,
1166 const syncer::StringOrdinal& page_ordinal,
1167 int install_flags,
1168 const std::string& install_parameter) {
1169 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1170 base::DictionaryValue* extension_dict = update.Get();
1171 const base::Time install_time = time_provider_->GetCurrentTime();
1172 PopulateExtensionInfoPrefs(extension,
1173 install_time,
1174 initial_state,
1175 install_flags,
1176 install_parameter,
1177 extension_dict);
1179 bool requires_sort_ordinal = extension->RequiresSortOrdinal() &&
1180 (install_flags & kInstallFlagIsEphemeral) == 0;
1181 FinishExtensionInfoPrefs(extension->id(),
1182 install_time,
1183 requires_sort_ordinal,
1184 page_ordinal,
1185 extension_dict);
1188 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1189 const Manifest::Location& location,
1190 bool external_uninstall) {
1191 app_sorting()->ClearOrdinals(extension_id);
1193 // For external extensions, we save a preference reminding ourself not to try
1194 // and install the extension anymore (except when |external_uninstall| is
1195 // true, which signifies that the registry key was deleted or the pref file
1196 // no longer lists the extension).
1197 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1198 UpdateExtensionPref(extension_id, kPrefState,
1199 new base::FundamentalValue(
1200 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1201 extension_pref_value_map_->SetExtensionState(extension_id, false);
1202 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1203 observer_list_,
1204 OnExtensionStateChanged(extension_id, false));
1205 } else {
1206 DeleteExtensionPrefs(extension_id);
1210 void ExtensionPrefs::SetExtensionEnabled(const std::string& extension_id) {
1211 UpdateExtensionPref(extension_id, kPrefState,
1212 new base::FundamentalValue(Extension::ENABLED));
1213 extension_pref_value_map_->SetExtensionState(extension_id, true);
1214 UpdateExtensionPref(extension_id, kPrefDisableReasons, nullptr);
1215 FOR_EACH_OBSERVER(ExtensionPrefsObserver, observer_list_,
1216 OnExtensionStateChanged(extension_id, true));
1219 void ExtensionPrefs::SetExtensionDisabled(const std::string& extension_id,
1220 int disable_reasons) {
1221 if (!IsExternalExtensionUninstalled(extension_id)) {
1222 UpdateExtensionPref(extension_id, kPrefState,
1223 new base::FundamentalValue(Extension::DISABLED));
1224 extension_pref_value_map_->SetExtensionState(extension_id, false);
1226 UpdateExtensionPref(extension_id, kPrefDisableReasons,
1227 new base::FundamentalValue(disable_reasons));
1228 FOR_EACH_OBSERVER(ExtensionPrefsObserver, observer_list_,
1229 OnExtensionStateChanged(extension_id, false));
1232 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1233 BlacklistState state) {
1234 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1235 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1236 new base::FundamentalValue(state));
1239 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1240 const std::string& extension_id) const {
1241 if (IsExtensionBlacklisted(extension_id))
1242 return BLACKLISTED_MALWARE;
1243 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1244 int int_value = 0;
1245 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1246 return static_cast<BlacklistState>(int_value);
1248 return NOT_BLACKLISTED;
1251 std::string ExtensionPrefs::GetVersionString(
1252 const std::string& extension_id) const {
1253 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1254 if (!extension)
1255 return std::string();
1257 std::string version;
1258 extension->GetString(kPrefVersion, &version);
1260 return version;
1263 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1264 if (!Manifest::IsUnpackedLocation(extension->location())) {
1265 const base::DictionaryValue* extension_dict =
1266 GetExtensionPref(extension->id());
1267 if (!extension_dict)
1268 return;
1269 const base::DictionaryValue* old_manifest = NULL;
1270 bool update_required =
1271 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1272 !extension->manifest()->value()->Equals(old_manifest);
1273 if (update_required) {
1274 UpdateExtensionPref(extension->id(), kPrefManifest,
1275 extension->manifest()->value()->DeepCopy());
1280 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1281 const std::string& extension_id,
1282 const base::DictionaryValue* extension) const {
1283 int location_value;
1284 if (!extension->GetInteger(kPrefLocation, &location_value))
1285 return scoped_ptr<ExtensionInfo>();
1287 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1288 if (location == Manifest::COMPONENT) {
1289 // Component extensions are ignored. Component extensions may have data
1290 // saved in preferences, but they are already loaded at this point (by
1291 // ComponentLoader) and shouldn't be populated into the result of
1292 // GetInstalledExtensionsInfo, otherwise InstalledLoader would also want to
1293 // load them.
1294 return scoped_ptr<ExtensionInfo>();
1297 // Only the following extension types have data saved in the preferences.
1298 if (location != Manifest::INTERNAL &&
1299 !Manifest::IsUnpackedLocation(location) &&
1300 !Manifest::IsExternalLocation(location)) {
1301 NOTREACHED();
1302 return scoped_ptr<ExtensionInfo>();
1305 const base::DictionaryValue* manifest = NULL;
1306 if (!Manifest::IsUnpackedLocation(location) &&
1307 !extension->GetDictionary(kPrefManifest, &manifest)) {
1308 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1309 // Just a warning for now.
1312 base::FilePath::StringType path;
1313 if (!extension->GetString(kPrefPath, &path))
1314 return scoped_ptr<ExtensionInfo>();
1316 // Make path absolute. Most (but not all) extension types have relative paths.
1317 if (!base::FilePath(path).IsAbsolute())
1318 path = install_directory_.Append(path).value();
1320 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1321 manifest, extension_id, base::FilePath(path), location));
1324 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1325 const std::string& extension_id) const {
1326 const base::DictionaryValue* ext = NULL;
1327 const base::DictionaryValue* extensions =
1328 prefs_->GetDictionary(pref_names::kExtensions);
1329 if (!extensions ||
1330 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1331 return scoped_ptr<ExtensionInfo>();
1332 int state_value;
1333 if (ext->GetInteger(kPrefState, &state_value) &&
1334 state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1335 LOG(WARNING) << "External extension with id " << extension_id
1336 << " has been uninstalled by the user";
1337 return scoped_ptr<ExtensionInfo>();
1340 return GetInstalledInfoHelper(extension_id, ext);
1343 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1344 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1345 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1347 const base::DictionaryValue* extensions =
1348 prefs_->GetDictionary(pref_names::kExtensions);
1349 for (base::DictionaryValue::Iterator extension_id(*extensions);
1350 !extension_id.IsAtEnd(); extension_id.Advance()) {
1351 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1352 continue;
1354 scoped_ptr<ExtensionInfo> info =
1355 GetInstalledExtensionInfo(extension_id.key());
1356 if (info)
1357 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1360 return extensions_info.Pass();
1363 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1364 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1365 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1367 const base::DictionaryValue* extensions =
1368 prefs_->GetDictionary(pref_names::kExtensions);
1369 for (base::DictionaryValue::Iterator extension_id(*extensions);
1370 !extension_id.IsAtEnd(); extension_id.Advance()) {
1371 const base::DictionaryValue* ext = NULL;
1372 if (!crx_file::id_util::IdIsValid(extension_id.key()) ||
1373 !IsExternalExtensionUninstalled(extension_id.key()) ||
1374 !extension_id.value().GetAsDictionary(&ext))
1375 continue;
1377 scoped_ptr<ExtensionInfo> info =
1378 GetInstalledInfoHelper(extension_id.key(), ext);
1379 if (info)
1380 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1383 return extensions_info.Pass();
1386 void ExtensionPrefs::SetDelayedInstallInfo(
1387 const Extension* extension,
1388 Extension::State initial_state,
1389 int install_flags,
1390 DelayReason delay_reason,
1391 const syncer::StringOrdinal& page_ordinal,
1392 const std::string& install_parameter) {
1393 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1394 PopulateExtensionInfoPrefs(extension,
1395 time_provider_->GetCurrentTime(),
1396 initial_state,
1397 install_flags,
1398 install_parameter,
1399 extension_dict);
1401 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1402 // should not be in the final extension prefs. All entries here should have
1403 // a corresponding Remove() call in FinishDelayedInstallInfo().
1404 if (extension->RequiresSortOrdinal() &&
1405 (install_flags & kInstallFlagIsEphemeral) == 0) {
1406 extension_dict->SetString(
1407 kPrefSuggestedPageOrdinal,
1408 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1409 : std::string());
1411 extension_dict->SetInteger(kDelayedInstallReason,
1412 static_cast<int>(delay_reason));
1414 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1417 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1418 const std::string& extension_id) {
1419 if (!GetExtensionPref(extension_id))
1420 return false;
1421 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1422 bool result = update->Remove(kDelayedInstallInfo, NULL);
1423 return result;
1426 bool ExtensionPrefs::FinishDelayedInstallInfo(
1427 const std::string& extension_id) {
1428 CHECK(crx_file::id_util::IdIsValid(extension_id));
1429 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1430 base::DictionaryValue* extension_dict = update.Get();
1431 base::DictionaryValue* pending_install_dict = NULL;
1432 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1433 &pending_install_dict)) {
1434 return false;
1437 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1438 // Also do any other data cleanup that makes sense.
1439 std::string serialized_ordinal;
1440 syncer::StringOrdinal suggested_page_ordinal;
1441 bool needs_sort_ordinal = false;
1442 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1443 &serialized_ordinal)) {
1444 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1445 needs_sort_ordinal = true;
1446 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1448 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1450 const base::Time install_time = time_provider_->GetCurrentTime();
1451 pending_install_dict->Set(
1452 kPrefInstallTime,
1453 new base::StringValue(
1454 base::Int64ToString(install_time.ToInternalValue())));
1456 // Some extension pref values are written conditionally. If they are not
1457 // present in the delayed install data, they should be removed when the
1458 // delayed install is committed.
1459 extension_dict->Remove(kPrefEphemeralApp, NULL);
1461 // Commit the delayed install data.
1462 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1463 it.Advance()) {
1464 extension_dict->Set(it.key(), it.value().DeepCopy());
1466 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1467 suggested_page_ordinal, extension_dict);
1468 return true;
1471 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1472 const std::string& extension_id) const {
1473 const base::DictionaryValue* extension_prefs =
1474 GetExtensionPref(extension_id);
1475 if (!extension_prefs)
1476 return scoped_ptr<ExtensionInfo>();
1478 const base::DictionaryValue* ext = NULL;
1479 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1480 return scoped_ptr<ExtensionInfo>();
1482 return GetInstalledInfoHelper(extension_id, ext);
1485 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1486 const std::string& extension_id) const {
1487 const base::DictionaryValue* extension_prefs =
1488 GetExtensionPref(extension_id);
1489 if (!extension_prefs)
1490 return DELAY_REASON_NONE;
1492 const base::DictionaryValue* ext = NULL;
1493 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1494 return DELAY_REASON_NONE;
1496 int delay_reason;
1497 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1498 return DELAY_REASON_NONE;
1500 return static_cast<DelayReason>(delay_reason);
1503 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1504 GetAllDelayedInstallInfo() const {
1505 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1507 const base::DictionaryValue* extensions =
1508 prefs_->GetDictionary(pref_names::kExtensions);
1509 for (base::DictionaryValue::Iterator extension_id(*extensions);
1510 !extension_id.IsAtEnd(); extension_id.Advance()) {
1511 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1512 continue;
1514 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1515 if (info)
1516 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1519 return extensions_info.Pass();
1522 bool ExtensionPrefs::IsEphemeralApp(const std::string& extension_id) const {
1523 if (ReadPrefAsBooleanAndReturn(extension_id, kPrefEphemeralApp))
1524 return true;
1526 // Ephemerality was previously stored in the creation flags, so we must also
1527 // check it for backcompatibility.
1528 return (GetCreationFlags(extension_id) & Extension::IS_EPHEMERAL) != 0;
1531 void ExtensionPrefs::OnEphemeralAppPromoted(const std::string& extension_id) {
1532 DCHECK(IsEphemeralApp(extension_id));
1534 UpdateExtensionPref(extension_id, kPrefEphemeralApp, NULL);
1536 // Ephemerality was previously stored in the creation flags, so ensure the bit
1537 // is cleared.
1538 int creation_flags = Extension::NO_FLAGS;
1539 if (ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1540 if (creation_flags & Extension::IS_EPHEMERAL) {
1541 creation_flags &= ~static_cast<int>(Extension::IS_EPHEMERAL);
1542 UpdateExtensionPref(extension_id,
1543 kPrefCreationFlags,
1544 new base::FundamentalValue(creation_flags));
1549 bool ExtensionPrefs::WasAppDraggedByUser(
1550 const std::string& extension_id) const {
1551 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1554 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1555 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1556 new base::FundamentalValue(true));
1559 bool ExtensionPrefs::IsFromWebStore(
1560 const std::string& extension_id) const {
1561 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1562 bool result = false;
1563 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1564 return result;
1565 return false;
1568 bool ExtensionPrefs::IsFromBookmark(
1569 const std::string& extension_id) const {
1570 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1571 bool result = false;
1572 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1573 return result;
1574 return false;
1577 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1578 int creation_flags = Extension::NO_FLAGS;
1579 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1580 // Since kPrefCreationFlags was added later, it will be missing for
1581 // previously installed extensions.
1582 if (IsFromBookmark(extension_id))
1583 creation_flags |= Extension::FROM_BOOKMARK;
1584 if (IsFromWebStore(extension_id))
1585 creation_flags |= Extension::FROM_WEBSTORE;
1586 if (WasInstalledByDefault(extension_id))
1587 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1588 if (WasInstalledByOem(extension_id))
1589 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
1591 return creation_flags;
1594 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1595 const std::string& extension_id) const {
1596 int creation_flags = Extension::NO_FLAGS;
1597 const base::DictionaryValue* delayed_info = NULL;
1598 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1599 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1601 return creation_flags;
1604 bool ExtensionPrefs::WasInstalledByDefault(
1605 const std::string& extension_id) const {
1606 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1607 bool result = false;
1608 if (dictionary &&
1609 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1610 return result;
1611 return false;
1614 bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const {
1615 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1616 bool result = false;
1617 if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result))
1618 return result;
1619 return false;
1622 base::Time ExtensionPrefs::GetInstallTime(
1623 const std::string& extension_id) const {
1624 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1625 if (!extension) {
1626 NOTREACHED();
1627 return base::Time();
1629 std::string install_time_str;
1630 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1631 return base::Time();
1632 int64 install_time_i64 = 0;
1633 if (!base::StringToInt64(install_time_str, &install_time_i64))
1634 return base::Time();
1635 return base::Time::FromInternalValue(install_time_i64);
1638 bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const {
1639 bool do_not_sync;
1640 if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync))
1641 return false;
1643 return do_not_sync;
1646 base::Time ExtensionPrefs::GetLastLaunchTime(
1647 const std::string& extension_id) const {
1648 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1649 if (!extension)
1650 return base::Time();
1652 std::string launch_time_str;
1653 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1654 return base::Time();
1655 int64 launch_time_i64 = 0;
1656 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1657 return base::Time();
1658 return base::Time::FromInternalValue(launch_time_i64);
1661 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1662 const base::Time& time) {
1663 DCHECK(crx_file::id_util::IdIsValid(extension_id));
1664 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1665 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1668 void ExtensionPrefs::ClearLastLaunchTimes() {
1669 const base::DictionaryValue* dict =
1670 prefs_->GetDictionary(pref_names::kExtensions);
1671 if (!dict || dict->empty())
1672 return;
1674 // Collect all the keys to remove the last launched preference from.
1675 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
1676 base::DictionaryValue* update_dict = update.Get();
1677 for (base::DictionaryValue::Iterator i(*update_dict); !i.IsAtEnd();
1678 i.Advance()) {
1679 base::DictionaryValue* extension_dict = NULL;
1680 if (!update_dict->GetDictionary(i.key(), &extension_dict))
1681 continue;
1683 if (extension_dict->HasKey(kPrefLastLaunchTime))
1684 extension_dict->Remove(kPrefLastLaunchTime, NULL);
1688 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) const {
1689 CHECK(out);
1691 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1693 for (size_t i = 0; i < extensions_info->size(); ++i) {
1694 ExtensionInfo* info = extensions_info->at(i).get();
1695 out->push_back(info->extension_id);
1699 // static
1700 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1701 const PrefService* pref_service) {
1702 ExtensionIdList result;
1704 const base::DictionaryValue* extension_prefs = NULL;
1705 const base::Value* extension_prefs_value =
1706 pref_service->GetUserPrefValue(pref_names::kExtensions);
1707 if (!extension_prefs_value ||
1708 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1709 return result; // Empty set
1712 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1713 it.Advance()) {
1714 const base::DictionaryValue* ext = NULL;
1715 if (!it.value().GetAsDictionary(&ext)) {
1716 NOTREACHED() << "Invalid pref for extension " << it.key();
1717 continue;
1719 if (!IsBlacklistBitSet(ext))
1720 result.push_back(it.key());
1722 return result;
1725 void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) {
1726 observer_list_.AddObserver(observer);
1729 void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) {
1730 observer_list_.RemoveObserver(observer);
1733 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1734 // Fix old entries that did not get an installation time entry when they
1735 // were installed or don't have a preferences field.
1736 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1737 ext_id != extension_ids.end(); ++ext_id) {
1738 if (GetInstallTime(*ext_id) == base::Time()) {
1739 VLOG(1) << "Could not parse installation time of extension "
1740 << *ext_id << ". It was probably installed before setting "
1741 << kPrefInstallTime << " was introduced. Updating "
1742 << kPrefInstallTime << " to the current time.";
1743 const base::Time install_time = time_provider_->GetCurrentTime();
1744 UpdateExtensionPref(*ext_id,
1745 kPrefInstallTime,
1746 new base::StringValue(base::Int64ToString(
1747 install_time.ToInternalValue())));
1752 void ExtensionPrefs::InitPrefStore() {
1753 TRACE_EVENT0("browser,startup", "ExtensionPrefs::InitPrefStore")
1754 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefStoreTime");
1756 if (extensions_disabled_) {
1757 extension_pref_value_map_->NotifyInitializationCompleted();
1758 return;
1761 // When this is called, the PrefService is initialized and provides access
1762 // to the user preferences stored in a JSON file.
1763 ExtensionIdList extension_ids;
1765 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefGetExtensionsTime");
1766 GetExtensions(&extension_ids);
1768 // Create empty preferences dictionary for each extension (these dictionaries
1769 // are pruned when persisting the preferences to disk).
1770 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1771 ext_id != extension_ids.end(); ++ext_id) {
1772 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1773 // This creates an empty dictionary if none is stored.
1774 update.Get();
1777 FixMissingPrefs(extension_ids);
1778 MigratePermissions(extension_ids);
1779 MigrateDisableReasons(extension_ids);
1781 InitExtensionControlledPrefs(extension_pref_value_map_);
1783 extension_pref_value_map_->NotifyInitializationCompleted();
1786 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) const {
1787 bool has_incognito_pref_value = false;
1788 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1789 true,
1790 &has_incognito_pref_value);
1791 return has_incognito_pref_value;
1794 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1795 const std::string& extension_id) const {
1796 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1797 if (!extension_prefs)
1798 return NULL;
1800 const base::DictionaryValue* ext = NULL;
1801 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1802 return NULL;
1804 return ext;
1807 void ExtensionPrefs::SetGeometryCache(
1808 const std::string& extension_id,
1809 scoped_ptr<base::DictionaryValue> cache) {
1810 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1813 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() const {
1814 return prefs_->GetDictionary(kInstallSignature);
1817 void ExtensionPrefs::SetInstallSignature(
1818 const base::DictionaryValue* signature) {
1819 if (signature) {
1820 prefs_->Set(kInstallSignature, *signature);
1821 DVLOG(1) << "SetInstallSignature - saving";
1822 } else {
1823 DVLOG(1) << "SetInstallSignature - clearing";
1824 prefs_->ClearPref(kInstallSignature);
1828 std::string ExtensionPrefs::GetInstallParam(
1829 const std::string& extension_id) const {
1830 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1831 if (!extension) // Expected during unit testing.
1832 return std::string();
1833 std::string install_parameter;
1834 if (!extension->GetString(kPrefInstallParam, &install_parameter))
1835 return std::string();
1836 return install_parameter;
1839 void ExtensionPrefs::SetInstallParam(const std::string& extension_id,
1840 const std::string& install_parameter) {
1841 UpdateExtensionPref(extension_id,
1842 kPrefInstallParam,
1843 new base::StringValue(install_parameter));
1846 int ExtensionPrefs::GetCorruptedDisableCount() const {
1847 return prefs_->GetInteger(kCorruptedDisableCount);
1850 void ExtensionPrefs::IncrementCorruptedDisableCount() {
1851 int count = prefs_->GetInteger(kCorruptedDisableCount);
1852 prefs_->SetInteger(kCorruptedDisableCount, count + 1);
1855 bool ExtensionPrefs::NeedsSync(const std::string& extension_id) const {
1856 return ReadPrefAsBooleanAndReturn(extension_id, kPrefNeedsSync);
1859 void ExtensionPrefs::SetNeedsSync(const std::string& extension_id,
1860 bool needs_sync) {
1861 UpdateExtensionPref(extension_id, kPrefNeedsSync,
1862 needs_sync ? new base::FundamentalValue(true) : nullptr);
1865 ExtensionPrefs::ExtensionPrefs(
1866 content::BrowserContext* browser_context,
1867 PrefService* prefs,
1868 const base::FilePath& root_dir,
1869 ExtensionPrefValueMap* extension_pref_value_map,
1870 scoped_ptr<TimeProvider> time_provider,
1871 bool extensions_disabled,
1872 const std::vector<ExtensionPrefsObserver*>& early_observers)
1873 : browser_context_(browser_context),
1874 prefs_(prefs),
1875 install_directory_(root_dir),
1876 extension_pref_value_map_(extension_pref_value_map),
1877 time_provider_(time_provider.Pass()),
1878 extensions_disabled_(extensions_disabled) {
1879 MakePathsRelative();
1881 // Ensure that any early observers are watching before prefs are initialized.
1882 for (std::vector<ExtensionPrefsObserver*>::const_iterator iter =
1883 early_observers.begin();
1884 iter != early_observers.end();
1885 ++iter) {
1886 AddObserver(*iter);
1889 InitPrefStore();
1892 AppSorting* ExtensionPrefs::app_sorting() const {
1893 return ExtensionSystem::Get(browser_context_)->app_sorting();
1896 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1897 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1900 bool ExtensionPrefs::NeedsStorageGarbageCollection() const {
1901 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1904 // static
1905 void ExtensionPrefs::RegisterProfilePrefs(
1906 user_prefs::PrefRegistrySyncable* registry) {
1907 registry->RegisterDictionaryPref(pref_names::kExtensions);
1908 registry->RegisterListPref(pref_names::kToolbar,
1909 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1910 registry->RegisterIntegerPref(pref_names::kToolbarSize, -1);
1911 registry->RegisterDictionaryPref(kExtensionsBlacklistUpdate);
1912 registry->RegisterListPref(pref_names::kInstallAllowList);
1913 registry->RegisterListPref(pref_names::kInstallDenyList);
1914 registry->RegisterDictionaryPref(pref_names::kInstallForceList);
1915 registry->RegisterListPref(pref_names::kAllowedTypes);
1916 registry->RegisterBooleanPref(pref_names::kStorageGarbageCollect, false);
1917 registry->RegisterInt64Pref(pref_names::kLastUpdateCheck, 0);
1918 registry->RegisterInt64Pref(pref_names::kNextUpdateCheck, 0);
1919 registry->RegisterListPref(pref_names::kAllowedInstallSites);
1920 registry->RegisterStringPref(pref_names::kLastChromeVersion, std::string());
1921 registry->RegisterDictionaryPref(kInstallSignature);
1923 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist);
1924 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist);
1925 registry->RegisterBooleanPref(pref_names::kNativeMessagingUserLevelHosts,
1926 true);
1927 registry->RegisterIntegerPref(kCorruptedDisableCount, 0);
1929 #if !defined(OS_MACOSX)
1930 registry->RegisterBooleanPref(pref_names::kAppFullscreenAllowed, true);
1931 #endif
1934 template <class ExtensionIdContainer>
1935 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
1936 const char* pref,
1937 ExtensionIdContainer* id_container_out) const {
1938 DCHECK(id_container_out->empty());
1940 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
1941 const base::ListValue* user_pref_as_list;
1942 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
1943 return false;
1945 std::insert_iterator<ExtensionIdContainer> insert_iterator(
1946 *id_container_out, id_container_out->end());
1947 std::string extension_id;
1948 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
1949 value_it != user_pref_as_list->end(); ++value_it) {
1950 if (!(*value_it)->GetAsString(&extension_id)) {
1951 NOTREACHED();
1952 continue;
1954 insert_iterator = extension_id;
1956 return true;
1959 template <class ExtensionIdContainer>
1960 void ExtensionPrefs::SetExtensionPrefFromContainer(
1961 const char* pref,
1962 const ExtensionIdContainer& strings) {
1963 ListPrefUpdate update(prefs_, pref);
1964 base::ListValue* list_of_values = update.Get();
1965 list_of_values->Clear();
1966 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
1967 iter != strings.end(); ++iter) {
1968 list_of_values->Append(new base::StringValue(*iter));
1972 void ExtensionPrefs::PopulateExtensionInfoPrefs(
1973 const Extension* extension,
1974 const base::Time install_time,
1975 Extension::State initial_state,
1976 int install_flags,
1977 const std::string& install_parameter,
1978 base::DictionaryValue* extension_dict) const {
1979 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
1980 extension_dict->Set(kPrefLocation,
1981 new base::FundamentalValue(extension->location()));
1982 extension_dict->Set(kPrefCreationFlags,
1983 new base::FundamentalValue(extension->creation_flags()));
1984 extension_dict->Set(kPrefFromWebStore,
1985 new base::FundamentalValue(extension->from_webstore()));
1986 extension_dict->Set(kPrefFromBookmark,
1987 new base::FundamentalValue(extension->from_bookmark()));
1988 extension_dict->Set(
1989 kPrefWasInstalledByDefault,
1990 new base::FundamentalValue(extension->was_installed_by_default()));
1991 extension_dict->Set(
1992 kPrefWasInstalledByOem,
1993 new base::FundamentalValue(extension->was_installed_by_oem()));
1994 extension_dict->Set(kPrefInstallTime,
1995 new base::StringValue(
1996 base::Int64ToString(install_time.ToInternalValue())));
1997 if (install_flags & kInstallFlagIsBlacklistedForMalware)
1998 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
2000 if (install_flags & kInstallFlagIsEphemeral)
2001 extension_dict->Set(kPrefEphemeralApp, new base::FundamentalValue(true));
2002 else
2003 extension_dict->Remove(kPrefEphemeralApp, NULL);
2005 base::FilePath::StringType path = MakePathRelative(install_directory_,
2006 extension->path());
2007 extension_dict->Set(kPrefPath, new base::StringValue(path));
2008 if (!install_parameter.empty()) {
2009 extension_dict->Set(kPrefInstallParam,
2010 new base::StringValue(install_parameter));
2012 // We store prefs about LOAD extensions, but don't cache their manifest
2013 // since it may change on disk.
2014 if (!Manifest::IsUnpackedLocation(extension->location())) {
2015 extension_dict->Set(kPrefManifest,
2016 extension->manifest()->value()->DeepCopy());
2019 // Only writes kPrefDoNotSync when it is not the default.
2020 if (install_flags & kInstallFlagDoNotSync)
2021 extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true));
2022 else
2023 extension_dict->Remove(kPrefDoNotSync, NULL);
2026 void ExtensionPrefs::InitExtensionControlledPrefs(
2027 ExtensionPrefValueMap* value_map) {
2028 TRACE_EVENT0("browser,startup",
2029 "ExtensionPrefs::InitExtensionControlledPrefs")
2030 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitExtensionControlledPrefsTime");
2032 ExtensionIdList extension_ids;
2033 GetExtensions(&extension_ids);
2035 for (ExtensionIdList::iterator extension_id = extension_ids.begin();
2036 extension_id != extension_ids.end();
2037 ++extension_id) {
2038 base::Time install_time = GetInstallTime(*extension_id);
2039 bool is_enabled = !IsExtensionDisabled(*extension_id);
2040 bool is_incognito_enabled = IsIncognitoEnabled(*extension_id);
2041 value_map->RegisterExtension(
2042 *extension_id, install_time, is_enabled, is_incognito_enabled);
2044 FOR_EACH_OBSERVER(
2045 ExtensionPrefsObserver,
2046 observer_list_,
2047 OnExtensionRegistered(*extension_id, install_time, is_enabled));
2049 // Set regular extension controlled prefs.
2050 LoadExtensionControlledPrefs(
2051 this, value_map, *extension_id, kExtensionPrefsScopeRegular);
2052 // Set incognito extension controlled prefs.
2053 LoadExtensionControlledPrefs(this,
2054 value_map,
2055 *extension_id,
2056 kExtensionPrefsScopeIncognitoPersistent);
2057 // Set regular-only extension controlled prefs.
2058 LoadExtensionControlledPrefs(
2059 this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly);
2061 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
2062 observer_list_,
2063 OnExtensionPrefsLoaded(*extension_id, this));
2067 void ExtensionPrefs::FinishExtensionInfoPrefs(
2068 const std::string& extension_id,
2069 const base::Time install_time,
2070 bool needs_sort_ordinal,
2071 const syncer::StringOrdinal& suggested_page_ordinal,
2072 base::DictionaryValue* extension_dict) {
2073 // Reinitializes various preferences with empty dictionaries.
2074 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
2075 extension_dict->Set(pref_names::kPrefPreferences,
2076 new base::DictionaryValue);
2079 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
2080 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
2081 new base::DictionaryValue);
2084 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
2085 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
2086 new base::DictionaryValue);
2089 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
2090 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
2092 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
2093 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
2094 new base::ListValue);
2097 // If this point has been reached, any pending installs should be considered
2098 // out of date.
2099 extension_dict->Remove(kDelayedInstallInfo, NULL);
2101 // Clear state that may be registered from a previous install.
2102 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
2104 // FYI, all code below here races on sudden shutdown because |extension_dict|,
2105 // |app_sorting|, |extension_pref_value_map_|, and (potentially) observers
2106 // are updated non-transactionally. This is probably not fixable without
2107 // nested transactional updates to pref dictionaries.
2108 if (needs_sort_ordinal)
2109 app_sorting()->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
2111 bool is_enabled = false;
2112 int initial_state;
2113 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
2114 is_enabled = initial_state == Extension::ENABLED;
2116 bool is_incognito_enabled = IsIncognitoEnabled(extension_id);
2118 extension_pref_value_map_->RegisterExtension(
2119 extension_id, install_time, is_enabled, is_incognito_enabled);
2121 FOR_EACH_OBSERVER(
2122 ExtensionPrefsObserver,
2123 observer_list_,
2124 OnExtensionRegistered(extension_id, install_time, is_enabled));
2127 } // namespace extensions