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